From f76a3defb27b9c858ff48f8235845199d74b682f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:04:49 -0800 Subject: [PATCH 0001/1529] Revert "Use app auth instead of token auth" This reverts commit f9d942fd1709ac801fa749921e0fc59768736b08. Signed-off-by: Michael D Kinney --- .github/workflows/CheckCodeOwnerMaintainers.yml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/CheckCodeOwnerMaintainers.yml b/.github/workflows/CheckCodeOwnerMaintainers.yml index 216415c996..1189642c3c 100644 --- a/.github/workflows/CheckCodeOwnerMaintainers.yml +++ b/.github/workflows/CheckCodeOwnerMaintainers.yml @@ -72,9 +72,7 @@ jobs: with: checks: "files,owners,duppatterns,syntax" experimental_checks: "notowned,avoid-shadowing" - github_app_id: ${{ secrets.APPLICATION_ID }} - github_app_installation_id: ${{ secrets.APPLICATION_INSTALLATION_ID }} - github_app_private_key: ${{ secrets.APPLICATION_PRIVATE_KEY }} + github_access_token: "${{ secrets.CODEOWNERS_VALIDATOR_TOKEN }}" reviewers_validator_user: if: github.event.pull_request.draft == false && github.event.pull_request.base.user.type == 'User' @@ -120,6 +118,4 @@ jobs: with: checks: "files,owners,duppatterns,syntax" experimental_checks: "avoid-shadowing" - github_app_id: ${{ secrets.APPLICATION_ID }} - github_app_installation_id: ${{ secrets.APPLICATION_INSTALLATION_ID }} - github_app_private_key: ${{ secrets.APPLICATION_PRIVATE_KEY }} + github_access_token: "${{ secrets.CODEOWNERS_VALIDATOR_TOKEN }}" From 660b0178dd58e42f9b295135f5c3790acb159e7a Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:29 -0800 Subject: [PATCH 0002/1529] Revert "Update action dependencies" This reverts commit 8b377f8f03c0dddd9d178c7ef08cf84b45a4983b. Signed-off-by: Michael D Kinney --- .github/workflows/AssignReviewers.yml | 4 ++-- .github/workflows/CheckCodeOwnerFiles.yml | 2 +- .github/workflows/CheckCodeOwnerMaintainers.yml | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml index c09a6cff27..7778bc0d03 100644 --- a/.github/workflows/AssignReviewers.yml +++ b/.github/workflows/AssignReviewers.yml @@ -19,10 +19,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request Target - uses: actions/checkout@v4 + uses: actions/checkout@v2 - name: Get Token id: get_workflow_token - uses: peter-murray/workflow-application-token-action@v2 + uses: peter-murray/workflow-application-token-action@v1 with: application_id: ${{ secrets.APPLICATION_ID }} application_private_key: ${{ secrets.APPLICATION_PRIVATE_KEY }} diff --git a/.github/workflows/CheckCodeOwnerFiles.yml b/.github/workflows/CheckCodeOwnerFiles.yml index a72461d806..38c2807640 100644 --- a/.github/workflows/CheckCodeOwnerFiles.yml +++ b/.github/workflows/CheckCodeOwnerFiles.yml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 - name: CODEOWNERS Validator uses: mszostok/codeowners-validator@v0.7.4 with: diff --git a/.github/workflows/CheckCodeOwnerMaintainers.yml b/.github/workflows/CheckCodeOwnerMaintainers.yml index 1189642c3c..19c7c9d2d3 100644 --- a/.github/workflows/CheckCodeOwnerMaintainers.yml +++ b/.github/workflows/CheckCodeOwnerMaintainers.yml @@ -36,7 +36,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - name: Check CODEOWNERS, REVIEWERS, and Maintainers.txt files @@ -49,7 +49,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - name: CODEOWNERS Validator @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - name: CODEOWNERS Validator @@ -79,7 +79,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - name: Copy REVIEWERS to CODEOWNERS @@ -102,7 +102,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Pull Request - uses: actions/checkout@v4 + uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - name: Copy REVIEWERS to CODEOWNERS From 69816bb1dab77d10b346e41ffa52439227bd2847 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:34 -0800 Subject: [PATCH 0003/1529] Revert ".github/workflows: Use tianocore-assign-reviewers [bot] app" This reverts commit 15b3fb702b5363f55eab04af3ed86e05ceb2e5bb. Signed-off-by: Michael D Kinney --- .github/workflows/AssignReviewers.yml | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml index 7778bc0d03..06baa4d0da 100644 --- a/.github/workflows/AssignReviewers.yml +++ b/.github/workflows/AssignReviewers.yml @@ -20,13 +20,6 @@ jobs: steps: - name: Checkout Pull Request Target uses: actions/checkout@v2 - - name: Get Token - id: get_workflow_token - uses: peter-murray/workflow-application-token-action@v1 - with: - application_id: ${{ secrets.APPLICATION_ID }} - application_private_key: ${{ secrets.APPLICATION_PRIVATE_KEY }} - organization: tianocore - uses: mdkinney/github-action-assign-reviewers@main with: - token: ${{ steps.get_workflow_token.outputs.token }} + token: ${{secrets.CODEOWNERS_VALIDATOR_TOKEN}} From 18aabdbda8599322d8a367f4030c6403f0d265ea Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:39 -0800 Subject: [PATCH 0004/1529] Revert ".github/workflows: Use configurable secret for AssignReviewers" This reverts commit fa15fd8ccc9aa5d4e7b0918916f40d6dd8c422f3. Signed-off-by: Michael D Kinney --- .github/workflows/AssignReviewers.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml index 06baa4d0da..50a27647a2 100644 --- a/.github/workflows/AssignReviewers.yml +++ b/.github/workflows/AssignReviewers.yml @@ -22,4 +22,4 @@ jobs: uses: actions/checkout@v2 - uses: mdkinney/github-action-assign-reviewers@main with: - token: ${{secrets.CODEOWNERS_VALIDATOR_TOKEN}} + token: ${{secrets.GITHUB_TOKEN}} From 8d33f77d3ec54e788e0e4e466c20207629f2e4f4 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:45 -0800 Subject: [PATCH 0005/1529] Revert ".github/workflows: Use token permissions for AssignReviewers" This reverts commit ca920757b679f2015278e6d6f85c7386b11dce0d. Signed-off-by: Michael D Kinney --- .github/workflows/AssignReviewers.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml index 50a27647a2..b49f2e8add 100644 --- a/.github/workflows/AssignReviewers.yml +++ b/.github/workflows/AssignReviewers.yml @@ -17,6 +17,10 @@ jobs: assign_reviewers: if: github.event.pull_request.draft == false runs-on: ubuntu-latest + permissions: + actions: read + contents: read + pull-requests: write steps: - name: Checkout Pull Request Target uses: actions/checkout@v2 From a87c88ee5ca7ac83d217d0f96a864850ed2f7065 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:49 -0800 Subject: [PATCH 0006/1529] Revert ".github/workflows: Update permissions for AssignReviewers action" This reverts commit e435b02344da1b6d1f7d452a493a02105bb477d5. Signed-off-by: Michael D Kinney --- .github/workflows/AssignReviewers.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml index b49f2e8add..d517fe0780 100644 --- a/.github/workflows/AssignReviewers.yml +++ b/.github/workflows/AssignReviewers.yml @@ -18,8 +18,6 @@ jobs: if: github.event.pull_request.draft == false runs-on: ubuntu-latest permissions: - actions: read - contents: read pull-requests: write steps: - name: Checkout Pull Request Target From 4f066cdd7c085ad90d409829c29b105fd1a2ad8c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:53 -0800 Subject: [PATCH 0007/1529] Revert ".github: Add stewards as codeowners for CODEOWNERS and REVIEWERS" This reverts commit eb7b7dbc88417c72a50f5719f1e6160784550cfb. Signed-off-by: Michael D Kinney --- .github/CODEOWNERS | 10 +++------- .github/REVIEWERS | 6 +++--- Maintainers.txt | 16 ++-------------- 3 files changed, 8 insertions(+), 24 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index cf472e2cc4..07c1d1d18d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -121,17 +121,13 @@ # R: Liming Gao [lgao4] /.azurepipelines/** @spbrogan @corthon -# Tianocore Stewards must approve changes to CODEOWNERS and REVIEWERS -/.github/CODEOWNERS @ajfish @leiflindholm @mdkinney -/.github/REVIEWERS @ajfish @leiflindholm @mdkinney - -# .github/workflows/ -# F: .github/workflows/ +# .github/ +# F: .github/ # M: Michael D Kinney [mdkinney] # M: Michael Kubacki [makubacki] # R: Sean Brogan [spbrogan] # R: Liming Gao [lgao4] -/.github/workflows/** @mdkinney @makubacki +/.github/** @mdkinney @makubacki # .mergify/ # F: .mergify/ diff --git a/.github/REVIEWERS b/.github/REVIEWERS index 683d8bbf53..d645604c85 100644 --- a/.github/REVIEWERS +++ b/.github/REVIEWERS @@ -120,13 +120,13 @@ # R: Liming Gao [lgao4] /.azurepipelines/** @mdkinney @lgao4 -# .github/workflows/ -# F: .github/workflows/ +# .github/ +# F: .github/ # M: Michael D Kinney [mdkinney] # M: Michael Kubacki [makubacki] # R: Sean Brogan [spbrogan] # R: Liming Gao [lgao4] -/.github/workflows/** @spbrogan @lgao4 +/.github/** @spbrogan @lgao4 # .mergify/ # F: .mergify/ diff --git a/Maintainers.txt b/Maintainers.txt index edb4955ea0..d5fb4a1ab6 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -111,20 +111,8 @@ M: Bret Barkelew [corthon] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] -.github/CODEOWNERS -F: .github/CODEOWNERS -M: Andrew Fish [ajfish] -M: Leif Lindholm [leiflindholm] -M: Michael D Kinney [mdkinney] - -.github/REVIEWERS -F: .github/REVIEWERS -M: Andrew Fish [ajfish] -M: Leif Lindholm [leiflindholm] -M: Michael D Kinney [mdkinney] - -.github/workflows/ -F: .github/workflows/ +.github/ +F: .github/ M: Michael D Kinney [mdkinney] M: Michael Kubacki [makubacki] R: Sean Brogan [spbrogan] From ede7765f0f227da73d29b632fc8037709a0e93b8 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:05:59 -0800 Subject: [PATCH 0008/1529] Revert ".github: Fix path to UefiPayloadPkg in REVIEWERS" This reverts commit 3614ca0a3d39e713dce0ee61ec42014aee622c15. Signed-off-by: Michael D Kinney --- .github/REVIEWERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/REVIEWERS b/.github/REVIEWERS index d645604c85..9c478b88ae 100644 --- a/.github/REVIEWERS +++ b/.github/REVIEWERS @@ -857,7 +857,7 @@ # M: James Lu [jameslu8] # R: Gua Guo [gguo11837463] # S: Maintained -/UefiPayloadPkg/** @gguo11837463 +/UefiPalyloadPkg/** @gguo11837463 # UnitTestFrameworkPkg # F: UnitTestFrameworkPkg/ From bfa2af3aa83019fb1974fa0242c32daf4a5adfdd Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:06:03 -0800 Subject: [PATCH 0009/1529] Revert ".github: Add CODEOWNERS and REVIEWERS" This reverts commit 93992fdd4ef080bba8e493fa5e5cbdb5dd8d8e80. Signed-off-by: Michael D Kinney --- .github/CODEOWNERS | 685 -------------- .github/REVIEWERS | 870 ------------------ .github/workflows/AssignReviewers.yml | 27 - .github/workflows/CheckCodeOwnerFiles.yml | 39 - .../workflows/CheckCodeOwnerMaintainers.yml | 121 --- Maintainers.txt | 7 - 6 files changed, 1749 deletions(-) delete mode 100644 .github/CODEOWNERS delete mode 100644 .github/REVIEWERS delete mode 100644 .github/workflows/AssignReviewers.yml delete mode 100644 .github/workflows/CheckCodeOwnerFiles.yml delete mode 100644 .github/workflows/CheckCodeOwnerMaintainers.yml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 07c1d1d18d..0000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,685 +0,0 @@ -## @file -# CODEOWNERS file that contains EDK II Maintainers -# -# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -# -# EDK II Maintainers -# ================== -# -# This file provides information about the primary maintainers for -# EDK II. -# -# In general, you should not privately email the maintainer. You should -# email the edk2-devel list, and Cc the package maintainers and -# reviewers. -# -# If the package maintainer wants to hand over the role to other people, -# the package maintainer should send the patch to update Maintainers.txt -# with new maintainer, and the new maintainer should follow up with -# an Acked-by or a Reviewed-by. -# -# Descriptions of section entries: -# -# L: Mailing list that is relevant to this area (default is edk2-devel) -# Patches and questions should be sent to the email list. -# M: Package Maintainer: Cc address for patches and questions. Responsible -# for reviewing and pushing package changes to source control. -# R: Package Reviewer: Cc address for patches and questions. Reviewers help -# maintainers review code, but don't have push access. A designated Package -# Reviewer is reasonably familiar with the Package (or some modules -# thereof), and/or provides testing or regression testing for the Package -# (or some modules thereof), in certain platforms and environments. -# W: Web-page with status/info -# T: SCM tree type and location. Type is one of: git, svn. -# S: Status, one of the following: -# Supported: Someone is actually paid to look after this. -# Maintained: Someone actually looks after it. -# Odd Fixes: It has a maintainer but they don't have time to do -# much other than throw the odd patch in. See below. -# Orphan: No current maintainer [but maybe you could take the -# role as you write your new code]. -# Obsolete: Old code. Something tagged obsolete generally means -# it has been replaced by a better system and you -# should be using that. -# F: Files and directories with wildcard patterns. -# A trailing slash includes all files and subdirectory files. -# F: MdeModulePkg/ all files in and below MdeModulePkg -# F: MdeModulePkg/* all files in MdeModulePkg, but not below -# F: */Pci/* all files in a directory called Pci, at any depth in -# the hierarchy, but not below -# One pattern per line. Multiple F: lines per section acceptable. -# X: Files and directories that are NOT maintained, same rules as F: -# Files exclusions are tested after file matches. -# Can be useful for excluding a specific subdirectory, for instance: -# F: NetworkPkg/ -# X: NetworkPkg/Ip6Dxe/ -# matches all files in and below NetworkPkg excluding NetworkPkg/Ip6Dxe/ -# Filenames not caught by any F: rule get matched as being located in the top- -# level directory. (Internally, the script looks for a match called '', -# so please don't add a file called that in the top-level directory.) -# -# EDK II -# ------ -# W: http://www.tianocore.org/edk2/ -# L: https://edk2.groups.io/g/devel/ -# T: git - https://github.com/tianocore/edk2.git -# T: git (mirror) - https://bitbucket.org/tianocore/edk2.git -# -# All patches CC:d here -# L: devel@edk2.groups.io -# F: * -# F: */ -# -# Tianocore Stewards -# ------------------ -# F: * -# M: Andrew Fish [ajfish] -# M: Leif Lindholm [leiflindholm] -# M: Michael D Kinney [mdkinney] -* @ajfish @leiflindholm @mdkinney - -# Responsible Disclosure, Reporting Security Issues -# ------------------------------------------------- -# W: https://github.com/tianocore/tianocore.github.io/wiki/Security -# -# EDK II Releases: -# ---------------- -# W: https://github.com/tianocore/tianocore.github.io/wiki/EDK-II-Release-Planning -# M: Liming Gao [lgao4] -# -# UEFI Shell Binaries (ShellBinPkg.zip) from EDK II Releases: -# ----------------------------------------------------------- -# W: https://github.com/tianocore/edk2/releases/ -# M: Ray Ni [niruiyu] (Ia32/X64) -# M: Zhichao Gao [ZhichaoGao] (Ia32/X64) -# M: Leif Lindholm [leiflindholm] (ARM/AArch64) -# M: Ard Biesheuvel [ardbiesheuvel] (ARM/AArch64) -# -# EDK II Architectures: -# --------------------- -# ARM, AARCH64 -# F: */AArch64/ -# F: */Arm/ -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# -# RISCV64 -# F: */RiscV64/ -# M: Sunil V L [vlsunil] -# R: Daniel Schaefer [JohnAZoidberg] -# -# EDK II Continuous Integration: -# ------------------------------ -# .azurepipelines/ -# F: .azurepipelines/ -# M: Sean Brogan [spbrogan] -# M: Bret Barkelew [corthon] -# R: Michael D Kinney [mdkinney] -# R: Liming Gao [lgao4] -/.azurepipelines/** @spbrogan @corthon - -# .github/ -# F: .github/ -# M: Michael D Kinney [mdkinney] -# M: Michael Kubacki [makubacki] -# R: Sean Brogan [spbrogan] -# R: Liming Gao [lgao4] -/.github/** @mdkinney @makubacki - -# .mergify/ -# F: .mergify/ -# M: Michael D Kinney [mdkinney] -# M: Liming Gao [lgao4] -# R: Sean Brogan [spbrogan] -# R: Bret Barkelew [corthon] -/.mergify/** @mdkinney @lgao4 - -# .pytool/ -# F: .pytool/ -# M: Sean Brogan [spbrogan] -# M: Bret Barkelew [corthon] -# R: Michael D Kinney [mdkinney] -# R: Liming Gao [lgao4] -/.pytool/** @spbrogan @corthon - -# EDK II Packages: -# ---------------- -# ArmPkg -# F: ArmPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# R: Sami Mujawar [samimujawar] -/ArmPkg/** @leiflindholm @ardbiesheuvel - -# ArmPlatformPkg -# F: ArmPlatformPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPlatformPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -/ArmPlatformPkg/** @leiflindholm @ardbiesheuvel - -# ArmVirtPkg -# F: ArmVirtPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmVirtPkg -# M: Ard Biesheuvel [ardbiesheuvel] -# R: Leif Lindholm [leiflindholm] -# R: Sami Mujawar [samimujawar] -# R: Gerd Hoffmann [kraxel] -/ArmVirtPkg/** @ardbiesheuvel -/ArmVirtPkg/**/AArch64/** @ardbiesheuvel @leiflindholm -/ArmVirtPkg/**/Arm/** @ardbiesheuvel @leiflindholm - -# ArmVirtPkg: modules used on Xen -# F: ArmVirtPkg/ArmVirtXen.* -# F: ArmVirtPkg/Library/XenArmGenericTimerVirtCounterLib/ -# F: ArmVirtPkg/Library/XenVirtMemInfoLib/ -# F: ArmVirtPkg/PrePi/ -# F: ArmVirtPkg/XenAcpiPlatformDxe/ -# F: ArmVirtPkg/XenPlatformHasAcpiDtDxe/ -# F: ArmVirtPkg/XenioFdtDxe/ -# R: Julien Grall [jgrall] - -# BaseTools -# F: BaseTools/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/BaseTools -# M: Bob Feng [BobCF] -# M: Liming Gao [lgao4] -# R: Yuwei Chen [YuweiChen1110] -/BaseTools/** @BobCF @lgao4 -/BaseTools/**/AArch64/** @BobCF @lgao4 @leiflindholm @ardbiesheuvel -/BaseTools/**/Arm/** @BobCF @lgao4 @leiflindholm @ardbiesheuvel -/BaseTools/**/RiscV64/** @BobCF @lgao4 @vlsunil - -# CryptoPkg -# F: CryptoPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/CryptoPkg -# M: Jiewen Yao [jyao1] -# M: Jian J Wang [jwang36] -# R: Xiaoyu Lu [xiaoyuxlu] -# R: Guomin Jiang [guominjia] -/CryptoPkg/** @jyao1 @jwang36 - -# DynamicTablesPkg -# F: DynamicTablesPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/DynamicTablesPkg -# M: Sami Mujawar [samimujawar] -# M: Alexei Fedorov [AlexeiFedorov] -/DynamicTablesPkg/** @samimujawar @AlexeiFedorov -/DynamicTablesPkg/**/Arm/** @samimujawar @AlexeiFedorov @leiflindholm @ardbiesheuvel - -# EmbeddedPkg -# F: EmbeddedPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/EmbeddedPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Abner Chang [changab] -# R: Daniel Schaefer [JohnAZoidberg] -/EmbeddedPkg/** @leiflindholm @ardbiesheuvel @changab - -# EmulatorPkg -# F: EmulatorPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/EmulatorPkg -# M: Andrew Fish [ajfish] -# M: Ray Ni [niruiyu] -# S: Maintained -/EmulatorPkg/** @ajfish @niruiyu - -# EmulatorPkg: Redfish-related modules -# F: EmulatorPkg/*Redfish* -# M: Abner Chang [changab] -# R: Nickle Wang [nicklela] -/EmulatorPkg/**/Redfish*/** @ajfish @niruiyu @changab - -# FatPkg -# F: FatPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/Edk2-fat-driver -# M: Ray Ni [niruiyu] -# T: svn - https://svn.code.sf.net/p/edk2-fatdriver2/code/trunk/EnhancedFat -# T: git - https://github.com/tianocore/edk2-FatPkg.git -/FatPkg/** @niruiyu - -# FmpDevicePkg -# F: FmpDevicePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/FmpDevicePkg -# M: Liming Gao [lgao4] -# M: Michael D Kinney [mdkinney] -# R: Guomin Jiang [guominjia] -# R: Wei6 Xu [xuweiintel] -/FmpDevicePkg/** @lgao4 @mdkinney - -# IntelFsp2Pkg -# F: IntelFsp2Pkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/IntelFsp2Pkg -# M: Chasel Chiu [ChaselChiu] -# M: Nate DeSimone [nate-desimone] -# R: Star Zeng [lzeng14] -/IntelFsp2Pkg/** @ChaselChiu @nate-desimone - -# IntelFsp2WrapperPkg -# F: IntelFsp2WrapperPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/IntelFsp2WrapperPkg -# M: Chasel Chiu [ChaselChiu] -# M: Nate DeSimone [nate-desimone] -# R: Star Zeng [lzeng14] -/IntelFsp2WrapperPkg/** @ChaselChiu @nate-desimone - -# MdeModulePkg -# F: MdeModulePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/MdeModulePkg -# M: Jian J Wang [jwang36] -# M: Liming Gao [lgao4] -/MdeModulePkg/** @jwang36 @lgao4 -/MdeModulePkg/**/AArch64/** @jwang36 @lgao4 @leiflindholm @ardbiesheuvel -/MdeModulePkg/**/Arm/** @jwang36 @lgao4 @leiflindholm @ardbiesheuvel -/MdeModulePkg/**/RiscV64/** @jwang36 @lgao4 @vlsunil - -# MdeModulePkg: ACPI modules -# F: MdeModulePkg/Include/*Acpi*.h -# F: MdeModulePkg/Universal/Acpi/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] - -# MdeModulePkg: ACPI modules related to S3 -# F: MdeModulePkg/*LockBox*/ -# F: MdeModulePkg/Include/*BootScript*.h -# F: MdeModulePkg/Include/*LockBox*.h -# F: MdeModulePkg/Include/*S3*.h -# F: MdeModulePkg/Library/*S3*/ -# R: Hao A Wu [hwu25] -# R: Eric Dong [ydong10] - -# MdeModulePkg: BDS modules -# F: MdeModulePkg/*BootManager*/ -# F: MdeModulePkg/Include/Library/UefiBootManagerLib.h -# F: MdeModulePkg/Universal/BdsDxe/ -# F: MdeModulePkg/Universal/DevicePathDxe/ -# F: MdeModulePkg/Universal/DriverHealthManagerDxe/ -# F: MdeModulePkg/Universal/LoadFileOnFv2/ -# F: MdeModulePkg/Universal/SecurityStubDxe/Defer3rdPartyImageLoad.* -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] - -# MdeModulePkg: Console and Graphics modules -# F: MdeModulePkg/*Logo*/ -# F: MdeModulePkg/Include/*Logo*.h -# F: MdeModulePkg/Include/Guid/ConnectConInEvent.h -# F: MdeModulePkg/Include/Guid/Console*.h -# F: MdeModulePkg/Include/Guid/StandardErrorDevice.h -# F: MdeModulePkg/Include/Guid/TtyTerm.h -# F: MdeModulePkg/Include/Library/BmpSupportLib.h -# F: MdeModulePkg/Include/Library/FrameBufferBltLib.h -# F: MdeModulePkg/Library/BaseBmpSupportLib/ -# F: MdeModulePkg/Library/FrameBufferBltLib/ -# F: MdeModulePkg/Universal/Console/ -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] - -# MdeModulePkg: Core services (PEI, DXE and Runtime) modules -# F: MdeModulePkg/*Mem*/ -# F: MdeModulePkg/*SectionExtract*/ -# F: MdeModulePkg/*StatusCode*/ -# F: MdeModulePkg/Application/DumpDynPcd/ -# F: MdeModulePkg/Core/Dxe/ -# F: MdeModulePkg/Core/DxeIplPeim/ -# F: MdeModulePkg/Core/RuntimeDxe/ -# F: MdeModulePkg/Include/*Mem*.h -# F: MdeModulePkg/Include/*Pcd*.h -# F: MdeModulePkg/Include/*Perf*.h -# F: MdeModulePkg/Include/*StatusCode*.h -# F: MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h -# F: MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h -# F: MdeModulePkg/Include/Guid/IdleLoopEvent.h -# F: MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h -# F: MdeModulePkg/Include/Guid/LzmaDecompress.h -# F: MdeModulePkg/Include/Library/SecurityManagementLib.h -# F: MdeModulePkg/Library/*Decompress*/ -# F: MdeModulePkg/Library/*Perf*/ -# F: MdeModulePkg/Library/DxeSecurityManagementLib/ -# F: MdeModulePkg/Universal/PCD/ -# F: MdeModulePkg/Universal/PlatformDriOverrideDxe/ -# F: MdeModulePkg/Universal/SecurityStubDxe/SecurityStub.c -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] - -# MdeModulePkg: Device and Peripheral modules -# F: MdeModulePkg/*PciHostBridge*/ -# F: MdeModulePkg/Bus/ -# F: MdeModulePkg/Include/*Ata*.h -# F: MdeModulePkg/Include/*IoMmu*.h -# F: MdeModulePkg/Include/*NonDiscoverableDevice*.h -# F: MdeModulePkg/Include/*NvmExpress*.h -# F: MdeModulePkg/Include/*SdMmc*.h -# F: MdeModulePkg/Include/*Ufs*.h -# F: MdeModulePkg/Include/*Usb*.h -# F: MdeModulePkg/Include/Guid/RecoveryDevice.h -# F: MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h -# F: MdeModulePkg/Include/Library/PciHostBridgeLib.h -# F: MdeModulePkg/Include/Ppi/StorageSecurityCommand.h -# F: MdeModulePkg/Include/Protocol/Ps2Policy.h -# F: MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/ -# F: MdeModulePkg/Universal/PcatSingleSegmentPciCfg2Pei/ -# R: Hao A Wu [hwu25] -# R: Ray Ni [niruiyu] - -# MdeModulePkg: Disk modules -# F: MdeModulePkg/Universal/Disk/ -# R: Hao A Wu [hwu25] -# R: Ray Ni [niruiyu] -# R: Zhichao Gao [ZhichaoGao] - -# MdeModulePkg: Firmware Update modules -# F: MdeModulePkg/*Capsule*/ -# F: MdeModulePkg/Include/*Capsule*.h -# F: MdeModulePkg/Include/Library/DisplayUpdateProgressLib.h -# F: MdeModulePkg/Include/Library/FmpAuthenticationLib.h -# F: MdeModulePkg/Include/Protocol/EsrtManagement.h -# F: MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h -# F: MdeModulePkg/Library/DisplayUpdateProgressLib*/ -# F: MdeModulePkg/Library/FmpAuthenticationLibNull/ -# F: MdeModulePkg/Universal/Esrt*/ -# R: Liming Gao [lgao4] -# R: Guomin Jiang [guominjia] - -# MdeModulePkg: HII and UI modules -# F: MdeModulePkg/*FileExplorer*/ -# F: MdeModulePkg/*Hii*/ -# F: MdeModulePkg/*Ui*/ -# F: MdeModulePkg/Application/BootManagerMenuApp/ -# F: MdeModulePkg/Include/*FileExplorer*.h -# F: MdeModulePkg/Include/*FormBrowser*.h -# F: MdeModulePkg/Include/*Hii*.h -# F: MdeModulePkg/Include/Library/CustomizedDisplayLib.h -# F: MdeModulePkg/Include/Protocol/DisplayProtocol.h -# F: MdeModulePkg/Library/CustomizedDisplayLib/ -# F: MdeModulePkg/Universal/DisplayEngineDxe/ -# F: MdeModulePkg/Universal/DriverSampleDxe/ -# F: MdeModulePkg/Universal/SetupBrowserDxe/ -# R: Dandan Bi [dandanbi] -# R: Eric Dong [ydong10] - -# MdeModulePkg: Management Mode (MM, SMM) modules -# F: MdeModulePkg/*Smi*/ -# F: MdeModulePkg/*Smm*/ -# F: MdeModulePkg/Include/*Smi*.h -# F: MdeModulePkg/Include/*Smm*.h -# R: Eric Dong [ydong10] -# R: Ray Ni [niruiyu] - -# MdeModulePkg: Reset modules -# F: MdeModulePkg/*Reset*/ -# F: MdeModulePkg/Include/*Reset*.h -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] - -# MdeModulePkg: Pei Core -# F: MdeModulePkg/Core/Pei/ -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] -# R: Debkumar De [dde01] -# R: Catharine West [catharine-intl] - -# MdeModulePkg: Serial modules -# F: MdeModulePkg/*Serial*/ -# F: MdeModulePkg/Include/*SerialPort*.h -# R: Ray Ni [niruiyu] -# R: Zhichao Gao [ZhichaoGao] - -# MdeModulePkg: SMBIOS modules -# F: MdeModulePkg/Universal/Smbios*/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Dandan Bi [dandanbi] -# R: Star Zeng [lzeng14] -# R: Zhichao Gao [ZhichaoGao] - -# MdeModulePkg: UEFI Variable modules -# F: MdeModulePkg/*Var*/ -# F: MdeModulePkg/Include/*/*FaultTolerantWrite*.h -# F: MdeModulePkg/Include/*/*Var*.h -# F: MdeModulePkg/Include/Guid/SystemNvDataGuid.h -# F: MdeModulePkg/Include/Protocol/SwapAddressRange.h -# F: MdeModulePkg/Universal/FaultTolerantWrite*/ -# R: Hao A Wu [hwu25] -# R: Liming Gao [lgao4] - -# MdeModulePkg: Universal Payload definitions -# F: MdeModulePkg/Include/UniversalPayload/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Ray Ni [niruiyu] -# R: Gua Guo [gguo11837463] -# MdePkg -# F: MdePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/MdePkg -# M: Michael D Kinney [mdkinney] -# M: Liming Gao [lgao4] -# R: Zhiguang Liu [LiuZhiguang001] -/MdePkg/** @mdkinney @lgao4 -/MdePkg/**/AArch64/** @mdkinney @lgao4 @leiflindholm @ardbiesheuvel -/MdePkg/**/Arm/** @mdkinney @lgao4 @leiflindholm @ardbiesheuvel -/MdePkg/**/RiscV64/** @mdkinney @lgao4 @vlsunil - -# NetworkPkg -# F: NetworkPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg -# M: Maciej Rabeda [mrabeda] -# R: Jiaxin Wu [jiaxinwu] -# R: Siyuan Fu [sfu5] -/NetworkPkg/** @mrabeda - -# OvmfPkg -# F: OvmfPkg/ -# W: http://www.tianocore.org/ovmf/ -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Jiewen Yao [jyao1] -# R: Jordan Justen [jljusten] -# R: Gerd Hoffmann [kraxel] -# S: Maintained -/OvmfPkg/** @ardbiesheuvel @jyao1 -/OvmfPkg/**/AArch64/** @ardbiesheuvel @jyao1 @leiflindholm -/OvmfPkg/**/Arm/** @ardbiesheuvel @jyao1 @leiflindholm - -# -# OvmfPkg: bhyve-related modules -# F: OvmfPkg/Bhyve/ -# F: OvmfPkg/Include/IndustryStandard/Bhyve.h -# F: OvmfPkg/Include/Library/BhyveFwCtlLib.h -# F: OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.c -# F: OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.inf -# F: OvmfPkg/Library/BhyveFwCtlLib/ -# F: OvmfPkg/Library/PciHostBridgeLibScan/ -# F: OvmfPkg/Library/PlatformBootManagerLibBhyve/ -# F: OvmfPkg/Library/ResetSystemLib/BaseResetShutdownBhyve.c -# F: OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf -# R: Rebecca Cran [bcran] -# R: Peter Grehan [grehan-freebsd] - -# OvmfPkg: cloudhv-related modules -# F: OvmfPkg/CloudHv/ -# F: OvmfPkg/Include/IndustryStandard/CloudHv.h -# R: Sebastien Boeuf [sboeuf] - -# OvmfPkg: microvm-related modules -# F: OvmfPkg/Microvm/ -# F: OvmfPkg/Include/IndustryStandard/Microvm.h -# F: OvmfPkg/Library/ResetSystemLib/*Microvm.* -# R: Gerd Hoffmann [kraxel] - -# OvmfPkg: CSM modules -# F: OvmfPkg/Csm/ -# R: David Woodhouse [dwmw2] - -# OvmfPkg: Confidential Computing -# F: OvmfPkg/AmdSev/ -# F: OvmfPkg/AmdSevDxe/ -# F: OvmfPkg/Include/Guid/ConfidentialComputingSecret.h -# F: OvmfPkg/Include/Library/MemEncryptSevLib.h -# F: OvmfPkg/IoMmuDxe/AmdSevIoMmu.* -# F: OvmfPkg/Library/BaseMemEncryptSevLib/ -# F: OvmfPkg/Library/PlatformBootManagerLibGrub/ -# F: OvmfPkg/Library/VmgExitLib/ -# F: OvmfPkg/PlatformPei/AmdSev.c -# F: OvmfPkg/ResetVector/ -# F: OvmfPkg/Sec/ -# R: Brijesh Singh [codomania] -# R: Erdem Aktas [ruleof2] -# R: James Bottomley [jejb] -# R: Jiewen Yao [jyao1] -# R: Min Xu [mxu9] -# R: Tom Lendacky [tlendacky] - -# OvmfPkg: FDT related modules -# F: OvmfPkg/Fdt -# R: Leif Lindholm [leiflindholm] -# R: Gerd Hoffmann [kraxel] -# R: Abner Chang [changab] - -# OvmfPkg: LsiScsi driver -# F: OvmfPkg/LsiScsiDxe/ -# R: Gary Lin [lcp] - -# OvmfPkg: TCG- and TPM2-related modules -# F: OvmfPkg/Include/IndustryStandard/QemuTpm.h -# F: OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c -# F: OvmfPkg/Library/Tcg2PhysicalPresenceLib*/ -# F: OvmfPkg/PlatformPei/ClearCache.c -# F: OvmfPkg/Tcg/ -# R: Marc-André Lureau [elmarco] -# R: Stefan Berger [stefanberger] - -# OvmfPkg: Xen-related modules -# F: OvmfPkg/Include/Guid/XenBusRootDevice.h -# F: OvmfPkg/Include/Guid/XenInfo.h -# F: OvmfPkg/Include/IndustryStandard/Xen/ -# F: OvmfPkg/Include/Library/XenHypercallLib.h -# F: OvmfPkg/Include/Library/XenIoMmioLib.h -# F: OvmfPkg/Include/Library/XenPlatformLib.h -# F: OvmfPkg/Include/Protocol/XenBus.h -# F: OvmfPkg/Include/Protocol/XenIo.h -# F: OvmfPkg/Library/PciHostBridgeLibScan/ -# F: OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c -# F: OvmfPkg/Library/XenConsoleSerialPortLib/ -# F: OvmfPkg/Library/XenHypercallLib/ -# F: OvmfPkg/Library/XenIoMmioLib/ -# F: OvmfPkg/Library/XenPlatformLib/ -# F: OvmfPkg/Library/XenRealTimeClockLib/ -# F: OvmfPkg/OvmfXen.* -# F: OvmfPkg/OvmfXenElfHeaderGenerator.c -# F: OvmfPkg/SmbiosPlatformDxe/*Xen* -# F: OvmfPkg/XenAcpiPlatformDxe/ -# F: OvmfPkg/XenBusDxe/ -# F: OvmfPkg/XenIoPciDxe/ -# F: OvmfPkg/XenIoPvhDxe/ -# F: OvmfPkg/XenPlatformPei/ -# F: OvmfPkg/XenPvBlkDxe/ -# F: OvmfPkg/XenResetVector/ -# R: Anthony Perard [sheep] -# R: Julien Grall [jgrall] - -# PcAtChipsetPkg -# F: PcAtChipsetPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/PcAtChipsetPkg -# M: Ray Ni [niruiyu] -/PcAtChipsetPkg/** @niruiyu - -# PrmPkg -# F: PrmPkg/ -# M: Michael Kubacki [makubacki] -# M: Nate DeSimone [nate-desimone] -/PrmPkg/** @makubacki @nate-desimone - -# PrmPkg: ACPI related modules -# R: Ankit Sinha [ankit13s] - -# RedfishPkg: Redfish related modules -# F: RedfishPkg/ -# M: Abner Chang [changab] -# R: Nickle Wang [nicklela] -/RedfishPkg/** @changab - -# SecurityPkg -# F: SecurityPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SecurityPkg -# M: Jiewen Yao [jyao1] -# M: Jian J Wang [jwang36] -/SecurityPkg/** @jyao1 @jwang36 -/SecurityPkg/**/AArch64/** @jyao1 @jwang36 @leiflindholm @ardbiesheuvel - -# SecurityPkg: Secure boot related modules -# F: SecurityPkg/Library/DxeImageVerificationLib/ -# F: SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/ -# F: SecurityPkg/Library/AuthVariableLib/ -# R: Min Xu [mxu9] - -# SecurityPkg: Tcg related modules -# F: SecurityPkg/Tcg/ -# R: Qi Zhang [qizhangz] -# R: Rahul Kumar [rahul1-kumar] - -# ShellPkg -# F: ShellPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ShellPkg -# M: Ray Ni [niruiyu] -# M: Zhichao Gao [ZhichaoGao] -/ShellPkg/** @niruiyu @ZhichaoGao -/ShellPkg/**/Arm/** @niruiyu @ZhichaoGao @leiflindholm @ardbiesheuvel - -# SignedCapsulePkg -# F: SignedCapsulePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SignedCapsulePkg -# M: Jian J Wang [jwang36] -/SignedCapsulePkg/** @jwang36 - -# SourceLevelDebugPkg -# F: SourceLevelDebugPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SourceLevelDebugPkg -# M: Hao A Wu [hwu25] -/SourceLevelDebugPkg/** @hwu25 - -# StandaloneMmPkg -# F: StandaloneMmPkg/ -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Sami Mujawar [samimujawar] -# M: Jiewen Yao [jyao1] -# R: Supreeth Venkatesh [supven01] -/StandaloneMmPkg/** @ardbiesheuvel @samimujawar @jyao1 -/StandaloneMmPkg/**/AArch64/** @ardbiesheuvel @samimujawar @jyao1 @leiflindholm -/StandaloneMmPkg/**/Arm/** @ardbiesheuvel @samimujawar @jyao1 @leiflindholm - -# UefiCpuPkg -# F: UefiCpuPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/UefiCpuPkg -# M: Eric Dong [ydong10] -# M: Ray Ni [niruiyu] -# R: Rahul Kumar [rahul1-kumar] -/UefiCpuPkg/** @ydong10 @niruiyu - -# UefiCpuPkg: Sec related modules -# F: UefiCpuPkg/SecCore/ -# F: UefiCpuPkg/ResetVector/ -# R: Debkumar De [dde01] -# R: Catharine West [catharine-intl] - -# UefiPayloadPkg -# F: UefiPayloadPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/UefiPayloadPkg -# M: Guo Dong [gdong1] -# M: Ray Ni [niruiyu] -# M: Sean Rhodes [Sean-StarLabs] -# M: James Lu [jameslu8] -# R: Gua Guo [gguo11837463] -# S: Maintained -/UefiPayloadPkg/** @gdong1 @niruiyu @Sean-StarLabs @jameslu8 - -# UnitTestFrameworkPkg -# F: UnitTestFrameworkPkg/ -# M: Michael D Kinney [mdkinney] -# M: Michael Kubacki [makubacki] -# R: Sean Brogan [spbrogan] -# R: Bret Barkelew [corthon] -# S: Maintained -/UnitTestFrameworkPkg/** @mdkinney @makubacki - diff --git a/.github/REVIEWERS b/.github/REVIEWERS deleted file mode 100644 index 9c478b88ae..0000000000 --- a/.github/REVIEWERS +++ /dev/null @@ -1,870 +0,0 @@ -## @file -# REVIEWERS file that contains EDK II Reviewers -# -# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -# -# EDK II Maintainers -# ================== -# -# This file provides information about the primary maintainers for -# EDK II. -# -# In general, you should not privately email the maintainer. You should -# email the edk2-devel list, and Cc the package maintainers and -# reviewers. -# -# If the package maintainer wants to hand over the role to other people, -# the package maintainer should send the patch to update Maintainers.txt -# with new maintainer, and the new maintainer should follow up with -# an Acked-by or a Reviewed-by. -# -# Descriptions of section entries: -# -# L: Mailing list that is relevant to this area (default is edk2-devel) -# Patches and questions should be sent to the email list. -# M: Package Maintainer: Cc address for patches and questions. Responsible -# for reviewing and pushing package changes to source control. -# R: Package Reviewer: Cc address for patches and questions. Reviewers help -# maintainers review code, but don't have push access. A designated Package -# Reviewer is reasonably familiar with the Package (or some modules -# thereof), and/or provides testing or regression testing for the Package -# (or some modules thereof), in certain platforms and environments. -# W: Web-page with status/info -# T: SCM tree type and location. Type is one of: git, svn. -# S: Status, one of the following: -# Supported: Someone is actually paid to look after this. -# Maintained: Someone actually looks after it. -# Odd Fixes: It has a maintainer but they don't have time to do -# much other than throw the odd patch in. See below. -# Orphan: No current maintainer [but maybe you could take the -# role as you write your new code]. -# Obsolete: Old code. Something tagged obsolete generally means -# it has been replaced by a better system and you -# should be using that. -# F: Files and directories with wildcard patterns. -# A trailing slash includes all files and subdirectory files. -# F: MdeModulePkg/ all files in and below MdeModulePkg -# F: MdeModulePkg/* all files in MdeModulePkg, but not below -# F: */Pci/* all files in a directory called Pci, at any depth in -# the hierarchy, but not below -# One pattern per line. Multiple F: lines per section acceptable. -# X: Files and directories that are NOT maintained, same rules as F: -# Files exclusions are tested after file matches. -# Can be useful for excluding a specific subdirectory, for instance: -# F: NetworkPkg/ -# X: NetworkPkg/Ip6Dxe/ -# matches all files in and below NetworkPkg excluding NetworkPkg/Ip6Dxe/ -# Filenames not caught by any F: rule get matched as being located in the top- -# level directory. (Internally, the script looks for a match called '', -# so please don't add a file called that in the top-level directory.) -# -# EDK II -# ------ -# W: http://www.tianocore.org/edk2/ -# L: https://edk2.groups.io/g/devel/ -# T: git - https://github.com/tianocore/edk2.git -# T: git (mirror) - https://bitbucket.org/tianocore/edk2.git -# -# All patches CC:d here -# L: devel@edk2.groups.io -# F: * -# F: */ -# -# Tianocore Stewards -# ------------------ -# F: * -# M: Andrew Fish [ajfish] -# M: Leif Lindholm [leiflindholm] -# M: Michael D Kinney [mdkinney] -# -# Responsible Disclosure, Reporting Security Issues -# ------------------------------------------------- -# W: https://github.com/tianocore/tianocore.github.io/wiki/Security -# -# EDK II Releases: -# ---------------- -# W: https://github.com/tianocore/tianocore.github.io/wiki/EDK-II-Release-Planning -# M: Liming Gao [lgao4] -# -# UEFI Shell Binaries (ShellBinPkg.zip) from EDK II Releases: -# ----------------------------------------------------------- -# W: https://github.com/tianocore/edk2/releases/ -# M: Ray Ni [niruiyu] (Ia32/X64) -# M: Zhichao Gao [ZhichaoGao] (Ia32/X64) -# M: Leif Lindholm [leiflindholm] (ARM/AArch64) -# M: Ard Biesheuvel [ardbiesheuvel] (ARM/AArch64) -# -# EDK II Architectures: -# --------------------- -# ARM, AARCH64 -# F: */AArch64/ -# F: */Arm/ -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# -# RISCV64 -# F: */RiscV64/ -# M: Sunil V L [vlsunil] -# R: Daniel Schaefer [JohnAZoidberg] -# -# EDK II Continuous Integration: -# ------------------------------ -# .azurepipelines/ -# F: .azurepipelines/ -# M: Sean Brogan [spbrogan] -# M: Bret Barkelew [corthon] -# R: Michael D Kinney [mdkinney] -# R: Liming Gao [lgao4] -/.azurepipelines/** @mdkinney @lgao4 - -# .github/ -# F: .github/ -# M: Michael D Kinney [mdkinney] -# M: Michael Kubacki [makubacki] -# R: Sean Brogan [spbrogan] -# R: Liming Gao [lgao4] -/.github/** @spbrogan @lgao4 - -# .mergify/ -# F: .mergify/ -# M: Michael D Kinney [mdkinney] -# M: Liming Gao [lgao4] -# R: Sean Brogan [spbrogan] -# R: Bret Barkelew [corthon] -/.mergify/** @spbrogan @corthon - -# .pytool/ -# F: .pytool/ -# M: Sean Brogan [spbrogan] -# M: Bret Barkelew [corthon] -# R: Michael D Kinney [mdkinney] -# R: Liming Gao [lgao4] -/.pytool/** @mdkinney @lgao4 - -# EDK II Packages: -# ---------------- -# ArmPkg -# F: ArmPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# R: Sami Mujawar [samimujawar] -/ArmPkg/** @samimujawar - -# ArmPlatformPkg -# F: ArmPlatformPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmPlatformPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] - -# ArmVirtPkg -# F: ArmVirtPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ArmVirtPkg -# M: Ard Biesheuvel [ardbiesheuvel] -# R: Leif Lindholm [leiflindholm] -# R: Sami Mujawar [samimujawar] -# R: Gerd Hoffmann [kraxel] -/ArmVirtPkg/** @leiflindholm @samimujawar @kraxel - -# ArmVirtPkg: modules used on Xen -# F: ArmVirtPkg/ArmVirtXen.* -# F: ArmVirtPkg/Library/XenArmGenericTimerVirtCounterLib/ -# F: ArmVirtPkg/Library/XenVirtMemInfoLib/ -# F: ArmVirtPkg/PrePi/ -# F: ArmVirtPkg/XenAcpiPlatformDxe/ -# F: ArmVirtPkg/XenPlatformHasAcpiDtDxe/ -# F: ArmVirtPkg/XenioFdtDxe/ -# R: Julien Grall [jgrall] -/ArmVirtPkg/ArmVirtXen.* @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/Library/XenArmGenericTimerVirtCounterLib/** @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/Library/XenVirtMemInfoLib/** @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/PrePi/** @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/XenAcpiPlatformDxe/** @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/XenPlatformHasAcpiDtDxe/** @leiflindholm @samimujawar @kraxel @jgrall -/ArmVirtPkg/XenioFdtDxe/** @leiflindholm @samimujawar @kraxel @jgrall - -# BaseTools -# F: BaseTools/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/BaseTools -# M: Bob Feng [BobCF] -# M: Liming Gao [lgao4] -# R: Yuwei Chen [YuweiChen1110] -/BaseTools/** @YuweiChen1110 -/BaseTools/**/RiscV64/** @YuweiChen1110 @JohnAZoidberg - -# CryptoPkg -# F: CryptoPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/CryptoPkg -# M: Jiewen Yao [jyao1] -# M: Jian J Wang [jwang36] -# R: Xiaoyu Lu [xiaoyuxlu] -# R: Guomin Jiang [guominjia] -/CryptoPkg/** @xiaoyuxlu @guominjia - -# DynamicTablesPkg -# F: DynamicTablesPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/DynamicTablesPkg -# M: Sami Mujawar [samimujawar] -# M: Alexei Fedorov [AlexeiFedorov] - -# EmbeddedPkg -# F: EmbeddedPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/EmbeddedPkg -# M: Leif Lindholm [leiflindholm] -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Abner Chang [changab] -# R: Daniel Schaefer [JohnAZoidberg] -/EmbeddedPkg/** @JohnAZoidberg - -# EmulatorPkg -# F: EmulatorPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/EmulatorPkg -# M: Andrew Fish [ajfish] -# M: Ray Ni [niruiyu] -# S: Maintained - -# EmulatorPkg: Redfish-related modules -# F: EmulatorPkg/*Redfish* -# M: Abner Chang [changab] -# R: Nickle Wang [nicklela] -/EmulatorPkg/**/Redfish*/** @nicklela - -# FatPkg -# F: FatPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/Edk2-fat-driver -# M: Ray Ni [niruiyu] -# T: svn - https://svn.code.sf.net/p/edk2-fatdriver2/code/trunk/EnhancedFat -# T: git - https://github.com/tianocore/edk2-FatPkg.git - -# FmpDevicePkg -# F: FmpDevicePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/FmpDevicePkg -# M: Liming Gao [lgao4] -# M: Michael D Kinney [mdkinney] -# R: Guomin Jiang [guominjia] -# R: Wei6 Xu [xuweiintel] -/FmpDevicePkg/** @guominjia @xuweiintel - -# IntelFsp2Pkg -# F: IntelFsp2Pkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/IntelFsp2Pkg -# M: Chasel Chiu [ChaselChiu] -# M: Nate DeSimone [nate-desimone] -# R: Star Zeng [lzeng14] -/IntelFsp2Pkg/** @lzeng14 - -# IntelFsp2WrapperPkg -# F: IntelFsp2WrapperPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/IntelFsp2WrapperPkg -# M: Chasel Chiu [ChaselChiu] -# M: Nate DeSimone [nate-desimone] -# R: Star Zeng [lzeng14] -/IntelFsp2WrapperPkg/** @lzeng14 - -# MdeModulePkg -# F: MdeModulePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/MdeModulePkg -# M: Jian J Wang [jwang36] -# M: Liming Gao [lgao4] - -# MdeModulePkg: ACPI modules -# F: MdeModulePkg/Include/*Acpi*.h -# F: MdeModulePkg/Universal/Acpi/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] -/MdeModulePkg/Include/*/*Acpi*.h @LiuZhiguang001 @dandanbi @lgao4 -/MdeModulePkg/Universal/Acpi/** @LiuZhiguang001 @dandanbi @lgao4 - -# MdeModulePkg: ACPI modules related to S3 -# F: MdeModulePkg/*LockBox*/ -# F: MdeModulePkg/Include/*BootScript*.h -# F: MdeModulePkg/Include/*LockBox*.h -# F: MdeModulePkg/Include/*S3*.h -# F: MdeModulePkg/Library/*S3*/ -# R: Hao A Wu [hwu25] -# R: Eric Dong [ydong10] -/MdeModulePkg/**/*LockBox*/** @hwu25 @ydong10 -/MdeModulePkg/Include/*/*BootScript*.h @hwu25 @ydong10 -/MdeModulePkg/Include/*/*LockBox*.h @hwu25 @ydong10 -/MdeModulePkg/Include/*/*S3*.h @hwu25 @ydong10 -/MdeModulePkg/Library/*S3*/** @hwu25 @ydong10 - -# MdeModulePkg: BDS modules -# F: MdeModulePkg/*BootManager*/ -# F: MdeModulePkg/Include/Library/UefiBootManagerLib.h -# F: MdeModulePkg/Universal/BdsDxe/ -# F: MdeModulePkg/Universal/DevicePathDxe/ -# F: MdeModulePkg/Universal/DriverHealthManagerDxe/ -# F: MdeModulePkg/Universal/LoadFileOnFv2/ -# F: MdeModulePkg/Universal/SecurityStubDxe/Defer3rdPartyImageLoad.* -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] -/MdeModulePkg/**/*BootManager*/** @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Library/UefiBootManagerLib.h @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/BdsDxe/** @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/DevicePathDxe/** @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/DriverHealthManagerDxe/** @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/LoadFileOnFv2/** @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/SecurityStubDxe/Defer3rdPartyImageLoad.* @ZhichaoGao @niruiyu - -# MdeModulePkg: Console and Graphics modules -# F: MdeModulePkg/*Logo*/ -# F: MdeModulePkg/Include/*Logo*.h -# F: MdeModulePkg/Include/Guid/ConnectConInEvent.h -# F: MdeModulePkg/Include/Guid/Console*.h -# F: MdeModulePkg/Include/Guid/StandardErrorDevice.h -# F: MdeModulePkg/Include/Guid/TtyTerm.h -# F: MdeModulePkg/Include/Library/BmpSupportLib.h -# F: MdeModulePkg/Include/Library/FrameBufferBltLib.h -# F: MdeModulePkg/Library/BaseBmpSupportLib/ -# F: MdeModulePkg/Library/FrameBufferBltLib/ -# F: MdeModulePkg/Universal/Console/ -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] -/MdeModulePkg/**/*Logo*/** @ZhichaoGao @niruiyu -/MdeModulePkg/Include/*/*Logo*.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Guid/ConnectConInEvent.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Guid/Console*.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Guid/StandardErrorDevice.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Guid/TtyTerm.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Library/BmpSupportLib.h @ZhichaoGao @niruiyu -/MdeModulePkg/Include/Library/FrameBufferBltLib.h @ZhichaoGao @niruiyu -/MdeModulePkg/Library/BaseBmpSupportLib/** @ZhichaoGao @niruiyu -/MdeModulePkg/Library/FrameBufferBltLib/** @ZhichaoGao @niruiyu -/MdeModulePkg/Universal/Console/** @ZhichaoGao @niruiyu - -# MdeModulePkg: Core services (PEI, DXE and Runtime) modules -# F: MdeModulePkg/*Mem*/ -# F: MdeModulePkg/*SectionExtract*/ -# F: MdeModulePkg/*StatusCode*/ -# F: MdeModulePkg/Application/DumpDynPcd/ -# F: MdeModulePkg/Core/Dxe/ -# F: MdeModulePkg/Core/DxeIplPeim/ -# F: MdeModulePkg/Core/RuntimeDxe/ -# F: MdeModulePkg/Include/*Mem*.h -# F: MdeModulePkg/Include/*Pcd*.h -# F: MdeModulePkg/Include/*Perf*.h -# F: MdeModulePkg/Include/*StatusCode*.h -# F: MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h -# F: MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h -# F: MdeModulePkg/Include/Guid/IdleLoopEvent.h -# F: MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h -# F: MdeModulePkg/Include/Guid/LzmaDecompress.h -# F: MdeModulePkg/Include/Library/SecurityManagementLib.h -# F: MdeModulePkg/Library/*Decompress*/ -# F: MdeModulePkg/Library/*Perf*/ -# F: MdeModulePkg/Library/DxeSecurityManagementLib/ -# F: MdeModulePkg/Universal/PCD/ -# F: MdeModulePkg/Universal/PlatformDriOverrideDxe/ -# F: MdeModulePkg/Universal/SecurityStubDxe/SecurityStub.c -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] -/MdeModulePkg/**/*Mem*/** @dandanbi @lgao4 -/MdeModulePkg/**/*SectionExtract*/** @dandanbi @lgao4 -/MdeModulePkg/**/*StatusCode*/** @dandanbi @lgao4 -/MdeModulePkg/Application/DumpDynPcd/** @dandanbi @lgao4 -/MdeModulePkg/Core/Dxe/** @dandanbi @lgao4 -/MdeModulePkg/Core/DxeIplPeim/** @dandanbi @lgao4 -/MdeModulePkg/Core/DxeIplPeim/**/RiscV64/** @dandanbi @lgao4 @JohnAZoidberg -/MdeModulePkg/Core/RuntimeDxe/** @dandanbi @lgao4 -/MdeModulePkg/Include/*/*Mem*.h @dandanbi @lgao4 -/MdeModulePkg/Include/*/*Pcd*.h @dandanbi @lgao4 -/MdeModulePkg/Include/*/*Perf*.h @dandanbi @lgao4 -/MdeModulePkg/Include/*/*StatusCode*.h @dandanbi @lgao4 -/MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h @dandanbi @lgao4 -/MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h @dandanbi @lgao4 -/MdeModulePkg/Include/Guid/IdleLoopEvent.h @dandanbi @lgao4 -/MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h @dandanbi @lgao4 -/MdeModulePkg/Include/Guid/LzmaDecompress.h @dandanbi @lgao4 -/MdeModulePkg/Include/Library/SecurityManagementLib.h @dandanbi @lgao4 -/MdeModulePkg/Library/*Decompress*/** @dandanbi @lgao4 -/MdeModulePkg/Library/*Perf*/** @dandanbi @lgao4 -/MdeModulePkg/Library/DxeSecurityManagementLib/** @dandanbi @lgao4 -/MdeModulePkg/Universal/PCD/** @dandanbi @lgao4 -/MdeModulePkg/Universal/PlatformDriOverrideDxe/** @dandanbi @lgao4 -/MdeModulePkg/Universal/SecurityStubDxe/SecurityStub.c @dandanbi @lgao4 - -# MdeModulePkg: Device and Peripheral modules -# F: MdeModulePkg/*PciHostBridge*/ -# F: MdeModulePkg/Bus/ -# F: MdeModulePkg/Include/*Ata*.h -# F: MdeModulePkg/Include/*IoMmu*.h -# F: MdeModulePkg/Include/*NonDiscoverableDevice*.h -# F: MdeModulePkg/Include/*NvmExpress*.h -# F: MdeModulePkg/Include/*SdMmc*.h -# F: MdeModulePkg/Include/*Ufs*.h -# F: MdeModulePkg/Include/*Usb*.h -# F: MdeModulePkg/Include/Guid/RecoveryDevice.h -# F: MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h -# F: MdeModulePkg/Include/Library/PciHostBridgeLib.h -# F: MdeModulePkg/Include/Ppi/StorageSecurityCommand.h -# F: MdeModulePkg/Include/Protocol/Ps2Policy.h -# F: MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/ -# F: MdeModulePkg/Universal/PcatSingleSegmentPciCfg2Pei/ -# R: Hao A Wu [hwu25] -# R: Ray Ni [niruiyu] -/MdeModulePkg/**/*PciHostBridge*/** @hwu25 @niruiyu -/MdeModulePkg/Bus/** @hwu25 @niruiyu -/MdeModulePkg/Include/*/*Ata*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*IoMmu*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*NonDiscoverableDevice*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*NvmExpress*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*SdMmc*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*Ufs*.h @hwu25 @niruiyu -/MdeModulePkg/Include/*/*Usb*.h @hwu25 @niruiyu -/MdeModulePkg/Include/Guid/RecoveryDevice.h @hwu25 @niruiyu -/MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h @hwu25 @niruiyu @ydong10 -/MdeModulePkg/Include/Library/PciHostBridgeLib.h @hwu25 @niruiyu -/MdeModulePkg/Include/Ppi/StorageSecurityCommand.h @hwu25 @niruiyu -/MdeModulePkg/Include/Protocol/Ps2Policy.h @hwu25 @niruiyu -/MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/** @hwu25 @niruiyu -/MdeModulePkg/Universal/PcatSingleSegmentPciCfg2Pei/** @hwu25 @niruiyu - -# MdeModulePkg: Disk modules -# F: MdeModulePkg/Universal/Disk/ -# R: Hao A Wu [hwu25] -# R: Ray Ni [niruiyu] -# R: Zhichao Gao [ZhichaoGao] -/MdeModulePkg/Universal/Disk/** @hwu25 @niruiyu @ZhichaoGao - -# MdeModulePkg: Firmware Update modules -# F: MdeModulePkg/*Capsule*/ -# F: MdeModulePkg/Include/*Capsule*.h -# F: MdeModulePkg/Include/Library/DisplayUpdateProgressLib.h -# F: MdeModulePkg/Include/Library/FmpAuthenticationLib.h -# F: MdeModulePkg/Include/Protocol/EsrtManagement.h -# F: MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h -# F: MdeModulePkg/Library/DisplayUpdateProgressLib*/ -# F: MdeModulePkg/Library/FmpAuthenticationLibNull/ -# F: MdeModulePkg/Universal/Esrt*/ -# R: Liming Gao [lgao4] -# R: Guomin Jiang [guominjia] -/MdeModulePkg/**/*Capsule*/** @lgao4 @guominjia -/MdeModulePkg/Include/*/*Capsule*.h @lgao4 @guominjia -/MdeModulePkg/Include/Library/DisplayUpdateProgressLib.h @lgao4 @guominjia -/MdeModulePkg/Include/Library/FmpAuthenticationLib.h @lgao4 @guominjia -/MdeModulePkg/Include/Protocol/EsrtManagement.h @lgao4 @guominjia -/MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h @lgao4 @guominjia -/MdeModulePkg/Library/DisplayUpdateProgressLib*/** @lgao4 @guominjia -/MdeModulePkg/Library/FmpAuthenticationLibNull/** @lgao4 @guominjia -/MdeModulePkg/Universal/Esrt*/** @lgao4 @guominjia - -# MdeModulePkg: HII and UI modules -# F: MdeModulePkg/*FileExplorer*/ -# F: MdeModulePkg/*Hii*/ -# F: MdeModulePkg/*Ui*/ -# F: MdeModulePkg/Application/BootManagerMenuApp/ -# F: MdeModulePkg/Include/*FileExplorer*.h -# F: MdeModulePkg/Include/*FormBrowser*.h -# F: MdeModulePkg/Include/*Hii*.h -# F: MdeModulePkg/Include/Library/CustomizedDisplayLib.h -# F: MdeModulePkg/Include/Protocol/DisplayProtocol.h -# F: MdeModulePkg/Library/CustomizedDisplayLib/ -# F: MdeModulePkg/Universal/DisplayEngineDxe/ -# F: MdeModulePkg/Universal/DriverSampleDxe/ -# F: MdeModulePkg/Universal/SetupBrowserDxe/ -# R: Dandan Bi [dandanbi] -# R: Eric Dong [ydong10] -/MdeModulePkg/**/*FileExplorer*/** @dandanbi @ydong10 -/MdeModulePkg/**/*Hii*/** @dandanbi @ydong10 -/MdeModulePkg/**/*Ui*/** @dandanbi @ydong10 -/MdeModulePkg/Application/BootManagerMenuApp/** @ZhichaoGao @niruiyu @dandanbi @ydong10 -/MdeModulePkg/Include/*/*FileExplorer*.h @dandanbi @ydong10 -/MdeModulePkg/Include/*/*FormBrowser*.h @dandanbi @ydong10 -/MdeModulePkg/Include/*/*Hii*.h @dandanbi @ydong10 -/MdeModulePkg/Include/Library/CustomizedDisplayLib.h @dandanbi @ydong10 -/MdeModulePkg/Include/Protocol/DisplayProtocol.h @dandanbi @ydong10 -/MdeModulePkg/Library/CustomizedDisplayLib/** @dandanbi @ydong10 -/MdeModulePkg/Universal/DisplayEngineDxe/** @dandanbi @ydong10 -/MdeModulePkg/Universal/DriverSampleDxe/** @dandanbi @ydong10 -/MdeModulePkg/Universal/SetupBrowserDxe/** @dandanbi @ydong10 - -# MdeModulePkg: Management Mode (MM, SMM) modules -# F: MdeModulePkg/*Smi*/ -# F: MdeModulePkg/*Smm*/ -# F: MdeModulePkg/Include/*Smi*.h -# F: MdeModulePkg/Include/*Smm*.h -# R: Eric Dong [ydong10] -# R: Ray Ni [niruiyu] -/MdeModulePkg/**/*Smi*/** @ydong10 @niruiyu -/MdeModulePkg/**/*Smm*/** @ydong10 @niruiyu -/MdeModulePkg/Include/*/*Smi*.h @ydong10 @niruiyu -/MdeModulePkg/Include/*/*Smm*.h @ydong10 @niruiyu - -# MdeModulePkg: Reset modules -# F: MdeModulePkg/*Reset*/ -# F: MdeModulePkg/Include/*Reset*.h -# R: Zhichao Gao [ZhichaoGao] -# R: Ray Ni [niruiyu] -/MdeModulePkg/**/*Reset*/ @ZhichaoGao @niruiyu -/MdeModulePkg/Include/*/*Reset*.h @ZhichaoGao @niruiyu - -# MdeModulePkg: Pei Core -# F: MdeModulePkg/Core/Pei/ -# R: Dandan Bi [dandanbi] -# R: Liming Gao [lgao4] -# R: Debkumar De -# R: Catharine West [catharine-intl] -/MdeModulePkg/Core/Pei/** @dandanbi @lgao4 @dde01 @catharine-intl -/MdeModulePkg/Core/Pei/*Reset*/** @dandanbi @lgao4 @dde01 @catharine-intl @ZhichaoGao @niruiyu - -# MdeModulePkg: Serial modules -# F: MdeModulePkg/*Serial*/ -# F: MdeModulePkg/Include/*SerialPort*.h -# R: Ray Ni [niruiyu] -# R: Zhichao Gao [ZhichaoGao] -/MdeModulePkg/**/*Serial*/** @niruiyu @ZhichaoGao -/MdeModulePkg/Include/*/*SerialPort*.h @niruiyu @ZhichaoGao - -# MdeModulePkg: SMBIOS modules -# F: MdeModulePkg/Universal/Smbios*/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Dandan Bi [dandanbi] -# R: Star Zeng [lzeng14] -# R: Zhichao Gao [ZhichaoGao] -/MdeModulePkg/Universal/Smbios*/** @LiuZhiguang001 @dandanbi @lzeng14 @ZhichaoGao - -# MdeModulePkg: UEFI Variable modules -# F: MdeModulePkg/*Var*/ -# F: MdeModulePkg/Include/*/*FaultTolerantWrite*.h -# F: MdeModulePkg/Include/*/*Var*.h -# F: MdeModulePkg/Include/Guid/SystemNvDataGuid.h -# F: MdeModulePkg/Include/Protocol/SwapAddressRange.h -# F: MdeModulePkg/Universal/FaultTolerantWrite*/ -# R: Hao A Wu [hwu25] -# R: Liming Gao [lgao4] -/MdeModulePkg/**/*Var*/** @hwu25 @lgao4 -/MdeModulePkg/Include/*/*FaultTolerantWrite*.h @hwu25 @lgao4 -/MdeModulePkg/Include/*/*Var*.h @hwu25 @lgao4 -/MdeModulePkg/Include/Guid/SystemNvDataGuid.h @hwu25 @lgao4 -/MdeModulePkg/Include/Protocol/SwapAddressRange.h @hwu25 @lgao4 -/MdeModulePkg/Universal/FaultTolerantWrite*/** @hwu25 @lgao4 - -# MdeModulePkg: Universal Payload definitions -# F: MdeModulePkg/Include/UniversalPayload/ -# R: Zhiguang Liu [LiuZhiguang001] -# R: Ray Ni [niruiyu] -# R: Gua Guo [gguo11837463] -/MdeModulePkg/Include/UniversalPayload/** @LiuZhiguang001 @niruiyu @gguo11837463 -/MdeModulePkg/Include/UniversalPayload/*SerialPort*.h @LiuZhiguang001 @niruiyu @gguo11837463 @ZhichaoGao -/MdeModulePkg/Include/UniversalPayload/*Acpi*.h @LiuZhiguang001 @niruiyu @gguo11837463 @dandanbi @lgao4 - - - -### -### Extra rules -### - -/MdeModulePkg/**/*BootManagerUi*/** @dandanbi @ydong10 @ZhichaoGao @niruiyu -/MdeModulePkg/**/VarCheckHiiLib/** @hwu25 @lgao4 @dandanbi @ydong10 -/MdeModulePkg/Bus/**/*Serial*/** @niruiyu @ZhichaoGao @hwu25 -/MdeModulePkg/**/*Smm*LockBox*/** @hwu25 @ydong10 @niruiyu -/MdeModulePkg/**/*StatusCode*/Smm/** @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/**/*Smm*StatusCode*/** @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/**/*Smm*Perf*/** @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/**/*Perf*Smm*/** @LiuZhiguang001 @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/**/Acpi/*Smm*/** @LiuZhiguang001 @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/**/*Smm*Mem*/** @dandanbi @lgao4 @niruiyu @ydong10 - -/MdeModulePkg/Include/*/*Smm*LockBox*.h @hwu25 @ydong10 @niruiyu -/MdeModulePkg/Include/*/*Smm*Mem*.h @dandanbi @lgao4 @niruiyu @ydong10 -/MdeModulePkg/Include/*/*Acpi*S3*.h @LiuZhiguang001 @dandanbi @hwu25 @lgao4 @ydong10 -/MdeModulePkg/Include/*/*S3*Smm*.h @hwu25 @niruiyu @ydong10 -/MdeModulePkg/Include/*/*Smm*FaultTolerantWrite*.h @hwu25 @lgao4 @niruiyu @ydong10 -/MdeModulePkg/Include/*/*Smm*Var*.h @hwu25 @lgao4 @niruiyu @ydong10 -/MdeModulePkg/Include/*/*StatusCode*Var*.h @dandanbi @hwu25 @lgao4 -/MdeModulePkg/Include/*/*BootScript*Var*.h @hwu25 @lgao4 @ydong10 - - -# MdePkg -# F: MdePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/MdePkg -# M: Michael D Kinney [mdkinney] -# M: Liming Gao [lgao4] -# R: Zhiguang Liu [LiuZhiguang001] -/MdePkg/** @LiuZhiguang001 -/MdePkg/**/RiscV64/** @LiuZhiguang001 @JohnAZoidberg - -# NetworkPkg -# F: NetworkPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg -# M: Maciej Rabeda [mrabeda] -# R: Jiaxin Wu [jiaxinwu] -# R: Siyuan Fu [sfu5] -/NetworkPkg/** @jiaxinwu @sfu5 - -# OvmfPkg -# F: OvmfPkg/ -# W: http://www.tianocore.org/ovmf/ -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Jiewen Yao [jyao1] -# R: Jordan Justen [jljusten] -# R: Gerd Hoffmann [kraxel] -# S: Maintained -/OvmfPkg/** @jljusten @kraxel - -# OvmfPkg: bhyve-related modules -# F: OvmfPkg/Bhyve/ -# F: OvmfPkg/Include/IndustryStandard/Bhyve.h -# F: OvmfPkg/Include/Library/BhyveFwCtlLib.h -# F: OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.c -# F: OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.inf -# F: OvmfPkg/Library/BhyveFwCtlLib/ -# F: OvmfPkg/Library/PciHostBridgeLibScan/ -# F: OvmfPkg/Library/PlatformBootManagerLibBhyve/ -# F: OvmfPkg/Library/ResetSystemLib/BaseResetShutdownBhyve.c -# F: OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf -# R: Rebecca Cran [bcran] -# R: Peter Grehan [grehan-freebsd] -/OvmfPkg/Bhyve/** @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Include/IndustryStandard/Bhyve.h @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Include/Library/BhyveFwCtlLib.h @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.c @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLibBhyve.inf @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/BhyveFwCtlLib/** @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/PlatformBootManagerLibBhyve/** @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/ResetSystemLib/BaseResetShutdownBhyve.c @jljusten @kraxel @bcran @grehan-freebsd -/OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf @jljusten @kraxel @bcran @grehan-freebsd - -# OvmfPkg: cloudhv-related modules -# F: OvmfPkg/CloudHv/ -# F: OvmfPkg/Include/IndustryStandard/CloudHv.h -# R: Sebastien Boeuf [sboeuf] -/OvmfPkg/CloudHv/** @jljusten @kraxel @sboeuf -/OvmfPkg/Include/IndustryStandard/CloudHv.h @jljusten @kraxel @sboeuf - -# OvmfPkg: microvm-related modules -# F: OvmfPkg/Microvm/ -# F: OvmfPkg/Include/IndustryStandard/Microvm.h -# F: OvmfPkg/Library/ResetSystemLib/*Microvm.* -# R: Gerd Hoffmann [kraxel] -/OvmfPkg/Microvm/** @jljusten @kraxel -/OvmfPkg/Include/IndustryStandard/Microvm.h @jljusten @kraxel -/OvmfPkg/Library/ResetSystemLib/*Microvm.* @jljusten @kraxel - -# OvmfPkg: CSM modules -# F: OvmfPkg/Csm/ -# R: David Woodhouse [dwmw2] -/OvmfPkg/Csm/** @jljusten @kraxel @dwmw2 - -# OvmfPkg: Confidential Computing -# F: OvmfPkg/AmdSev/ -# F: OvmfPkg/AmdSevDxe/ -# F: OvmfPkg/Include/Guid/ConfidentialComputingSecret.h -# F: OvmfPkg/Include/Library/MemEncryptSevLib.h -# F: OvmfPkg/IoMmuDxe/AmdSevIoMmu.* -# F: OvmfPkg/Library/BaseMemEncryptSevLib/ -# F: OvmfPkg/Library/PlatformBootManagerLibGrub/ -# F: OvmfPkg/Library/VmgExitLib/ -# F: OvmfPkg/PlatformPei/AmdSev.c -# F: OvmfPkg/ResetVector/ -# F: OvmfPkg/Sec/ -# R: Brijesh Singh [codomania] -# R: Erdem Aktas [ruleof2] -# R: James Bottomley [jejb] -# R: Jiewen Yao [jyao1] -# R: Min Xu [mxu9] -# R: Tom Lendacky [tlendacky] -/OvmfPkg/AmdSev/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/AmdSevDxe/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Include/Guid/ConfidentialComputingSecret.h @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Include/Library/MemEncryptSevLib.h @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/IoMmuDxe/AmdSevIoMmu.* @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Library/BaseMemEncryptSevLib/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Library/PlatformBootManagerLibGrub/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Library/VmgExitLib/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/PlatformPei/AmdSev.c @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/ResetVector/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky -/OvmfPkg/Sec/** @jljusten @kraxel @codomania @ruleof2 @jejb @jyao1 @mxu9 @tlendacky - -# OvmfPkg: FDT related modules -# F: OvmfPkg/Fdt -# R: Leif Lindholm [leiflindholm] -# R: Gerd Hoffmann [kraxel] -# R: Abner Chang [changab] -/OvmfPkg/Fdt/** @jljusten @kraxel @leiflindholm @changab - -# OvmfPkg: LsiScsi driver -# F: OvmfPkg/LsiScsiDxe/ -# R: Gary Lin [lcp] -/OvmfPkg/LsiScsiDxe/** @jljusten @kraxel @lcp - -# OvmfPkg: TCG- and TPM2-related modules -# F: OvmfPkg/Include/IndustryStandard/QemuTpm.h -# F: OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c -# F: OvmfPkg/Library/Tcg2PhysicalPresenceLib*/ -# F: OvmfPkg/PlatformPei/ClearCache.c -# F: OvmfPkg/Tcg/ -# R: Marc-André Lureau [elmarco] -# R: Stefan Berger [stefanberger] -/OvmfPkg/Include/IndustryStandard/QemuTpm.h @jljusten @kraxel @elmarco @stefanberger -/OvmfPkg/Library/Tcg2PhysicalPresenceLib*/** @jljusten @kraxel @elmarco @stefanberger -/OvmfPkg/PlatformPei/ClearCache.c @jljusten @kraxel @elmarco @stefanberger -/OvmfPkg/Tcg/** @jljusten @kraxel @elmarco @stefanberger - -# OvmfPkg: Xen-related modules -# F: OvmfPkg/Include/Guid/XenBusRootDevice.h -# F: OvmfPkg/Include/Guid/XenInfo.h -# F: OvmfPkg/Include/IndustryStandard/Xen/ -# F: OvmfPkg/Include/Library/XenHypercallLib.h -# F: OvmfPkg/Include/Library/XenIoMmioLib.h -# F: OvmfPkg/Include/Library/XenPlatformLib.h -# F: OvmfPkg/Include/Protocol/XenBus.h -# F: OvmfPkg/Include/Protocol/XenIo.h -# F: OvmfPkg/Library/PciHostBridgeLibScan/ -# F: OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c -# F: OvmfPkg/Library/XenConsoleSerialPortLib/ -# F: OvmfPkg/Library/XenHypercallLib/ -# F: OvmfPkg/Library/XenIoMmioLib/ -# F: OvmfPkg/Library/XenPlatformLib/ -# F: OvmfPkg/Library/XenRealTimeClockLib/ -# F: OvmfPkg/OvmfXen.* -# F: OvmfPkg/OvmfXenElfHeaderGenerator.c -# F: OvmfPkg/SmbiosPlatformDxe/*Xen* -# F: OvmfPkg/XenAcpiPlatformDxe/ -# F: OvmfPkg/XenBusDxe/ -# F: OvmfPkg/XenIoPciDxe/ -# F: OvmfPkg/XenIoPvhDxe/ -# F: OvmfPkg/XenPlatformPei/ -# F: OvmfPkg/XenPvBlkDxe/ -# F: OvmfPkg/XenResetVector/ -# R: Anthony Perard [sheep] -# R: Julien Grall [jgrall] -/OvmfPkg/Include/Guid/XenBusRootDevice.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Guid/XenInfo.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/IndustryStandard/Xen/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Library/XenHypercallLib.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Library/XenIoMmioLib.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Library/XenPlatformLib.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Protocol/XenBus.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Include/Protocol/XenIo.h @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Library/XenConsoleSerialPortLib/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Library/XenHypercallLib/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Library/XenIoMmioLib/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Library/XenPlatformLib/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/Library/XenRealTimeClockLib/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/OvmfXen.* @jljusten @kraxel @sheep @jgrall -/OvmfPkg/OvmfXenElfHeaderGenerator.c @jljusten @kraxel @sheep @jgrall -/OvmfPkg/SmbiosPlatformDxe/*Xen* @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenAcpiPlatformDxe/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenBusDxe/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenIoPciDxe/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenIoPvhDxe/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenPlatformPei/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenPvBlkDxe/** @jljusten @kraxel @sheep @jgrall -/OvmfPkg/XenResetVector/** @jljusten @kraxel @sheep @jgrall -# -# ATTENTION: The following component does not exist anymore -# -#/OvmfPkg/XenTimerDxe/** @jljusten @kraxel @sheep julien@xen.org - -# Files common to Bhyve and Xen -/OvmfPkg/Library/PciHostBridgeLibScan/** @jljusten @kraxel @bcran @grehan-freebsd @sheep @jgrall - -# Files common to TCG and XEN -/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c @jljusten @kraxel @elmarco @stefanberger @sheep @jgrall - -# PcAtChipsetPkg -# F: PcAtChipsetPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/PcAtChipsetPkg -# M: Ray Ni [niruiyu] - -# PrmPkg -# F: PrmPkg/ -# M: Michael Kubacki [makubacki] -# M: Nate DeSimone [nate-desimone] - -# PrmPkg: ACPI related modules -# R: Ankit Sinha [ankit13s] - -# RedfishPkg: Redfish related modules -# F: RedfishPkg/ -# M: Abner Chang [changab] -# R: Nickle Wang [nicklela] -/RedfishPkg/** @nicklela - -# SecurityPkg -# F: SecurityPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SecurityPkg -# M: Jiewen Yao [jyao1] -# M: Jian J Wang [jwang36] - -# SecurityPkg: Secure boot related modules -# F: SecurityPkg/Library/DxeImageVerificationLib/ -# F: SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/ -# F: SecurityPkg/Library/AuthVariableLib/ -# R: Min Xu [mxu9] -/SecurityPkg/Library/DxeImageVerificationLib/** @mxu9 -/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/** @mxu9 -/SecurityPkg/Library/AuthVariableLib/** @mxu9 - -# SecurityPkg: Tcg related modules -# F: SecurityPkg/Tcg/ -# R: Qi Zhang [qizhangz] -# R: Rahul Kumar [rahul1-kumar] -/SecurityPkg/Tcg/** @qizhangz @rahul1-kumar - -# ShellPkg -# F: ShellPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/ShellPkg -# M: Ray Ni [niruiyu] -# M: Zhichao Gao [ZhichaoGao] - -# SignedCapsulePkg -# F: SignedCapsulePkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SignedCapsulePkg -# M: Jian J Wang [jwang36] - -# SourceLevelDebugPkg -# F: SourceLevelDebugPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/SourceLevelDebugPkg -# M: Hao A Wu [hwu25] - -# StandaloneMmPkg -# F: StandaloneMmPkg/ -# M: Ard Biesheuvel [ardbiesheuvel] -# M: Sami Mujawar [samimujawar] -# M: Jiewen Yao [jyao1] -# R: Supreeth Venkatesh [supven01] -/StandaloneMmPkg/** @supven01 - -# UefiCpuPkg -# F: UefiCpuPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/UefiCpuPkg -# M: Eric Dong [ydong10] -# M: Ray Ni [niruiyu] -# R: Rahul Kumar [rahul1-kumar] -/UefiCpuPkg/** @rahul1-kumar - -# UefiCpuPkg: Sec related modules -# F: UefiCpuPkg/SecCore/ -# F: UefiCpuPkg/ResetVector/ -# R: Debkumar De [dde01] -# R: Catharine West [catharine-intl] -/UefiCpuPkg/SecCore/** @rahul1-kumar @dde01 @catharine-intl -/UefiCpuPkg/ResetVector/** @rahul1-kumar @dde01 @catharine-intl - -# UefiPayloadPkg -# F: UefiPayloadPkg/ -# W: https://github.com/tianocore/tianocore.github.io/wiki/UefiPayloadPkg -# M: Guo Dong [gdong1] -# M: Ray Ni [niruiyu] -# M: Sean Rhodes [Sean-StarLabs] -# M: James Lu [jameslu8] -# R: Gua Guo [gguo11837463] -# S: Maintained -/UefiPalyloadPkg/** @gguo11837463 - -# UnitTestFrameworkPkg -# F: UnitTestFrameworkPkg/ -# M: Michael D Kinney [mdkinney] -# M: Michael Kubacki [makubacki] -# R: Sean Brogan [spbrogan] -# R: Bret Barkelew [corthon] -# S: Maintained -/UnitTestFrameworkPkg/** @spbrogan @corthon - diff --git a/.github/workflows/AssignReviewers.yml b/.github/workflows/AssignReviewers.yml deleted file mode 100644 index d517fe0780..0000000000 --- a/.github/workflows/AssignReviewers.yml +++ /dev/null @@ -1,27 +0,0 @@ -## @file -# Assign reviewers from a REVIEWERS file using CODEOWNERS syntax -# -# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -name: Assign reviewers from a REVIEWERS file using CODEOWNERS syntax - -on: - pull_request_target: - types: [opened, synchronize, reopened, ready_for_review] - branches: - - 'master' - -jobs: - assign_reviewers: - if: github.event.pull_request.draft == false - runs-on: ubuntu-latest - permissions: - pull-requests: write - steps: - - name: Checkout Pull Request Target - uses: actions/checkout@v2 - - uses: mdkinney/github-action-assign-reviewers@main - with: - token: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/CheckCodeOwnerFiles.yml b/.github/workflows/CheckCodeOwnerFiles.yml deleted file mode 100644 index 38c2807640..0000000000 --- a/.github/workflows/CheckCodeOwnerFiles.yml +++ /dev/null @@ -1,39 +0,0 @@ -## @file -# Check CODEOWNERS coverage of all files in PR -# -# Only run this check if one or more files modified in the PR -# are not CODEOWNERS, REVIEWERS, or Maintainers.txt. -# -# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -name: Check CODEOWNERS coverage of all files in PR - -on: - pull_request: - types: [opened, synchronize, reopened, ready_for_review] - branches: - - 'master' - paths-ignore: - - 'CODEOWNERS' - - 'docs/CODEOWNERS' - - '.github/CODEOWNERS' - - 'REVIEWERS' - - 'docs/REVIEWERS' - - '.github/REVIEWERS' - - 'Maintainers.txt' - -jobs: - codeowners_files_validator: - if: github.event.pull_request.draft == false - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - - name: CODEOWNERS Validator - uses: mszostok/codeowners-validator@v0.7.4 - with: - checks: "files" - experimental_checks: "notowned" - github_access_token: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/CheckCodeOwnerMaintainers.yml b/.github/workflows/CheckCodeOwnerMaintainers.yml deleted file mode 100644 index 19c7c9d2d3..0000000000 --- a/.github/workflows/CheckCodeOwnerMaintainers.yml +++ /dev/null @@ -1,121 +0,0 @@ -## @file -# Check CODEOWNERS, REVIEWERS, and Maintainers.txt files. -# -# Only run this check if any of the files modified in the PR -# are CODEOWNERS, REVIEWERS, or Maintainers.txt. -# -# This workflow uses pull_request_target to support passing in -# github_access_token that is not available for pull_request. -# The checkout action checks out the head of the PR. In this -# specific workflow, this is safe because there are no dependencies -# on any files other that this .yml file and known external actions. -# -# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -name: Check CODEOWNERS, REVIEWERS, and Maintainers.txt files - -on: - pull_request_target: - types: [opened, synchronize, reopened, ready_for_review] - branches: - - 'master' - paths: - - 'CODEOWNERS' - - 'docs/CODEOWNERS' - - '.github/CODEOWNERS' - - 'REVIEWERS' - - 'docs/REVIEWERS' - - '.github/REVIEWERS' - - 'Maintainers.txt' - -jobs: - check_codeowners_maintainers: - if: github.event.pull_request.draft == false - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: Check CODEOWNERS, REVIEWERS, and Maintainers.txt files - uses: mdkinney/github-action-check-codeowners-maintainers@main - with: - token: ${{secrets.GITHUB_TOKEN}} - - codeowners_validator_user: - if: github.event.pull_request.draft == false && github.event.pull_request.base.user.type == 'User' - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: CODEOWNERS Validator - uses: mszostok/codeowners-validator@v0.7.4 - with: - checks: "files,duppatterns,syntax" - experimental_checks: "notowned,avoid-shadowing" - github_access_token: "${{ secrets.GITHUB_TOKEN }}" - - codeowners_validator_organization: - if: github.event.pull_request.draft == false && github.event.pull_request.base.user.type == 'Organization' - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: CODEOWNERS Validator - uses: mszostok/codeowners-validator@v0.7.4 - with: - checks: "files,owners,duppatterns,syntax" - experimental_checks: "notowned,avoid-shadowing" - github_access_token: "${{ secrets.CODEOWNERS_VALIDATOR_TOKEN }}" - - reviewers_validator_user: - if: github.event.pull_request.draft == false && github.event.pull_request.base.user.type == 'User' - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: Copy REVIEWERS to CODEOWNERS - run: | - [[ -e CODEOWNERS ]] && rm CODEOWNERS - [[ -e docs/CODEOWNERS ]] && rm docs/CODEOWNERS - [[ -e .github/CODEOWNERS ]] && rm .github/CODEOWNERS - [[ -e REVIEWERS ]] && cp REVIEWERS CODEOWNERS - [[ -e docs/REVIEWERS ]] && cp docs/REVIEWERS docs/CODEOWNERS - [[ -e .github/REVIEWERS ]] && cp .github/REVIEWERS .github/CODEOWNERS - - name: REVIEWERS Validator - uses: mszostok/codeowners-validator@v0.7.4 - with: - checks: "files,duppatterns,syntax" - experimental_checks: "avoid-shadowing" - github_access_token: "${{ secrets.GITHUB_TOKEN }}" - - reviewers_validator_organization: - if: github.event.pull_request.draft == false && github.event.pull_request.base.user.type == 'Organization' - runs-on: ubuntu-latest - steps: - - name: Checkout Pull Request - uses: actions/checkout@v2 - with: - ref: ${{ github.event.pull_request.head.sha }} - - name: Copy REVIEWERS to CODEOWNERS - run: | - [[ -e CODEOWNERS ]] && rm CODEOWNERS - [[ -e docs/CODEOWNERS ]] && rm docs/CODEOWNERS - [[ -e .github/CODEOWNERS ]] && rm .github/CODEOWNERS - [[ -e REVIEWERS ]] && cp REVIEWERS CODEOWNERS - [[ -e docs/REVIEWERS ]] && cp docs/REVIEWERS docs/CODEOWNERS - [[ -e .github/REVIEWERS ]] && cp .github/REVIEWERS .github/CODEOWNERS - - name: REVIEWERS Validator - uses: mszostok/codeowners-validator@v0.7.4 - with: - checks: "files,owners,duppatterns,syntax" - experimental_checks: "avoid-shadowing" - github_access_token: "${{ secrets.CODEOWNERS_VALIDATOR_TOKEN }}" diff --git a/Maintainers.txt b/Maintainers.txt index d5fb4a1ab6..73ce13126b 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -111,13 +111,6 @@ M: Bret Barkelew [corthon] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] -.github/ -F: .github/ -M: Michael D Kinney [mdkinney] -M: Michael Kubacki [makubacki] -R: Sean Brogan [spbrogan] -R: Liming Gao [lgao4] - .mergify/ F: .mergify/ M: Michael D Kinney [mdkinney] From a71b5521a48be41739a891cc5190f5fee3e87256 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Nov 2023 10:06:08 -0800 Subject: [PATCH 0010/1529] Revert "BaseTools/Scripts: CODEOWNERS and REVIEWERS use LF line endings" This reverts commit 0fa11bfeb2a6c33dd92570a1447c0f5f39bce09e. Signed-off-by: Michael D Kinney --- BaseTools/Scripts/PatchCheck.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index b5d9041fe6..63e6223f8e 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -367,9 +367,7 @@ def run(self): self.filename.startswith('BaseTools/BinWrappers/PosixLike/') or \ self.filename.startswith('BaseTools/BinPipWrappers/PosixLike/') or \ self.filename.startswith('BaseTools/Bin/CYGWIN_NT-5.1-i686/') or \ - self.filename == 'BaseTools/BuildEnv' or \ - self.filename.endswith('CODEOWNERS') or \ - self.filename.endswith('REVIEWERS'): + self.filename == 'BaseTools/BuildEnv': # # Do not enforce CR/LF line endings for linux shell scripts. # Some linux shell scripts don't end with the ".sh" extension, From 878acc89acdbe2d7a88ed8c96bb48bb061ed01c0 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 21 Aug 2022 15:31:21 +0200 Subject: [PATCH 0011/1529] BaseTools/GenFw AARCH64: Convert more types of explicit GOT references Rebecca reports that builds of AArch64 DSCs that involve PIE linking when using ELF based toolchains are failing in some cases, resulting in an error message like bad definition for symbol '_GLOBAL_OFFSET_TABLE_'@0x72d8 or unsupported symbol type. For example, absolute and undefined symbols are not supported. The reason turns out to be that, while GenFw does carry some logic to convert GOT based symbol references into direct ones (which is always possible given that our ELF to PE/COFF conversion only supports fully linked executables), it does not support all possible combinations of relocations that the linker may emit to load symbol addresses from the GOT. In particular, when performing a non-LTO link on object code built with GCC using -fpie, we may end up with GOT based references such as the one below, where the address of the GOT itself is taken, and the offset of the symbol in the GOT is reflected in the immediate offset of the subsequent LDR instruction. 838: adrp x0, 16000 838: R_AARCH64_ADR_PREL_PG_HI21 _GLOBAL_OFFSET_TABLE_ 83c: ldr x0, [x0, #2536] 83c: R_AARCH64_LD64_GOTPAGE_LO15 _gPcd_BinaryPatch_PcdFdBaseAddress The reason that we omit GOT based symbol references when performing ELF to PE/COFF conversion is that the GOT is not described by static ELF relocations, which means that the ELF file lacks the metadata to generate the PE/COFF relocations covering the GOT table in the PE/COFF executable. Given that none of the usual motivations for using a GOT (copy on write footprint, shared libraries) apply to EFI executables in the first place, the easiest way around this is to convert all GOT based symbol address loads to PC relative ADR/ADRP instructions. So implement this handling for R_AARCH64_LD64_GOTPAGE_LO15 and R_AARCH64_LD64_GOTOFF_LO15 relocations as well, and turn the LDR instructions in question into ADR instructions that generate the address immediately. This leaves the reference to _GLOBAL_OFFSET_TABLE_ itself, which is what generated the error to begin with. Considering that this symbol is never referenced (i.e., it doesn't appear anywhere in the code) and is only meaningful in combination with R_*_GOT_* based relocations that follow it, we can just disregard any references to it entirely, given that we convert all of those followup relocations into direct references. Signed-off-by: Ard Biesheuvel Tested-by: Rebecca Cran Acked-by: Leif Lindholm Acked-by: Bob Feng --- BaseTools/Source/C/GenFw/Elf64Convert.c | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index 35e96dd05b..ca3c8f8bee 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -1305,6 +1305,22 @@ WriteSections64 ( Elf_Shdr *SymShdr; UINT8 *Targ; + // + // The _GLOBAL_OFFSET_TABLE_ symbol is not actually an absolute symbol, + // but carries the SHN_ABS section index for historical reasons. + // It must be accompanied by a R_*_GOT_* type relocation on a + // subsequent instruction, which we handle below, specifically to avoid + // the GOT indirection, and to refer to the symbol directly. This means + // we can simply disregard direct references to the GOT symbol itself, + // as the resulting value will never be used. + // + if (Sym->st_shndx == SHN_ABS) { + const UINT8 *SymName = GetSymName (Sym); + if (strcmp ((CHAR8 *)SymName, "_GLOBAL_OFFSET_TABLE_") == 0) { + continue; + } + } + // // Check section header index found in symbol table and get the section // header location. @@ -1448,6 +1464,23 @@ WriteSections64 ( switch (ELF_R_TYPE(Rel->r_info)) { INT64 Offset; + case R_AARCH64_LD64_GOTOFF_LO15: + case R_AARCH64_LD64_GOTPAGE_LO15: + // + // Convert into an ADR instruction that refers to the symbol directly. + // + Offset = Sym->st_value - Rel->r_offset; + + *(UINT32 *)Targ &= 0x1000001f; + *(UINT32 *)Targ |= ((Offset & 0x1ffffc) << (5 - 2)) | ((Offset & 0x3) << 29); + + if (Offset < -0x100000 || Offset > 0xfffff) { + Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s failed to relax GOT based symbol reference - image is too big (>1 MiB).", + mInImageName); + break; + } + break; + case R_AARCH64_LD64_GOT_LO12_NC: // // Convert into an ADD instruction - see R_AARCH64_ADR_GOT_PAGE below. @@ -1686,6 +1719,8 @@ WriteRelocations64 ( case R_AARCH64_LDST128_ABS_LO12_NC: case R_AARCH64_ADR_GOT_PAGE: case R_AARCH64_LD64_GOT_LO12_NC: + case R_AARCH64_LD64_GOTOFF_LO15: + case R_AARCH64_LD64_GOTPAGE_LO15: // // No fixups are required for relative relocations, provided that // the relative offsets between sections have been preserved in From 01f85d5c2f5d91273e6229b6bf427c82853b7c9f Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Aug 2022 07:44:45 -0400 Subject: [PATCH 0012/1529] ArmPlatformPkg/NorFlashDxe: Remove unused debug print specifier These debug messages are repeated in both NorFlashBlockIoReadBlocks() and NorFlashBlockIoWriteBlocks(): "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x" "bytes (%d kB), BufferPtr @ 0x%08x)\n" Although this requires 5 arguments, only 4 are provided. The kilobyte value was never given. This change removes that specifier so the 4 arguments match the 4 specifiers in the debug macro. Cc: Leif Lindholm Cc: Ard Biesheuvel Signed-off-by: Michael Kubacki Reviewed-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c index 5afab0a79f..9d4732c690 100644 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c +++ b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c @@ -54,7 +54,7 @@ NorFlashBlockIoReadBlocks ( Instance = INSTANCE_FROM_BLKIO_THIS (This); Media = This->Media; - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, BufferSizeInBytes, Buffer)); if (!Media) { Status = EFI_INVALID_PARAMETER; @@ -89,7 +89,7 @@ NorFlashBlockIoWriteBlocks ( Instance = INSTANCE_FROM_BLKIO_THIS (This); - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes, BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); if ( !This->Media->MediaPresent ) { Status = EFI_NO_MEDIA; From ee2a24686a93c41ad4022acf8232f4e852ac91b6 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Aug 2022 07:52:09 -0400 Subject: [PATCH 0013/1529] FatPkg/FatPei: Remove extraneous debug message argument This debug macro should take one argument based on the number of print specifiers defined. However, two arguments are given. It looks like the code may have been refactored such that the second argument was moved to a new print and this argument was not removed. In any case, it should not be there now. Cc: Ray Ni Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- FatPkg/FatPei/Gpt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FatPkg/FatPei/Gpt.c b/FatPkg/FatPei/Gpt.c index 0a1a25ceef..9e17ce8808 100644 --- a/FatPkg/FatPei/Gpt.c +++ b/FatPkg/FatPei/Gpt.c @@ -361,7 +361,7 @@ PartitionCheckGptEntryArray ( PrivateData->BlockDeviceCount++; - DEBUG ((DEBUG_INFO, "Find GPT Partition [0x%lx", PartitionEntryBuffer[Index].StartingLBA, BlockDevPtr->LastBlock)); + DEBUG ((DEBUG_INFO, "Find GPT Partition [0x%lx", PartitionEntryBuffer[Index].StartingLBA)); DEBUG ((DEBUG_INFO, ", 0x%lx]\n", BlockDevPtr->LastBlock)); DEBUG ((DEBUG_INFO, " BlockSize %x\n", BlockDevPtr->BlockSize)); } From 1e694547625f7c7e27f3b29046705e27a739f9b1 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Aug 2022 13:28:21 -0400 Subject: [PATCH 0014/1529] MdeModulePkg: Fix imbalanced debug macros Updates debug macros in the package that have an imbalanced number of print specifiers to arguments. These changes try to preserve what was likely intended by the author. In cases information was missing due to the bug, the specifier may be removed since it was not previously accurately printing the expected value. Cc: Dandan Bi Cc: Guomin Jiang Cc: Hao A Wu Cc: Jian J Wang Cc: Liming Gao Cc: Liming Gao Cc: Ray Ni Signed-off-by: Michael Kubacki Reviewed-by: Hao A Wu Reviewed-by: Liming Gao --- MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c | 2 +- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 2 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c | 8 ++++---- MdeModulePkg/Core/Dxe/Image/Image.c | 2 +- .../DisplayUpdateProgressLibGraphics.c | 2 +- MdeModulePkg/Universal/CapsulePei/UefiCapsule.c | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c index 0d02c2785d..3e6f75345d 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c @@ -264,7 +264,7 @@ NvmeInitPrivateData ( if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, - "%a: The device path is invalid for Controller %d.\n", + "%a: The device path is invalid.\n", __FUNCTION__ )); return Status; diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index 53b63ab52b..dd45167a00 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -64,7 +64,7 @@ DumpCapabilityReg ( DEBUG ((DEBUG_INFO, " Driver Type D %a\n", Capability->DriverTypeD ? "TRUE" : "FALSE")); DEBUG ((DEBUG_INFO, " Driver Type 4 %a\n", Capability->DriverType4 ? "TRUE" : "FALSE")); if (Capability->TimerCount == 0) { - DEBUG ((DEBUG_INFO, " Retuning TimerCnt Disabled\n", 2 * (Capability->TimerCount - 1))); + DEBUG ((DEBUG_INFO, " Retuning TimerCnt Disabled\n")); } else { DEBUG ((DEBUG_INFO, " Retuning TimerCnt %dseconds\n", 2 * (Capability->TimerCount - 1))); } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c index 5495b324b3..aed34596f4 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c @@ -941,7 +941,7 @@ UsbEnumeratePort ( // which probably is caused by short circuit. It has to wait system hardware // to perform recovery. // - DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: Critical Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: Critical Over Current (port %d)\n", Port)); return EFI_DEVICE_ERROR; } @@ -951,7 +951,7 @@ UsbEnumeratePort ( // over current. As a result, all ports are nearly power-off, so // it's necessary to detach and enumerate all ports again. // - DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 2.0 device Recovery Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 2.0 device Recovery Over Current (port %d)\n", Port)); } if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_ENABLE)) { @@ -961,7 +961,7 @@ UsbEnumeratePort ( // on 2.0 roothub does. When over-current has influence on 1.1 device, the port // would be disabled, so it's also necessary to detach and enumerate again. // - DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 1.1 device Recovery Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 1.1 device Recovery Over Current (port %d)\n", Port)); } if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_CONNECTION)) { @@ -969,7 +969,7 @@ UsbEnumeratePort ( // Case4: // Device connected or disconnected normally. // - DEBUG ((DEBUG_INFO, "UsbEnumeratePort: Device Connect/Disconnect Normally\n", Port)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: Device Connect/Disconnect Normally (port %d)\n", Port)); } // diff --git a/MdeModulePkg/Core/Dxe/Image/Image.c b/MdeModulePkg/Core/Dxe/Image/Image.c index 68bde5c15c..06cc6744b8 100644 --- a/MdeModulePkg/Core/Dxe/Image/Image.c +++ b/MdeModulePkg/Core/Dxe/Image/Image.c @@ -1741,7 +1741,7 @@ CoreStartImage ( if ((Image->ExitDataSize != 0) || (Image->ExitData != NULL)) { DEBUG ((DEBUG_LOAD, "StartImage: ExitDataSize %d, ExitData %p", (UINT32)Image->ExitDataSize, Image->ExitData)); if (Image->ExitData != NULL) { - DEBUG ((DEBUG_LOAD, " (%hs)", Image->ExitData)); + DEBUG ((DEBUG_LOAD, " (%s)", Image->ExitData)); } DEBUG ((DEBUG_LOAD, "\n")); diff --git a/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c b/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c index 83053464e0..6b012fed35 100644 --- a/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c +++ b/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c @@ -148,7 +148,7 @@ FindDim ( (VOID **)&BootLogo ); if ((BootLogo == NULL) || (EFI_ERROR (Status))) { - DEBUG ((DEBUG_ERROR, "Failed to locate gEdkiiBootLogo2ProtocolGuid. No Progress bar support. \n", Status)); + DEBUG ((DEBUG_ERROR, "Failed to locate gEdkiiBootLogo2ProtocolGuid Status = %r. No Progress bar support. \n", Status)); return; } diff --git a/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c b/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c index ef60d4e1b7..cdeffa9113 100644 --- a/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c +++ b/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c @@ -976,7 +976,7 @@ GetScatterGatherHeadEntries ( if (EFI_ERROR (Status)) { if (Status != EFI_NOT_FOUND) { - DEBUG ((DEBUG_ERROR, "Unexpected error getting Capsule Update variable. Status = %r\n")); + DEBUG ((DEBUG_ERROR, "Unexpected error getting Capsule Update variable. Status = %r\n", Status)); } break; From 4b8d145840192c7aaf45d443650fb8b6c6f823b5 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Aug 2022 13:36:22 -0400 Subject: [PATCH 0015/1529] RedfishPkg/RedfishRestExDxe: Remove extra debug macro argument The debug macro argument in this change is removed since it does have a corresponding print specifier in the debug message string. Cc: Abner Chang Cc: Nickle Wang Signed-off-by: Michael Kubacki Reviewed-by: Abner Chang Reviewed-by: Nickle Wang --- RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c | 6 +++--- .../RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c | 2 +- RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c index 35dba40473..1293ddd633 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c @@ -263,12 +263,12 @@ Tcp6GetSubnetInfo ( Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n")); + DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__)); return Status; } if (IpModedata.AddressCount == 0) { - DEBUG ((DEBUG_INFO, "%a: No IPv6 address configured.\n")); + DEBUG ((DEBUG_INFO, "%a: No IPv6 address configured.\n", __FUNCTION__)); } if (Instance->SubnetAddrInfoIPv6 != NULL) { @@ -277,7 +277,7 @@ Tcp6GetSubnetInfo ( Instance->SubnetAddrInfoIPv6 = AllocateZeroPool (IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)); if (Instance->SubnetAddrInfoIPv6 == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Failed to allocate memory fir IPv6 subnet address information\n")); + DEBUG ((DEBUG_ERROR, "%a: Failed to allocate memory for IPv6 subnet address information\n", __FUNCTION__)); return EFI_OUT_OF_RESOURCES; } diff --git a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c index 8a05764ac6..623350bc26 100644 --- a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c +++ b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c @@ -119,7 +119,7 @@ RedfishCreateSmbiosTable42 ( } else { NewProtocolRecords = ReallocatePool (CurrentProtocolsDataLength, NewProtocolsDataLength, (VOID *)ProtocolRecords); if (NewProtocolRecords == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Fail to allocate memory for Redfish host interface protocol data.")); + DEBUG ((DEBUG_ERROR, "%a: Fail to allocate memory for Redfish host interface protocol data.", __FUNCTION__)); FreePool (ProtocolRecords); FreePool (ProtocolRecord); return EFI_OUT_OF_RESOURCES; diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c index f224104ad6..4b61fc01ad 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c @@ -224,7 +224,7 @@ ReSendRequest:; DEBUG ((DEBUG_INFO, "HTTP_STATUS_200_OK\n")); if (SendChunkProcess == HttpIoSendChunkHeaderZeroContent) { - DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks.", ResponseData->Response.StatusCode)); + DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks.")); SendChunkProcess++; goto ReSendRequest; } From 849215b71625e2c09e7abcd5369254754bd6cc8d Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Aug 2022 13:39:48 -0400 Subject: [PATCH 0016/1529] SecurityPkg/SmmTcg2PhysicalPresenceLib: Add missing debug print specifier The debug macro modified in this change was missing a print specifier for a debug message argument given. Cc: Jiewen Yao Cc: Jian J Wang Cc: Qi Zhang Cc: Rahul Kumar Signed-off-by: Michael Kubacki Reviewed-by: Jiewen Yao --- .../MmTcg2PhysicalPresenceLibCommon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c index 1fbfc00547..f2ab4f1250 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c @@ -176,7 +176,7 @@ Tcg2PhysicalPresenceLibSubmitRequestToPreOSFunctionEx ( // Sync PPRQ/PPRM from PP Variable if PP submission fails // if (ReturnCode != TCG_PP_SUBMIT_REQUEST_TO_PREOS_SUCCESS) { - DEBUG ((DEBUG_ERROR, "[TPM2] Submit PP Request failure! Sync PPRQ/PPRM with PP variable.\n", Status)); + DEBUG ((DEBUG_ERROR, "[TPM2] Submit PP Request failure! Sync PPRQ/PPRM with PP variable. Status = %r\n", Status)); DataSize = sizeof (EFI_TCG2_PHYSICAL_PRESENCE); ZeroMem (&PpData, DataSize); Status = mTcg2PpSmmVariable->SmmGetVariable ( From 6a6c162539abb08b0c0662f4c09b24959205fcc8 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 24 Aug 2022 22:51:43 -0400 Subject: [PATCH 0017/1529] DynamicTablesPkg/AcpiPpttLibArm: Fix debug macro arguments Cc: Sami Mujawar Cc: Alexei Fedorov Signed-off-by: Michael Kubacki Reviewed-by: Sami Mujawar --- .../Library/Acpi/Arm/AcpiPpttLibArm/PpttGenerator.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiPpttLibArm/PpttGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPpttLibArm/PpttGenerator.c index 59001378c4..78fa63ff47 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiPpttLibArm/PpttGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPpttLibArm/PpttGenerator.c @@ -436,7 +436,6 @@ IsGicCTokenEqual ( "the same GICC Info object. ACPI Processor IDs are not unique. " \ "GicCToken = %p.\n", Index1, - IndexedObject1->Token, Index2, ProcNode1->GicCToken )); @@ -566,7 +565,7 @@ AddProcHierarchyNodes ( DEBUG (( DEBUG_ERROR, "ERROR: PPTT: Failed to get parent processor hierarchy node " \ - "reference. Token = %p, Status = %r\n", + "reference. ParentToken = %p. ChildToken = %p. Status = %r\n", ProcInfoNode->ParentToken, ProcInfoNode->Token, Status From eaff43e169f7ac1abc4fbbf3be2babb07bddea61 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 24 Aug 2022 22:55:48 -0400 Subject: [PATCH 0018/1529] NetworkPkg/TcpDxe: Fix debug macro arguments Removes Status argument that is not needed from DEBUG macros. Cc: Maciej Rabeda Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Michael Kubacki Reviewed-by: Maciej Rabeda --- NetworkPkg/TcpDxe/SockInterface.c | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/NetworkPkg/TcpDxe/SockInterface.c b/NetworkPkg/TcpDxe/SockInterface.c index 413d6e1373..6e8cbb74a8 100644 --- a/NetworkPkg/TcpDxe/SockInterface.c +++ b/NetworkPkg/TcpDxe/SockInterface.c @@ -661,11 +661,7 @@ SockSend ( ); if (NULL == SockToken) { - DEBUG ( - (DEBUG_ERROR, - "SockSend: Failed to buffer IO token into socket processing SndToken List\n", - Status) - ); + DEBUG ((DEBUG_ERROR, "SockSend: Failed to buffer IO token into socket processing SndToken List\n")); Status = EFI_OUT_OF_RESOURCES; goto Exit; @@ -674,11 +670,7 @@ SockSend ( Status = SockProcessTcpSndData (Sock, TxData); if (EFI_ERROR (Status)) { - DEBUG ( - (DEBUG_ERROR, - "SockSend: Failed to process Snd Data\n", - Status) - ); + DEBUG ((DEBUG_ERROR, "SockSend: Failed to process Snd Data\n")); RemoveEntryList (&(SockToken->TokenList)); FreePool (SockToken); From 75c044d445aeea0436acda8483012650f8c5a08a Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 24 Aug 2022 23:01:51 -0400 Subject: [PATCH 0019/1529] OvmfPkg/LegacyBootManagerLib: Fix debug macro arguments The DEBUG macro updated in this patch previously contained 11 print specifiers in the debug string but passeed 13 arguments. This change attempts to update the macro to the author's intention so the number of specifiers match the number of arguments. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: David Woodhouse Signed-off-by: Michael Kubacki Reviewed-by: Ard Biesheuvel Acked-by: Gerd Hoffmann --- OvmfPkg/Csm/LegacyBootManagerLib/LegacyBm.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/Csm/LegacyBootManagerLib/LegacyBm.c b/OvmfPkg/Csm/LegacyBootManagerLib/LegacyBm.c index 032aacba68..2e92bce726 100644 --- a/OvmfPkg/Csm/LegacyBootManagerLib/LegacyBm.c +++ b/OvmfPkg/Csm/LegacyBootManagerLib/LegacyBm.c @@ -1159,8 +1159,8 @@ LegacyBmPrintBbsTable ( UINT16 Index; DEBUG ((DEBUG_INFO, "\n")); - DEBUG ((DEBUG_INFO, " NO Prio bb/dd/ff cl/sc Type Stat segm:offs\n")); - DEBUG ((DEBUG_INFO, "=============================================\n")); + DEBUG ((DEBUG_INFO, " NO Prio bb/dd/ff cl/sc Type Stat segm:offs mseg dseg\n")); + DEBUG ((DEBUG_INFO, "======================================================\n")); for (Index = 0; Index < BbsCount; Index++) { if (!LegacyBmValidBbsEntry (&LocalBbsTable[Index])) { continue; @@ -1168,7 +1168,7 @@ LegacyBmPrintBbsTable ( DEBUG ( (DEBUG_INFO, - " %02x: %04x %02x/%02x/%02x %02x/%02x %04x %04x %04x:%04x\n", + " %02x: %04x %02x/%02x/%02x %02x/%02x %04x %04x %04x:%04x %04x %04x\n", (UINTN)Index, (UINTN)LocalBbsTable[Index].BootPriority, (UINTN)LocalBbsTable[Index].Bus, From 4b0dc53d728ce864e1bef70fbfdbda0e07c5ead3 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 7 Sep 2022 17:24:26 +0200 Subject: [PATCH 0020/1529] ArmPkg, ArmVirtPkg: put SpellCheck in AuditOnly mode Don't allow spelling errors to break the CI build and inadvertently reject pull requests - spelling is important but not that important. Signed-off-by: Ard Biesheuvel Reviewed-by: Michael Kubacki Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar --- ArmPkg/ArmPkg.ci.yaml | 2 +- ArmVirtPkg/ArmVirtPkg.ci.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmPkg/ArmPkg.ci.yaml b/ArmPkg/ArmPkg.ci.yaml index b7e07aaef6..24db742505 100644 --- a/ArmPkg/ArmPkg.ci.yaml +++ b/ArmPkg/ArmPkg.ci.yaml @@ -87,7 +87,7 @@ ## options defined .pytool/Plugin/SpellCheck "SpellCheck": { - "AuditOnly": False, + "AuditOnly": True, "IgnoreFiles": [ "Library/ArmSoftFloatLib/berkeley-softfloat-3/**" ], # use gitignore syntax to ignore errors diff --git a/ArmVirtPkg/ArmVirtPkg.ci.yaml b/ArmVirtPkg/ArmVirtPkg.ci.yaml index d5d63ddd4f..1e799dc4e1 100644 --- a/ArmVirtPkg/ArmVirtPkg.ci.yaml +++ b/ArmVirtPkg/ArmVirtPkg.ci.yaml @@ -96,7 +96,7 @@ ## options defined .pytool/Plugin/SpellCheck "SpellCheck": { - "AuditOnly": False, # Fails right now with over 270 errors + "AuditOnly": True, "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files "ExtendWords": [ "acpiview", From 4ceeb6e47a5e1e5e753ca39189a76b590bce1511 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 15 Aug 2022 10:47:51 +0200 Subject: [PATCH 0021/1529] OvmfPkg: Introduce alternate UefiDriverEntrypoint to inhibit driver load Add a new library that can be incorporated into any driver built from source, and which permits loading of the driver to be inhibited based on the value of a QEMU fw_cfg boolean variable. This will be used in a subsequent patch to allow dispatch of the IPv4 and IPv6 network protocol driver to be controlled from the QEMU command line. This approach is based on the notion that all UEFI and DXE drivers share a single UefiDriverEntryPoint implementation, which we can easily swap out at build time with one that will abort execution based on the value of some QEMU fw_cfg variable. Signed-off-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek Acked-by: Gerd Hoffmann --- .../UefiDriverEntryPointFwCfgOverrideLib.c | 148 ++++++++++++++++++ .../UefiDriverEntryPointFwCfgOverrideLib.inf | 57 +++++++ OvmfPkg/OvmfPkg.dec | 4 + 3 files changed, 209 insertions(+) create mode 100644 OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.c create mode 100644 OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf diff --git a/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.c b/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.c new file mode 100644 index 0000000000..debbacb42f --- /dev/null +++ b/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.c @@ -0,0 +1,148 @@ +/** @file + Entry point to a EFI/DXE driver. This version is specific to QEMU, and ties + dispatch of the driver in question on the value of a QEMU fw_cfg boolean + variable which is referenced by name via a fixed pointer PCD. + +Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2022, Google LLC. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +#include + +#include +#include +#include +#include +#include + +/** + Unloads an image from memory. + + This function is a callback that a driver registers to do cleanup + when the UnloadImage boot service function is called. + + @param ImageHandle The handle to the image to unload. + + @return Status returned by all unload(). + +**/ +STATIC +EFI_STATUS +EFIAPI +_DriverUnloadHandler ( + EFI_HANDLE ImageHandle + ) +{ + EFI_STATUS Status; + + // + // If an UnloadImage() handler is specified, then call it + // + Status = ProcessModuleUnloadList (ImageHandle); + + // + // If the driver specific unload handler does not return an error, then call + // all of the library destructors. If the unload handler returned an error, + // then the driver can not be unloaded, and the library destructors should + // not be called + // + if (!EFI_ERROR (Status)) { + ProcessLibraryDestructorList (ImageHandle, gST); + } + + // + // Return the status from the driver specific unload handler + // + return Status; +} + +/** + The entry point of PE/COFF Image for a DXE Driver, DXE Runtime Driver, or + UEFI Driver. + + @param ImageHandle The image handle of the DXE Driver, DXE + Runtime Driver, or UEFI Driver. + @param SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The DXE Driver, DXE Runtime Driver, or + UEFI Driver exited normally. + @retval EFI_INCOMPATIBLE_VERSION _gUefiDriverRevision is greater than + SystemTable->Hdr.Revision. + @retval Other Return value from + ProcessModuleEntryPointList(). + +**/ +EFI_STATUS +EFIAPI +_ModuleEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + RETURN_STATUS RetStatus; + BOOLEAN Enabled; + + if (_gUefiDriverRevision != 0) { + // + // Make sure that the EFI/UEFI spec revision of the platform is >= EFI/UEFI + // spec revision of the driver + // + if (SystemTable->Hdr.Revision < _gUefiDriverRevision) { + return EFI_INCOMPATIBLE_VERSION; + } + } + + // + // Call constructor for all libraries + // + ProcessLibraryConstructorList (ImageHandle, SystemTable); + + // + // Install unload handler... + // + if (_gDriverUnloadImageCount != 0) { + Status = gBS->HandleProtocol ( + ImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&LoadedImage + ); + ASSERT_EFI_ERROR (Status); + LoadedImage->Unload = _DriverUnloadHandler; + } + + RetStatus = QemuFwCfgParseBool ( + FixedPcdGetPtr (PcdEntryPointOverrideFwCfgVarName), + &Enabled + ); + if (!RETURN_ERROR (RetStatus) && !Enabled) { + // + // The QEMU fw_cfg variable tells us not to load this image. So abort. + // + Status = EFI_ABORTED; + } else { + // + // Call the driver entry point + // + Status = ProcessModuleEntryPointList (ImageHandle, SystemTable); + } + + // + // If all of the drivers returned errors, or we if are aborting, then invoke + // all of the library destructors + // + if (EFI_ERROR (Status)) { + ProcessLibraryDestructorList (ImageHandle, SystemTable); + } + + // + // Return the cumulative return status code from all of the driver entry + // points + // + return Status; +} diff --git a/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf b/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf new file mode 100644 index 0000000000..263e00ceef --- /dev/null +++ b/OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf @@ -0,0 +1,57 @@ +## @file +# Entry point to a EFI/DXE driver. This version is specific to QEMU, and ties +# dispatch of the driver in question on the value of a QEMU fw_cfg boolean +# variable which is referenced by name via a fixed pointer PCD. +# +# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2022, Google LLC. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = UefiDriverEntryPointFwCfgOverrideLib + FILE_GUID = 73349b79-f148-43b8-b24e-9098a6f3e1db + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiDriverEntryPoint|DXE_DRIVER DXE_RUNTIME_DRIVER UEFI_DRIVER + +[Sources] + UefiDriverEntryPointFwCfgOverrideLib.c + +[Packages] + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + QemuFwCfgSimpleParserLib + UefiBootServicesTableLib + +[Protocols] + gEfiLoadedImageProtocolGuid ## SOMETIMES_CONSUMES + +[FixedPcd] + gUefiOvmfPkgTokenSpaceGuid.PcdEntryPointOverrideFwCfgVarName + +# +# For UEFI drivers, these architectural protocols defined in PI 1.0 spec need +# to be appended and merged to the final dependency section. +# +[Depex.common.UEFI_DRIVER] + gEfiBdsArchProtocolGuid AND + gEfiCpuArchProtocolGuid AND + gEfiMetronomeArchProtocolGuid AND + gEfiMonotonicCounterArchProtocolGuid AND + gEfiRealTimeClockArchProtocolGuid AND + gEfiResetArchProtocolGuid AND + gEfiRuntimeArchProtocolGuid AND + gEfiSecurityArchProtocolGuid AND + gEfiTimerArchProtocolGuid AND + gEfiVariableWriteArchProtocolGuid AND + gEfiVariableArchProtocolGuid AND + gEfiWatchdogTimerArchProtocolGuid diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index 6b1296b15a..6d689ecc5d 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -400,6 +400,10 @@ ## The Tdx accept page size. 0x1000(4k),0x200000(2M) gUefiOvmfPkgTokenSpaceGuid.PcdTdxAcceptPageSize|0x200000|UINT32|0x65 + ## The QEMU fw_cfg variable that UefiDriverEntryPointFwCfgOverrideLib will + # check to decide whether to abort dispatch of the driver it is linked into. + gUefiOvmfPkgTokenSpaceGuid.PcdEntryPointOverrideFwCfgVarName|""|VOID*|0x68 + [PcdsDynamic, PcdsDynamicEx] gUefiOvmfPkgTokenSpaceGuid.PcdEmuVariableEvent|0|UINT64|2 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFlashVariablesEnable|FALSE|BOOLEAN|0x10 From 21a4b29b17b32d99ebecfd099de5fcfe6312405d Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 6 Sep 2022 13:26:35 +0200 Subject: [PATCH 0022/1529] OvmfPkg: gather common NetworkComponents overrides in .dsc.inc file All QEMU based OVMF platforms override the same set of network components, to specify NULL library class resolutions that modify the behavior of those components in a QEMU specific way. Before adding more occurrences of that, let's drop those definitions in a common include file. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann --- OvmfPkg/CloudHv/CloudHvX64.dsc | 12 +----------- OvmfPkg/Microvm/MicrovmX64.dsc | 12 +----------- OvmfPkg/NetworkComponents.dsc.inc | 17 +++++++++++++++++ OvmfPkg/OvmfPkgIa32.dsc | 12 +----------- OvmfPkg/OvmfPkgIa32X64.dsc | 12 +----------- OvmfPkg/OvmfPkgX64.dsc | 12 +----------- 6 files changed, 22 insertions(+), 55 deletions(-) create mode 100644 OvmfPkg/NetworkComponents.dsc.inc diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 0f0fc9a1de..10b16104ac 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -827,18 +827,8 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc +!include OvmfPkg/NetworkComponents.dsc.inc - NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { - - NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf - } - -!if $(NETWORK_TLS_ENABLE) == TRUE - NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { - - NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf - } -!endif OvmfPkg/VirtioNetDxe/VirtioNet.inf !if $(TOOL_CHAIN_TAG) != "XCODE5" diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 52498bbe90..33d68a5493 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -793,18 +793,8 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc +!include OvmfPkg/NetworkComponents.dsc.inc - NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { - - NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf - } - -!if $(NETWORK_TLS_ENABLE) == TRUE - NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { - - NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf - } -!endif OvmfPkg/VirtioNetDxe/VirtioNet.inf # diff --git a/OvmfPkg/NetworkComponents.dsc.inc b/OvmfPkg/NetworkComponents.dsc.inc new file mode 100644 index 0000000000..85a1653916 --- /dev/null +++ b/OvmfPkg/NetworkComponents.dsc.inc @@ -0,0 +1,17 @@ +## +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +!if $(NETWORK_ENABLE) == TRUE + NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { + + NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf + } + + !if $(NETWORK_TLS_ENABLE) == TRUE + NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { + + NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf + } + !endif +!endif diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 985e34b2ca..e9ba491237 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -879,18 +879,8 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc +!include OvmfPkg/NetworkComponents.dsc.inc - NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { - - NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf - } - -!if $(NETWORK_TLS_ENABLE) == TRUE - NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { - - NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf - } -!endif OvmfPkg/VirtioNetDxe/VirtioNet.inf # diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index aa7eb4d79d..af566b953f 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -893,18 +893,8 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc +!include OvmfPkg/NetworkComponents.dsc.inc - NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { - - NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf - } - -!if $(NETWORK_TLS_ENABLE) == TRUE - NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { - - NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf - } -!endif OvmfPkg/VirtioNetDxe/VirtioNet.inf # diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 493db7be11..f39d9cd117 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -961,18 +961,8 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc +!include OvmfPkg/NetworkComponents.dsc.inc - NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { - - NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf - } - -!if $(NETWORK_TLS_ENABLE) == TRUE - NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { - - NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf - } -!endif OvmfPkg/VirtioNetDxe/VirtioNet.inf # From d26f14ba9c0029ac8cc819300c87c0592aaaec1b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 15 Aug 2022 11:17:12 +0200 Subject: [PATCH 0023/1529] OvmfPkg: Allow runtime control of IPv4 and IPv6 support on QEMU Wire up the newly added UefiDriverEntrypoint in a way that ties dispatch of the Ip4Dxe and Ip6Dxe drivers to QEMU fw_cfg variables 'opt/org.tianocore/IPv4Support' and 'opt/org.tianocore/IPv6Support' respectively. Setting both variables to 'n' disables IP based networking entirely, without the need for additional code changes at the NIC driver or network boot protocol level. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann --- OvmfPkg/NetworkComponents.dsc.inc | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/OvmfPkg/NetworkComponents.dsc.inc b/OvmfPkg/NetworkComponents.dsc.inc index 85a1653916..713eec7dd1 100644 --- a/OvmfPkg/NetworkComponents.dsc.inc +++ b/OvmfPkg/NetworkComponents.dsc.inc @@ -14,4 +14,22 @@ NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf } !endif + + !if $(NETWORK_IP4_ENABLE) == TRUE + NetworkPkg/Ip4Dxe/Ip4Dxe.inf { + + UefiDriverEntryPoint|OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf + + gUefiOvmfPkgTokenSpaceGuid.PcdEntryPointOverrideFwCfgVarName|"opt/org.tianocore/IPv4Support" + } + !endif + + !if $(NETWORK_IP6_ENABLE) == TRUE + NetworkPkg/Ip6Dxe/Ip6Dxe.inf { + + UefiDriverEntryPoint|OvmfPkg/Library/UefiDriverEntryPointFwCfgOverrideLib/UefiDriverEntryPointFwCfgOverrideLib.inf + + gUefiOvmfPkgTokenSpaceGuid.PcdEntryPointOverrideFwCfgVarName|"opt/org.tianocore/IPv6Support" + } + !endif !endif From edb4fa313bb8ce6db34d913f44d85dba0275bd82 Mon Sep 17 00:00:00 2001 From: Baraneedharan Anbazhagan Date: Wed, 7 Sep 2022 23:23:32 -0500 Subject: [PATCH 0024/1529] MdeModulePkg: Use configurable PCD for AHCI command retries REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4011 AHCI commands are retried internally which prevents platform feature like drive password to process correctly entered password on subsequent attempts. PCD allows the platform to determine the number of retries. Signed-off-by: Baraneedharan Anbazhagan Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h | 2 +- MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf | 3 ++- MdeModulePkg/MdeModulePkg.dec | 4 ++++ MdeModulePkg/MdeModulePkg.uni | 4 ++++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h index 7802ebd200..d7434b408c 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h @@ -193,7 +193,7 @@ typedef union { #define AHCI_PORT_DEVSLP_DITO_MASK 0x01FF8000 #define AHCI_PORT_DEVSLP_DM_MASK 0x1E000000 -#define AHCI_COMMAND_RETRIES 5 +#define AHCI_COMMAND_RETRIES (PcdGet32 (PcdAhciCommandRetryCount)) #pragma pack(1) // diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf index a3e42a9ab4..78caa3c458 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf @@ -65,7 +65,8 @@ gEdkiiAtaAtapiPolicyProtocolGuid ## CONSUMES [Pcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdAtaSmartEnable ## SOMETIMES_CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdAtaSmartEnable ## SOMETIMES_CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdAhciCommandRetryCount ## SOMETIMES_CONSUMES # [Event] # EVENT_TYPE_PERIODIC_TIMER ## SOMETIMES_CONSUMES diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 7d98910832..58e6ab0048 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -1574,6 +1574,10 @@ # @Prompt SD/MMC Host Controller Operations Timeout (us). gEfiMdeModulePkgTokenSpaceGuid.PcdSdMmcGenericTimeoutValue|1000000|UINT32|0x00000031 + ## The Retry Count of AHCI command if there is a failure + # @Prompt The value of Retry Count, Default value is 5. + gEfiMdeModulePkgTokenSpaceGuid.PcdAhciCommandRetryCount|5|UINT32|0x00000032 + [PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx] ## This PCD defines the Console output row. The default value is 25 according to UEFI spec. # This PCD could be set to 0 then console output would be at max column and max row. diff --git a/MdeModulePkg/MdeModulePkg.uni b/MdeModulePkg/MdeModulePkg.uni index b070f15ff2..33ce9f6198 100644 --- a/MdeModulePkg/MdeModulePkg.uni +++ b/MdeModulePkg/MdeModulePkg.uni @@ -1166,6 +1166,10 @@ "in the DXE phase. Minimum value is 1. Sections nested more deeply are
" "rejected." +#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdAhciCommandRetryCount_PROMPT #language en-US "Retry Count of AHCI command if there is a failure" + +#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdAhciCommandRetryCount_HELP #language en-US "This value is used to configure number of retries on AHCI commands, if there is a failure." + #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdCapsuleInRamSupport_PROMPT #language en-US "Enable Capsule In Ram support" #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdCapsuleInRamSupport_HELP #language en-US "Capsule In Ram is to use memory to deliver the capsules that will be processed after system reset.

" From 1ccaa140f218b87ec315d2db05a56fe73e416680 Mon Sep 17 00:00:00 2001 From: Heng Luo Date: Thu, 8 Sep 2022 13:40:59 +0800 Subject: [PATCH 0025/1529] MdeModulePkg SmbiosMeasurementDxe: Add Type4 CurrentSpeed to filter table REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4051 The Type4 CurrentSpeed field may be various. So this patch adds it into the filter table. Cc: Jian J Wang Cc: Liming Gao Cc: Zhiguang Liu Cc: Dandan Bi Cc: Star Zeng Cc: Zhichao Gao Signed-off-by: Heng Luo Reviewed-by: Jiewen Yao Reviewed-by: James Lu Reviewed-by: Zhichao Gao --- .../Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c index 348082ff86..d61edc846b 100644 --- a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c +++ b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c @@ -1,7 +1,7 @@ /** @file This driver measures SMBIOS table to TPM. -Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -66,6 +66,7 @@ SMBIOS_FILTER_TABLE mSmbiosFilterType4BlackList[] = { { 0x04, OFFSET_OF (SMBIOS_TABLE_TYPE4, EnabledCoreCount2), FIELD_SIZE_OF (SMBIOS_TABLE_TYPE4, EnabledCoreCount2), 0 }, { 0x04, OFFSET_OF (SMBIOS_TABLE_TYPE4, ThreadCount2), FIELD_SIZE_OF (SMBIOS_TABLE_TYPE4, ThreadCount2), 0 }, { 0x04, OFFSET_OF (SMBIOS_TABLE_TYPE4, Voltage), FIELD_SIZE_OF (SMBIOS_TABLE_TYPE4, Voltage), 0 }, + { 0x04, OFFSET_OF (SMBIOS_TABLE_TYPE4, CurrentSpeed), FIELD_SIZE_OF (SMBIOS_TABLE_TYPE4, CurrentSpeed), 0 }, }; SMBIOS_FILTER_TABLE mSmbiosFilterType17BlackList[] = { { 0x11, OFFSET_OF (SMBIOS_TABLE_TYPE17, SerialNumber), FIELD_SIZE_OF (SMBIOS_TABLE_TYPE17, SerialNumber), SMBIOS_FILTER_TABLE_FLAG_IS_STRING }, From 71ae6bd698f6d5dd4f4b54961df75b29b46bb831 Mon Sep 17 00:00:00 2001 From: "Czajkowski, Maciej" Date: Sat, 10 Sep 2022 02:10:55 +0800 Subject: [PATCH 0026/1529] MdeModulePkg/AhciPei: Fix MMIO base assignment REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4041 There is a mistake in getting MMIO base using PciDevicePpi that can lead to the data corruption. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Maciej Czajkowski Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c index 98dd732a40..e33d863d2a 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c @@ -405,7 +405,7 @@ AtaAhciInitPrivateDataFromPciDevice ( { EFI_STATUS Status; PCI_TYPE00 PciData; - UINTN MmioBase; + UINT32 MmioBase; EFI_DEVICE_PATH_PROTOCOL *DevicePath; UINTN DevicePathLength; UINT64 EnabledPciAttributes; @@ -454,13 +454,15 @@ AtaAhciInitPrivateDataFromPciDevice ( &PciDevice->PciIo, EfiPciIoWidthUint32, 0x24, - sizeof (UINTN), + 1, &MmioBase ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } + MmioBase &= 0xFFFFFFF0; + DevicePathLength = GetDevicePathSize (PciDevice->DevicePath); DevicePath = PciDevice->DevicePath; From d304d62979277f0ead3833473828079ad6911404 Mon Sep 17 00:00:00 2001 From: "Kuo, Ted" Date: Mon, 29 Aug 2022 17:28:17 +0800 Subject: [PATCH 0027/1529] BaseTools: 64bit FSP FV map file cannot be created correctly https://bugzilla.tianocore.org/show_bug.cgi?id=4035 64bit FSP FV map file cannot be created correctly when using CLANG compiler. When compiling 64bit FSP with CLANG, there is no prefix symbol '_' added to function name. Hence FSP FV map file cannot be created properly. Updated the if condition for CLANG in GenFv to get the issue fixed. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Lee Hamel Signed-off-by: Ted Kuo Reviewed-by: Bob Feng --- BaseTools/Source/C/GenFv/GenFvInternalLib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index d650a527a5..d28ac8f6eb 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -1004,7 +1004,7 @@ Routine Description: if (IsUseClang) { sscanf (Line, "%llx %s %s %s", &TempLongAddress, KeyWord, KeyWord2, FunctionTypeName); FunctionAddress = (UINT64) TempLongAddress; - if (FunctionTypeName [0] == '_' ) { + if (FunctionTypeName [0] != '/' && FunctionTypeName [0] != '.' && FunctionTypeName [1] != ':') { fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress)); fprintf (FvMapFile, "%s\n", FunctionTypeName); } From cf30ba54efcdc5243a17261175d01561a4f019c1 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Tue, 6 Sep 2022 14:33:56 -0600 Subject: [PATCH 0028/1529] DynamicTablesPkg: AcpiSsdtPcieLibArm: Allow use of segment number as UID Add support for selecting to use index or segment number as UID and name. This allows the path of the nodes to be well known. For example, if the PCIe node needs to be notified from by an interrupt for a Generic Event Device Signed-off-by: Jeff Brasen Reviewed-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/DynamicTablesPkg.dec | 3 +++ .../AcpiSsdtPcieLibArm/SsdtPcieGenerator.c | 19 ++++++++++++++++++- .../Arm/AcpiSsdtPcieLibArm/SsdtPcieLibArm.inf | 3 +++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/DynamicTablesPkg/DynamicTablesPkg.dec b/DynamicTablesPkg/DynamicTablesPkg.dec index cc34c2bdd6..adc2e67cbf 100644 --- a/DynamicTablesPkg/DynamicTablesPkg.dec +++ b/DynamicTablesPkg/DynamicTablesPkg.dec @@ -60,5 +60,8 @@ # Non BSA Compliant 16550 Serial HID gEdkiiDynamicTablesPkgTokenSpaceGuid.PcdNonBsaCompliant16550SerialHid|""|VOID*|0x40000008 + # Use PCI segment numbers as UID + gEdkiiDynamicTablesPkgTokenSpaceGuid.PcdPciUseSegmentAsUid|FALSE|BOOLEAN|0x40000009 + [Guids] gEdkiiDynamicTablesPkgTokenSpaceGuid = { 0xab226e66, 0x31d8, 0x4613, { 0x87, 0x9d, 0xd2, 0xfa, 0xb6, 0x10, 0x26, 0x3c } } diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c index d82f071e85..85098752c6 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c @@ -981,6 +981,7 @@ BuildSsdtPciTableEx ( UINTN Index; EFI_ACPI_DESCRIPTION_HEADER **TableList; ACPI_PCI_GENERATOR *Generator; + UINT32 Uid; ASSERT (This != NULL); ASSERT (AcpiTableInfo != NULL); @@ -1036,13 +1037,29 @@ BuildSsdtPciTableEx ( *Table = TableList; for (Index = 0; Index < PciCount; Index++) { + if (PcdGetBool (PcdPciUseSegmentAsUid)) { + Uid = PciInfo[Index].PciSegmentGroupNumber; + if (Uid > MAX_PCI_ROOT_COMPLEXES_SUPPORTED) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SSDT-PCI: Pci root complexes segment number: %d." + " Greater than maximum number of Pci root complexes supported = %d.\n", + Uid, + MAX_PCI_ROOT_COMPLEXES_SUPPORTED + )); + return EFI_INVALID_PARAMETER; + } + } else { + Uid = Index; + } + // Build a SSDT table describing the Pci devices. Status = BuildSsdtPciTable ( Generator, CfgMgrProtocol, AcpiTableInfo, &PciInfo[Index], - Index, + Uid, &TableList[Index] ); if (EFI_ERROR (Status)) { diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieLibArm.inf b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieLibArm.inf index b38a4e9d34..c2a1acb570 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieLibArm.inf +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieLibArm.inf @@ -30,3 +30,6 @@ AmlLib BaseLib SsdtPcieSupportLib + +[Pcd] + gEdkiiDynamicTablesPkgTokenSpaceGuid.PcdPciUseSegmentAsUid From f40320cd223b6026f8b14a73e73e47576c17cd65 Mon Sep 17 00:00:00 2001 From: "Kuo, Ted" Date: Thu, 15 Sep 2022 06:39:33 -0700 Subject: [PATCH 0029/1529] IntelFsp2Pkg: NvsBufferPtr is missing in Fsp24ApiEntryM.nasm REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4063 Added NvsBufferPtr to FSPM_UPD_COMMON_FSP24 in Fsp24ApiEntryM.nasm to align with FSP 2.4 SPEC. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Cc: Ashraf Ali S Cc: Chinni B Duggapu Signed-off-by: Ted Kuo Reviewed-by: Chasel Chiu --- IntelFsp2Pkg/FspSecCore/Ia32/Fsp24ApiEntryM.nasm | 3 ++- IntelFsp2Pkg/FspSecCore/X64/Fsp24ApiEntryM.nasm | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/Fsp24ApiEntryM.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/Fsp24ApiEntryM.nasm index 997b9c0bff..15f8ecea83 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/Fsp24ApiEntryM.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/Fsp24ApiEntryM.nasm @@ -40,12 +40,13 @@ struc FSPM_UPD_COMMON_FSP24 .Revision: resb 1 .Reserved: resb 3 .Length resd 1 + .NvsBufferPtr resq 1 .StackBase: resq 1 .StackSize: resq 1 .BootLoaderTolumSize: resd 1 .BootMode: resd 1 .FspEventHandler resq 1 - .Reserved1: resb 24 + .Reserved1: resb 16 ; } .size: endstruc diff --git a/IntelFsp2Pkg/FspSecCore/X64/Fsp24ApiEntryM.nasm b/IntelFsp2Pkg/FspSecCore/X64/Fsp24ApiEntryM.nasm index 8880721f29..a3b38e4585 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/Fsp24ApiEntryM.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/Fsp24ApiEntryM.nasm @@ -22,12 +22,13 @@ struc FSPM_UPD_COMMON_FSP24 .Revision: resb 1 .Reserved: resb 3 .Length resd 1 + .NvsBufferPtr resq 1 .StackBase: resq 1 .StackSize: resq 1 .BootLoaderTolumSize: resd 1 .BootMode: resd 1 .FspEventHandler resq 1 - .Reserved1: resb 24 + .Reserved1: resb 16 ; } .size: endstruc From 3493fffd2879f08ce5dfd249ac4a99bf7cf01824 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Wed, 7 Sep 2022 08:46:06 -0700 Subject: [PATCH 0030/1529] IntelFsp2Pkg: Fix FspSecCoreI build failure. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4049 Link error occurred in certain compiling environment when building FspSecCoreI: unresolved external symbol _TempRamInitApi. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryI.nasm | 11 +++++++++++ IntelFsp2Pkg/FspSecCore/X64/FspApiEntryI.nasm | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryI.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryI.nasm index e9365d6832..e392ebed58 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryI.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryI.nasm @@ -22,6 +22,17 @@ global ASM_PFX(FspApiCommonContinue) ASM_PFX(FspApiCommonContinue): jmp $ +;---------------------------------------------------------------------------- +; TempRamInit API +; +; Empty function for WHOLEARCHIVE build option +; +;---------------------------------------------------------------------------- +global ASM_PFX(TempRamInitApi) +ASM_PFX(TempRamInitApi): + jmp $ + ret + ;---------------------------------------------------------------------------- ; FspSmmInit API ; diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryI.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryI.nasm index e74bf0a26b..5c9ffbd569 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryI.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryI.nasm @@ -22,6 +22,17 @@ global ASM_PFX(FspApiCommonContinue) ASM_PFX(FspApiCommonContinue): jmp $ +;---------------------------------------------------------------------------- +; TempRamInit API +; +; Empty function for WHOLEARCHIVE build option +; +;---------------------------------------------------------------------------- +global ASM_PFX(TempRamInitApi) +ASM_PFX(TempRamInitApi): + jmp $ + ret + ;---------------------------------------------------------------------------- ; FspSmmInit API ; From 26a36077b15905b3931c34965bb16942176a1b78 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 2 Sep 2022 20:23:39 -0400 Subject: [PATCH 0031/1529] Maintainers.txt: Update maintainers/reviewers for CI and Test Remove Bret Barkelew from: - .azurepipelines - .mergify - .pytool - UnitTestFrameworkPkg Add Michael Kubacki to: - .azurepipelines - .pytool Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Cc: Michael Kubacki Signed-off-by: Bret Barkelew Reviewed-by: Michael D Kinney Reviewed-by: Michael Kubacki --- Maintainers.txt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Maintainers.txt b/Maintainers.txt index 73ce13126b..d869dc46f0 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -107,7 +107,7 @@ EDK II Continuous Integration: .azurepipelines/ F: .azurepipelines/ M: Sean Brogan [spbrogan] -M: Bret Barkelew [corthon] +M: Michael Kubacki [makubacki] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] @@ -116,12 +116,11 @@ F: .mergify/ M: Michael D Kinney [mdkinney] M: Liming Gao [lgao4] R: Sean Brogan [spbrogan] -R: Bret Barkelew [corthon] .pytool/ F: .pytool/ M: Sean Brogan [spbrogan] -M: Bret Barkelew [corthon] +M: Michael Kubacki [makubacki] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] @@ -614,5 +613,4 @@ F: UnitTestFrameworkPkg/ M: Michael D Kinney [mdkinney] M: Michael Kubacki [makubacki] R: Sean Brogan [spbrogan] -R: Bret Barkelew [corthon] S: Maintained From 493af3d673a50aea5f0c1aeb4cd711377a539f0a Mon Sep 17 00:00:00 2001 From: James Lu Date: Thu, 15 Sep 2022 16:48:07 +0800 Subject: [PATCH 0032/1529] UefiPayloadPkg/PayloadLoaderPeim: remove GCC build warning Fix the gcc build warning: variable PldInfo set but not used [-Wunused-but-set-variable] Reviewed-by: James Lu Reviewed-by: Zhiguang Liu Cc: Ray Ni Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Gang Chen --- .../PayloadLoaderPeim/PayloadLoaderPeim.c | 29 ++++++++----------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c index 9a2c3c148d..9f9d3c13e1 100644 --- a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c +++ b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c @@ -44,19 +44,18 @@ PeiLoadFileLoadPayload ( OUT UINT32 *AuthenticationState ) { - EFI_STATUS Status; - VOID *Elf; - UNIVERSAL_PAYLOAD_EXTRA_DATA *ExtraData; - ELF_IMAGE_CONTEXT Context; - UNIVERSAL_PAYLOAD_INFO_HEADER *PldInfo; - UINT32 Index; - UINT16 ExtraDataIndex; - CHAR8 *SectionName; - UINTN Offset; - UINTN Size; - UINT32 ExtraDataCount; - UINTN Instance; - UINTN Length; + EFI_STATUS Status; + VOID *Elf; + UNIVERSAL_PAYLOAD_EXTRA_DATA *ExtraData; + ELF_IMAGE_CONTEXT Context; + UINT32 Index; + UINT16 ExtraDataIndex; + CHAR8 *SectionName; + UINTN Offset; + UINTN Size; + UINT32 ExtraDataCount; + UINTN Instance; + UINTN Length; // // ELF is added to file as RAW section for EDKII bootloader. @@ -85,7 +84,6 @@ PeiLoadFileLoadPayload ( // // Get UNIVERSAL_PAYLOAD_INFO_HEADER and number of additional PLD sections. // - PldInfo = NULL; ExtraDataCount = 0; for (Index = 0; Index < Context.ShNum; Index++) { Status = GetElfSectionName (&Context, Index, &SectionName); @@ -96,9 +94,6 @@ PeiLoadFileLoadPayload ( DEBUG ((DEBUG_INFO, "Payload Section[%d]: %a\n", Index, SectionName)); if (AsciiStrCmp (SectionName, UNIVERSAL_PAYLOAD_INFO_SEC_NAME) == 0) { Status = GetElfSectionPos (&Context, Index, &Offset, &Size); - if (!EFI_ERROR (Status)) { - PldInfo = (UNIVERSAL_PAYLOAD_INFO_HEADER *)(Context.FileBase + Offset); - } } else if (AsciiStrnCmp (SectionName, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH) == 0) { Status = GetElfSectionPos (&Context, Index, &Offset, &Size); if (!EFI_ERROR (Status)) { From 5e9da16caa60596b2d2e20f5188a54ff031ae751 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Thu, 15 Sep 2022 09:46:17 +0800 Subject: [PATCH 0033/1529] Maintainers.txt: Update email address Update Nickle's email address from csie.io to nvidia.com for those packages which are reviewed by Nickle. Per suggestion from Abner, change Nickle from reviewer to maintainer for RedfishPkg. Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Cc: Abner Chang Signed-off-by: Nickle Wang Reviewed-by: Abner Chang Reviewed-by: Michael D Kinney Reviewed-by: Andrew Fish --- Maintainers.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Maintainers.txt b/Maintainers.txt index d869dc46f0..c641414109 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -196,7 +196,7 @@ S: Maintained EmulatorPkg: Redfish-related modules F: EmulatorPkg/*Redfish* M: Abner Chang [changab] -R: Nickle Wang [nicklela] +M: Nickle Wang [nicklela] FatPkg F: FatPkg/ @@ -543,7 +543,7 @@ R: Ankit Sinha [ankit13s] RedfishPkg: Redfish related modules F: RedfishPkg/ M: Abner Chang [changab] -R: Nickle Wang [nicklela] +M: Nickle Wang [nicklela] SecurityPkg F: SecurityPkg/ From 3ba9cefd4368b52252bc13686a4902cb41bfc852 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Thu, 22 Sep 2022 04:44:59 +0800 Subject: [PATCH 0034/1529] BaseTools: Edk2ToolsBuild: Fixing pipeline build due to path too long Current implementation of looking up toolchain will _insert_ the findings from vsvarsall.bat to existing path and potentially stuff the variable to exceed the length of maximal path length accepted by Windows. This change updated the logic to use the discovered shell varialbes to replace the existing path, which is desirable in the specific use case. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Co-authored-by: Sean Brogan Signed-off-by: Kun Qin Reviewed-by: Sean Brogan Reviewed-by: Bob Feng --- BaseTools/Edk2ToolsBuild.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Edk2ToolsBuild.py b/BaseTools/Edk2ToolsBuild.py index 1ea8187de6..f862468ce2 100644 --- a/BaseTools/Edk2ToolsBuild.py +++ b/BaseTools/Edk2ToolsBuild.py @@ -122,7 +122,7 @@ def Go(self): for key in vc_vars.keys(): logging.debug(f"Var - {key} = {vc_vars[key]}") if key.lower() == 'path': - shell_env.insert_path(vc_vars[key]) + shell_env.set_path(vc_vars[key]) else: shell_env.set_shell_var(key, vc_vars[key]) From 9de0a63c500643569bdf60545e20c9496aa9f8a7 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 16 Sep 2022 15:44:27 -0400 Subject: [PATCH 0035/1529] nasm_ext_dep.yaml: Remove leading zero in patch version The patch version is currently: "2.15.05" When a formal semantic version validator is run against this version it is recognized as being invalid due to the leading zero in the patch which is not allowed per the Semantic Versioning Specification: https://semver.org/#spec-item-2 The NuGet Gallery already reports the version without the leading zero: https://www.nuget.org/packages/mu_nasm/2.15.5 This change simply removes the leading zero to prevent code such as https://pypi.org/project/semantic-version/ from reporting a version error. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- BaseTools/Bin/nasm_ext_dep.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Bin/nasm_ext_dep.yaml b/BaseTools/Bin/nasm_ext_dep.yaml index 7a56dd2b8b..56703d4c18 100644 --- a/BaseTools/Bin/nasm_ext_dep.yaml +++ b/BaseTools/Bin/nasm_ext_dep.yaml @@ -13,6 +13,6 @@ "type": "nuget", "name": "mu_nasm", "source": "https://api.nuget.org/v3/index.json", - "version": "2.15.05", + "version": "2.15.5", "flags": ["set_path", "host_specific"] } From 7268ddb86acbc29f96c60a408ecde9edc0dad411 Mon Sep 17 00:00:00 2001 From: Wenyi Xie Date: Thu, 15 Sep 2022 17:26:20 +0800 Subject: [PATCH 0036/1529] CryptoPkg/BaseCryptLib:Remove redundant init CertCtx is used to be defined as a struct and ZeroMem is called to init this struct. But now CertCtx is defined as a point, so use ZeroMem (&CertCtx, sizeof (CertCtx)) is not correct any more. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Wenyi Xie Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c index 3336d2f60a..f8028181e4 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c @@ -502,8 +502,6 @@ Pkcs7GetCertificatesList ( OldBuf = NULL; Signers = NULL; - ZeroMem (&CertCtx, sizeof (CertCtx)); - // // Parameter Checking // From 92888d9d0442830a7eca3a86fead08d23868fbcb Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Thu, 22 Sep 2022 22:06:32 +0800 Subject: [PATCH 0037/1529] RedfishPkg/JsonLib: Fix JsonLib build failure VS2019 reports build failure: "warning C4701: potentially uninitialized local variable 'Ucs2Str' used". Initial Ucs2Str to NULL at the beginning of function. Cc: Abner Chang Cc: Nick Ramirez Signed-off-by: Nickle Wang Reviewed-by: Abner Chang --- RedfishPkg/Library/JsonLib/JsonLib.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/RedfishPkg/Library/JsonLib/JsonLib.c b/RedfishPkg/Library/JsonLib/JsonLib.c index 75bd8f9853..5d75882004 100644 --- a/RedfishPkg/Library/JsonLib/JsonLib.c +++ b/RedfishPkg/Library/JsonLib/JsonLib.c @@ -6,6 +6,7 @@ Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -569,6 +570,7 @@ JsonValueGetUnicodeString ( CONST CHAR8 *Utf8Str; CHAR16 *Ucs2Str; + Ucs2Str = NULL; Utf8Str = json_string_value ((json_t *)Json); if (Utf8Str == NULL) { return NULL; From 145be27ba672e0458f08aa24aef8a836a98b3260 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 09:14:48 +0800 Subject: [PATCH 0038/1529] CryptoPkg: Add new hmac definition to cryptlib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4025 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 188 ++++++++++++++++ .../Pcd/PcdCryptoServiceFamilyEnable.h | 13 ++ CryptoPkg/Private/Protocol/Crypto.h | 200 +++++++++++++++++- 3 files changed, 400 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 7d1499350a..3a42e3494f 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -1045,6 +1045,194 @@ HmacSha256Final ( OUT UINT8 *HmacValue ); +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HashValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ); + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha384New ( + VOID + ); + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha384Free ( + IN VOID *HmacSha384Ctx + ); + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ); + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ); + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ); + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ); + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HashValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ); + // ===================================================================================== // Symmetric Cryptography Primitive // ===================================================================================== diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 3d53c2f105..e646d8ac05 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -53,9 +53,22 @@ typedef struct { UINT8 Duplicate : 1; UINT8 Update : 1; UINT8 Final : 1; + UINT8 All : 1; } Services; UINT32 Family; } HmacSha256; + union { + struct { + UINT8 New : 1; + UINT8 Free : 1; + UINT8 SetKey : 1; + UINT8 Duplicate : 1; + UINT8 Update : 1; + UINT8 Final : 1; + UINT8 All : 1; + } Services; + UINT32 Family; + } HmacSha384; union { struct { UINT8 GetContextSize : 1; diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index c417568e96..23445cf1e8 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 8 +#define EDKII_CRYPTO_VERSION 9 /// /// EDK II Crypto Protocol forward declaration @@ -266,6 +266,194 @@ BOOLEAN OUT UINT8 *HmacValue ); +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA256_ALL)( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ); + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_NEW)( + VOID + ); + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_FREE)( + IN VOID *HmacSha384Ctx + ); + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_SET_KEY)( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ); + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_DUPLICATE)( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ); + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_UPDATE)( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ); + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_FINAL)( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ); + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HMAC_SHA384_ALL)( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ); + // ===================================================================================== // One-Way Cryptographic Hash Primitives // ===================================================================================== @@ -3675,6 +3863,16 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_RSA_PSS_VERIFY RsaPssVerify; /// Parallel hash EDKII_CRYPTO_PARALLEL_HASH_ALL ParallelHash256HashAll; + /// HMAC SHA256 (continued) + EDKII_CRYPTO_HMAC_SHA256_ALL HmacSha256All; + /// HMAC SHA384 + EDKII_CRYPTO_HMAC_SHA384_NEW HmacSha384New; + EDKII_CRYPTO_HMAC_SHA384_FREE HmacSha384Free; + EDKII_CRYPTO_HMAC_SHA384_SET_KEY HmacSha384SetKey; + EDKII_CRYPTO_HMAC_SHA384_DUPLICATE HmacSha384Duplicate; + EDKII_CRYPTO_HMAC_SHA384_UPDATE HmacSha384Update; + EDKII_CRYPTO_HMAC_SHA384_FINAL HmacSha384Final; + EDKII_CRYPTO_HMAC_SHA384_ALL HmacSha384All; }; extern GUID gEdkiiCryptoProtocolGuid; From 289487b0d0ea340df2b92709dd01b7454f8c8714 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 09:14:49 +0800 Subject: [PATCH 0039/1529] CryptoPkg: Add HMAC-SHA384 cipher support. Rename file from CryptHmacSha256 to CryptHmac and add HmacSha384 and HmacSha256All funcitons. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4025 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/Hmac/CryptHmac.c | 629 ++++++++++++++++++ .../Library/BaseCryptLib/Hmac/CryptHmacNull.c | 359 ++++++++++ .../BaseCryptLib/Hmac/CryptHmacSha256.c | 217 ------ .../BaseCryptLib/Hmac/CryptHmacSha256Null.c | 139 ---- .../BaseCryptLibNull/Hmac/CryptHmacNull.c | 359 ++++++++++ .../Hmac/CryptHmacSha256Null.c | 139 ---- 6 files changed, 1347 insertions(+), 495 deletions(-) create mode 100644 CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacNull.c delete mode 100644 CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256.c delete mode 100644 CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256Null.c create mode 100644 CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacNull.c delete mode 100644 CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacSha256Null.c diff --git a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c new file mode 100644 index 0000000000..2786267a0b --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c @@ -0,0 +1,629 @@ +/** @file + HMAC-SHA256/SHA384 Wrapper Implementation over OpenSSL. + +Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" +#include + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-MD use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacMdNew() returns NULL. + +**/ +VOID * +HmacMdNew ( + VOID + ) +{ + // + // Allocates & Initializes HMAC_CTX Context by OpenSSL HMAC_CTX_new() + // + return (VOID *)HMAC_CTX_new (); +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacMdCtx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +HmacMdFree ( + IN VOID *HmacMdCtx + ) +{ + // + // Free OpenSSL HMAC_CTX Context + // + HMAC_CTX_free ((HMAC_CTX *)HmacMdCtx); +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacMdUpdate(). + + If HmacMdContext is NULL, then return FALSE. + + @param[in] Md Message Digest. + @param[out] HmacMdContext Pointer to HMAC-MD context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + +**/ +BOOLEAN +HmacMdSetKey ( + IN CONST EVP_MD *Md, + OUT VOID *HmacMdContext, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + // + // Check input parameters. + // + if ((HmacMdContext == NULL) || (KeySize > INT_MAX)) { + return FALSE; + } + + if (HMAC_Init_ex ((HMAC_CTX *)HmacMdContext, Key, (UINT32)KeySize, Md, NULL) != 1) { + return FALSE; + } + + return TRUE; +} + +/** + Makes a copy of an existing HMAC-MD context. + + If HmacMdContext is NULL, then return FALSE. + If NewHmacMdContext is NULL, then return FALSE. + + @param[in] HmacMdContext Pointer to HMAC-MD context being copied. + @param[out] NewHmacMdContext Pointer to new HMAC-MD context. + + @retval TRUE HMAC-MD context copy succeeded. + @retval FALSE HMAC-MD context copy failed. + +**/ +BOOLEAN +HmacMdDuplicate ( + IN CONST VOID *HmacMdContext, + OUT VOID *NewHmacMdContext + ) +{ + // + // Check input parameters. + // + if ((HmacMdContext == NULL) || (NewHmacMdContext == NULL)) { + return FALSE; + } + + if (HMAC_CTX_copy ((HMAC_CTX *)NewHmacMdContext, (HMAC_CTX *)HmacMdContext) != 1) { + return FALSE; + } + + return TRUE; +} + +/** + Digests the input data and updates HMAC-MD context. + + This function performs HMAC-MD digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-MD context should be initialized by HmacMdNew(), and should not be finalized + by HmacMdFinal(). Behavior with invalid context is undefined. + + If HmacMdContext is NULL, then return FALSE. + + @param[in, out] HmacMdContext Pointer to the HMAC-MD context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-MD data digest succeeded. + @retval FALSE HMAC-MD data digest failed. + +**/ +BOOLEAN +HmacMdUpdate ( + IN OUT VOID *HmacMdContext, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + // + // Check input parameters. + // + if (HmacMdContext == NULL) { + return FALSE; + } + + // + // Check invalid parameters, in case that only DataLength was checked in OpenSSL + // + if ((Data == NULL) && (DataSize != 0)) { + return FALSE; + } + + // + // OpenSSL HMAC-MD digest update + // + if (HMAC_Update ((HMAC_CTX *)HmacMdContext, Data, DataSize) != 1) { + return FALSE; + } + + return TRUE; +} + +/** + Completes computation of the HMAC-MD digest value. + + This function completes HMAC-MD hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-MD context cannot + be used again. + HMAC-MD context should be initialized by HmacMdNew(), and should not be finalized + by HmacMdFinal(). Behavior with invalid HMAC-MD context is undefined. + + If HmacMdContext is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + + @param[in, out] HmacMdContext Pointer to the HMAC-MD context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-MD digest + value. + + @retval TRUE HMAC-MD digest computation succeeded. + @retval FALSE HMAC-MD digest computation failed. + +**/ +BOOLEAN +HmacMdFinal ( + IN OUT VOID *HmacMdContext, + OUT UINT8 *HmacValue + ) +{ + UINT32 Length; + + // + // Check input parameters. + // + if ((HmacMdContext == NULL) || (HmacValue == NULL)) { + return FALSE; + } + + // + // OpenSSL HMAC-MD digest finalization + // + if (HMAC_Final ((HMAC_CTX *)HmacMdContext, HmacValue, &Length) != 1) { + return FALSE; + } + + if (HMAC_CTX_reset ((HMAC_CTX *)HmacMdContext) != 1) { + return FALSE; + } + + return TRUE; +} + +/** + Computes the HMAC-MD digest of a input data buffer. + + This function performs the HMAC-MD digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Md Message Digest. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-MD digest + value. + + @retval TRUE HMAC-MD digest computation succeeded. + @retval FALSE HMAC-MD digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +HmacMdAll ( + IN CONST EVP_MD *Md, + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + UINT32 Length; + HMAC_CTX *Ctx; + BOOLEAN RetVal; + + Ctx = HMAC_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)HMAC_CTX_reset (Ctx); + if (!RetVal) { + goto Done; + } + + RetVal = (BOOLEAN)HMAC_Init_ex (Ctx, Key, (UINT32)KeySize, Md, NULL); + if (!RetVal) { + goto Done; + } + + RetVal = (BOOLEAN)HMAC_Update (Ctx, Data, DataSize); + if (!RetVal) { + goto Done; + } + + RetVal = (BOOLEAN)HMAC_Final (Ctx, HmacValue, &Length); + if (!RetVal) { + goto Done; + } + +Done: + HMAC_CTX_free (Ctx); + + return RetVal; +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha256New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha256New ( + VOID + ) +{ + return HmacMdNew (); +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha256Free ( + IN VOID *HmacSha256Ctx + ) +{ + HmacMdFree (HmacSha256Ctx); +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha256Update(). + + If HmacSha256Context is NULL, then return FALSE. + + @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + +**/ +BOOLEAN +EFIAPI +HmacSha256SetKey ( + OUT VOID *HmacSha256Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + return HmacMdSetKey (EVP_sha256 (), HmacSha256Context, Key, KeySize); +} + +/** + Makes a copy of an existing HMAC-SHA256 context. + + If HmacSha256Context is NULL, then return FALSE. + If NewHmacSha256Context is NULL, then return FALSE. + + @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. + @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. + + @retval TRUE HMAC-SHA256 context copy succeeded. + @retval FALSE HMAC-SHA256 context copy failed. + +**/ +BOOLEAN +EFIAPI +HmacSha256Duplicate ( + IN CONST VOID *HmacSha256Context, + OUT VOID *NewHmacSha256Context + ) +{ + return HmacMdDuplicate (HmacSha256Context, NewHmacSha256Context); +} + +/** + Digests the input data and updates HMAC-SHA256 context. + + This function performs HMAC-SHA256 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA256 context should be initialized by HmacSha256New(), and should not be finalized + by HmacSha256Final(). Behavior with invalid context is undefined. + + If HmacSha256Context is NULL, then return FALSE. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA256 data digest succeeded. + @retval FALSE HMAC-SHA256 data digest failed. + +**/ +BOOLEAN +EFIAPI +HmacSha256Update ( + IN OUT VOID *HmacSha256Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + return HmacMdUpdate (HmacSha256Context, Data, DataSize); +} + +/** + Completes computation of the HMAC-SHA256 digest value. + + This function completes HMAC-SHA256 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA256 context cannot + be used again. + HMAC-SHA256 context should be initialized by HmacSha256New(), and should not be finalized + by HmacSha256Final(). Behavior with invalid HMAC-SHA256 context is undefined. + + If HmacSha256Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + +**/ +BOOLEAN +EFIAPI +HmacSha256Final ( + IN OUT VOID *HmacSha256Context, + OUT UINT8 *HmacValue + ) +{ + return HmacMdFinal (HmacSha256Context, HmacValue); +} + +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + return HmacMdAll (EVP_sha256 (), Data, DataSize, Key, KeySize, HmacValue); +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha384New ( + VOID + ) +{ + return HmacMdNew (); +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha384Free ( + IN VOID *HmacSha384Ctx + ) +{ + HmacMdFree (HmacSha384Ctx); +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + return HmacMdSetKey (EVP_sha384 (), HmacSha384Context, Key, KeySize); +} + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ) +{ + return HmacMdDuplicate (HmacSha384Context, NewHmacSha384Context); +} + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + return HmacMdUpdate (HmacSha384Context, Data, DataSize); +} + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ) +{ + return HmacMdFinal (HmacSha384Context, HmacValue); +} + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + return HmacMdAll (EVP_sha384 (), Data, DataSize, Key, KeySize, HmacValue); +} diff --git a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacNull.c b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacNull.c new file mode 100644 index 0000000000..0a76db41ec --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacNull.c @@ -0,0 +1,359 @@ +/** @file + HMAC-SHA256/SHA384 Wrapper Implementation which does not provide real capabilities. + +Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. + + Return NULL to indicate this interface is not supported. + + @return NULL This interface is not supported.. + +**/ +VOID * +EFIAPI +HmacSha256New ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified HMAC_CTX context. + + This function will do nothing. + + @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha256Free ( + IN VOID *HmacSha256Ctx + ) +{ + ASSERT (FALSE); + return; +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha256Update(). + + Return FALSE to indicate this interface is not supported. + + @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256SetKey ( + OUT VOID *HmacSha256Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Makes a copy of an existing HMAC-SHA256 context. + + Return FALSE to indicate this interface is not supported. + + @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. + @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Duplicate ( + IN CONST VOID *HmacSha256Context, + OUT VOID *NewHmacSha256Context + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Digests the input data and updates HMAC-SHA256 context. + + Return FALSE to indicate this interface is not supported. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Update ( + IN OUT VOID *HmacSha256Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Completes computation of the HMAC-SHA256 digest value. + + Return FALSE to indicate this interface is not supported. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Final ( + IN OUT VOID *HmacSha256Context, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha384New ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha384Free ( + IN VOID *HmacSha384Ctx + ) +{ + ASSERT (FALSE); + return; +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256.c b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256.c deleted file mode 100644 index 7e83551c1b..0000000000 --- a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256.c +++ /dev/null @@ -1,217 +0,0 @@ -/** @file - HMAC-SHA256 Wrapper Implementation over OpenSSL. - -Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "InternalCryptLib.h" -#include - -/** - Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. - - @return Pointer to the HMAC_CTX context that has been initialized. - If the allocations fails, HmacSha256New() returns NULL. - -**/ -VOID * -EFIAPI -HmacSha256New ( - VOID - ) -{ - // - // Allocates & Initializes HMAC_CTX Context by OpenSSL HMAC_CTX_new() - // - return (VOID *)HMAC_CTX_new (); -} - -/** - Release the specified HMAC_CTX context. - - @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. - -**/ -VOID -EFIAPI -HmacSha256Free ( - IN VOID *HmacSha256Ctx - ) -{ - // - // Free OpenSSL HMAC_CTX Context - // - HMAC_CTX_free ((HMAC_CTX *)HmacSha256Ctx); -} - -/** - Set user-supplied key for subsequent use. It must be done before any - calling to HmacSha256Update(). - - If HmacSha256Context is NULL, then return FALSE. - - @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. - @param[in] Key Pointer to the user-supplied key. - @param[in] KeySize Key size in bytes. - - @retval TRUE The Key is set successfully. - @retval FALSE The Key is set unsuccessfully. - -**/ -BOOLEAN -EFIAPI -HmacSha256SetKey ( - OUT VOID *HmacSha256Context, - IN CONST UINT8 *Key, - IN UINTN KeySize - ) -{ - // - // Check input parameters. - // - if ((HmacSha256Context == NULL) || (KeySize > INT_MAX)) { - return FALSE; - } - - if (HMAC_Init_ex ((HMAC_CTX *)HmacSha256Context, Key, (UINT32)KeySize, EVP_sha256 (), NULL) != 1) { - return FALSE; - } - - return TRUE; -} - -/** - Makes a copy of an existing HMAC-SHA256 context. - - If HmacSha256Context is NULL, then return FALSE. - If NewHmacSha256Context is NULL, then return FALSE. - - @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. - @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. - - @retval TRUE HMAC-SHA256 context copy succeeded. - @retval FALSE HMAC-SHA256 context copy failed. - -**/ -BOOLEAN -EFIAPI -HmacSha256Duplicate ( - IN CONST VOID *HmacSha256Context, - OUT VOID *NewHmacSha256Context - ) -{ - // - // Check input parameters. - // - if ((HmacSha256Context == NULL) || (NewHmacSha256Context == NULL)) { - return FALSE; - } - - if (HMAC_CTX_copy ((HMAC_CTX *)NewHmacSha256Context, (HMAC_CTX *)HmacSha256Context) != 1) { - return FALSE; - } - - return TRUE; -} - -/** - Digests the input data and updates HMAC-SHA256 context. - - This function performs HMAC-SHA256 digest on a data buffer of the specified size. - It can be called multiple times to compute the digest of long or discontinuous data streams. - HMAC-SHA256 context should be initialized by HmacSha256New(), and should not be finalized - by HmacSha256Final(). Behavior with invalid context is undefined. - - If HmacSha256Context is NULL, then return FALSE. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[in] Data Pointer to the buffer containing the data to be digested. - @param[in] DataSize Size of Data buffer in bytes. - - @retval TRUE HMAC-SHA256 data digest succeeded. - @retval FALSE HMAC-SHA256 data digest failed. - -**/ -BOOLEAN -EFIAPI -HmacSha256Update ( - IN OUT VOID *HmacSha256Context, - IN CONST VOID *Data, - IN UINTN DataSize - ) -{ - // - // Check input parameters. - // - if (HmacSha256Context == NULL) { - return FALSE; - } - - // - // Check invalid parameters, in case that only DataLength was checked in OpenSSL - // - if ((Data == NULL) && (DataSize != 0)) { - return FALSE; - } - - // - // OpenSSL HMAC-SHA256 digest update - // - if (HMAC_Update ((HMAC_CTX *)HmacSha256Context, Data, DataSize) != 1) { - return FALSE; - } - - return TRUE; -} - -/** - Completes computation of the HMAC-SHA256 digest value. - - This function completes HMAC-SHA256 hash computation and retrieves the digest value into - the specified memory. After this function has been called, the HMAC-SHA256 context cannot - be used again. - HMAC-SHA256 context should be initialized by HmacSha256New(), and should not be finalized - by HmacSha256Final(). Behavior with invalid HMAC-SHA256 context is undefined. - - If HmacSha256Context is NULL, then return FALSE. - If HmacValue is NULL, then return FALSE. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest - value (32 bytes). - - @retval TRUE HMAC-SHA256 digest computation succeeded. - @retval FALSE HMAC-SHA256 digest computation failed. - -**/ -BOOLEAN -EFIAPI -HmacSha256Final ( - IN OUT VOID *HmacSha256Context, - OUT UINT8 *HmacValue - ) -{ - UINT32 Length; - - // - // Check input parameters. - // - if ((HmacSha256Context == NULL) || (HmacValue == NULL)) { - return FALSE; - } - - // - // OpenSSL HMAC-SHA256 digest finalization - // - if (HMAC_Final ((HMAC_CTX *)HmacSha256Context, HmacValue, &Length) != 1) { - return FALSE; - } - - if (HMAC_CTX_reset ((HMAC_CTX *)HmacSha256Context) != 1) { - return FALSE; - } - - return TRUE; -} diff --git a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256Null.c b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256Null.c deleted file mode 100644 index 2e3cb3bdfe..0000000000 --- a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmacSha256Null.c +++ /dev/null @@ -1,139 +0,0 @@ -/** @file - HMAC-SHA256 Wrapper Implementation which does not provide real capabilities. - -Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "InternalCryptLib.h" - -/** - Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. - - Return NULL to indicate this interface is not supported. - - @return NULL This interface is not supported.. - -**/ -VOID * -EFIAPI -HmacSha256New ( - VOID - ) -{ - ASSERT (FALSE); - return NULL; -} - -/** - Release the specified HMAC_CTX context. - - This function will do nothing. - - @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. - -**/ -VOID -EFIAPI -HmacSha256Free ( - IN VOID *HmacSha256Ctx - ) -{ - ASSERT (FALSE); - return; -} - -/** - Set user-supplied key for subsequent use. It must be done before any - calling to HmacSha256Update(). - - Return FALSE to indicate this interface is not supported. - - @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. - @param[in] Key Pointer to the user-supplied key. - @param[in] KeySize Key size in bytes. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256SetKey ( - OUT VOID *HmacSha256Context, - IN CONST UINT8 *Key, - IN UINTN KeySize - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Makes a copy of an existing HMAC-SHA256 context. - - Return FALSE to indicate this interface is not supported. - - @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. - @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Duplicate ( - IN CONST VOID *HmacSha256Context, - OUT VOID *NewHmacSha256Context - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Digests the input data and updates HMAC-SHA256 context. - - Return FALSE to indicate this interface is not supported. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[in] Data Pointer to the buffer containing the data to be digested. - @param[in] DataSize Size of Data buffer in bytes. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Update ( - IN OUT VOID *HmacSha256Context, - IN CONST VOID *Data, - IN UINTN DataSize - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Completes computation of the HMAC-SHA256 digest value. - - Return FALSE to indicate this interface is not supported. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest - value (32 bytes). - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Final ( - IN OUT VOID *HmacSha256Context, - OUT UINT8 *HmacValue - ) -{ - ASSERT (FALSE); - return FALSE; -} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacNull.c b/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacNull.c new file mode 100644 index 0000000000..0a76db41ec --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacNull.c @@ -0,0 +1,359 @@ +/** @file + HMAC-SHA256/SHA384 Wrapper Implementation which does not provide real capabilities. + +Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. + + Return NULL to indicate this interface is not supported. + + @return NULL This interface is not supported.. + +**/ +VOID * +EFIAPI +HmacSha256New ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified HMAC_CTX context. + + This function will do nothing. + + @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha256Free ( + IN VOID *HmacSha256Ctx + ) +{ + ASSERT (FALSE); + return; +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha256Update(). + + Return FALSE to indicate this interface is not supported. + + @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256SetKey ( + OUT VOID *HmacSha256Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Makes a copy of an existing HMAC-SHA256 context. + + Return FALSE to indicate this interface is not supported. + + @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. + @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Duplicate ( + IN CONST VOID *HmacSha256Context, + OUT VOID *NewHmacSha256Context + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Digests the input data and updates HMAC-SHA256 context. + + Return FALSE to indicate this interface is not supported. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Update ( + IN OUT VOID *HmacSha256Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Completes computation of the HMAC-SHA256 digest value. + + Return FALSE to indicate this interface is not supported. + + @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256Final ( + IN OUT VOID *HmacSha256Context, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha384New ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha384Free ( + IN VOID *HmacSha384Ctx + ) +{ + ASSERT (FALSE); + return; +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacSha256Null.c b/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacSha256Null.c deleted file mode 100644 index 2e3cb3bdfe..0000000000 --- a/CryptoPkg/Library/BaseCryptLibNull/Hmac/CryptHmacSha256Null.c +++ /dev/null @@ -1,139 +0,0 @@ -/** @file - HMAC-SHA256 Wrapper Implementation which does not provide real capabilities. - -Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "InternalCryptLib.h" - -/** - Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA256 use. - - Return NULL to indicate this interface is not supported. - - @return NULL This interface is not supported.. - -**/ -VOID * -EFIAPI -HmacSha256New ( - VOID - ) -{ - ASSERT (FALSE); - return NULL; -} - -/** - Release the specified HMAC_CTX context. - - This function will do nothing. - - @param[in] HmacSha256Ctx Pointer to the HMAC_CTX context to be released. - -**/ -VOID -EFIAPI -HmacSha256Free ( - IN VOID *HmacSha256Ctx - ) -{ - ASSERT (FALSE); - return; -} - -/** - Set user-supplied key for subsequent use. It must be done before any - calling to HmacSha256Update(). - - Return FALSE to indicate this interface is not supported. - - @param[out] HmacSha256Context Pointer to HMAC-SHA256 context. - @param[in] Key Pointer to the user-supplied key. - @param[in] KeySize Key size in bytes. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256SetKey ( - OUT VOID *HmacSha256Context, - IN CONST UINT8 *Key, - IN UINTN KeySize - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Makes a copy of an existing HMAC-SHA256 context. - - Return FALSE to indicate this interface is not supported. - - @param[in] HmacSha256Context Pointer to HMAC-SHA256 context being copied. - @param[out] NewHmacSha256Context Pointer to new HMAC-SHA256 context. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Duplicate ( - IN CONST VOID *HmacSha256Context, - OUT VOID *NewHmacSha256Context - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Digests the input data and updates HMAC-SHA256 context. - - Return FALSE to indicate this interface is not supported. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[in] Data Pointer to the buffer containing the data to be digested. - @param[in] DataSize Size of Data buffer in bytes. - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Update ( - IN OUT VOID *HmacSha256Context, - IN CONST VOID *Data, - IN UINTN DataSize - ) -{ - ASSERT (FALSE); - return FALSE; -} - -/** - Completes computation of the HMAC-SHA256 digest value. - - Return FALSE to indicate this interface is not supported. - - @param[in, out] HmacSha256Context Pointer to the HMAC-SHA256 context. - @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest - value (32 bytes). - - @retval FALSE This interface is not supported. - -**/ -BOOLEAN -EFIAPI -HmacSha256Final ( - IN OUT VOID *HmacSha256Context, - OUT UINT8 *HmacValue - ) -{ - ASSERT (FALSE); - return FALSE; -} From 8adbbc9e4fbcd223f7f97aa7b5bd5063f5c5838f Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 09:14:50 +0800 Subject: [PATCH 0040/1529] CryptoPkg: Update CryptLib inf as the file name changed. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4025 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 3d7b917103..2a9664ad3e 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -35,7 +35,7 @@ Hash/CryptSha512.c Hash/CryptSm3.c Hash/CryptParallelHashNull.c - Hmac/CryptHmacSha256.c + Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 01de27e037..f88f8312f6 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -41,7 +41,7 @@ Hash/CryptSm3.c Hash/CryptSha512.c Hash/CryptParallelHashNull.c - Hmac/CryptHmacSha256.c + Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAesNull.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index d28fb98b66..9213952701 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -41,7 +41,7 @@ Hash/CryptSm3.c Hash/CryptSha512.c Hash/CryptParallelHashNull.c - Hmac/CryptHmacSha256.c + Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf index 070b44447e..0b1dd31c41 100644 --- a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf @@ -34,7 +34,7 @@ Hash/CryptSha256Null.c Hash/CryptSm3Null.c Hash/CryptParallelHashNull.c - Hmac/CryptHmacSha256Null.c + Hmac/CryptHmacNull.c Kdf/CryptHkdfNull.c Cipher/CryptAesNull.c Pk/CryptRsaBasicNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 91a1715095..ed76520fcc 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -42,7 +42,7 @@ Hash/CryptXkcp.c Hash/CryptCShake256.c Hash/CryptParallelHash.c - Hmac/CryptHmacSha256.c + Hmac/CryptHmac.c Kdf/CryptHkdfNull.c Cipher/CryptAes.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf index 63d1d82d19..728e0793ac 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +++ b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf @@ -35,7 +35,7 @@ Hash/CryptSha512Null.c Hash/CryptSm3Null.c Hash/CryptParallelHashNull.c - Hmac/CryptHmacSha256Null.c + Hmac/CryptHmacNull.c Kdf/CryptHkdfNull.c Cipher/CryptAesNull.c Pk/CryptRsaBasicNull.c From 05187537b9a2a3be9d9a274bdb5bdbac71ee405e Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 09:14:51 +0800 Subject: [PATCH 0041/1529] CryptoPkg: Add new hmac SHA api to Crypto Service. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4025 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 3 + CryptoPkg/Driver/Crypto.c | 224 +++++++++++++++++- .../BaseCryptLibOnProtocolPpi/CryptLib.c | 212 +++++++++++++++++ 3 files changed, 438 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 50e7721f25..417804f64f 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -147,6 +147,7 @@ !if $(CRYPTO_SERVICES) IN "PACKAGE ALL" gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Md5.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Dh.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -172,6 +173,7 @@ !if $(CRYPTO_SERVICES) == MIN_PEI gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -186,6 +188,7 @@ !if $(CRYPTO_SERVICES) == MIN_DXE_MIN_SMM gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs1v2Encrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs7Verify | TRUE diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index 76cb9f4da0..d99be08022 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -1847,6 +1847,218 @@ CryptoServiceHmacSha256Final ( return CALL_BASECRYPTLIB (HmacSha256.Services.Final, HmacSha256Final, (HmacSha256Context, HmacValue), FALSE); } +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + return CALL_BASECRYPTLIB (HmacSha256.Services.All, HmacSha256All, (Data, DataSize, Key, KeySize, HmacValue), FALSE); +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +CryptoServiceHmacSha384New ( + VOID + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.New, HmacSha384New, (), NULL); +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +CryptoServiceHmacSha384Free ( + IN VOID *HmacSha384Ctx + ) +{ + CALL_VOID_BASECRYPTLIB (HmacSha384.Services.Free, HmacSha384Free, (HmacSha384Ctx)); +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.SetKey, HmacSha384SetKey, (HmacSha384Context, Key, KeySize), FALSE); +} + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.Duplicate, HmacSha256Duplicate, (HmacSha384Context, NewHmacSha384Context), FALSE); +} + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.Update, HmacSha384Update, (HmacSha384Context, Data, DataSize), FALSE); +} + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.Final, HmacSha384Final, (HmacSha384Context, HmacValue), FALSE); +} + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + return CALL_BASECRYPTLIB (HmacSha384.Services.All, HmacSha384All, (Data, DataSize, Key, KeySize, HmacValue), FALSE); +} + // ===================================================================================== // Symmetric Cryptography Primitive // ===================================================================================== @@ -4787,5 +4999,15 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceRsaPssSign, CryptoServiceRsaPssVerify, /// Parallel hash - CryptoServiceParallelHash256HashAll + CryptoServiceParallelHash256HashAll, + /// HMAC SHA256 (continued) + CryptoServiceHmacSha256All, + /// HMAC SHA384 + CryptoServiceHmacSha384New, + CryptoServiceHmacSha384Free, + CryptoServiceHmacSha384SetKey, + CryptoServiceHmacSha384Duplicate, + CryptoServiceHmacSha384Update, + CryptoServiceHmacSha384Final, + CryptoServiceHmacSha384All }; diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 8ee1b53cf9..0218e9b594 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -1201,6 +1201,218 @@ HmacSha256Final ( CALL_CRYPTO_SERVICE (HmacSha256Final, (HmacSha256Context, HmacValue), FALSE); } +/** + Computes the HMAC-SHA256 digest of a input data buffer. + + This function performs the HMAC-SHA256 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA256 digest + value (32 bytes). + + @retval TRUE HMAC-SHA256 digest computation succeeded. + @retval FALSE HMAC-SHA256 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha256All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + CALL_CRYPTO_SERVICE (HmacSha256All, (Data, DataSize, Key, KeySize, HmacValue), FALSE); +} + +/** + Allocates and initializes one HMAC_CTX context for subsequent HMAC-SHA384 use. + + @return Pointer to the HMAC_CTX context that has been initialized. + If the allocations fails, HmacSha384New() returns NULL. + +**/ +VOID * +EFIAPI +HmacSha384New ( + VOID + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384New, (), NULL); +} + +/** + Release the specified HMAC_CTX context. + + @param[in] HmacSha384Ctx Pointer to the HMAC_CTX context to be released. + +**/ +VOID +EFIAPI +HmacSha384Free ( + IN VOID *HmacSha384Ctx + ) +{ + CALL_VOID_CRYPTO_SERVICE (HmacSha384Free, (HmacSha384Ctx)); +} + +/** + Set user-supplied key for subsequent use. It must be done before any + calling to HmacSha384Update(). + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[out] HmacSha384Context Pointer to HMAC-SHA384 context. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + + @retval TRUE The Key is set successfully. + @retval FALSE The Key is set unsuccessfully. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384SetKey ( + OUT VOID *HmacSha384Context, + IN CONST UINT8 *Key, + IN UINTN KeySize + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384SetKey, (HmacSha384Context, Key, KeySize), FALSE); +} + +/** + Makes a copy of an existing HMAC-SHA384 context. + + If HmacSha384Context is NULL, then return FALSE. + If NewHmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] HmacSha384Context Pointer to HMAC-SHA384 context being copied. + @param[out] NewHmacSha384Context Pointer to new HMAC-SHA384 context. + + @retval TRUE HMAC-SHA384 context copy succeeded. + @retval FALSE HMAC-SHA384 context copy failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Duplicate ( + IN CONST VOID *HmacSha384Context, + OUT VOID *NewHmacSha384Context + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384Duplicate, (HmacSha384Context, NewHmacSha384Context), FALSE); +} + +/** + Digests the input data and updates HMAC-SHA384 context. + + This function performs HMAC-SHA384 digest on a data buffer of the specified size. + It can be called multiple times to compute the digest of long or discontinuous data streams. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + + @retval TRUE HMAC-SHA384 data digest succeeded. + @retval FALSE HMAC-SHA384 data digest failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Update ( + IN OUT VOID *HmacSha384Context, + IN CONST VOID *Data, + IN UINTN DataSize + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384Update, (HmacSha384Context, Data, DataSize), FALSE); +} + +/** + Completes computation of the HMAC-SHA384 digest value. + + This function completes HMAC-SHA384 hash computation and retrieves the digest value into + the specified memory. After this function has been called, the HMAC-SHA384 context cannot + be used again. + HMAC-SHA384 context should be initialized by HmacSha384New(), and should not be finalized + by HmacSha384Final(). Behavior with invalid HMAC-SHA384 context is undefined. + + If HmacSha384Context is NULL, then return FALSE. + If HmacValue is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in, out] HmacSha384Context Pointer to the HMAC-SHA384 context. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384Final ( + IN OUT VOID *HmacSha384Context, + OUT UINT8 *HmacValue + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384Final, (HmacSha384Context, HmacValue), FALSE); +} + +/** + Computes the HMAC-SHA384 digest of a input data buffer. + + This function performs the HMAC-SHA384 digest of a given data buffer, and places + the digest value into the specified memory. + + If this interface is not supported, then return FALSE. + + @param[in] Data Pointer to the buffer containing the data to be digested. + @param[in] DataSize Size of Data buffer in bytes. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[out] HmacValue Pointer to a buffer that receives the HMAC-SHA384 digest + value (48 bytes). + + @retval TRUE HMAC-SHA384 digest computation succeeded. + @retval FALSE HMAC-SHA384 digest computation failed. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +HmacSha384All ( + IN CONST VOID *Data, + IN UINTN DataSize, + IN CONST UINT8 *Key, + IN UINTN KeySize, + OUT UINT8 *HmacValue + ) +{ + CALL_CRYPTO_SERVICE (HmacSha384All, (Data, DataSize, Key, KeySize, HmacValue), FALSE); +} + // ===================================================================================== // Symmetric Cryptography Primitive // ===================================================================================== From 7e89bb0f6a3826d99c706e1c555cd5e8a104019f Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 09:14:52 +0800 Subject: [PATCH 0042/1529] CryptoPkg: add Hmac Sha384 to host UnitTest. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4025 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../BaseCryptLib/UnitTestHostBaseCryptLib.inf | 2 +- .../UnitTest/Library/BaseCryptLib/HmacTests.c | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf index 11ff1c6931..63282dc5ab 100644 --- a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf @@ -28,7 +28,7 @@ Hash/CryptSha256.c Hash/CryptSha512.c Hash/CryptSm3.c - Hmac/CryptHmacSha256.c + Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c index 595729424b..9c5b39410d 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c @@ -64,6 +64,23 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 HmacSha256Digest[] = { 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7 }; +// +// Key value for HMAC-SHA-384 validation. (From "4. Test Vectors" of IETF RFC4231) +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 HmacSha384Key[20] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b +}; + +// +// Result for HMAC-SHA-384 ("Hi There"). (From "4. Test Vectors" of IETF RFC4231) +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 HmacSha384Digest[] = { + 0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4, 0xab, 0x46, 0x90, 0x7f, + 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6, 0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, + 0xfa, 0xea, 0x9e, 0xa9, 0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6 +}; + typedef VOID * (EFIAPI *EFI_HMAC_NEW)( @@ -109,6 +126,7 @@ typedef struct { // HMAC_TEST_CONTEXT mHmacMd5TestCtx = {MD5_DIGEST_SIZE, HmacMd5New, HmacMd5SetKey, HmacMd5Update, HmacMd5Final, HmacMd5Key, sizeof(HmacMd5Key), HmacMd5Digest}; // HMAC_TEST_CONTEXT mHmacSha1TestCtx = {SHA1_DIGEST_SIZE, HmacSha1New, HmacSha1SetKey, HmacSha1Update, HmacSha1Final, HmacSha1Key, sizeof(HmacSha1Key), HmacSha1Digest}; HMAC_TEST_CONTEXT mHmacSha256TestCtx = { SHA256_DIGEST_SIZE, HmacSha256New, HmacSha256SetKey, HmacSha256Update, HmacSha256Final, HmacSha256Key, sizeof (HmacSha256Key), HmacSha256Digest }; +HMAC_TEST_CONTEXT mHmacSha384TestCtx = { SHA384_DIGEST_SIZE, HmacSha384New, HmacSha384SetKey, HmacSha384Update, HmacSha384Final, HmacSha384Key, sizeof (HmacSha384Key), HmacSha384Digest }; UNIT_TEST_STATUS EFIAPI @@ -174,6 +192,7 @@ TEST_DESC mHmacTest[] = { // -----Description---------------------Class---------------------Function---------------Pre------------------Post------------Context // { "TestVerifyHmacSha256()", "CryptoPkg.BaseCryptLib.Hmac", TestVerifyHmac, TestVerifyHmacPreReq, TestVerifyHmacCleanUp, &mHmacSha256TestCtx }, + { "TestVerifyHmacSha384()", "CryptoPkg.BaseCryptLib.Hmac", TestVerifyHmac, TestVerifyHmacPreReq, TestVerifyHmacCleanUp, &mHmacSha384TestCtx }, // These functions have been deprecated but they've been left commented out for future reference // {"TestVerifyHmacMd5()", "CryptoPkg.BaseCryptLib.Hmac", TestVerifyHmac, TestVerifyHmacPreReq, TestVerifyHmacCleanUp, &mHmacMd5TestCtx}, // {"TestVerifyHmacSha1()", "CryptoPkg.BaseCryptLib.Hmac", TestVerifyHmac, TestVerifyHmacPreReq, TestVerifyHmacCleanUp, &mHmacSha1TestCtx}, From 27c3dee87bbca8e2717f0b88c70b564039199a57 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:25:06 +0800 Subject: [PATCH 0043/1529] CryptoPkg: add new Hkdf api definition in Crypt Lib. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4033 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 129 ++++++++++++++++ .../Pcd/PcdCryptoServiceFamilyEnable.h | 7 +- CryptoPkg/Private/Protocol/Crypto.h | 139 +++++++++++++++++- 3 files changed, 273 insertions(+), 2 deletions(-) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 3a42e3494f..2a4302a052 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -2620,4 +2620,133 @@ HkdfSha256ExtractAndExpand ( IN UINTN OutSize ); +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ); + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ); + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + #endif // __BASE_CRYPT_LIB_H__ diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index e646d8ac05..5caf597421 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -245,7 +245,12 @@ typedef struct { } Sm3; union { struct { - UINT8 Sha256ExtractAndExpand; + UINT8 Sha256ExtractAndExpand : 1; + UINT8 Sha256Extract : 1; + UINT8 Sha256Expand : 1; + UINT8 Sha384ExtractAndExpand : 1; + UINT8 Sha384Extract : 1; + UINT8 Sha384Expand : 1; } Services; UINT32 Family; } Hkdf; diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index 23445cf1e8..da726e8381 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 9 +#define EDKII_CRYPTO_VERSION 10 /// /// EDK II Crypto Protocol forward declaration @@ -2770,6 +2770,137 @@ BOOLEAN IN UINTN OutSize ); +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HKDF_SHA_256_EXTRACT)( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ); + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HKDF_SHA_256_EXPAND)( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HKDF_SHA_384_EXTRACT_AND_EXPAND)( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HKDF_SHA_384_EXTRACT)( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ); + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_HKDF_SHA_384_EXPAND)( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ); + /** Initializes the OpenSSL library. @@ -3873,6 +4004,12 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_HMAC_SHA384_UPDATE HmacSha384Update; EDKII_CRYPTO_HMAC_SHA384_FINAL HmacSha384Final; EDKII_CRYPTO_HMAC_SHA384_ALL HmacSha384All; + /// HKDF (continued) + EDKII_CRYPTO_HKDF_SHA_256_EXTRACT HkdfSha256Extract; + EDKII_CRYPTO_HKDF_SHA_256_EXPAND HkdfSha256Expand; + EDKII_CRYPTO_HKDF_SHA_384_EXTRACT_AND_EXPAND HkdfSha384ExtractAndExpand; + EDKII_CRYPTO_HKDF_SHA_384_EXTRACT HkdfSha384Extract; + EDKII_CRYPTO_HKDF_SHA_384_EXPAND HkdfSha384Expand; }; extern GUID gEdkiiCryptoProtocolGuid; From 709b69bb4a9cfcf85731015c1ef3d2abd0d2c7c9 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:25:07 +0800 Subject: [PATCH 0044/1529] CryptoPkg: add new Hkdf api in Crypt Lib. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4033 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/Kdf/CryptHkdf.c | 362 +++++++++++++++++- .../Library/BaseCryptLib/Kdf/CryptHkdfNull.c | 151 +++++++- .../BaseCryptLibNull/Kdf/CryptHkdfNull.c | 151 +++++++- 3 files changed, 650 insertions(+), 14 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c index 9457b04f72..ffaf5fb131 100644 --- a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c +++ b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c @@ -1,7 +1,7 @@ /** @file HMAC-SHA256 KDF Wrapper Implementation over OpenSSL. -Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2018 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -13,6 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /** Derive HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + @param[in] Md Message Digest. @param[in] Key Pointer to the user-supplied key. @param[in] KeySize Key size in bytes. @param[in] Salt Pointer to the salt(non-secret) value. @@ -27,16 +28,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ BOOLEAN -EFIAPI -HkdfSha256ExtractAndExpand ( - IN CONST UINT8 *Key, - IN UINTN KeySize, - IN CONST UINT8 *Salt, - IN UINTN SaltSize, - IN CONST UINT8 *Info, - IN UINTN InfoSize, - OUT UINT8 *Out, - IN UINTN OutSize +HkdfMdExtractAndExpand ( + IN CONST EVP_MD *Md, + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize ) { EVP_PKEY_CTX *pHkdfCtx; @@ -55,7 +56,7 @@ HkdfSha256ExtractAndExpand ( Result = EVP_PKEY_derive_init (pHkdfCtx) > 0; if (Result) { - Result = EVP_PKEY_CTX_set_hkdf_md (pHkdfCtx, EVP_sha256 ()) > 0; + Result = EVP_PKEY_CTX_set_hkdf_md (pHkdfCtx, Md) > 0; } if (Result) { @@ -78,3 +79,340 @@ HkdfSha256ExtractAndExpand ( pHkdfCtx = NULL; return Result; } + +/** + Derive HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Md message digest. + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +HkdfMdExtract ( + IN CONST EVP_MD *Md, + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + EVP_PKEY_CTX *pHkdfCtx; + BOOLEAN Result; + + if ((Key == NULL) || (Salt == NULL) || (PrkOut == NULL) || + (KeySize > INT_MAX) || (SaltSize > INT_MAX) || + (PrkOutSize > INT_MAX)) + { + return FALSE; + } + + pHkdfCtx = EVP_PKEY_CTX_new_id (EVP_PKEY_HKDF, NULL); + if (pHkdfCtx == NULL) { + return FALSE; + } + + Result = EVP_PKEY_derive_init (pHkdfCtx) > 0; + if (Result) { + Result = EVP_PKEY_CTX_set_hkdf_md (pHkdfCtx, Md) > 0; + } + + if (Result) { + Result = + EVP_PKEY_CTX_hkdf_mode ( + pHkdfCtx, + EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY + ) > 0; + } + + if (Result) { + Result = EVP_PKEY_CTX_set1_hkdf_salt ( + pHkdfCtx, + Salt, + (uint32_t)SaltSize + ) > 0; + } + + if (Result) { + Result = EVP_PKEY_CTX_set1_hkdf_key ( + pHkdfCtx, + Key, + (uint32_t)KeySize + ) > 0; + } + + if (Result) { + Result = EVP_PKEY_derive (pHkdfCtx, PrkOut, &PrkOutSize) > 0; + } + + EVP_PKEY_CTX_free (pHkdfCtx); + pHkdfCtx = NULL; + return Result; +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Md Message Digest. + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +HkdfMdExpand ( + IN CONST EVP_MD *Md, + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + EVP_PKEY_CTX *pHkdfCtx; + BOOLEAN Result; + + if ((Prk == NULL) || (Info == NULL) || (Out == NULL) || + (PrkSize > INT_MAX) || (InfoSize > INT_MAX) || (OutSize > INT_MAX)) + { + return FALSE; + } + + pHkdfCtx = EVP_PKEY_CTX_new_id (EVP_PKEY_HKDF, NULL); + if (pHkdfCtx == NULL) { + return FALSE; + } + + Result = EVP_PKEY_derive_init (pHkdfCtx) > 0; + if (Result) { + Result = EVP_PKEY_CTX_set_hkdf_md (pHkdfCtx, Md) > 0; + } + + if (Result) { + Result = EVP_PKEY_CTX_hkdf_mode (pHkdfCtx, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) > 0; + } + + if (Result) { + Result = EVP_PKEY_CTX_set1_hkdf_key (pHkdfCtx, Prk, (UINT32)PrkSize) > 0; + } + + if (Result) { + Result = EVP_PKEY_CTX_add1_hkdf_info (pHkdfCtx, Info, (UINT32)InfoSize) > 0; + } + + if (Result) { + Result = EVP_PKEY_derive (pHkdfCtx, Out, &OutSize) > 0; + } + + EVP_PKEY_CTX_free (pHkdfCtx); + pHkdfCtx = NULL; + return Result; +} + +/** + Derive HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return HkdfMdExtractAndExpand (EVP_sha256 (), Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize); +} + +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + return HkdfMdExtract ( + EVP_sha256 (), + Key, + KeySize, + Salt, + SaltSize, + PrkOut, + PrkOutSize + ); +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return HkdfMdExpand (EVP_sha256 (), Prk, PrkSize, Info, InfoSize, Out, OutSize); +} + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return HkdfMdExtractAndExpand (EVP_sha384 (), Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize); +} + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + return HkdfMdExtract ( + EVP_sha384 (), + Key, + KeySize, + Salt, + SaltSize, + PrkOut, + PrkOutSize + ); +} + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return HkdfMdExpand (EVP_sha384 (), Prk, PrkSize, Info, InfoSize, Out, OutSize); +} diff --git a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdfNull.c b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdfNull.c index 19d795a4cc..d8c967d669 100644 --- a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdfNull.c +++ b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdfNull.c @@ -1,7 +1,7 @@ /** @file HMAC-SHA256 KDF Wrapper Implementation which does not provide real capabilities. -Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2018 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -41,3 +41,152 @@ HkdfSha256ExtractAndExpand ( ASSERT (FALSE); return FALSE; } + +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Kdf/CryptHkdfNull.c b/CryptoPkg/Library/BaseCryptLibNull/Kdf/CryptHkdfNull.c index 19d795a4cc..d8c967d669 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/Kdf/CryptHkdfNull.c +++ b/CryptoPkg/Library/BaseCryptLibNull/Kdf/CryptHkdfNull.c @@ -1,7 +1,7 @@ /** @file HMAC-SHA256 KDF Wrapper Implementation which does not provide real capabilities. -Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2018 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -41,3 +41,152 @@ HkdfSha256ExtractAndExpand ( ASSERT (FALSE); return FALSE; } + +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} From f70ba761269c09b05dbf24ef5a85cb549a7578d0 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:25:08 +0800 Subject: [PATCH 0045/1529] CryptoPkg: add new Hkdf api to Crypto Service. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4033 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/Driver/Crypto.c | 152 +++++++++++++++++- .../BaseCryptLibOnProtocolPpi/CryptLib.c | 144 +++++++++++++++++ 2 files changed, 295 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index d99be08022..b54e59fd07 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -3770,6 +3770,150 @@ CryptoServiceHkdfSha256ExtractAndExpand ( return CALL_BASECRYPTLIB (Hkdf.Services.Sha256ExtractAndExpand, HkdfSha256ExtractAndExpand, (Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize), FALSE); } +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + return CALL_BASECRYPTLIB (Hkdf.Services.Sha256Extract, HkdfSha256Extract, (Key, KeySize, Salt, SaltSize, PrkOut, PrkOutSize), FALSE); +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return CALL_BASECRYPTLIB (Hkdf.Services.Sha256Expand, HkdfSha256Expand, (Prk, PrkSize, Info, InfoSize, Out, OutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return CALL_BASECRYPTLIB (Hkdf.Services.Sha384ExtractAndExpand, HkdfSha384ExtractAndExpand, (Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + return CALL_BASECRYPTLIB (Hkdf.Services.Sha384Extract, HkdfSha384Extract, (Key, KeySize, Salt, SaltSize, PrkOut, PrkOutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceHkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + return CALL_BASECRYPTLIB (Hkdf.Services.Sha384Expand, HkdfSha384Expand, (Prk, PrkSize, Info, InfoSize, Out, OutSize), FALSE); +} + /** Initializes the OpenSSL library. @@ -5009,5 +5153,11 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceHmacSha384Duplicate, CryptoServiceHmacSha384Update, CryptoServiceHmacSha384Final, - CryptoServiceHmacSha384All + CryptoServiceHmacSha384All, + /// HKDF (continued) + CryptoServiceHkdfSha256Extract, + CryptoServiceHkdfSha256Expand, + CryptoServiceHkdfSha384ExtractAndExpand, + CryptoServiceHkdfSha384Extract, + CryptoServiceHkdfSha384Expand }; diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 0218e9b594..6a57daea6a 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -2913,6 +2913,150 @@ HkdfSha256ExtractAndExpand ( CALL_CRYPTO_SERVICE (HkdfSha256ExtractAndExpand, (Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize), FALSE); } +/** + Derive SHA256 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + CALL_CRYPTO_SERVICE (HkdfSha256Extract, (Key, KeySize, Salt, SaltSize, PrkOut, PrkOutSize), FALSE); +} + +/** + Derive SHA256 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha256Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + CALL_CRYPTO_SERVICE (HkdfSha256Expand, (Prk, PrkSize, Info, InfoSize, Out, OutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Extract-and-Expand Key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize Key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize Salt size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384ExtractAndExpand ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + CALL_CRYPTO_SERVICE (HkdfSha384ExtractAndExpand, (Key, KeySize, Salt, SaltSize, Info, InfoSize, Out, OutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Extract key Derivation Function (HKDF). + + @param[in] Key Pointer to the user-supplied key. + @param[in] KeySize key size in bytes. + @param[in] Salt Pointer to the salt(non-secret) value. + @param[in] SaltSize salt size in bytes. + @param[out] PrkOut Pointer to buffer to receive hkdf value. + @param[in] PrkOutSize size of hkdf bytes to generate. + + @retval true Hkdf generated successfully. + @retval false Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Extract ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Salt, + IN UINTN SaltSize, + OUT UINT8 *PrkOut, + UINTN PrkOutSize + ) +{ + CALL_CRYPTO_SERVICE (HkdfSha384Extract, (Key, KeySize, Salt, SaltSize, PrkOut, PrkOutSize), FALSE); +} + +/** + Derive SHA384 HMAC-based Expand Key Derivation Function (HKDF). + + @param[in] Prk Pointer to the user-supplied key. + @param[in] PrkSize Key size in bytes. + @param[in] Info Pointer to the application specific info. + @param[in] InfoSize Info size in bytes. + @param[out] Out Pointer to buffer to receive hkdf value. + @param[in] OutSize Size of hkdf bytes to generate. + + @retval TRUE Hkdf generated successfully. + @retval FALSE Hkdf generation failed. + +**/ +BOOLEAN +EFIAPI +HkdfSha384Expand ( + IN CONST UINT8 *Prk, + IN UINTN PrkSize, + IN CONST UINT8 *Info, + IN UINTN InfoSize, + OUT UINT8 *Out, + IN UINTN OutSize + ) +{ + CALL_CRYPTO_SERVICE (HkdfSha384Expand, (Prk, PrkSize, Info, InfoSize, Out, OutSize), FALSE); +} + /** Initializes the OpenSSL library. From 17fb70a9b9ed7feb74ae3ecf617f6ed50499c28d Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:25:09 +0800 Subject: [PATCH 0046/1529] CryptoPkg: add Hkdf UnitTest. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4033 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../BaseCryptLib/BaseCryptLibUnitTests.c | 29 +-- .../UnitTest/Library/BaseCryptLib/HkdfTests.c | 202 ++++++++++++++++++ .../Library/BaseCryptLib/TestBaseCryptLib.h | 3 + .../BaseCryptLib/TestBaseCryptLibHost.inf | 1 + .../BaseCryptLib/TestBaseCryptLibShell.inf | 1 + 5 files changed, 222 insertions(+), 14 deletions(-) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HkdfTests.c diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c index 3c57aead1e..dc81143b43 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c @@ -11,20 +11,21 @@ SUITE_DESC mSuiteDesc[] = { // // Title--------------------------Package-------------------Sup--Tdn----TestNum------------TestDesc // - { "EKU verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs7EkuTestNum, mPkcs7EkuTest }, - { "HASH verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHashTestNum, mHashTest }, - { "HMAC verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHmacTestNum, mHmacTest }, - { "BlockCipher verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mBlockCipherTestNum, mBlockCipherTest }, - { "RSA verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaTestNum, mRsaTest }, - { "RSA PSS verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaPssTestNum, mRsaPssTest }, - { "RSACert verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaCertTestNum, mRsaCertTest }, - { "PKCS7 verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs7TestNum, mPkcs7Test }, - { "PKCS5 verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs5TestNum, mPkcs5Test }, - { "Authenticode verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAuthenticodeTestNum, mAuthenticodeTest }, - { "ImageTimestamp verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mImageTimestampTestNum, mImageTimestampTest }, - { "DH verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mDhTestNum, mDhTest }, - { "PRNG verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPrngTestNum, mPrngTest }, - { "OAEP encrypt verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mOaepTestNum, mOaepTest }, + { "EKU verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs7EkuTestNum, mPkcs7EkuTest }, + { "HASH verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHashTestNum, mHashTest }, + { "HMAC verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHmacTestNum, mHmacTest }, + { "BlockCipher verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mBlockCipherTestNum, mBlockCipherTest }, + { "RSA verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaTestNum, mRsaTest }, + { "RSA PSS verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaPssTestNum, mRsaPssTest }, + { "RSACert verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mRsaCertTestNum, mRsaCertTest }, + { "PKCS7 verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs7TestNum, mPkcs7Test }, + { "PKCS5 verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPkcs5TestNum, mPkcs5Test }, + { "Authenticode verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAuthenticodeTestNum, mAuthenticodeTest }, + { "ImageTimestamp verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mImageTimestampTestNum, mImageTimestampTest }, + { "DH verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mDhTestNum, mDhTest }, + { "PRNG verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPrngTestNum, mPrngTest }, + { "OAEP encrypt verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mOaepTestNum, mOaepTest }, + { "Hkdf extract and expand tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHkdfTestNum, mHkdfTest }, }; EFI_STATUS diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HkdfTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HkdfTests.c new file mode 100644 index 0000000000..bb2b5ea1b8 --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HkdfTests.c @@ -0,0 +1,202 @@ +/** @file + Application for Hkdf Primitives Validation. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "TestBaseCryptLib.h" + +/** + * HKDF KAT from RFC 5869 Appendix A. Test Vectors + * https://www.rfc-editor.org/rfc/rfc5869.html + **/ +UINT8 mHkdfSha256Ikm[22] = { + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b +}; + +UINT8 mHkdfSha256Salt[13] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0x0c, +}; + +UINT8 mHkdfSha256Info[10] = { + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, +}; + +UINT8 mHkdfSha256Prk[32] = { + 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, + 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, + 0xb5, 0x0f, 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, + 0xb3, 0xe5, +}; + +UINT8 mHkdfSha256Okm[42] = { + 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, + 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, + 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, + 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, + 0x58, 0x65, +}; + +/** + * This Hkdf-Sha384 test vector is form Project Wycheproof + * developed and maintained by members of Google Security Team. + * https://github.com/google/wycheproof/blob/master/testvectors/hkdf_sha384_test.json + **/ +UINT8 mHkdfSha384Ikm[16] = { + 0x86, 0x77, 0xdc, 0x79, 0x23, 0x3e, 0xf3, 0x48, 0x07, 0x77, + 0xc4, 0xc6, 0x01, 0xef, 0x4f, 0x0b, +}; + +UINT8 mHkdfSha384Salt[16] = { + 0xad, 0x88, 0xdb, 0x71, 0x82, 0x44, 0xe2, 0xcb, 0x60, 0xe3, + 0x5f, 0x87, 0x4d, 0x7a, 0xd8, 0x1f, +}; + +UINT8 mHkdfSha384Info[20] = { + 0xa3, 0x8f, 0x63, 0x4d, 0x94, 0x78, 0x19, 0xa9, 0xbf, 0xa7, + 0x92, 0x17, 0x4b, 0x42, 0xba, 0xa2, 0x0c, 0x9f, 0xce, 0x15, +}; + +UINT8 mHkdfSha384Prk[48] = { + 0x60, 0xae, 0xa0, 0xde, 0xca, 0x97, 0x62, 0xaa, 0x43, 0xaf, + 0x0e, 0x77, 0xa8, 0x0f, 0xb7, 0x76, 0xd0, 0x08, 0x19, 0x62, + 0xf8, 0x30, 0xb5, 0x0d, 0x92, 0x08, 0x92, 0x7a, 0x8a, 0xd5, + 0x6a, 0x3d, 0xc4, 0x4a, 0x5d, 0xfe, 0xb6, 0xb4, 0x79, 0x2f, + 0x97, 0x92, 0x71, 0xe6, 0xcb, 0x08, 0x86, 0x52, +}; + +UINT8 mHkdfSha384Okm[64] = { + 0x75, 0x85, 0x46, 0x36, 0x2a, 0x07, 0x0c, 0x0f, 0x13, 0xcb, + 0xfb, 0xf1, 0x75, 0x6e, 0x8f, 0x29, 0xb7, 0x81, 0x9f, 0xb9, + 0x03, 0xc7, 0xed, 0x4f, 0x97, 0xa5, 0x6b, 0xe3, 0xc8, 0xf8, + 0x1e, 0x8c, 0x37, 0xae, 0xf5, 0xc0, 0xf8, 0xe5, 0xd2, 0xb1, + 0x7e, 0xb1, 0xaa, 0x02, 0xec, 0x04, 0xc3, 0x3f, 0x54, 0x6c, + 0xb2, 0xf3, 0xd1, 0x93, 0xe9, 0x30, 0xa9, 0xf8, 0x9e, 0xc9, + 0xce, 0x3a, 0x82, 0xb5 +}; + +UNIT_TEST_STATUS +EFIAPI +TestVerifyHkdfSha256 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + UINT8 PrkOut[32]; + UINT8 Out[42]; + BOOLEAN Status; + + /* HKDF-SHA-256 digest Validation*/ + + ZeroMem (PrkOut, sizeof (PrkOut)); + Status = HkdfSha256Extract ( + mHkdfSha256Ikm, + sizeof (mHkdfSha256Ikm), + mHkdfSha256Salt, + sizeof (mHkdfSha256Salt), + PrkOut, + sizeof (PrkOut) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (PrkOut, mHkdfSha256Prk, sizeof (mHkdfSha256Prk)); + + ZeroMem (Out, sizeof (Out)); + Status = HkdfSha256Expand ( + mHkdfSha256Prk, + sizeof (mHkdfSha256Prk), + mHkdfSha256Info, + sizeof (mHkdfSha256Info), + Out, + sizeof (Out) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (Out, mHkdfSha256Okm, sizeof (mHkdfSha256Okm)); + + ZeroMem (Out, sizeof (Out)); + Status = HkdfSha256ExtractAndExpand ( + mHkdfSha256Ikm, + sizeof (mHkdfSha256Ikm), + mHkdfSha256Salt, + sizeof (mHkdfSha256Salt), + mHkdfSha256Info, + sizeof (mHkdfSha256Info), + Out, + sizeof (Out) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (Out, mHkdfSha256Okm, sizeof (mHkdfSha256Okm)); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestVerifyHkdfSha384 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + UINT8 PrkOut[48]; + UINT8 Out[64]; + BOOLEAN Status; + + /* HKDF-SHA-384 digest Validation*/ + ZeroMem (PrkOut, sizeof (PrkOut)); + Status = HkdfSha384Extract ( + mHkdfSha384Ikm, + sizeof (mHkdfSha384Ikm), + mHkdfSha384Salt, + sizeof (mHkdfSha384Salt), + PrkOut, + sizeof (PrkOut) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (PrkOut, mHkdfSha384Prk, sizeof (mHkdfSha384Prk)); + + ZeroMem (Out, sizeof (Out)); + Status = HkdfSha384Expand ( + mHkdfSha384Prk, + sizeof (mHkdfSha384Prk), + mHkdfSha384Info, + sizeof (mHkdfSha384Info), + Out, + sizeof (Out) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (Out, mHkdfSha384Okm, sizeof (mHkdfSha384Okm)); + + ZeroMem (Out, sizeof (Out)); + Status = HkdfSha384ExtractAndExpand ( + mHkdfSha384Ikm, + sizeof (mHkdfSha384Ikm), + mHkdfSha384Salt, + sizeof (mHkdfSha384Salt), + mHkdfSha384Info, + sizeof (mHkdfSha384Info), + Out, + sizeof (Out) + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_MEM_EQUAL (Out, mHkdfSha384Okm, sizeof (mHkdfSha384Okm)); + + return UNIT_TEST_PASSED; +} + +TEST_DESC mHkdfTest[] = { + // + // -----Description--------------------------------------Class----------------------Function---------------------------------Pre---------------------Post---------Context + // + { "TestVerifyHkdfSha256()", "CryptoPkg.BaseCryptLib.Hkdf", TestVerifyHkdfSha256, NULL, NULL, NULL }, + { "TestVerifyHkdfSha384()", "CryptoPkg.BaseCryptLib.Hkdf", TestVerifyHkdfSha384, NULL, NULL, NULL }, +}; + +UINTN mHkdfTestNum = ARRAY_SIZE (mHkdfTest); diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h index a6b3482742..b3aff86570 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h @@ -86,6 +86,9 @@ extern TEST_DESC mOaepTest[]; extern UINTN mRsaPssTestNum; extern TEST_DESC mRsaPssTest[]; +extern UINTN mHkdfTestNum; +extern TEST_DESC mHkdfTest[]; + /** Creates a framework you can use */ EFI_STATUS EFIAPI diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf index 399db596c2..e51877bded 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf @@ -37,6 +37,7 @@ OaepEncryptTests.c RsaPssTests.c ParallelhashTests.c + HkdfTests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf index ca789aa6ad..81469f48e7 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf @@ -36,6 +36,7 @@ Pkcs7EkuTests.c OaepEncryptTests.c RsaPssTests.c + HkdfTests.c [Packages] MdePkg/MdePkg.dec From 13c43c20c669f8e6c9d6dbabf5fb8bbb3bcf7bbd Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:31:58 +0800 Subject: [PATCH 0047/1529] CryptoPkg: add AeadAesGcm function() definition. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4036 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 87 ++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 2a4302a052..9436fe0f19 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -1360,6 +1360,93 @@ AesCbcDecrypt ( OUT UINT8 *Output ); +// ===================================================================================== +// Authenticated Encryption with Associated Data (AEAD) Cryptography Primitive +// ===================================================================================== + +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ); + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ); + // ===================================================================================== // Asymmetric Cryptography Primitive // ===================================================================================== From 6a7eda962ef7ed90556bb368b23033103dc87882 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:31:59 +0800 Subject: [PATCH 0048/1529] CryptoPkg: add AeadAesGcm support. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4036 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/BaseCryptLib.inf | 1 + .../BaseCryptLib/Cipher/CryptAeadAesGcm.c | 279 ++++++++++++++++++ .../BaseCryptLib/Cipher/CryptAeadAesGcmNull.c | 100 +++++++ .../Library/BaseCryptLib/PeiCryptLib.inf | 1 + .../Library/BaseCryptLib/RuntimeCryptLib.inf | 1 + .../Library/BaseCryptLib/SmmCryptLib.inf | 1 + .../BaseCryptLibNull/BaseCryptLibNull.inf | 1 + .../Cipher/CryptAeadAesGcmNull.c | 100 +++++++ 8 files changed, 484 insertions(+) create mode 100644 CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcm.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcmNull.c create mode 100644 CryptoPkg/Library/BaseCryptLibNull/Cipher/CryptAeadAesGcmNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 2a9664ad3e..a1785f3423 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -38,6 +38,7 @@ Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c + Cipher/CryptAeadAesGcm.c Pk/CryptRsaBasic.c Pk/CryptRsaExt.c Pk/CryptPkcs1Oaep.c diff --git a/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcm.c b/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcm.c new file mode 100644 index 0000000000..b4c93d47a9 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcm.c @@ -0,0 +1,279 @@ +/** @file + AEAD (AES-GCM) Wrapper Implementation over OpenSSL. + + RFC 5116 - An Interface and Algorithms for Authenticated Encryption + NIST SP800-38d - Cipher Modes of Operation: Galois / Counter Mode(GCM) and GMAC + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" +#include +#include + +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + EVP_CIPHER_CTX *Ctx; + CONST EVP_CIPHER *Cipher; + UINTN TempOutSize; + BOOLEAN RetValue; + + if (DataInSize > INT_MAX) { + return FALSE; + } + + if (ADataSize > INT_MAX) { + return FALSE; + } + + if (IvSize != 12) { + return FALSE; + } + + switch (KeySize) { + case 16: + Cipher = EVP_aes_128_gcm (); + break; + case 24: + Cipher = EVP_aes_192_gcm (); + break; + case 32: + Cipher = EVP_aes_256_gcm (); + break; + default: + return FALSE; + } + + if ((TagSize != 12) && (TagSize != 13) && (TagSize != 14) && (TagSize != 15) && (TagSize != 16)) { + return FALSE; + } + + if (DataOutSize != NULL) { + if ((*DataOutSize > INT_MAX) || (*DataOutSize < DataInSize)) { + return FALSE; + } + } + + Ctx = EVP_CIPHER_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetValue = (BOOLEAN)EVP_EncryptInit_ex (Ctx, Cipher, NULL, NULL, NULL); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_CIPHER_CTX_ctrl (Ctx, EVP_CTRL_GCM_SET_IVLEN, (INT32)IvSize, NULL); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_EncryptInit_ex (Ctx, NULL, NULL, Key, Iv); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_EncryptUpdate (Ctx, NULL, (INT32 *)&TempOutSize, AData, (INT32)ADataSize); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_EncryptUpdate (Ctx, DataOut, (INT32 *)&TempOutSize, DataIn, (INT32)DataInSize); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_EncryptFinal_ex (Ctx, DataOut, (INT32 *)&TempOutSize); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_CIPHER_CTX_ctrl (Ctx, EVP_CTRL_GCM_GET_TAG, (INT32)TagSize, (VOID *)TagOut); + +Done: + EVP_CIPHER_CTX_free (Ctx); + if (!RetValue) { + return RetValue; + } + + if (DataOutSize != NULL) { + *DataOutSize = DataInSize; + } + + return RetValue; +} + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + EVP_CIPHER_CTX *Ctx; + CONST EVP_CIPHER *Cipher; + UINTN TempOutSize; + BOOLEAN RetValue; + + if (DataInSize > INT_MAX) { + return FALSE; + } + + if (ADataSize > INT_MAX) { + return FALSE; + } + + if (IvSize != 12) { + return FALSE; + } + + switch (KeySize) { + case 16: + Cipher = EVP_aes_128_gcm (); + break; + case 24: + Cipher = EVP_aes_192_gcm (); + break; + case 32: + Cipher = EVP_aes_256_gcm (); + break; + default: + return FALSE; + } + + if ((TagSize != 12) && (TagSize != 13) && (TagSize != 14) && (TagSize != 15) && (TagSize != 16)) { + return FALSE; + } + + if (DataOutSize != NULL) { + if ((*DataOutSize > INT_MAX) || (*DataOutSize < DataInSize)) { + return FALSE; + } + } + + Ctx = EVP_CIPHER_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetValue = (BOOLEAN)EVP_DecryptInit_ex (Ctx, Cipher, NULL, NULL, NULL); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_CIPHER_CTX_ctrl (Ctx, EVP_CTRL_GCM_SET_IVLEN, (INT32)IvSize, NULL); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_DecryptInit_ex (Ctx, NULL, NULL, Key, Iv); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_DecryptUpdate (Ctx, NULL, (INT32 *)&TempOutSize, AData, (INT32)ADataSize); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_DecryptUpdate (Ctx, DataOut, (INT32 *)&TempOutSize, DataIn, (INT32)DataInSize); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_CIPHER_CTX_ctrl (Ctx, EVP_CTRL_GCM_SET_TAG, (INT32)TagSize, (VOID *)Tag); + if (!RetValue) { + goto Done; + } + + RetValue = (BOOLEAN)EVP_DecryptFinal_ex (Ctx, DataOut, (INT32 *)&TempOutSize); + +Done: + EVP_CIPHER_CTX_free (Ctx); + if (!RetValue) { + return RetValue; + } + + if (DataOutSize != NULL) { + *DataOutSize = DataInSize; + } + + return RetValue; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcmNull.c b/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcmNull.c new file mode 100644 index 0000000000..b9f9d16ff9 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Cipher/CryptAeadAesGcmNull.c @@ -0,0 +1,100 @@ +/** @file + AEAD Wrapper Implementation which does not provide real capabilities. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" + +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index f88f8312f6..84efeb246e 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -44,6 +44,7 @@ Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAesNull.c + Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasic.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1OaepNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index 9213952701..845708bf1a 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -44,6 +44,7 @@ Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c + Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasic.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1OaepNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index ed76520fcc..c81e9d5bb4 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -45,6 +45,7 @@ Hmac/CryptHmac.c Kdf/CryptHkdfNull.c Cipher/CryptAes.c + Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasic.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1Oaep.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf index 728e0793ac..80a432dfe1 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +++ b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf @@ -38,6 +38,7 @@ Hmac/CryptHmacNull.c Kdf/CryptHkdfNull.c Cipher/CryptAesNull.c + Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasicNull.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1OaepNull.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/Cipher/CryptAeadAesGcmNull.c b/CryptoPkg/Library/BaseCryptLibNull/Cipher/CryptAeadAesGcmNull.c new file mode 100644 index 0000000000..b9f9d16ff9 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibNull/Cipher/CryptAeadAesGcmNull.c @@ -0,0 +1,100 @@ +/** @file + AEAD Wrapper Implementation which does not provide real capabilities. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" + +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + ASSERT (FALSE); + return FALSE; +} From 110b55d294574be6c85536868857656d973a5ea6 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:32:00 +0800 Subject: [PATCH 0049/1529] CryptoPkg: add AeadAesGcm to Crypto Service. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4036 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 2 + CryptoPkg/Driver/Crypto.c | 94 ++++++++++++++++++- .../Pcd/PcdCryptoServiceFamilyEnable.h | 7 ++ .../BaseCryptLibOnProtocolPpi/CryptLib.c | 93 ++++++++++++++++++ CryptoPkg/Private/Protocol/Crypto.h | 88 ++++++++++++++++- 5 files changed, 282 insertions(+), 2 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 417804f64f..79c6a4eeae 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -215,6 +215,8 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Encrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Decrypt | TRUE !endif ################################################################################################### diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index b54e59fd07..9562dfeec5 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -4938,6 +4938,95 @@ CryptoServiceParallelHash256HashAll ( return CALL_BASECRYPTLIB (ParallelHash.Services.HashAll, ParallelHash256HashAll, (Input, InputByteLen, BlockSize, Output, OutputByteLen, Customization, CustomByteLen), FALSE); } +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceAeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + return CALL_BASECRYPTLIB (AeadAesGcm.Services.Encrypt, AeadAesGcmEncrypt, (Key, KeySize, Iv, IvSize, AData, ADataSize, DataIn, DataInSize, TagOut, TagSize, DataOut, DataOutSize), FALSE); +} + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +CryptoServiceAeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + return CALL_BASECRYPTLIB (AeadAesGcm.Services.Decrypt, AeadAesGcmDecrypt, (Key, KeySize, Iv, IvSize, AData, ADataSize, DataIn, DataInSize, Tag, TagSize, DataOut, DataOutSize), FALSE); +} + const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { /// Version CryptoServiceGetCryptoVersion, @@ -5159,5 +5248,8 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceHkdfSha256Expand, CryptoServiceHkdfSha384ExtractAndExpand, CryptoServiceHkdfSha384Extract, - CryptoServiceHkdfSha384Expand + CryptoServiceHkdfSha384Expand, + /// Aead Aes GCM + CryptoServiceAeadAesGcmEncrypt, + CryptoServiceAeadAesGcmDecrypt }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 5caf597421..8a8d7c179d 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -319,6 +319,13 @@ typedef struct { } Services; UINT32 Family; } ParallelHash; + union { + struct { + UINT8 Encrypt : 1; + UINT8 Decrypt : 1; + } Services; + UINT32 Family; + } AeadAesGcm; } PCD_CRYPTO_SERVICE_FAMILY_ENABLE; #endif diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 6a57daea6a..eaf9ad0550 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -1552,6 +1552,99 @@ AesCbcDecrypt ( CALL_CRYPTO_SERVICE (AesCbcDecrypt, (AesContext, Input, InputSize, Ivec, Output), FALSE); } +// ===================================================================================== +// Authenticated Encryption with Associated Data (AEAD) Cryptography Primitive +// ===================================================================================== + +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmEncrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + CALL_CRYPTO_SERVICE (AeadAesGcmEncrypt, (Key, KeySize, Iv, IvSize, AData, ADataSize, DataIn, DataInSize, TagOut, TagSize, DataOut, DataOutSize), FALSE); +} + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +BOOLEAN +EFIAPI +AeadAesGcmDecrypt ( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ) +{ + CALL_CRYPTO_SERVICE (AeadAesGcmDecrypt, (Key, KeySize, Iv, IvSize, AData, ADataSize, DataIn, DataInSize, Tag, TagSize, DataOut, DataOutSize), FALSE); +} + // ===================================================================================== // Asymmetric Cryptography Primitive // ===================================================================================== diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index da726e8381..a66be2c388 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 10 +#define EDKII_CRYPTO_VERSION 11 /// /// EDK II Crypto Protocol forward declaration @@ -3805,6 +3805,89 @@ BOOLEAN IN UINTN CustomByteLen ); +/** + Performs AEAD AES-GCM authenticated encryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be encrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[out] TagOut Pointer to a buffer that receives the authentication tag output. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the encryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated encryption succeeded. + @retval FALSE AEAD AES-GCM authenticated encryption failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_AEAD_AES_GCM_ENCRYPT)( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + OUT UINT8 *TagOut, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ); + +/** + Performs AEAD AES-GCM authenticated decryption on a data buffer and additional authenticated data (AAD). + + IvSize must be 12, otherwise FALSE is returned. + KeySize must be 16, 24 or 32, otherwise FALSE is returned. + TagSize must be 12, 13, 14, 15, 16, otherwise FALSE is returned. + If additional authenticated data verification fails, FALSE is returned. + + @param[in] Key Pointer to the encryption key. + @param[in] KeySize Size of the encryption key in bytes. + @param[in] Iv Pointer to the IV value. + @param[in] IvSize Size of the IV value in bytes. + @param[in] AData Pointer to the additional authenticated data (AAD). + @param[in] ADataSize Size of the additional authenticated data (AAD) in bytes. + @param[in] DataIn Pointer to the input data buffer to be decrypted. + @param[in] DataInSize Size of the input data buffer in bytes. + @param[in] Tag Pointer to a buffer that contains the authentication tag. + @param[in] TagSize Size of the authentication tag in bytes. + @param[out] DataOut Pointer to a buffer that receives the decryption output. + @param[out] DataOutSize Size of the output data buffer in bytes. + + @retval TRUE AEAD AES-GCM authenticated decryption succeeded. + @retval FALSE AEAD AES-GCM authenticated decryption failed. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_AEAD_AES_GCM_DECRYPT)( + IN CONST UINT8 *Key, + IN UINTN KeySize, + IN CONST UINT8 *Iv, + IN UINTN IvSize, + IN CONST UINT8 *AData, + IN UINTN ADataSize, + IN CONST UINT8 *DataIn, + IN UINTN DataInSize, + IN CONST UINT8 *Tag, + IN UINTN TagSize, + OUT UINT8 *DataOut, + OUT UINTN *DataOutSize + ); + /// /// EDK II Crypto Protocol /// @@ -4010,6 +4093,9 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_HKDF_SHA_384_EXTRACT_AND_EXPAND HkdfSha384ExtractAndExpand; EDKII_CRYPTO_HKDF_SHA_384_EXTRACT HkdfSha384Extract; EDKII_CRYPTO_HKDF_SHA_384_EXPAND HkdfSha384Expand; + /// AEAD AES-GCM + EDKII_AEAD_AES_GCM_ENCRYPT AeadAesGcmEncrypt; + EDKII_AEAD_AES_GCM_DECRYPT AeadAesGcmDecrypt; }; extern GUID gEdkiiCryptoProtocolGuid; From 1b1a690dc4a83f993a5d7ab659c5d01b7a07dae2 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Fri, 23 Sep 2022 14:32:01 +0800 Subject: [PATCH 0050/1529] CryptoPkg: add UnitTest for AeadAesGcm. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4036 Signed-off-by: Qi Zhang Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Reviewed-by: Jiewen Yao --- .../BaseCryptLib/UnitTestHostBaseCryptLib.inf | 1 + .../Library/BaseCryptLib/AeadAesGcmTests.c | 112 ++++++++++++++++++ .../BaseCryptLib/BaseCryptLibUnitTests.c | 1 + .../Library/BaseCryptLib/TestBaseCryptLib.h | 3 + .../BaseCryptLib/TestBaseCryptLibHost.inf | 1 + .../BaseCryptLib/TestBaseCryptLibShell.inf | 1 + 6 files changed, 119 insertions(+) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/AeadAesGcmTests.c diff --git a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf index 63282dc5ab..8a71b40a81 100644 --- a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf @@ -31,6 +31,7 @@ Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c + Cipher/CryptAeadAesGcm.c Pk/CryptRsaBasic.c Pk/CryptRsaExt.c Pk/CryptPkcs1Oaep.c diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/AeadAesGcmTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/AeadAesGcmTests.c new file mode 100644 index 0000000000..989a4df788 --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/AeadAesGcmTests.c @@ -0,0 +1,112 @@ +/** @file + Application for Authenticated Encryption with Associated Data + (AEAD) Validation. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "TestBaseCryptLib.h" + +/* AES-GCM test data from NIST public test vectors */ +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_key[] = { + 0xee, 0xbc, 0x1f, 0x57, 0x48, 0x7f, 0x51, 0x92, 0x1c, 0x04, 0x65, 0x66, + 0x5f, 0x8a, 0xe6, 0xd1, 0x65, 0x8b, 0xb2, 0x6d, 0xe6, 0xf8, 0xa0, 0x69, + 0xa3, 0x52, 0x02, 0x93, 0xa5, 0x72, 0x07, 0x8f +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_iv[] = { + 0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84 +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_pt[] = { + 0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea, + 0xcc, 0x2b, 0xf2, 0xa5 +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_aad[] = { + 0x4d, 0x23, 0xc3, 0xce, 0xc3, 0x34, 0xb4, 0x9b, 0xdb, 0x37, 0x0c, 0x43, + 0x7f, 0xec, 0x78, 0xde +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_ct[] = { + 0xf7, 0x26, 0x44, 0x13, 0xa8, 0x4c, 0x0e, 0x7c, 0xd5, 0x36, 0x86, 0x7e, + 0xb9, 0xf2, 0x17, 0x36 +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 gcm_tag[] = { + 0x67, 0xba, 0x05, 0x10, 0x26, 0x2a, 0xe4, 0x87, 0xd7, 0x37, 0xee, 0x62, + 0x98, 0xf7, 0x7e, 0x0c +}; + +UNIT_TEST_STATUS +EFIAPI +TestVerifyAeadAesGcm ( + IN UNIT_TEST_CONTEXT Context + ) +{ + BOOLEAN Status; + UINT8 OutBuffer[1024]; + UINTN OutBufferSize; + UINT8 OutTag[1024]; + UINTN OutTagSize; + + OutBufferSize = sizeof (OutBuffer); + OutTagSize = sizeof (gcm_tag); + ZeroMem (OutBuffer, sizeof (OutBuffer)); + ZeroMem (OutTag, sizeof (OutTag)); + Status = AeadAesGcmEncrypt ( + gcm_key, + sizeof (gcm_key), + gcm_iv, + sizeof (gcm_iv), + gcm_aad, + sizeof (gcm_aad), + gcm_pt, + sizeof (gcm_pt), + OutTag, + OutTagSize, + OutBuffer, + &OutBufferSize + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_EQUAL (OutBufferSize, sizeof (gcm_ct)); + + UT_ASSERT_MEM_EQUAL (OutBuffer, gcm_ct, sizeof (gcm_ct)); + + UT_ASSERT_MEM_EQUAL (OutTag, gcm_tag, sizeof (gcm_tag)); + + ZeroMem (OutBuffer, sizeof (OutBuffer)); + Status = AeadAesGcmDecrypt ( + gcm_key, + sizeof (gcm_key), + gcm_iv, + sizeof (gcm_iv), + gcm_aad, + sizeof (gcm_aad), + gcm_ct, + sizeof (gcm_ct), + gcm_tag, + sizeof (gcm_tag), + OutBuffer, + &OutBufferSize + ); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_EQUAL (OutBufferSize, sizeof (gcm_pt)); + + UT_ASSERT_MEM_EQUAL (OutBuffer, gcm_pt, sizeof (gcm_pt)); + + return UNIT_TEST_PASSED; +} + +TEST_DESC mAeadAesGcmTest[] = { + // + // -----Description--------------------------------------Class----------------------Function---------------------------------Pre---------------------Post---------Context + // + { "TestVerifyAeadAesGcm()", "CryptoPkg.BaseCryptLib.AeadAesGcm", TestVerifyAeadAesGcm, NULL, NULL, NULL }, +}; + +UINTN mAeadAesGcmTestNum = ARRAY_SIZE (mAeadAesGcmTest); diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c index dc81143b43..eb8ed94078 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c @@ -26,6 +26,7 @@ SUITE_DESC mSuiteDesc[] = { { "PRNG verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mPrngTestNum, mPrngTest }, { "OAEP encrypt verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mOaepTestNum, mOaepTest }, { "Hkdf extract and expand tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHkdfTestNum, mHkdfTest }, + { "Aead AES Gcm tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAeadAesGcmTestNum, mAeadAesGcmTest }, }; EFI_STATUS diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h index b3aff86570..58da1ba6c2 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h @@ -89,6 +89,9 @@ extern TEST_DESC mRsaPssTest[]; extern UINTN mHkdfTestNum; extern TEST_DESC mHkdfTest[]; +extern UINTN mAeadAesGcmTestNum; +extern TEST_DESC mAeadAesGcmTest[]; + /** Creates a framework you can use */ EFI_STATUS EFIAPI diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf index e51877bded..70c11790e6 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf @@ -38,6 +38,7 @@ RsaPssTests.c ParallelhashTests.c HkdfTests.c + AeadAesGcmTests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf index 81469f48e7..90f521f500 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf @@ -37,6 +37,7 @@ OaepEncryptTests.c RsaPssTests.c HkdfTests.c + AeadAesGcmTests.c [Packages] MdePkg/MdePkg.dec From 2222608951b555a0174e2d92980efa39e90bbd7e Mon Sep 17 00:00:00 2001 From: Yi Li Date: Wed, 7 Sep 2022 16:12:00 +0800 Subject: [PATCH 0051/1529] CryptoPkg: Add BigNum support REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3828 This patch is used to add CryptBn library, which is wrapped over OpenSSL. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 418 +++++++++++++ .../Library/BaseCryptLib/BaseCryptLib.inf | 1 + CryptoPkg/Library/BaseCryptLib/Bn/CryptBn.c | 581 ++++++++++++++++++ .../Library/BaseCryptLib/Bn/CryptBnNull.c | 520 ++++++++++++++++ .../Library/BaseCryptLib/PeiCryptLib.inf | 1 + .../Library/BaseCryptLib/SmmCryptLib.inf | 1 + .../BaseCryptLibNull/BaseCryptLibNull.inf | 1 + .../Library/BaseCryptLibNull/Bn/CryptBnNull.c | 520 ++++++++++++++++ 8 files changed, 2043 insertions(+) create mode 100644 CryptoPkg/Library/BaseCryptLib/Bn/CryptBn.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Bn/CryptBnNull.c create mode 100644 CryptoPkg/Library/BaseCryptLibNull/Bn/CryptBnNull.c diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 9436fe0f19..3026299e29 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -2836,4 +2836,422 @@ HkdfSha384Expand ( IN UINTN OutSize ); +// ===================================================================================== +// Big number primitives +// ===================================================================================== + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumInit ( + VOID + ); + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ); + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +BigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ); + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +BigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ); + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Calculate remainder: BnRes = BnA % BnB. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +BigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ); + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ + +UINTN +EFIAPI +BigNumBits ( + IN CONST VOID *Bn + ); + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +BigNumBytes ( + IN CONST VOID *Bn + ); + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ); + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsOdd ( + IN CONST VOID *Bn + ); + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +BigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ); + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +BigNumValueOne ( + VOID + ); + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ); + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number. +**/ +VOID +EFIAPI +BigNumConstTime ( + IN VOID *Bn + ); + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +BigNumNewContext ( + VOID + ); + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +BigNumContextFree ( + IN VOID *BnCtx + ); + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ); + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + #endif // __BASE_CRYPT_LIB_H__ diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index a1785f3423..0208d706b8 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -54,6 +54,7 @@ Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c Pem/CryptPem.c + Bn/CryptBn.c SysCall/CrtWrapper.c SysCall/TimerWrapper.c diff --git a/CryptoPkg/Library/BaseCryptLib/Bn/CryptBn.c b/CryptoPkg/Library/BaseCryptLib/Bn/CryptBn.c new file mode 100644 index 0000000000..282926ddcc --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Bn/CryptBn.c @@ -0,0 +1,581 @@ +/** @file Big number API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" +#include + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumInit ( + VOID + ) +{ + return BN_new (); +} + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ) +{ + return BN_bin2bn (Buf, (INT32)Len, NULL); +} + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +BigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ) +{ + return BN_bn2bin (Bn, Buf); +} + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +BigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ) +{ + if (Clear) { + BN_clear_free (Bn); + } else { + BN_free (Bn); + } +} + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return (BOOLEAN)BN_add (BnRes, BnA, BnB); +} + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return (BOOLEAN)BN_sub (BnRes, BnA, BnB); +} + +/** + Calculate remainder: BnRes = BnA % BnB. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_mod (BnRes, BnA, BnB, Ctx); + BN_CTX_free (Ctx); + + return RetVal; +} + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_mod_exp (BnRes, BnA, BnP, BnM, Ctx); + + BN_CTX_free (Ctx); + return RetVal; +} + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = FALSE; + if (BN_mod_inverse (BnRes, BnA, BnM, Ctx) != NULL) { + RetVal = TRUE; + } + + BN_CTX_free (Ctx); + return RetVal; +} + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_div (BnRes, NULL, BnA, BnB, Ctx); + BN_CTX_free (Ctx); + + return RetVal; +} + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_mod_mul (BnRes, BnA, BnB, BnM, Ctx); + BN_CTX_free (Ctx); + + return RetVal; +} + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +BigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ) +{ + return BN_cmp (BnA, BnB); +} + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +UINTN +EFIAPI +BigNumBits ( + IN CONST VOID *Bn + ) +{ + return BN_num_bits (Bn); +} + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +BigNumBytes ( + IN CONST VOID *Bn + ) +{ + return BN_num_bytes (Bn); +} + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ) +{ + return (BOOLEAN)BN_is_word (Bn, Num); +} + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsOdd ( + IN CONST VOID *Bn + ) +{ + return (BOOLEAN)BN_is_odd (Bn); +} + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +BigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ) +{ + return BN_copy (BnDst, BnSrc); +} + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +BigNumValueOne ( + VOID + ) +{ + return BN_value_one (); +} + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ) +{ + return (BOOLEAN)BN_rshift (BnRes, Bn, (INT32)N); +} + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number +**/ +VOID +EFIAPI +BigNumConstTime ( + IN VOID *Bn + ) +{ + BN_set_flags (Bn, BN_FLG_CONSTTIME); +} + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_mod_sqr (BnRes, BnA, BnM, Ctx); + BN_CTX_free (Ctx); + + return RetVal; +} + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +BigNumNewContext ( + VOID + ) +{ + return BN_CTX_new (); +} + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +BigNumContextFree ( + IN VOID *BnCtx + ) +{ + BN_CTX_free (BnCtx); +} + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ) +{ + return (BOOLEAN)BN_set_word (Bn, Val); +} + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + BOOLEAN RetVal; + BN_CTX *Ctx; + + Ctx = BN_CTX_new (); + if (Ctx == NULL) { + return FALSE; + } + + RetVal = (BOOLEAN)BN_mod_add (BnRes, BnA, BnB, BnM, Ctx); + BN_CTX_free (Ctx); + + return RetVal; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Bn/CryptBnNull.c b/CryptoPkg/Library/BaseCryptLib/Bn/CryptBnNull.c new file mode 100644 index 0000000000..547401fa12 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Bn/CryptBnNull.c @@ -0,0 +1,520 @@ +/** @file + Big number API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumInit ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +BigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ) +{ + ASSERT (FALSE); + return -1; +} + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +BigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ) +{ + ASSERT (FALSE); +} + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Calculate remainder: BnRes = BnA % BnB. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +BigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +UINTN +EFIAPI +BigNumBits ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +BigNumBytes ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsOdd ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +BigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +BigNumValueOne ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number +**/ +VOID +EFIAPI +BigNumConstTime ( + IN VOID *Bn + ) +{ + ASSERT (FALSE); +} + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +BigNumNewContext ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +BigNumContextFree ( + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); +} + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 84efeb246e..82b97bc6d3 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -61,6 +61,7 @@ Pk/CryptRsaPssSignNull.c Pem/CryptPemNull.c Rand/CryptRandNull.c + Bn/CryptBnNull.c SysCall/CrtWrapper.c SysCall/ConstantTimeClock.c diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index c81e9d5bb4..986581319c 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -61,6 +61,7 @@ Pk/CryptRsaPss.c Pk/CryptRsaPssSignNull.c Pem/CryptPem.c + Bn/CryptBnNull.c SysCall/CrtWrapper.c SysCall/ConstantTimeClock.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf index 80a432dfe1..88ada0430d 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +++ b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf @@ -54,6 +54,7 @@ Rand/CryptRandNull.c Pk/CryptRsaPssNull.c Pk/CryptRsaPssSignNull.c + Bn/CryptBnNull.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Library/BaseCryptLibNull/Bn/CryptBnNull.c b/CryptoPkg/Library/BaseCryptLibNull/Bn/CryptBnNull.c new file mode 100644 index 0000000000..547401fa12 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibNull/Bn/CryptBnNull.c @@ -0,0 +1,520 @@ +/** @file + Big number API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumInit ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +BigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ) +{ + ASSERT (FALSE); + return -1; +} + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +BigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ) +{ + ASSERT (FALSE); +} + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Calculate remainder: BnRes = BnA % BnB. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +BigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +UINTN +EFIAPI +BigNumBits ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +BigNumBytes ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsOdd ( + IN CONST VOID *Bn + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +BigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +BigNumValueOne ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number +**/ +VOID +EFIAPI +BigNumConstTime ( + IN VOID *Bn + ) +{ + ASSERT (FALSE); +} + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +BigNumNewContext ( + VOID + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +BigNumContextFree ( + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); +} + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + ASSERT (FALSE); + return FALSE; +} From 07e0d697e83a53706a3eb34abe1dfe6f3d8eb60f Mon Sep 17 00:00:00 2001 From: Yi Li Date: Wed, 7 Sep 2022 16:14:35 +0800 Subject: [PATCH 0052/1529] CryptoPkg: Add BigNum API to DXE and protocol REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3828 The implementation provides CryptBn library functions for EFI Driver and EFI BaseCrypt Protocol. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 1 + CryptoPkg/Driver/Crypto.c | 520 +++++++++++++++++- .../Pcd/PcdCryptoServiceFamilyEnable.h | 30 + .../BaseCryptLibOnProtocolPpi/CryptLib.c | 492 +++++++++++++++++ CryptoPkg/Private/Protocol/Crypto.h | 429 ++++++++++++++- 5 files changed, 1470 insertions(+), 2 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 79c6a4eeae..9bee423e21 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -169,6 +169,7 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tls.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsSet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsGet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Bn.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif !if $(CRYPTO_SERVICES) == MIN_PEI diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index 9562dfeec5..9872b5bf70 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -5027,6 +5027,498 @@ CryptoServiceAeadAesGcmDecrypt ( return CALL_BASECRYPTLIB (AeadAesGcm.Services.Decrypt, AeadAesGcmDecrypt, (Key, KeySize, Iv, IvSize, AData, ADataSize, DataIn, DataInSize, Tag, TagSize, DataOut, DataOutSize), FALSE); } +// ===================================================================================== +// Big number primitives +// ===================================================================================== + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +CryptoServiceBigNumInit ( + VOID + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Init, BigNumInit, (), NULL); +} + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +CryptoServiceBigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.FromBin, BigNumFromBin, (Buf, Len), NULL); +} + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +CryptoServiceBigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.ToBin, BigNumToBin, (Bn, Buf), -1); +} + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +CryptoServiceBigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ) +{ + CALL_VOID_BASECRYPTLIB (Bn.Services.Free, BigNumFree, (Bn, Clear)); +} + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Add, BigNumAdd, (BnA, BnB, BnRes), FALSE); +} + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Sub, BigNumSub, (BnA, BnB, BnRes), FALSE); +} + +/** + Calculate remainder: BnRes = BnA % BnB. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Mod, BigNumMod, (BnA, BnB, BnRes), FALSE); +} + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized. + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.ExpMod, BigNumExpMod, (BnA, BnP, BnM, BnRes), FALSE); +} + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.InverseMod, BigNumInverseMod, (BnA, BnM, BnRes), FALSE); +} + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Div, BigNumDiv, (BnA, BnB, BnRes), FALSE); +} + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.MulMod, BigNumMulMod, (BnA, BnB, BnM, BnRes), FALSE); +} + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +CryptoServiceBigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Cmp, BigNumCmp, (BnA, BnB), 0); +} + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +UINTN +EFIAPI +CryptoServiceBigNumBits ( + IN CONST VOID *Bn + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Bits, BigNumBits, (Bn), 0); +} + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +CryptoServiceBigNumBytes ( + IN CONST VOID *Bn + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Bytes, BigNumBytes, (Bn), 0); +} + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.IsWord, BigNumIsWord, (Bn, Num), FALSE); +} + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumIsOdd ( + IN CONST VOID *Bn + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.IsOdd, BigNumIsOdd, (Bn), FALSE); +} + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +CryptoServiceBigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.Copy, BigNumCopy, (BnDst, BnSrc), NULL); +} + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +CryptoServiceBigNumValueOne ( + VOID + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.ValueOne, BigNumValueOne, (), NULL); +} + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.RShift, BigNumRShift, (Bn, N, BnRes), FALSE); +} + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number. +**/ +VOID +EFIAPI +CryptoServiceBigNumConstTime ( + IN VOID *Bn + ) +{ + CALL_VOID_BASECRYPTLIB (Bn.Services.ConstTime, BigNumConstTime, (Bn)); +} + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.SqrMod, BigNumSqrMod, (BnA, BnM, BnRes), FALSE); +} + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +CryptoServiceBigNumNewContext ( + VOID + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.NewContext, BigNumNewContext, (), NULL); +} + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +CryptoServiceBigNumContextFree ( + IN VOID *BnCtx + ) +{ + CALL_VOID_BASECRYPTLIB (Bn.Services.ContextFree, BigNumContextFree, (BnCtx)); +} + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.SetUint, BigNumSetUint, (Bn, Val), FALSE); +} + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceBigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + return CALL_BASECRYPTLIB (Bn.Services.AddMod, BigNumAddMod, (BnA, BnB, BnM, BnRes), FALSE); +} + const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { /// Version CryptoServiceGetCryptoVersion, @@ -5251,5 +5743,31 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceHkdfSha384Expand, /// Aead Aes GCM CryptoServiceAeadAesGcmEncrypt, - CryptoServiceAeadAesGcmDecrypt + CryptoServiceAeadAesGcmDecrypt, + /// Big Numbers + CryptoServiceBigNumInit, + CryptoServiceBigNumFromBin, + CryptoServiceBigNumToBin, + CryptoServiceBigNumFree, + CryptoServiceBigNumAdd, + CryptoServiceBigNumSub, + CryptoServiceBigNumMod, + CryptoServiceBigNumExpMod, + CryptoServiceBigNumInverseMod, + CryptoServiceBigNumDiv, + CryptoServiceBigNumMulMod, + CryptoServiceBigNumCmp, + CryptoServiceBigNumBits, + CryptoServiceBigNumBytes, + CryptoServiceBigNumIsWord, + CryptoServiceBigNumIsOdd, + CryptoServiceBigNumCopy, + CryptoServiceBigNumValueOne, + CryptoServiceBigNumRShift, + CryptoServiceBigNumConstTime, + CryptoServiceBigNumSqrMod, + CryptoServiceBigNumNewContext, + CryptoServiceBigNumContextFree, + CryptoServiceBigNumSetUint, + CryptoServiceBigNumAddMod, }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 8a8d7c179d..52b44ca4f8 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -326,6 +326,36 @@ typedef struct { } Services; UINT32 Family; } AeadAesGcm; + union { + struct { + UINT8 Init : 1; + UINT8 FromBin : 1; + UINT8 ToBin : 1; + UINT8 Free : 1; + UINT8 Add : 1; + UINT8 Sub : 1; + UINT8 Mod : 1; + UINT8 ExpMod : 1; + UINT8 InverseMod : 1; + UINT8 Div : 1; + UINT8 MulMod : 1; + UINT8 Cmp : 1; + UINT8 Bits : 1; + UINT8 Bytes : 1; + UINT8 IsWord : 1; + UINT8 IsOdd : 1; + UINT8 Copy : 1; + UINT8 ValueOne : 1; + UINT8 RShift : 1; + UINT8 ConstTime : 1; + UINT8 SqrMod : 1; + UINT8 NewContext : 1; + UINT8 ContextFree : 1; + UINT8 SetUint : 1; + UINT8 AddMod : 1; + } Services; + UINT32 Family; + } Bn; } PCD_CRYPTO_SERVICE_FAMILY_ENABLE; #endif diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index eaf9ad0550..ce6981f091 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -4061,3 +4061,495 @@ TlsGetCertRevocationList ( { CALL_CRYPTO_SERVICE (TlsGetCertRevocationList, (Data, DataSize), EFI_UNSUPPORTED); } + +// ===================================================================================== +// Big number primitive +// ===================================================================================== + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumInit ( + VOID + ) +{ + CALL_CRYPTO_SERVICE (BigNumInit, (), NULL); +} + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New BigNum opaque structure or NULL on failure. +**/ +VOID * +EFIAPI +BigNumFromBin ( + IN CONST UINT8 *Buf, + IN UINTN Len + ) +{ + CALL_CRYPTO_SERVICE (BigNumFromBin, (Buf, Len), NULL); +} + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least BigNumBytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +INTN +EFIAPI +BigNumToBin ( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ) +{ + CALL_CRYPTO_SERVICE (BigNumToBin, (Bn, Buf), -1); +} + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +VOID +EFIAPI +BigNumFree ( + IN VOID *Bn, + IN BOOLEAN Clear + ) +{ + CALL_VOID_CRYPTO_SERVICE (BigNumFree, (Bn, Clear)); +} + +/** + Calculate the sum of two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAdd ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumAdd, (BnA, BnB, BnRes), FALSE); +} + +/** + Subtract two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSub ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumSub, (BnA, BnB, BnRes), FALSE); +} + +/** + Calculate remainder: BnRes = BnA % BnB + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumMod, (BnA, BnB, BnRes), FALSE); +} + +/** + Compute BnA to the BnP-th power modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of (BnA ^ BnP) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumExpMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumExpMod, (BnA, BnP, BnM, BnRes), FALSE); +} + +/** + Compute BnA inverse modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumInverseMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumInverseMod, (BnA, BnM, BnRes), FALSE); +} + +/** + Divide two Big Numbers. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumDiv ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumDiv, (BnA, BnB, BnRes), FALSE); +} + +/** + Multiply two Big Numbers modulo BnM. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumMulMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumMulMod, (BnA, BnB, BnM, BnRes), FALSE); +} + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +INTN +EFIAPI +BigNumCmp ( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ) +{ + CALL_CRYPTO_SERVICE (BigNumCmp, (BnA, BnB), 0); +} + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +UINTN +EFIAPI +BigNumBits ( + IN CONST VOID *Bn + ) +{ + CALL_CRYPTO_SERVICE (BigNumBits, (Bn), 0); +} + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +UINTN +EFIAPI +BigNumBytes ( + IN CONST VOID *Bn + ) +{ + CALL_CRYPTO_SERVICE (BigNumBytes, (Bn), 0); +} + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsWord ( + IN CONST VOID *Bn, + IN UINTN Num + ) +{ + CALL_CRYPTO_SERVICE (BigNumIsWord, (Bn, Num), FALSE); +} + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +BOOLEAN +EFIAPI +BigNumIsOdd ( + IN CONST VOID *Bn + ) +{ + CALL_CRYPTO_SERVICE (BigNumIsOdd, (Bn), FALSE); +} + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +VOID * +EFIAPI +BigNumCopy ( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ) +{ + CALL_CRYPTO_SERVICE (BigNumCopy, (BnDst, BnSrc), NULL); +} + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +CONST VOID * +EFIAPI +BigNumValueOne ( + VOID + ) +{ + CALL_CRYPTO_SERVICE (BigNumValueOne, (), NULL); +} + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumRShift ( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumRShift, (Bn, N, BnRes), FALSE); +} + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number. +**/ +VOID +EFIAPI +BigNumConstTime ( + IN VOID *Bn + ) +{ + CALL_VOID_CRYPTO_SERVICE (BigNumConstTime, (Bn)); +} + +/** + Calculate square modulo. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSqrMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumSqrMod, (BnA, BnM, BnRes), FALSE); +} + +/** + Create new Big Number computation context. This is an opaque structure + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +VOID * +EFIAPI +BigNumNewContext ( + VOID + ) +{ + CALL_CRYPTO_SERVICE (BigNumNewContext, (), NULL); +} + +/** + Free Big Number context that was allocated with BigNumNewContext(). + + @param[in] BnCtx Big number context to free. +**/ +VOID +EFIAPI +BigNumContextFree ( + IN VOID *BnCtx + ) +{ + CALL_VOID_CRYPTO_SERVICE (BigNumContextFree, (BnCtx)); +} + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumSetUint ( + IN VOID *Bn, + IN UINTN Val + ) +{ + CALL_CRYPTO_SERVICE (BigNumSetUint, (Bn, Val), FALSE); +} + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +BigNumAddMod ( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ) +{ + CALL_CRYPTO_SERVICE (BigNumAddMod, (BnA, BnB, BnM, BnRes), FALSE); +} diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index a66be2c388..3bf37575e9 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 11 +#define EDKII_CRYPTO_VERSION 12 /// /// EDK II Crypto Protocol forward declaration @@ -3888,6 +3888,407 @@ BOOLEAN OUT UINTN *DataOutSize ); +// ===================================================================================== +// Big Number Primitive +// ===================================================================================== + +/** + Allocate new Big Number. + + @retval New BigNum opaque structure or NULL on failure. +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_BIGNUM_INIT)( + VOID + ); + +/** + Allocate new Big Number and assign the provided value to it. + + @param[in] Buf Big endian encoded buffer. + @param[in] Len Buffer length. + + @retval New EDKII_CRYPTO_BIGNUM_ opaque structure or NULL on failure. +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_BIGNUM_FROM_BIN)( + IN CONST UINT8 *Buf, + IN UINTN Len + ); + +/** + Convert the absolute value of Bn into big-endian form and store it at Buf. + The Buf array should have at least EDKII_CRYPTO_BIGNUM_Bytes() in it. + + @param[in] Bn Big number to convert. + @param[out] Buf Output buffer. + + @retval The length of the big-endian number placed at Buf or -1 on error. +**/ +typedef +INTN +(EFIAPI *EDKII_CRYPTO_BIGNUM_TO_BIN)( + IN CONST VOID *Bn, + OUT UINT8 *Buf + ); + +/** + Free the Big Number. + + @param[in] Bn Big number to free. + @param[in] Clear TRUE if the buffer should be cleared. +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_BIGNUM_FREE)( + IN VOID *Bn, + IN BOOLEAN Clear + ); + +/** + Calculate the sum of two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA + BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_ADD)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Subtract two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA - BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_SUB)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Calculate remainder: BnRes = BnA % BnB. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result of BnA % BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Compute BnA to the BnP-th power modulo BnM. + + @param[in] BnA Big number. + @param[in] BnP Big number (power). + @param[in] BnM Big number (modulo). + @param[out] BnRes The result of BnA ^ BnP % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_EXP_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnP, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Compute BnA inverse modulo BnM. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnRes) % BnM == 1. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_INVERSE_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Divide two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[out] BnRes The result, such that BnA / BnB. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_DIV)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + OUT VOID *BnRes + ); + +/** + Multiply two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA * BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_MUL_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Compare two Big Numbers. + + @param[in] BnA Big number. + @param[in] BnB Big number. + + @retval 0 BnA == BnB. + @retval 1 BnA > BnB. + @retval -1 BnA < BnB. +**/ +typedef +INTN +(EFIAPI *EDKII_CRYPTO_BIGNUM_CMP)( + IN CONST VOID *BnA, + IN CONST VOID *BnB + ); + +/** + Get number of bits in Bn. + + @param[in] Bn Big number. + + @retval Number of bits. +**/ +typedef +UINTN +(EFIAPI *EDKII_CRYPTO_BIGNUM_BITS)( + IN CONST VOID *Bn + ); + +/** + Get number of bytes in Bn. + + @param[in] Bn Big number. + + @retval Number of bytes. +**/ +typedef +UINTN +(EFIAPI *EDKII_CRYPTO_BIGNUM_BYTES)( + IN CONST VOID *Bn + ); + +/** + Checks if Big Number equals to the given Num. + + @param[in] Bn Big number. + @param[in] Num Number. + + @retval TRUE iff Bn == Num. + @retval FALSE otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_IS_WORD)( + IN CONST VOID *Bn, + IN UINTN Num + ); + +/** + Checks if Big Number is odd. + + @param[in] Bn Big number. + + @retval TRUE Bn is odd (Bn % 2 == 1). + @retval FALSE otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_IS_ODD)( + IN CONST VOID *Bn + ); + +/** + Copy Big number. + + @param[out] BnDst Destination. + @param[in] BnSrc Source. + + @retval BnDst on success. + @retval NULL otherwise. +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_BIGNUM_COPY)( + OUT VOID *BnDst, + IN CONST VOID *BnSrc + ); + +/** + Get constant Big number with value of "1". + This may be used to save expensive allocations. + + @retval Big Number with value of 1. +**/ +typedef +CONST VOID * +(EFIAPI *EDKII_CRYPTO_BIGNUM_VALUE_ONE)( + VOID + ); + +/** + Shift right Big Number. + Please note, all "out" Big number arguments should be properly initialized + by calling to BigNumInit() or BigNumFromBin() functions. + + @param[in] Bn Big number. + @param[in] N Number of bits to shift. + @param[out] BnRes The result. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_R_SHIFT)( + IN CONST VOID *Bn, + IN UINTN N, + OUT VOID *BnRes + ); + +/** + Mark Big Number for constant time computations. + This function should be called before any constant time computations are + performed on the given Big number. + + @param[in] Bn Big number. +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_BIGNUM_CONST_TIME)( + IN VOID *Bn + ); + +/** + Calculate square modulo. + + @param[in] BnA Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA ^ 2) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_SQR_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + +/** + Create new Big Number computation context. This is an opaque structure. + which should be passed to any function that requires it. The BN context is + needed to optimize calculations and expensive allocations. + + @retval Big Number context struct or NULL on failure. +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_BIGNUM_NEW_CONTEXT)( + VOID + ); + +/** + Free Big Number context that was allocated with EDKII_CRYPTO_BIGNUM_NewContext(). + + @param[in] BnCtx Big number context to free. +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_BIGNUM_CONTEXT_FREE)( + IN VOID *BnCtx + ); + +/** + Set Big Number to a given value. + + @param[in] Bn Big number to set. + @param[in] Val Value to set. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_SET_UINT)( + IN VOID *Bn, + IN UINTN Val + ); + +/** + Add two Big Numbers modulo BnM. + + @param[in] BnA Big number. + @param[in] BnB Big number. + @param[in] BnM Big number (modulo). + @param[out] BnRes The result, such that (BnA + BnB) % BnM. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_BIGNUM_ADD_MOD)( + IN CONST VOID *BnA, + IN CONST VOID *BnB, + IN CONST VOID *BnM, + OUT VOID *BnRes + ); + /// /// EDK II Crypto Protocol /// @@ -4096,6 +4497,32 @@ struct _EDKII_CRYPTO_PROTOCOL { /// AEAD AES-GCM EDKII_AEAD_AES_GCM_ENCRYPT AeadAesGcmEncrypt; EDKII_AEAD_AES_GCM_DECRYPT AeadAesGcmDecrypt; + /// BIGNUM + EDKII_CRYPTO_BIGNUM_INIT BigNumInit; + EDKII_CRYPTO_BIGNUM_FROM_BIN BigNumFromBin; + EDKII_CRYPTO_BIGNUM_TO_BIN BigNumToBin; + EDKII_CRYPTO_BIGNUM_FREE BigNumFree; + EDKII_CRYPTO_BIGNUM_ADD BigNumAdd; + EDKII_CRYPTO_BIGNUM_SUB BigNumSub; + EDKII_CRYPTO_BIGNUM_MOD BigNumMod; + EDKII_CRYPTO_BIGNUM_EXP_MOD BigNumExpMod; + EDKII_CRYPTO_BIGNUM_INVERSE_MOD BigNumInverseMod; + EDKII_CRYPTO_BIGNUM_DIV BigNumDiv; + EDKII_CRYPTO_BIGNUM_MUL_MOD BigNumMulMod; + EDKII_CRYPTO_BIGNUM_CMP BigNumCmp; + EDKII_CRYPTO_BIGNUM_BITS BigNumBits; + EDKII_CRYPTO_BIGNUM_BYTES BigNumBytes; + EDKII_CRYPTO_BIGNUM_IS_WORD BigNumIsWord; + EDKII_CRYPTO_BIGNUM_IS_ODD BigNumIsOdd; + EDKII_CRYPTO_BIGNUM_COPY BigNumCopy; + EDKII_CRYPTO_BIGNUM_VALUE_ONE BigNumValueOne; + EDKII_CRYPTO_BIGNUM_R_SHIFT BigNumRShift; + EDKII_CRYPTO_BIGNUM_CONST_TIME BigNumConstTime; + EDKII_CRYPTO_BIGNUM_SQR_MOD BigNumSqrMod; + EDKII_CRYPTO_BIGNUM_NEW_CONTEXT BigNumNewContext; + EDKII_CRYPTO_BIGNUM_CONTEXT_FREE BigNumContextFree; + EDKII_CRYPTO_BIGNUM_SET_UINT BigNumSetUint; + EDKII_CRYPTO_BIGNUM_ADD_MOD BigNumAddMod; }; extern GUID gEdkiiCryptoProtocolGuid; From ac0a7631def3b37014d1c709c49456abc86a86e6 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Thu, 12 May 2022 17:10:16 +0800 Subject: [PATCH 0053/1529] CryptoPkg/Test: Add unit test for CryptoBn Add unit test for CryptoBn. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- .../BaseCryptLib/UnitTestHostBaseCryptLib.inf | 1 + .../BaseCryptLib/BaseCryptLibUnitTests.c | 1 + .../UnitTest/Library/BaseCryptLib/BnTests.c | 266 ++++++++++++++++++ .../Library/BaseCryptLib/TestBaseCryptLib.h | 3 + .../BaseCryptLib/TestBaseCryptLibHost.inf | 1 + .../BaseCryptLib/TestBaseCryptLibShell.inf | 1 + 6 files changed, 273 insertions(+) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BnTests.c diff --git a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf index 8a71b40a81..6891db97fb 100644 --- a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf @@ -47,6 +47,7 @@ Pem/CryptPem.c Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c + Bn/CryptBn.c SysCall/UnitTestHostCrtWrapper.c diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c index eb8ed94078..8450e95172 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c @@ -27,6 +27,7 @@ SUITE_DESC mSuiteDesc[] = { { "OAEP encrypt verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mOaepTestNum, mOaepTest }, { "Hkdf extract and expand tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHkdfTestNum, mHkdfTest }, { "Aead AES Gcm tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAeadAesGcmTestNum, mAeadAesGcmTest }, + { "Bn verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mBnTestNum, mBnTest }, }; EFI_STATUS diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BnTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BnTests.c new file mode 100644 index 0000000000..2636bb6318 --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BnTests.c @@ -0,0 +1,266 @@ +/** @file + Application for BigNumber Primitives Validation. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "TestBaseCryptLib.h" + +// +// Debug data +// +#define MAX_TEST_DATA_SIZE 512 +#define BYTES_OF_OPERATION_A 60 +#define BITS_OF_OPERATION_A 480// (8 * 60) + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnOperationA[] = { + 0x00, 0x00, 0x00, 0x00, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, + 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, + 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, + 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnOperationB[] = { + 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad, + 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07, + 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed, + 0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnOperationC[] = { + 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnOperationExp[] = { + 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63 +}; + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnOperationMod[] = { + 0x48, 0xbe, 0xcb, 0xd5, 0x36, 0x2e, 0x93, 0x0b, 0x51, 0x45, 0x9c, 0x7d, 0xe7, 0xfe, 0x47, 0xaa, + 0xc5, 0xd3, 0x4b, 0x4f, 0x06, 0x24, 0xb4, 0x31, 0x83, 0x55, 0xb5, 0xf0, 0xda, 0x14, 0xca, 0x46 +}; + +// BnOperationA + BnOperationB +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultSum[] = { + 0xb0, 0x03, 0x61, 0xa4, 0x29, 0x78, 0xf5, 0x57, 0x80, 0x52, 0x72, 0xab, 0xa0, 0x20, 0x56, 0xde, + 0xdd, 0xe7, 0x6f, 0x8d, 0xcf, 0x4c, 0xdd, 0x2d, 0xc0, 0x3f, 0x2c, 0x4f, 0xe6, 0x1c, 0x23, 0xa1, + 0x48, 0xbe, 0xcb, 0xd5, 0x36, 0x2e, 0x93, 0x0b, 0x51, 0x45, 0x9c, 0x7d, 0xe7, 0xfe, 0x47, 0xaa, + 0xc5, 0xd3, 0x4b, 0x4f, 0x06, 0x24, 0xb4, 0x31, 0x83, 0x55, 0xb5, 0xf0, 0xda, 0x14, 0xca, 0x46 +}; + +// (BnOperationA + BnOperationC) % BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultSumMod[] = { + 0x16, 0x0a, 0xcf, 0x78, 0x20, 0xac, 0x31, 0x53, 0xd9, 0x0f, 0x22, 0xfc, 0x08, 0x8d, 0xde, 0x0d, + 0x29, 0xf4, 0x07, 0xdd, 0xfa, 0xf5, 0x61, 0xd4, 0x1a, 0xe5, 0xa1, 0xef, 0x4a, 0x37, 0xfe, 0xec +}; + +// (BnOperationA * BnOperationC) % BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultMulMod[] = { + 0x01, 0xDB, 0xD2, 0x82, 0xC9, 0x24, 0x66, 0x2A, 0x96, 0x05, 0x11, 0xF2, 0x31, 0xF0, 0xCB, 0x28, + 0xBA, 0x5C, 0xBE, 0x7D, 0xEE, 0x37, 0x25, 0xB1, 0x24, 0x7E, 0x15, 0xAB, 0xCD, 0x86, 0x8E, 0x39 +}; + +// BnOperationA / BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultDiv[] = { + 0x02, 0x06, 0xA6, 0xDC, 0x2E, 0x97, 0x05, 0xEA, 0xCD, 0xF7, 0xAB, 0xCD, 0xE5, 0x9C, 0x33, 0x03, + 0xCE, 0x3D, 0x7E, 0x63, 0x23, 0xB2, 0xEC, 0xED, 0x96, 0x9D, 0xC9, 0xBB, 0x78 +}; + +// BnOperationA % BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultMod[] = { + 0x06, 0x2A, 0x8D, 0x06, 0x9D, 0x14, 0x53, 0x3B, 0x05, 0xD9, 0x86, 0x00, 0xA5, 0xB9, 0x05, 0x7F, + 0xC1, 0x82, 0xEC, 0x23, 0x44, 0x23, 0xC8, 0xA2, 0x42, 0xB3, 0x43, 0xB8, 0x7C, 0xD6, 0xB1, 0xCF +}; + +// BnOperationA % BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultInverseMod[] = { + 0x3a, 0xeb, 0xc5, 0x98, 0x9c, 0x22, 0xd6, 0x76, 0x7d, 0x1c, 0xc6, 0xd6, 0xbb, 0x1b, 0xed, 0xfd, + 0x0f, 0x34, 0xbf, 0xe0, 0x2b, 0x4a, 0x26, 0xc3, 0xc0, 0xd9, 0x57, 0xc7, 0x11, 0xc0, 0xd6, 0x35 +}; + +// BnOperationA % BnOperationMod +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultExpMod[] = { + 0x39, 0xf8, 0x74, 0xa0, 0xe8, 0x02, 0x8b, 0xf2, 0x22, 0x62, 0x82, 0x4c, 0xe0, 0xed, 0x63, 0x48, + 0xb9, 0xa2, 0xaa, 0xbc, 0xba, 0xb1, 0xd3, 0x6a, 0x02, 0xfd, 0xf3, 0x0e, 0x3a, 0x19, 0x39, 0x37 +}; + +// BnOperationA >> 128 +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultRShift[] = { + 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, + 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6,0x4b, 0x55, 0xd3, 0x9a, + 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23,0xa3, 0xfe, 0xeb, 0xbd +}; + +// 0x12345678 +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 BnResultUIntSet[] = { 0x12, 0x34, 0x56, 0x78 }; + +typedef struct { + VOID *BnA; + VOID *BnB; + VOID *BnC; + VOID *BnD; + VOID *BnCTX; +} BN_TEST_CONTEXT; + +GLOBAL_REMOVE_IF_UNREFERENCED STATIC BN_TEST_CONTEXT mBnContext = { NULL, NULL, NULL, NULL, NULL }; + +// +// Debug function +// +STATIC +BOOLEAN +EqualBn2Bn ( + CONST VOID *Expected, + CONST VOID *Actual + ) +{ + if (BigNumCmp (Expected, Actual) == 0) { + return TRUE; + } + + return FALSE; +} + +STATIC +BOOLEAN +EqualBn2Bin ( + CONST VOID *Bn, + CONST UINT8 *Buffer, + CONST UINTN BufferSize + ) +{ + UINTN BnTestBufferSize; + UINT8 BnTestBuffer[MAX_TEST_DATA_SIZE]; + + BnTestBufferSize = BigNumToBin (Bn, BnTestBuffer); + if (BnTestBufferSize == BufferSize) { + if (CompareMem (Buffer, BnTestBuffer, BnTestBufferSize) == 0) { + return TRUE; + } + } + + return FALSE; +} + +UNIT_TEST_STATUS +EFIAPI +TestVerifyBnPreReq ( + UNIT_TEST_CONTEXT Context + ) +{ + BN_TEST_CONTEXT *BnContext; + + BnContext = Context; + BnContext->BnCTX = BigNumNewContext (); + BnContext->BnA = BigNumInit (); + BnContext->BnB = BigNumInit (); + BnContext->BnC = BigNumInit (); + BnContext->BnD = BigNumInit (); + if ( (BnContext->BnCTX == NULL) + || (BnContext->BnA == NULL) + || (BnContext->BnB == NULL) + || (BnContext->BnC == NULL) + || (BnContext->BnD == NULL) + ) + { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + return UNIT_TEST_PASSED; +} + +VOID +EFIAPI +TestVerifyBnCleanUp ( + UNIT_TEST_CONTEXT Context + ) +{ + BN_TEST_CONTEXT *BnContext; + + BnContext = Context; + BigNumContextFree (BnContext->BnCTX); + BigNumFree (BnContext->BnA, TRUE); + BigNumFree (BnContext->BnB, TRUE); + BigNumFree (BnContext->BnC, TRUE); + BigNumFree (BnContext->BnD, TRUE); +} + +UNIT_TEST_STATUS +EFIAPI +TestVerifyBn ( + IN UNIT_TEST_CONTEXT Context + ) +{ + BN_TEST_CONTEXT *BnContext; + UINTN Num; + CONST VOID *BnOne; + + BnContext = Context; + + // Calculation tests + BnContext->BnA = BigNumFromBin (BnOperationA, sizeof (BnOperationA)); + BnContext->BnB = BigNumFromBin (BnOperationB, sizeof (BnOperationB)); + // C=A+B + BigNumAdd (BnContext->BnA, BnContext->BnB, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultSum, sizeof (BnResultSum))); + // D=C-A=B + BigNumSub (BnContext->BnC, BnContext->BnA, BnContext->BnD); + UT_ASSERT_TRUE (EqualBn2Bn (BnContext->BnB, BnContext->BnD)); + // C=(A+B)%D + BnContext->BnD = BigNumFromBin (BnOperationMod, sizeof (BnOperationMod)); + BigNumAddMod (BnContext->BnA, BnContext->BnB, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultSumMod, sizeof (BnResultSumMod))); + // C=(A*B)%D + BigNumMulMod (BnContext->BnA, BnContext->BnB, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultMulMod, sizeof (BnResultMulMod))); + // C=A/D + BigNumDiv (BnContext->BnA, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultDiv, sizeof (BnResultDiv))); + // C=A%D + BigNumMod (BnContext->BnA, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultMod, sizeof (BnResultMod))); + // 1=(A*C)%D + BigNumInverseMod (BnContext->BnA, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultInverseMod, sizeof (BnResultInverseMod))); + // C=(A^B)%D + BnContext->BnB = BigNumFromBin (BnOperationExp, sizeof (BnOperationExp)); + BigNumExpMod (BnContext->BnA, BnContext->BnB, BnContext->BnD, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultExpMod, sizeof (BnResultExpMod))); + // C=A>>128 + BigNumRShift (BnContext->BnA, 128, BnContext->BnC); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultRShift, sizeof (BnResultRShift))); + // C=0x12345678 + BigNumSetUint (BnContext->BnC, 0x12345678); + UT_ASSERT_TRUE (EqualBn2Bin (BnContext->BnC, BnResultUIntSet, sizeof (BnResultUIntSet))); + // Bn compare + UT_ASSERT_TRUE (BigNumIsWord (BnContext->BnC, 0x12345678)); + UT_ASSERT_FALSE (BigNumIsWord (BnContext->BnC, 0x12345600)); + UT_ASSERT_FALSE (BigNumIsOdd (BnContext->BnC)); + UT_ASSERT_TRUE (BigNumIsOdd (BnContext->BnA)); + + // Other tests + BigNumConstTime (BnContext->BnA); + Num = BigNumBytes (BnContext->BnA); + UT_ASSERT_EQUAL (Num, BYTES_OF_OPERATION_A); + Num = BigNumBits (BnContext->BnA); + UT_ASSERT_EQUAL (Num, BITS_OF_OPERATION_A); + BnOne = BigNumValueOne (); + if (BnOne == NULL) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + UT_ASSERT_TRUE (BigNumIsWord (BnOne, 0x1)); + + return UNIT_TEST_PASSED; +} + +TEST_DESC mBnTest[] = { + // + // -----Description----------------Class---------------------Function-----------Pre----------------Post---------Context + // + { "TestVerifyBn()", "CryptoPkg.BaseCryptLib.BigNumber", TestVerifyBn, TestVerifyBnPreReq, TestVerifyBnCleanUp, &mBnContext }, +}; + +UINTN mBnTestNum = ARRAY_SIZE (mBnTest); diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h index 58da1ba6c2..fc44030ff6 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h @@ -92,6 +92,9 @@ extern TEST_DESC mHkdfTest[]; extern UINTN mAeadAesGcmTestNum; extern TEST_DESC mAeadAesGcmTest[]; +extern UINTN mBnTestNum; +extern TEST_DESC mBnTest[]; + /** Creates a framework you can use */ EFI_STATUS EFIAPI diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf index 70c11790e6..40dfade717 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf @@ -39,6 +39,7 @@ ParallelhashTests.c HkdfTests.c AeadAesGcmTests.c + BnTests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf index 90f521f500..00e6b088b8 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf @@ -38,6 +38,7 @@ RsaPssTests.c HkdfTests.c AeadAesGcmTests.c + BnTests.c [Packages] MdePkg/MdePkg.dec From 22e26683e5cfe673567fdb3907b4b2f6c9feb848 Mon Sep 17 00:00:00 2001 From: Christopher Zurcher Date: Thu, 22 Sep 2022 04:25:39 +0800 Subject: [PATCH 0054/1529] CryptoPkg/OpensslLib: Add native instruction support for IA32 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3654 Adding native instruction support for accelerated OpenSSL features for IA32 architecture, following the pattern set by the previous commits for X64 native support. Cc: Yi Li Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Christopher Zurcher Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.ci.yaml | 4 + .../Library/OpensslLib/OpensslLibIa32.inf | 699 ++++++++++++++++++ .../Library/OpensslLib/OpensslLibIa32Gcc.inf | 699 ++++++++++++++++++ CryptoPkg/Library/OpensslLib/UefiAsm.conf | 18 + CryptoPkg/Library/OpensslLib/process_files.pl | 12 + 5 files changed, 1432 insertions(+) create mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf create mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf diff --git a/CryptoPkg/CryptoPkg.ci.yaml b/CryptoPkg/CryptoPkg.ci.yaml index bb52ceb547..2fa3a3d5ee 100644 --- a/CryptoPkg/CryptoPkg.ci.yaml +++ b/CryptoPkg/CryptoPkg.ci.yaml @@ -9,6 +9,8 @@ "LicenseCheck": { "IgnoreFiles": [ # These directories contain auto-generated OpenSSL content + "Library/OpensslLib/IA32", + "Library/OpensslLib/IA32Gcc", "Library/OpensslLib/X64", "Library/OpensslLib/X64Gcc", "Library/Include/openssl" @@ -72,6 +74,8 @@ "DscPath": "CryptoPkg.dsc", "IgnoreInf": [ # These are alternatives to OpensslLib.inf + "CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf", + "CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf", "CryptoPkg/Library/OpensslLib/OpensslLibX64.inf", "CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf" ] diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf b/CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf new file mode 100644 index 0000000000..b6ee718ede --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf @@ -0,0 +1,699 @@ +## @file +# This module provides OpenSSL Library implementation. +# +# Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
+# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = OpensslLibIa32 + MODULE_UNI_FILE = OpensslLib.uni + FILE_GUID = 5805D1D4-F8EE-4FBA-BDD8-74465F16A534 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = OpensslLib + DEFINE OPENSSL_PATH = openssl + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE + DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM + CONSTRUCTOR = OpensslLibConstructor + +# +# VALID_ARCHITECTURES = IA32 +# + +[Sources.IA32] + OpensslLibConstructor.c + $(OPENSSL_PATH)/e_os.h + $(OPENSSL_PATH)/ms/uplink.h +# Autogenerated files list starts here + IA32/crypto/aes/aesni-x86.nasm + IA32/crypto/aes/vpaes-x86.nasm + IA32/crypto/modes/ghash-x86.nasm + IA32/crypto/sha/sha1-586.nasm + IA32/crypto/sha/sha256-586.nasm + IA32/crypto/sha/sha512-586.nasm + IA32/crypto/x86cpuid.nasm + $(OPENSSL_PATH)/crypto/aes/aes_cbc.c + $(OPENSSL_PATH)/crypto/aes/aes_cfb.c + $(OPENSSL_PATH)/crypto/aes/aes_core.c + $(OPENSSL_PATH)/crypto/aes/aes_ige.c + $(OPENSSL_PATH)/crypto/aes/aes_misc.c + $(OPENSSL_PATH)/crypto/aes/aes_ofb.c + $(OPENSSL_PATH)/crypto/aes/aes_wrap.c + $(OPENSSL_PATH)/crypto/aria/aria.c + $(OPENSSL_PATH)/crypto/asn1/a_bitstr.c + $(OPENSSL_PATH)/crypto/asn1/a_d2i_fp.c + $(OPENSSL_PATH)/crypto/asn1/a_digest.c + $(OPENSSL_PATH)/crypto/asn1/a_dup.c + $(OPENSSL_PATH)/crypto/asn1/a_gentm.c + $(OPENSSL_PATH)/crypto/asn1/a_i2d_fp.c + $(OPENSSL_PATH)/crypto/asn1/a_int.c + $(OPENSSL_PATH)/crypto/asn1/a_mbstr.c + $(OPENSSL_PATH)/crypto/asn1/a_object.c + $(OPENSSL_PATH)/crypto/asn1/a_octet.c + $(OPENSSL_PATH)/crypto/asn1/a_print.c + $(OPENSSL_PATH)/crypto/asn1/a_sign.c + $(OPENSSL_PATH)/crypto/asn1/a_strex.c + $(OPENSSL_PATH)/crypto/asn1/a_strnid.c + $(OPENSSL_PATH)/crypto/asn1/a_time.c + $(OPENSSL_PATH)/crypto/asn1/a_type.c + $(OPENSSL_PATH)/crypto/asn1/a_utctm.c + $(OPENSSL_PATH)/crypto/asn1/a_utf8.c + $(OPENSSL_PATH)/crypto/asn1/a_verify.c + $(OPENSSL_PATH)/crypto/asn1/ameth_lib.c + $(OPENSSL_PATH)/crypto/asn1/asn1_err.c + $(OPENSSL_PATH)/crypto/asn1/asn1_gen.c + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.c + $(OPENSSL_PATH)/crypto/asn1/asn1_lib.c + $(OPENSSL_PATH)/crypto/asn1/asn1_par.c + $(OPENSSL_PATH)/crypto/asn1/asn_mime.c + $(OPENSSL_PATH)/crypto/asn1/asn_moid.c + $(OPENSSL_PATH)/crypto/asn1/asn_mstbl.c + $(OPENSSL_PATH)/crypto/asn1/asn_pack.c + $(OPENSSL_PATH)/crypto/asn1/bio_asn1.c + $(OPENSSL_PATH)/crypto/asn1/bio_ndef.c + $(OPENSSL_PATH)/crypto/asn1/d2i_pr.c + $(OPENSSL_PATH)/crypto/asn1/d2i_pu.c + $(OPENSSL_PATH)/crypto/asn1/evp_asn1.c + $(OPENSSL_PATH)/crypto/asn1/f_int.c + $(OPENSSL_PATH)/crypto/asn1/f_string.c + $(OPENSSL_PATH)/crypto/asn1/i2d_pr.c + $(OPENSSL_PATH)/crypto/asn1/i2d_pu.c + $(OPENSSL_PATH)/crypto/asn1/n_pkey.c + $(OPENSSL_PATH)/crypto/asn1/nsseq.c + $(OPENSSL_PATH)/crypto/asn1/p5_pbe.c + $(OPENSSL_PATH)/crypto/asn1/p5_pbev2.c + $(OPENSSL_PATH)/crypto/asn1/p5_scrypt.c + $(OPENSSL_PATH)/crypto/asn1/p8_pkey.c + $(OPENSSL_PATH)/crypto/asn1/t_bitst.c + $(OPENSSL_PATH)/crypto/asn1/t_pkey.c + $(OPENSSL_PATH)/crypto/asn1/t_spki.c + $(OPENSSL_PATH)/crypto/asn1/tasn_dec.c + $(OPENSSL_PATH)/crypto/asn1/tasn_enc.c + $(OPENSSL_PATH)/crypto/asn1/tasn_fre.c + $(OPENSSL_PATH)/crypto/asn1/tasn_new.c + $(OPENSSL_PATH)/crypto/asn1/tasn_prn.c + $(OPENSSL_PATH)/crypto/asn1/tasn_scn.c + $(OPENSSL_PATH)/crypto/asn1/tasn_typ.c + $(OPENSSL_PATH)/crypto/asn1/tasn_utl.c + $(OPENSSL_PATH)/crypto/asn1/x_algor.c + $(OPENSSL_PATH)/crypto/asn1/x_bignum.c + $(OPENSSL_PATH)/crypto/asn1/x_info.c + $(OPENSSL_PATH)/crypto/asn1/x_int64.c + $(OPENSSL_PATH)/crypto/asn1/x_long.c + $(OPENSSL_PATH)/crypto/asn1/x_pkey.c + $(OPENSSL_PATH)/crypto/asn1/x_sig.c + $(OPENSSL_PATH)/crypto/asn1/x_spki.c + $(OPENSSL_PATH)/crypto/asn1/x_val.c + $(OPENSSL_PATH)/crypto/async/arch/async_null.c + $(OPENSSL_PATH)/crypto/async/arch/async_posix.c + $(OPENSSL_PATH)/crypto/async/arch/async_win.c + $(OPENSSL_PATH)/crypto/async/async.c + $(OPENSSL_PATH)/crypto/async/async_err.c + $(OPENSSL_PATH)/crypto/async/async_wait.c + $(OPENSSL_PATH)/crypto/bio/b_addr.c + $(OPENSSL_PATH)/crypto/bio/b_dump.c + $(OPENSSL_PATH)/crypto/bio/b_sock.c + $(OPENSSL_PATH)/crypto/bio/b_sock2.c + $(OPENSSL_PATH)/crypto/bio/bf_buff.c + $(OPENSSL_PATH)/crypto/bio/bf_lbuf.c + $(OPENSSL_PATH)/crypto/bio/bf_nbio.c + $(OPENSSL_PATH)/crypto/bio/bf_null.c + $(OPENSSL_PATH)/crypto/bio/bio_cb.c + $(OPENSSL_PATH)/crypto/bio/bio_err.c + $(OPENSSL_PATH)/crypto/bio/bio_lib.c + $(OPENSSL_PATH)/crypto/bio/bio_meth.c + $(OPENSSL_PATH)/crypto/bio/bss_acpt.c + $(OPENSSL_PATH)/crypto/bio/bss_bio.c + $(OPENSSL_PATH)/crypto/bio/bss_conn.c + $(OPENSSL_PATH)/crypto/bio/bss_dgram.c + $(OPENSSL_PATH)/crypto/bio/bss_fd.c + $(OPENSSL_PATH)/crypto/bio/bss_file.c + $(OPENSSL_PATH)/crypto/bio/bss_log.c + $(OPENSSL_PATH)/crypto/bio/bss_mem.c + $(OPENSSL_PATH)/crypto/bio/bss_null.c + $(OPENSSL_PATH)/crypto/bio/bss_sock.c + $(OPENSSL_PATH)/crypto/bn/bn_add.c + $(OPENSSL_PATH)/crypto/bn/bn_asm.c + $(OPENSSL_PATH)/crypto/bn/bn_blind.c + $(OPENSSL_PATH)/crypto/bn/bn_const.c + $(OPENSSL_PATH)/crypto/bn/bn_ctx.c + $(OPENSSL_PATH)/crypto/bn/bn_depr.c + $(OPENSSL_PATH)/crypto/bn/bn_dh.c + $(OPENSSL_PATH)/crypto/bn/bn_div.c + $(OPENSSL_PATH)/crypto/bn/bn_err.c + $(OPENSSL_PATH)/crypto/bn/bn_exp.c + $(OPENSSL_PATH)/crypto/bn/bn_exp2.c + $(OPENSSL_PATH)/crypto/bn/bn_gcd.c + $(OPENSSL_PATH)/crypto/bn/bn_gf2m.c + $(OPENSSL_PATH)/crypto/bn/bn_intern.c + $(OPENSSL_PATH)/crypto/bn/bn_kron.c + $(OPENSSL_PATH)/crypto/bn/bn_lib.c + $(OPENSSL_PATH)/crypto/bn/bn_mod.c + $(OPENSSL_PATH)/crypto/bn/bn_mont.c + $(OPENSSL_PATH)/crypto/bn/bn_mpi.c + $(OPENSSL_PATH)/crypto/bn/bn_mul.c + $(OPENSSL_PATH)/crypto/bn/bn_nist.c + $(OPENSSL_PATH)/crypto/bn/bn_prime.c + $(OPENSSL_PATH)/crypto/bn/bn_print.c + $(OPENSSL_PATH)/crypto/bn/bn_rand.c + $(OPENSSL_PATH)/crypto/bn/bn_recp.c + $(OPENSSL_PATH)/crypto/bn/bn_shift.c + $(OPENSSL_PATH)/crypto/bn/bn_sqr.c + $(OPENSSL_PATH)/crypto/bn/bn_sqrt.c + $(OPENSSL_PATH)/crypto/bn/bn_srp.c + $(OPENSSL_PATH)/crypto/bn/bn_word.c + $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/buffer/buf_err.c + $(OPENSSL_PATH)/crypto/buffer/buffer.c + $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c + $(OPENSSL_PATH)/crypto/cmac/cm_pmeth.c + $(OPENSSL_PATH)/crypto/cmac/cmac.c + $(OPENSSL_PATH)/crypto/comp/c_zlib.c + $(OPENSSL_PATH)/crypto/comp/comp_err.c + $(OPENSSL_PATH)/crypto/comp/comp_lib.c + $(OPENSSL_PATH)/crypto/conf/conf_api.c + $(OPENSSL_PATH)/crypto/conf/conf_def.c + $(OPENSSL_PATH)/crypto/conf/conf_err.c + $(OPENSSL_PATH)/crypto/conf/conf_lib.c + $(OPENSSL_PATH)/crypto/conf/conf_mall.c + $(OPENSSL_PATH)/crypto/conf/conf_mod.c + $(OPENSSL_PATH)/crypto/conf/conf_sap.c + $(OPENSSL_PATH)/crypto/conf/conf_ssl.c + $(OPENSSL_PATH)/crypto/cpt_err.c + $(OPENSSL_PATH)/crypto/cryptlib.c + $(OPENSSL_PATH)/crypto/ctype.c + $(OPENSSL_PATH)/crypto/cversion.c + $(OPENSSL_PATH)/crypto/dh/dh_ameth.c + $(OPENSSL_PATH)/crypto/dh/dh_asn1.c + $(OPENSSL_PATH)/crypto/dh/dh_check.c + $(OPENSSL_PATH)/crypto/dh/dh_depr.c + $(OPENSSL_PATH)/crypto/dh/dh_err.c + $(OPENSSL_PATH)/crypto/dh/dh_gen.c + $(OPENSSL_PATH)/crypto/dh/dh_kdf.c + $(OPENSSL_PATH)/crypto/dh/dh_key.c + $(OPENSSL_PATH)/crypto/dh/dh_lib.c + $(OPENSSL_PATH)/crypto/dh/dh_meth.c + $(OPENSSL_PATH)/crypto/dh/dh_pmeth.c + $(OPENSSL_PATH)/crypto/dh/dh_prn.c + $(OPENSSL_PATH)/crypto/dh/dh_rfc5114.c + $(OPENSSL_PATH)/crypto/dh/dh_rfc7919.c + $(OPENSSL_PATH)/crypto/dso/dso_dl.c + $(OPENSSL_PATH)/crypto/dso/dso_dlfcn.c + $(OPENSSL_PATH)/crypto/dso/dso_err.c + $(OPENSSL_PATH)/crypto/dso/dso_lib.c + $(OPENSSL_PATH)/crypto/dso/dso_openssl.c + $(OPENSSL_PATH)/crypto/dso/dso_vms.c + $(OPENSSL_PATH)/crypto/dso/dso_win32.c + $(OPENSSL_PATH)/crypto/ebcdic.c + $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/err/err.c + $(OPENSSL_PATH)/crypto/err/err_prn.c + $(OPENSSL_PATH)/crypto/evp/bio_b64.c + $(OPENSSL_PATH)/crypto/evp/bio_enc.c + $(OPENSSL_PATH)/crypto/evp/bio_md.c + $(OPENSSL_PATH)/crypto/evp/bio_ok.c + $(OPENSSL_PATH)/crypto/evp/c_allc.c + $(OPENSSL_PATH)/crypto/evp/c_alld.c + $(OPENSSL_PATH)/crypto/evp/cmeth_lib.c + $(OPENSSL_PATH)/crypto/evp/digest.c + $(OPENSSL_PATH)/crypto/evp/e_aes.c + $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha1.c + $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha256.c + $(OPENSSL_PATH)/crypto/evp/e_aria.c + $(OPENSSL_PATH)/crypto/evp/e_bf.c + $(OPENSSL_PATH)/crypto/evp/e_camellia.c + $(OPENSSL_PATH)/crypto/evp/e_cast.c + $(OPENSSL_PATH)/crypto/evp/e_chacha20_poly1305.c + $(OPENSSL_PATH)/crypto/evp/e_des.c + $(OPENSSL_PATH)/crypto/evp/e_des3.c + $(OPENSSL_PATH)/crypto/evp/e_idea.c + $(OPENSSL_PATH)/crypto/evp/e_null.c + $(OPENSSL_PATH)/crypto/evp/e_old.c + $(OPENSSL_PATH)/crypto/evp/e_rc2.c + $(OPENSSL_PATH)/crypto/evp/e_rc4.c + $(OPENSSL_PATH)/crypto/evp/e_rc4_hmac_md5.c + $(OPENSSL_PATH)/crypto/evp/e_rc5.c + $(OPENSSL_PATH)/crypto/evp/e_seed.c + $(OPENSSL_PATH)/crypto/evp/e_sm4.c + $(OPENSSL_PATH)/crypto/evp/e_xcbc_d.c + $(OPENSSL_PATH)/crypto/evp/encode.c + $(OPENSSL_PATH)/crypto/evp/evp_cnf.c + $(OPENSSL_PATH)/crypto/evp/evp_enc.c + $(OPENSSL_PATH)/crypto/evp/evp_err.c + $(OPENSSL_PATH)/crypto/evp/evp_key.c + $(OPENSSL_PATH)/crypto/evp/evp_lib.c + $(OPENSSL_PATH)/crypto/evp/evp_pbe.c + $(OPENSSL_PATH)/crypto/evp/evp_pkey.c + $(OPENSSL_PATH)/crypto/evp/m_md2.c + $(OPENSSL_PATH)/crypto/evp/m_md4.c + $(OPENSSL_PATH)/crypto/evp/m_md5.c + $(OPENSSL_PATH)/crypto/evp/m_md5_sha1.c + $(OPENSSL_PATH)/crypto/evp/m_mdc2.c + $(OPENSSL_PATH)/crypto/evp/m_null.c + $(OPENSSL_PATH)/crypto/evp/m_ripemd.c + $(OPENSSL_PATH)/crypto/evp/m_sha1.c + $(OPENSSL_PATH)/crypto/evp/m_sha3.c + $(OPENSSL_PATH)/crypto/evp/m_sigver.c + $(OPENSSL_PATH)/crypto/evp/m_wp.c + $(OPENSSL_PATH)/crypto/evp/names.c + $(OPENSSL_PATH)/crypto/evp/p5_crpt.c + $(OPENSSL_PATH)/crypto/evp/p5_crpt2.c + $(OPENSSL_PATH)/crypto/evp/p_dec.c + $(OPENSSL_PATH)/crypto/evp/p_enc.c + $(OPENSSL_PATH)/crypto/evp/p_lib.c + $(OPENSSL_PATH)/crypto/evp/p_open.c + $(OPENSSL_PATH)/crypto/evp/p_seal.c + $(OPENSSL_PATH)/crypto/evp/p_sign.c + $(OPENSSL_PATH)/crypto/evp/p_verify.c + $(OPENSSL_PATH)/crypto/evp/pbe_scrypt.c + $(OPENSSL_PATH)/crypto/evp/pmeth_fn.c + $(OPENSSL_PATH)/crypto/evp/pmeth_gn.c + $(OPENSSL_PATH)/crypto/evp/pmeth_lib.c + $(OPENSSL_PATH)/crypto/ex_data.c + $(OPENSSL_PATH)/crypto/getenv.c + $(OPENSSL_PATH)/crypto/hmac/hm_ameth.c + $(OPENSSL_PATH)/crypto/hmac/hm_pmeth.c + $(OPENSSL_PATH)/crypto/hmac/hmac.c + $(OPENSSL_PATH)/crypto/init.c + $(OPENSSL_PATH)/crypto/kdf/hkdf.c + $(OPENSSL_PATH)/crypto/kdf/kdf_err.c + $(OPENSSL_PATH)/crypto/kdf/scrypt.c + $(OPENSSL_PATH)/crypto/kdf/tls1_prf.c + $(OPENSSL_PATH)/crypto/lhash/lh_stats.c + $(OPENSSL_PATH)/crypto/lhash/lhash.c + $(OPENSSL_PATH)/crypto/md5/md5_dgst.c + $(OPENSSL_PATH)/crypto/md5/md5_one.c + $(OPENSSL_PATH)/crypto/mem.c + $(OPENSSL_PATH)/crypto/mem_dbg.c + $(OPENSSL_PATH)/crypto/mem_sec.c + $(OPENSSL_PATH)/crypto/modes/cbc128.c + $(OPENSSL_PATH)/crypto/modes/ccm128.c + $(OPENSSL_PATH)/crypto/modes/cfb128.c + $(OPENSSL_PATH)/crypto/modes/ctr128.c + $(OPENSSL_PATH)/crypto/modes/cts128.c + $(OPENSSL_PATH)/crypto/modes/gcm128.c + $(OPENSSL_PATH)/crypto/modes/ocb128.c + $(OPENSSL_PATH)/crypto/modes/ofb128.c + $(OPENSSL_PATH)/crypto/modes/wrap128.c + $(OPENSSL_PATH)/crypto/modes/xts128.c + $(OPENSSL_PATH)/crypto/o_dir.c + $(OPENSSL_PATH)/crypto/o_fips.c + $(OPENSSL_PATH)/crypto/o_fopen.c + $(OPENSSL_PATH)/crypto/o_init.c + $(OPENSSL_PATH)/crypto/o_str.c + $(OPENSSL_PATH)/crypto/o_time.c + $(OPENSSL_PATH)/crypto/objects/o_names.c + $(OPENSSL_PATH)/crypto/objects/obj_dat.c + $(OPENSSL_PATH)/crypto/objects/obj_err.c + $(OPENSSL_PATH)/crypto/objects/obj_lib.c + $(OPENSSL_PATH)/crypto/objects/obj_xref.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_asn.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_cl.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_err.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_ext.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_ht.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_lib.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_prn.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_srv.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_vfy.c + $(OPENSSL_PATH)/crypto/ocsp/v3_ocsp.c + $(OPENSSL_PATH)/crypto/pem/pem_all.c + $(OPENSSL_PATH)/crypto/pem/pem_err.c + $(OPENSSL_PATH)/crypto/pem/pem_info.c + $(OPENSSL_PATH)/crypto/pem/pem_lib.c + $(OPENSSL_PATH)/crypto/pem/pem_oth.c + $(OPENSSL_PATH)/crypto/pem/pem_pk8.c + $(OPENSSL_PATH)/crypto/pem/pem_pkey.c + $(OPENSSL_PATH)/crypto/pem/pem_sign.c + $(OPENSSL_PATH)/crypto/pem/pem_x509.c + $(OPENSSL_PATH)/crypto/pem/pem_xaux.c + $(OPENSSL_PATH)/crypto/pem/pvkfmt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_add.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_asn.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_attr.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_crpt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_crt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_decr.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_init.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_key.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_kiss.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_mutl.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_npas.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_p8d.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_p8e.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_sbag.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_utl.c + $(OPENSSL_PATH)/crypto/pkcs12/pk12err.c + $(OPENSSL_PATH)/crypto/pkcs7/bio_pk7.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_asn1.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_attr.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_doit.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_lib.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_mime.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_smime.c + $(OPENSSL_PATH)/crypto/pkcs7/pkcs7err.c + $(OPENSSL_PATH)/crypto/rand/drbg_ctr.c + $(OPENSSL_PATH)/crypto/rand/drbg_lib.c + $(OPENSSL_PATH)/crypto/rand/rand_egd.c + $(OPENSSL_PATH)/crypto/rand/rand_err.c + $(OPENSSL_PATH)/crypto/rand/rand_lib.c + $(OPENSSL_PATH)/crypto/rand/rand_unix.c + $(OPENSSL_PATH)/crypto/rand/rand_vms.c + $(OPENSSL_PATH)/crypto/rand/rand_win.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ameth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_asn1.c + $(OPENSSL_PATH)/crypto/rsa/rsa_chk.c + $(OPENSSL_PATH)/crypto/rsa/rsa_crpt.c + $(OPENSSL_PATH)/crypto/rsa/rsa_depr.c + $(OPENSSL_PATH)/crypto/rsa/rsa_err.c + $(OPENSSL_PATH)/crypto/rsa/rsa_gen.c + $(OPENSSL_PATH)/crypto/rsa/rsa_lib.c + $(OPENSSL_PATH)/crypto/rsa/rsa_meth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_mp.c + $(OPENSSL_PATH)/crypto/rsa/rsa_none.c + $(OPENSSL_PATH)/crypto/rsa/rsa_oaep.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ossl.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pk1.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pmeth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_prn.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pss.c + $(OPENSSL_PATH)/crypto/rsa/rsa_saos.c + $(OPENSSL_PATH)/crypto/rsa/rsa_sign.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ssl.c + $(OPENSSL_PATH)/crypto/rsa/rsa_x931.c + $(OPENSSL_PATH)/crypto/rsa/rsa_x931g.c + $(OPENSSL_PATH)/crypto/sha/keccak1600.c + $(OPENSSL_PATH)/crypto/sha/sha1_one.c + $(OPENSSL_PATH)/crypto/sha/sha1dgst.c + $(OPENSSL_PATH)/crypto/sha/sha256.c + $(OPENSSL_PATH)/crypto/sha/sha512.c + $(OPENSSL_PATH)/crypto/siphash/siphash.c + $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c + $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm3/m_sm3.c + $(OPENSSL_PATH)/crypto/sm3/sm3.c + $(OPENSSL_PATH)/crypto/sm4/sm4.c + $(OPENSSL_PATH)/crypto/stack/stack.c + $(OPENSSL_PATH)/crypto/threads_none.c + $(OPENSSL_PATH)/crypto/threads_pthread.c + $(OPENSSL_PATH)/crypto/threads_win.c + $(OPENSSL_PATH)/crypto/txt_db/txt_db.c + $(OPENSSL_PATH)/crypto/ui/ui_err.c + $(OPENSSL_PATH)/crypto/ui/ui_lib.c + $(OPENSSL_PATH)/crypto/ui/ui_null.c + $(OPENSSL_PATH)/crypto/ui/ui_openssl.c + $(OPENSSL_PATH)/crypto/ui/ui_util.c + $(OPENSSL_PATH)/crypto/uid.c + $(OPENSSL_PATH)/crypto/x509/by_dir.c + $(OPENSSL_PATH)/crypto/x509/by_file.c + $(OPENSSL_PATH)/crypto/x509/t_crl.c + $(OPENSSL_PATH)/crypto/x509/t_req.c + $(OPENSSL_PATH)/crypto/x509/t_x509.c + $(OPENSSL_PATH)/crypto/x509/x509_att.c + $(OPENSSL_PATH)/crypto/x509/x509_cmp.c + $(OPENSSL_PATH)/crypto/x509/x509_d2.c + $(OPENSSL_PATH)/crypto/x509/x509_def.c + $(OPENSSL_PATH)/crypto/x509/x509_err.c + $(OPENSSL_PATH)/crypto/x509/x509_ext.c + $(OPENSSL_PATH)/crypto/x509/x509_lu.c + $(OPENSSL_PATH)/crypto/x509/x509_meth.c + $(OPENSSL_PATH)/crypto/x509/x509_obj.c + $(OPENSSL_PATH)/crypto/x509/x509_r2x.c + $(OPENSSL_PATH)/crypto/x509/x509_req.c + $(OPENSSL_PATH)/crypto/x509/x509_set.c + $(OPENSSL_PATH)/crypto/x509/x509_trs.c + $(OPENSSL_PATH)/crypto/x509/x509_txt.c + $(OPENSSL_PATH)/crypto/x509/x509_v3.c + $(OPENSSL_PATH)/crypto/x509/x509_vfy.c + $(OPENSSL_PATH)/crypto/x509/x509_vpm.c + $(OPENSSL_PATH)/crypto/x509/x509cset.c + $(OPENSSL_PATH)/crypto/x509/x509name.c + $(OPENSSL_PATH)/crypto/x509/x509rset.c + $(OPENSSL_PATH)/crypto/x509/x509spki.c + $(OPENSSL_PATH)/crypto/x509/x509type.c + $(OPENSSL_PATH)/crypto/x509/x_all.c + $(OPENSSL_PATH)/crypto/x509/x_attrib.c + $(OPENSSL_PATH)/crypto/x509/x_crl.c + $(OPENSSL_PATH)/crypto/x509/x_exten.c + $(OPENSSL_PATH)/crypto/x509/x_name.c + $(OPENSSL_PATH)/crypto/x509/x_pubkey.c + $(OPENSSL_PATH)/crypto/x509/x_req.c + $(OPENSSL_PATH)/crypto/x509/x_x509.c + $(OPENSSL_PATH)/crypto/x509/x_x509a.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_cache.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_data.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_lib.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_map.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_node.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_tree.c + $(OPENSSL_PATH)/crypto/x509v3/v3_addr.c + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.c + $(OPENSSL_PATH)/crypto/x509v3/v3_akey.c + $(OPENSSL_PATH)/crypto/x509v3/v3_akeya.c + $(OPENSSL_PATH)/crypto/x509v3/v3_alt.c + $(OPENSSL_PATH)/crypto/x509v3/v3_asid.c + $(OPENSSL_PATH)/crypto/x509v3/v3_bcons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_bitst.c + $(OPENSSL_PATH)/crypto/x509v3/v3_conf.c + $(OPENSSL_PATH)/crypto/x509v3/v3_cpols.c + $(OPENSSL_PATH)/crypto/x509v3/v3_crld.c + $(OPENSSL_PATH)/crypto/x509v3/v3_enum.c + $(OPENSSL_PATH)/crypto/x509v3/v3_extku.c + $(OPENSSL_PATH)/crypto/x509v3/v3_genn.c + $(OPENSSL_PATH)/crypto/x509v3/v3_ia5.c + $(OPENSSL_PATH)/crypto/x509v3/v3_info.c + $(OPENSSL_PATH)/crypto/x509v3/v3_int.c + $(OPENSSL_PATH)/crypto/x509v3/v3_lib.c + $(OPENSSL_PATH)/crypto/x509v3/v3_ncons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pci.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pcia.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pcons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pku.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pmaps.c + $(OPENSSL_PATH)/crypto/x509v3/v3_prn.c + $(OPENSSL_PATH)/crypto/x509v3/v3_purp.c + $(OPENSSL_PATH)/crypto/x509v3/v3_skey.c + $(OPENSSL_PATH)/crypto/x509v3/v3_sxnet.c + $(OPENSSL_PATH)/crypto/x509v3/v3_tlsf.c + $(OPENSSL_PATH)/crypto/x509v3/v3_utl.c + $(OPENSSL_PATH)/crypto/x509v3/v3err.c + $(OPENSSL_PATH)/crypto/arm_arch.h + $(OPENSSL_PATH)/crypto/mips_arch.h + $(OPENSSL_PATH)/crypto/ppc_arch.h + $(OPENSSL_PATH)/crypto/s390x_arch.h + $(OPENSSL_PATH)/crypto/sparc_arch.h + $(OPENSSL_PATH)/crypto/vms_rms.h + $(OPENSSL_PATH)/crypto/aes/aes_local.h + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h + $(OPENSSL_PATH)/crypto/asn1/asn1_local.h + $(OPENSSL_PATH)/crypto/asn1/charmap.h + $(OPENSSL_PATH)/crypto/asn1/standard_methods.h + $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h + $(OPENSSL_PATH)/crypto/async/async_local.h + $(OPENSSL_PATH)/crypto/async/arch/async_null.h + $(OPENSSL_PATH)/crypto/async/arch/async_posix.h + $(OPENSSL_PATH)/crypto/async/arch/async_win.h + $(OPENSSL_PATH)/crypto/bio/bio_local.h + $(OPENSSL_PATH)/crypto/bn/bn_local.h + $(OPENSSL_PATH)/crypto/bn/bn_prime.h + $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h + $(OPENSSL_PATH)/crypto/comp/comp_local.h + $(OPENSSL_PATH)/crypto/conf/conf_def.h + $(OPENSSL_PATH)/crypto/conf/conf_local.h + $(OPENSSL_PATH)/crypto/dh/dh_local.h + $(OPENSSL_PATH)/crypto/dso/dso_local.h + $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/evp/evp_local.h + $(OPENSSL_PATH)/crypto/hmac/hmac_local.h + $(OPENSSL_PATH)/crypto/lhash/lhash_local.h + $(OPENSSL_PATH)/crypto/md5/md5_local.h + $(OPENSSL_PATH)/crypto/modes/modes_local.h + $(OPENSSL_PATH)/crypto/objects/obj_dat.h + $(OPENSSL_PATH)/crypto/objects/obj_local.h + $(OPENSSL_PATH)/crypto/objects/obj_xref.h + $(OPENSSL_PATH)/crypto/ocsp/ocsp_local.h + $(OPENSSL_PATH)/crypto/pkcs12/p12_local.h + $(OPENSSL_PATH)/crypto/rand/rand_local.h + $(OPENSSL_PATH)/crypto/rsa/rsa_local.h + $(OPENSSL_PATH)/crypto/sha/sha_local.h + $(OPENSSL_PATH)/crypto/siphash/siphash_local.h + $(OPENSSL_PATH)/crypto/sm3/sm3_local.h + $(OPENSSL_PATH)/crypto/store/store_local.h + $(OPENSSL_PATH)/crypto/ui/ui_local.h + $(OPENSSL_PATH)/crypto/x509/x509_local.h + $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h + $(OPENSSL_PATH)/crypto/x509v3/pcy_local.h + $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h + $(OPENSSL_PATH)/ssl/bio_ssl.c + $(OPENSSL_PATH)/ssl/d1_lib.c + $(OPENSSL_PATH)/ssl/d1_msg.c + $(OPENSSL_PATH)/ssl/d1_srtp.c + $(OPENSSL_PATH)/ssl/methods.c + $(OPENSSL_PATH)/ssl/packet.c + $(OPENSSL_PATH)/ssl/pqueue.c + $(OPENSSL_PATH)/ssl/record/dtls1_bitmap.c + $(OPENSSL_PATH)/ssl/record/rec_layer_d1.c + $(OPENSSL_PATH)/ssl/record/rec_layer_s3.c + $(OPENSSL_PATH)/ssl/record/ssl3_buffer.c + $(OPENSSL_PATH)/ssl/record/ssl3_record.c + $(OPENSSL_PATH)/ssl/record/ssl3_record_tls13.c + $(OPENSSL_PATH)/ssl/s3_cbc.c + $(OPENSSL_PATH)/ssl/s3_enc.c + $(OPENSSL_PATH)/ssl/s3_lib.c + $(OPENSSL_PATH)/ssl/s3_msg.c + $(OPENSSL_PATH)/ssl/ssl_asn1.c + $(OPENSSL_PATH)/ssl/ssl_cert.c + $(OPENSSL_PATH)/ssl/ssl_ciph.c + $(OPENSSL_PATH)/ssl/ssl_conf.c + $(OPENSSL_PATH)/ssl/ssl_err.c + $(OPENSSL_PATH)/ssl/ssl_init.c + $(OPENSSL_PATH)/ssl/ssl_lib.c + $(OPENSSL_PATH)/ssl/ssl_mcnf.c + $(OPENSSL_PATH)/ssl/ssl_rsa.c + $(OPENSSL_PATH)/ssl/ssl_sess.c + $(OPENSSL_PATH)/ssl/ssl_stat.c + $(OPENSSL_PATH)/ssl/ssl_txt.c + $(OPENSSL_PATH)/ssl/ssl_utst.c + $(OPENSSL_PATH)/ssl/statem/extensions.c + $(OPENSSL_PATH)/ssl/statem/extensions_clnt.c + $(OPENSSL_PATH)/ssl/statem/extensions_cust.c + $(OPENSSL_PATH)/ssl/statem/extensions_srvr.c + $(OPENSSL_PATH)/ssl/statem/statem.c + $(OPENSSL_PATH)/ssl/statem/statem_clnt.c + $(OPENSSL_PATH)/ssl/statem/statem_dtls.c + $(OPENSSL_PATH)/ssl/statem/statem_lib.c + $(OPENSSL_PATH)/ssl/statem/statem_srvr.c + $(OPENSSL_PATH)/ssl/t1_enc.c + $(OPENSSL_PATH)/ssl/t1_lib.c + $(OPENSSL_PATH)/ssl/t1_trce.c + $(OPENSSL_PATH)/ssl/tls13_enc.c + $(OPENSSL_PATH)/ssl/tls_srp.c + $(OPENSSL_PATH)/ssl/packet_local.h + $(OPENSSL_PATH)/ssl/ssl_cert_table.h + $(OPENSSL_PATH)/ssl/ssl_local.h + $(OPENSSL_PATH)/ssl/record/record.h + $(OPENSSL_PATH)/ssl/record/record_local.h + $(OPENSSL_PATH)/ssl/statem/statem.h + $(OPENSSL_PATH)/ssl/statem/statem_local.h +# Autogenerated files list ends here + buildinf.h + ossl_store.c + rand_pool.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + RngLib + PrintLib + +[FixedPcd] + gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES + +[BuildOptions] + # + # Disables the following Visual Studio compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4090: 'function' : different 'const' qualifiers + # C4132: 'object' : const object should be initialized (tls13_enc.c) + # C4210: nonstandard extension used: function given file scope + # C4244: conversion from type1 to type2, possible loss of data + # C4245: conversion from type1 to type2, signed/unsigned mismatch + # C4267: conversion from size_t to type, possible loss of data + # C4306: 'identifier' : conversion from 'type1' to 'type2' of greater size + # C4310: cast truncates constant value + # C4389: 'operator' : signed/unsigned mismatch (xxxx) + # C4700: uninitialized local variable 'name' used. (conf_sap.c(71)) + # C4702: unreachable code + # C4706: assignment within conditional expression + # C4819: The file contains a character that cannot be represented in the current code page + # + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 + + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w + + # + # Suppress the following build warnings in openssl so we don't break the build with -Werror + # -Werror=maybe-uninitialized: there exist some other paths for which the variable is not initialized. + # -Werror=format: Check calls to printf and scanf, etc., to make sure that the arguments supplied have + # types appropriate to the format string specified. + # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). + # + GCC:*_*_IA32_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + + # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: + # 1295: Deprecated declaration - give arg types + # 550: was set but never used + # 1293: assignment in condition + # 111: statement is unreachable (invariably "break;" after "return X;" in case statement) + # 68: integer conversion resulted in a change of sign ("if (Status == -1)") + # 177: was declared but never referenced + # 223: function declared implicitly + # 144: a value of type cannot be used to initialize an entity of type + # 513: a value of type cannot be assigned to an entity of type + # 188: enumerated type mixed with another type (i.e. passing an integer as an enum without a cast) + # 1296: Extended constant initialiser used + # 128: loop is not reachable - may be emitted inappropriately if code follows a conditional return + # from the function that evaluates to true at compile time + # 546: transfer of control bypasses initialization - may be emitted inappropriately if the uninitialized + # variable is never referenced after the jump + # 1: ignore "#1-D: last line of file ends without a newline" + # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with + # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf b/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf new file mode 100644 index 0000000000..150a82ec7a --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf @@ -0,0 +1,699 @@ +## @file +# This module provides OpenSSL Library implementation. +# +# Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
+# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = OpensslLibIa32Gcc + MODULE_UNI_FILE = OpensslLib.uni + FILE_GUID = B1B32F26-A4E1-4D38-9E34-53A148B8EB11 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = OpensslLib + DEFINE OPENSSL_PATH = openssl + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE + DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM + CONSTRUCTOR = OpensslLibConstructor + +# +# VALID_ARCHITECTURES = IA32 +# + +[Sources.IA32] + OpensslLibConstructor.c + $(OPENSSL_PATH)/e_os.h + $(OPENSSL_PATH)/ms/uplink.h +# Autogenerated files list starts here + IA32Gcc/crypto/aes/aesni-x86.S + IA32Gcc/crypto/aes/vpaes-x86.S + IA32Gcc/crypto/modes/ghash-x86.S + IA32Gcc/crypto/sha/sha1-586.S + IA32Gcc/crypto/sha/sha256-586.S + IA32Gcc/crypto/sha/sha512-586.S + IA32Gcc/crypto/x86cpuid.S + $(OPENSSL_PATH)/crypto/aes/aes_cbc.c + $(OPENSSL_PATH)/crypto/aes/aes_cfb.c + $(OPENSSL_PATH)/crypto/aes/aes_core.c + $(OPENSSL_PATH)/crypto/aes/aes_ige.c + $(OPENSSL_PATH)/crypto/aes/aes_misc.c + $(OPENSSL_PATH)/crypto/aes/aes_ofb.c + $(OPENSSL_PATH)/crypto/aes/aes_wrap.c + $(OPENSSL_PATH)/crypto/aria/aria.c + $(OPENSSL_PATH)/crypto/asn1/a_bitstr.c + $(OPENSSL_PATH)/crypto/asn1/a_d2i_fp.c + $(OPENSSL_PATH)/crypto/asn1/a_digest.c + $(OPENSSL_PATH)/crypto/asn1/a_dup.c + $(OPENSSL_PATH)/crypto/asn1/a_gentm.c + $(OPENSSL_PATH)/crypto/asn1/a_i2d_fp.c + $(OPENSSL_PATH)/crypto/asn1/a_int.c + $(OPENSSL_PATH)/crypto/asn1/a_mbstr.c + $(OPENSSL_PATH)/crypto/asn1/a_object.c + $(OPENSSL_PATH)/crypto/asn1/a_octet.c + $(OPENSSL_PATH)/crypto/asn1/a_print.c + $(OPENSSL_PATH)/crypto/asn1/a_sign.c + $(OPENSSL_PATH)/crypto/asn1/a_strex.c + $(OPENSSL_PATH)/crypto/asn1/a_strnid.c + $(OPENSSL_PATH)/crypto/asn1/a_time.c + $(OPENSSL_PATH)/crypto/asn1/a_type.c + $(OPENSSL_PATH)/crypto/asn1/a_utctm.c + $(OPENSSL_PATH)/crypto/asn1/a_utf8.c + $(OPENSSL_PATH)/crypto/asn1/a_verify.c + $(OPENSSL_PATH)/crypto/asn1/ameth_lib.c + $(OPENSSL_PATH)/crypto/asn1/asn1_err.c + $(OPENSSL_PATH)/crypto/asn1/asn1_gen.c + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.c + $(OPENSSL_PATH)/crypto/asn1/asn1_lib.c + $(OPENSSL_PATH)/crypto/asn1/asn1_par.c + $(OPENSSL_PATH)/crypto/asn1/asn_mime.c + $(OPENSSL_PATH)/crypto/asn1/asn_moid.c + $(OPENSSL_PATH)/crypto/asn1/asn_mstbl.c + $(OPENSSL_PATH)/crypto/asn1/asn_pack.c + $(OPENSSL_PATH)/crypto/asn1/bio_asn1.c + $(OPENSSL_PATH)/crypto/asn1/bio_ndef.c + $(OPENSSL_PATH)/crypto/asn1/d2i_pr.c + $(OPENSSL_PATH)/crypto/asn1/d2i_pu.c + $(OPENSSL_PATH)/crypto/asn1/evp_asn1.c + $(OPENSSL_PATH)/crypto/asn1/f_int.c + $(OPENSSL_PATH)/crypto/asn1/f_string.c + $(OPENSSL_PATH)/crypto/asn1/i2d_pr.c + $(OPENSSL_PATH)/crypto/asn1/i2d_pu.c + $(OPENSSL_PATH)/crypto/asn1/n_pkey.c + $(OPENSSL_PATH)/crypto/asn1/nsseq.c + $(OPENSSL_PATH)/crypto/asn1/p5_pbe.c + $(OPENSSL_PATH)/crypto/asn1/p5_pbev2.c + $(OPENSSL_PATH)/crypto/asn1/p5_scrypt.c + $(OPENSSL_PATH)/crypto/asn1/p8_pkey.c + $(OPENSSL_PATH)/crypto/asn1/t_bitst.c + $(OPENSSL_PATH)/crypto/asn1/t_pkey.c + $(OPENSSL_PATH)/crypto/asn1/t_spki.c + $(OPENSSL_PATH)/crypto/asn1/tasn_dec.c + $(OPENSSL_PATH)/crypto/asn1/tasn_enc.c + $(OPENSSL_PATH)/crypto/asn1/tasn_fre.c + $(OPENSSL_PATH)/crypto/asn1/tasn_new.c + $(OPENSSL_PATH)/crypto/asn1/tasn_prn.c + $(OPENSSL_PATH)/crypto/asn1/tasn_scn.c + $(OPENSSL_PATH)/crypto/asn1/tasn_typ.c + $(OPENSSL_PATH)/crypto/asn1/tasn_utl.c + $(OPENSSL_PATH)/crypto/asn1/x_algor.c + $(OPENSSL_PATH)/crypto/asn1/x_bignum.c + $(OPENSSL_PATH)/crypto/asn1/x_info.c + $(OPENSSL_PATH)/crypto/asn1/x_int64.c + $(OPENSSL_PATH)/crypto/asn1/x_long.c + $(OPENSSL_PATH)/crypto/asn1/x_pkey.c + $(OPENSSL_PATH)/crypto/asn1/x_sig.c + $(OPENSSL_PATH)/crypto/asn1/x_spki.c + $(OPENSSL_PATH)/crypto/asn1/x_val.c + $(OPENSSL_PATH)/crypto/async/arch/async_null.c + $(OPENSSL_PATH)/crypto/async/arch/async_posix.c + $(OPENSSL_PATH)/crypto/async/arch/async_win.c + $(OPENSSL_PATH)/crypto/async/async.c + $(OPENSSL_PATH)/crypto/async/async_err.c + $(OPENSSL_PATH)/crypto/async/async_wait.c + $(OPENSSL_PATH)/crypto/bio/b_addr.c + $(OPENSSL_PATH)/crypto/bio/b_dump.c + $(OPENSSL_PATH)/crypto/bio/b_sock.c + $(OPENSSL_PATH)/crypto/bio/b_sock2.c + $(OPENSSL_PATH)/crypto/bio/bf_buff.c + $(OPENSSL_PATH)/crypto/bio/bf_lbuf.c + $(OPENSSL_PATH)/crypto/bio/bf_nbio.c + $(OPENSSL_PATH)/crypto/bio/bf_null.c + $(OPENSSL_PATH)/crypto/bio/bio_cb.c + $(OPENSSL_PATH)/crypto/bio/bio_err.c + $(OPENSSL_PATH)/crypto/bio/bio_lib.c + $(OPENSSL_PATH)/crypto/bio/bio_meth.c + $(OPENSSL_PATH)/crypto/bio/bss_acpt.c + $(OPENSSL_PATH)/crypto/bio/bss_bio.c + $(OPENSSL_PATH)/crypto/bio/bss_conn.c + $(OPENSSL_PATH)/crypto/bio/bss_dgram.c + $(OPENSSL_PATH)/crypto/bio/bss_fd.c + $(OPENSSL_PATH)/crypto/bio/bss_file.c + $(OPENSSL_PATH)/crypto/bio/bss_log.c + $(OPENSSL_PATH)/crypto/bio/bss_mem.c + $(OPENSSL_PATH)/crypto/bio/bss_null.c + $(OPENSSL_PATH)/crypto/bio/bss_sock.c + $(OPENSSL_PATH)/crypto/bn/bn_add.c + $(OPENSSL_PATH)/crypto/bn/bn_asm.c + $(OPENSSL_PATH)/crypto/bn/bn_blind.c + $(OPENSSL_PATH)/crypto/bn/bn_const.c + $(OPENSSL_PATH)/crypto/bn/bn_ctx.c + $(OPENSSL_PATH)/crypto/bn/bn_depr.c + $(OPENSSL_PATH)/crypto/bn/bn_dh.c + $(OPENSSL_PATH)/crypto/bn/bn_div.c + $(OPENSSL_PATH)/crypto/bn/bn_err.c + $(OPENSSL_PATH)/crypto/bn/bn_exp.c + $(OPENSSL_PATH)/crypto/bn/bn_exp2.c + $(OPENSSL_PATH)/crypto/bn/bn_gcd.c + $(OPENSSL_PATH)/crypto/bn/bn_gf2m.c + $(OPENSSL_PATH)/crypto/bn/bn_intern.c + $(OPENSSL_PATH)/crypto/bn/bn_kron.c + $(OPENSSL_PATH)/crypto/bn/bn_lib.c + $(OPENSSL_PATH)/crypto/bn/bn_mod.c + $(OPENSSL_PATH)/crypto/bn/bn_mont.c + $(OPENSSL_PATH)/crypto/bn/bn_mpi.c + $(OPENSSL_PATH)/crypto/bn/bn_mul.c + $(OPENSSL_PATH)/crypto/bn/bn_nist.c + $(OPENSSL_PATH)/crypto/bn/bn_prime.c + $(OPENSSL_PATH)/crypto/bn/bn_print.c + $(OPENSSL_PATH)/crypto/bn/bn_rand.c + $(OPENSSL_PATH)/crypto/bn/bn_recp.c + $(OPENSSL_PATH)/crypto/bn/bn_shift.c + $(OPENSSL_PATH)/crypto/bn/bn_sqr.c + $(OPENSSL_PATH)/crypto/bn/bn_sqrt.c + $(OPENSSL_PATH)/crypto/bn/bn_srp.c + $(OPENSSL_PATH)/crypto/bn/bn_word.c + $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/buffer/buf_err.c + $(OPENSSL_PATH)/crypto/buffer/buffer.c + $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c + $(OPENSSL_PATH)/crypto/cmac/cm_pmeth.c + $(OPENSSL_PATH)/crypto/cmac/cmac.c + $(OPENSSL_PATH)/crypto/comp/c_zlib.c + $(OPENSSL_PATH)/crypto/comp/comp_err.c + $(OPENSSL_PATH)/crypto/comp/comp_lib.c + $(OPENSSL_PATH)/crypto/conf/conf_api.c + $(OPENSSL_PATH)/crypto/conf/conf_def.c + $(OPENSSL_PATH)/crypto/conf/conf_err.c + $(OPENSSL_PATH)/crypto/conf/conf_lib.c + $(OPENSSL_PATH)/crypto/conf/conf_mall.c + $(OPENSSL_PATH)/crypto/conf/conf_mod.c + $(OPENSSL_PATH)/crypto/conf/conf_sap.c + $(OPENSSL_PATH)/crypto/conf/conf_ssl.c + $(OPENSSL_PATH)/crypto/cpt_err.c + $(OPENSSL_PATH)/crypto/cryptlib.c + $(OPENSSL_PATH)/crypto/ctype.c + $(OPENSSL_PATH)/crypto/cversion.c + $(OPENSSL_PATH)/crypto/dh/dh_ameth.c + $(OPENSSL_PATH)/crypto/dh/dh_asn1.c + $(OPENSSL_PATH)/crypto/dh/dh_check.c + $(OPENSSL_PATH)/crypto/dh/dh_depr.c + $(OPENSSL_PATH)/crypto/dh/dh_err.c + $(OPENSSL_PATH)/crypto/dh/dh_gen.c + $(OPENSSL_PATH)/crypto/dh/dh_kdf.c + $(OPENSSL_PATH)/crypto/dh/dh_key.c + $(OPENSSL_PATH)/crypto/dh/dh_lib.c + $(OPENSSL_PATH)/crypto/dh/dh_meth.c + $(OPENSSL_PATH)/crypto/dh/dh_pmeth.c + $(OPENSSL_PATH)/crypto/dh/dh_prn.c + $(OPENSSL_PATH)/crypto/dh/dh_rfc5114.c + $(OPENSSL_PATH)/crypto/dh/dh_rfc7919.c + $(OPENSSL_PATH)/crypto/dso/dso_dl.c + $(OPENSSL_PATH)/crypto/dso/dso_dlfcn.c + $(OPENSSL_PATH)/crypto/dso/dso_err.c + $(OPENSSL_PATH)/crypto/dso/dso_lib.c + $(OPENSSL_PATH)/crypto/dso/dso_openssl.c + $(OPENSSL_PATH)/crypto/dso/dso_vms.c + $(OPENSSL_PATH)/crypto/dso/dso_win32.c + $(OPENSSL_PATH)/crypto/ebcdic.c + $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/err/err.c + $(OPENSSL_PATH)/crypto/err/err_prn.c + $(OPENSSL_PATH)/crypto/evp/bio_b64.c + $(OPENSSL_PATH)/crypto/evp/bio_enc.c + $(OPENSSL_PATH)/crypto/evp/bio_md.c + $(OPENSSL_PATH)/crypto/evp/bio_ok.c + $(OPENSSL_PATH)/crypto/evp/c_allc.c + $(OPENSSL_PATH)/crypto/evp/c_alld.c + $(OPENSSL_PATH)/crypto/evp/cmeth_lib.c + $(OPENSSL_PATH)/crypto/evp/digest.c + $(OPENSSL_PATH)/crypto/evp/e_aes.c + $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha1.c + $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha256.c + $(OPENSSL_PATH)/crypto/evp/e_aria.c + $(OPENSSL_PATH)/crypto/evp/e_bf.c + $(OPENSSL_PATH)/crypto/evp/e_camellia.c + $(OPENSSL_PATH)/crypto/evp/e_cast.c + $(OPENSSL_PATH)/crypto/evp/e_chacha20_poly1305.c + $(OPENSSL_PATH)/crypto/evp/e_des.c + $(OPENSSL_PATH)/crypto/evp/e_des3.c + $(OPENSSL_PATH)/crypto/evp/e_idea.c + $(OPENSSL_PATH)/crypto/evp/e_null.c + $(OPENSSL_PATH)/crypto/evp/e_old.c + $(OPENSSL_PATH)/crypto/evp/e_rc2.c + $(OPENSSL_PATH)/crypto/evp/e_rc4.c + $(OPENSSL_PATH)/crypto/evp/e_rc4_hmac_md5.c + $(OPENSSL_PATH)/crypto/evp/e_rc5.c + $(OPENSSL_PATH)/crypto/evp/e_seed.c + $(OPENSSL_PATH)/crypto/evp/e_sm4.c + $(OPENSSL_PATH)/crypto/evp/e_xcbc_d.c + $(OPENSSL_PATH)/crypto/evp/encode.c + $(OPENSSL_PATH)/crypto/evp/evp_cnf.c + $(OPENSSL_PATH)/crypto/evp/evp_enc.c + $(OPENSSL_PATH)/crypto/evp/evp_err.c + $(OPENSSL_PATH)/crypto/evp/evp_key.c + $(OPENSSL_PATH)/crypto/evp/evp_lib.c + $(OPENSSL_PATH)/crypto/evp/evp_pbe.c + $(OPENSSL_PATH)/crypto/evp/evp_pkey.c + $(OPENSSL_PATH)/crypto/evp/m_md2.c + $(OPENSSL_PATH)/crypto/evp/m_md4.c + $(OPENSSL_PATH)/crypto/evp/m_md5.c + $(OPENSSL_PATH)/crypto/evp/m_md5_sha1.c + $(OPENSSL_PATH)/crypto/evp/m_mdc2.c + $(OPENSSL_PATH)/crypto/evp/m_null.c + $(OPENSSL_PATH)/crypto/evp/m_ripemd.c + $(OPENSSL_PATH)/crypto/evp/m_sha1.c + $(OPENSSL_PATH)/crypto/evp/m_sha3.c + $(OPENSSL_PATH)/crypto/evp/m_sigver.c + $(OPENSSL_PATH)/crypto/evp/m_wp.c + $(OPENSSL_PATH)/crypto/evp/names.c + $(OPENSSL_PATH)/crypto/evp/p5_crpt.c + $(OPENSSL_PATH)/crypto/evp/p5_crpt2.c + $(OPENSSL_PATH)/crypto/evp/p_dec.c + $(OPENSSL_PATH)/crypto/evp/p_enc.c + $(OPENSSL_PATH)/crypto/evp/p_lib.c + $(OPENSSL_PATH)/crypto/evp/p_open.c + $(OPENSSL_PATH)/crypto/evp/p_seal.c + $(OPENSSL_PATH)/crypto/evp/p_sign.c + $(OPENSSL_PATH)/crypto/evp/p_verify.c + $(OPENSSL_PATH)/crypto/evp/pbe_scrypt.c + $(OPENSSL_PATH)/crypto/evp/pmeth_fn.c + $(OPENSSL_PATH)/crypto/evp/pmeth_gn.c + $(OPENSSL_PATH)/crypto/evp/pmeth_lib.c + $(OPENSSL_PATH)/crypto/ex_data.c + $(OPENSSL_PATH)/crypto/getenv.c + $(OPENSSL_PATH)/crypto/hmac/hm_ameth.c + $(OPENSSL_PATH)/crypto/hmac/hm_pmeth.c + $(OPENSSL_PATH)/crypto/hmac/hmac.c + $(OPENSSL_PATH)/crypto/init.c + $(OPENSSL_PATH)/crypto/kdf/hkdf.c + $(OPENSSL_PATH)/crypto/kdf/kdf_err.c + $(OPENSSL_PATH)/crypto/kdf/scrypt.c + $(OPENSSL_PATH)/crypto/kdf/tls1_prf.c + $(OPENSSL_PATH)/crypto/lhash/lh_stats.c + $(OPENSSL_PATH)/crypto/lhash/lhash.c + $(OPENSSL_PATH)/crypto/md5/md5_dgst.c + $(OPENSSL_PATH)/crypto/md5/md5_one.c + $(OPENSSL_PATH)/crypto/mem.c + $(OPENSSL_PATH)/crypto/mem_dbg.c + $(OPENSSL_PATH)/crypto/mem_sec.c + $(OPENSSL_PATH)/crypto/modes/cbc128.c + $(OPENSSL_PATH)/crypto/modes/ccm128.c + $(OPENSSL_PATH)/crypto/modes/cfb128.c + $(OPENSSL_PATH)/crypto/modes/ctr128.c + $(OPENSSL_PATH)/crypto/modes/cts128.c + $(OPENSSL_PATH)/crypto/modes/gcm128.c + $(OPENSSL_PATH)/crypto/modes/ocb128.c + $(OPENSSL_PATH)/crypto/modes/ofb128.c + $(OPENSSL_PATH)/crypto/modes/wrap128.c + $(OPENSSL_PATH)/crypto/modes/xts128.c + $(OPENSSL_PATH)/crypto/o_dir.c + $(OPENSSL_PATH)/crypto/o_fips.c + $(OPENSSL_PATH)/crypto/o_fopen.c + $(OPENSSL_PATH)/crypto/o_init.c + $(OPENSSL_PATH)/crypto/o_str.c + $(OPENSSL_PATH)/crypto/o_time.c + $(OPENSSL_PATH)/crypto/objects/o_names.c + $(OPENSSL_PATH)/crypto/objects/obj_dat.c + $(OPENSSL_PATH)/crypto/objects/obj_err.c + $(OPENSSL_PATH)/crypto/objects/obj_lib.c + $(OPENSSL_PATH)/crypto/objects/obj_xref.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_asn.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_cl.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_err.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_ext.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_ht.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_lib.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_prn.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_srv.c + $(OPENSSL_PATH)/crypto/ocsp/ocsp_vfy.c + $(OPENSSL_PATH)/crypto/ocsp/v3_ocsp.c + $(OPENSSL_PATH)/crypto/pem/pem_all.c + $(OPENSSL_PATH)/crypto/pem/pem_err.c + $(OPENSSL_PATH)/crypto/pem/pem_info.c + $(OPENSSL_PATH)/crypto/pem/pem_lib.c + $(OPENSSL_PATH)/crypto/pem/pem_oth.c + $(OPENSSL_PATH)/crypto/pem/pem_pk8.c + $(OPENSSL_PATH)/crypto/pem/pem_pkey.c + $(OPENSSL_PATH)/crypto/pem/pem_sign.c + $(OPENSSL_PATH)/crypto/pem/pem_x509.c + $(OPENSSL_PATH)/crypto/pem/pem_xaux.c + $(OPENSSL_PATH)/crypto/pem/pvkfmt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_add.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_asn.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_attr.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_crpt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_crt.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_decr.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_init.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_key.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_kiss.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_mutl.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_npas.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_p8d.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_p8e.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_sbag.c + $(OPENSSL_PATH)/crypto/pkcs12/p12_utl.c + $(OPENSSL_PATH)/crypto/pkcs12/pk12err.c + $(OPENSSL_PATH)/crypto/pkcs7/bio_pk7.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_asn1.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_attr.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_doit.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_lib.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_mime.c + $(OPENSSL_PATH)/crypto/pkcs7/pk7_smime.c + $(OPENSSL_PATH)/crypto/pkcs7/pkcs7err.c + $(OPENSSL_PATH)/crypto/rand/drbg_ctr.c + $(OPENSSL_PATH)/crypto/rand/drbg_lib.c + $(OPENSSL_PATH)/crypto/rand/rand_egd.c + $(OPENSSL_PATH)/crypto/rand/rand_err.c + $(OPENSSL_PATH)/crypto/rand/rand_lib.c + $(OPENSSL_PATH)/crypto/rand/rand_unix.c + $(OPENSSL_PATH)/crypto/rand/rand_vms.c + $(OPENSSL_PATH)/crypto/rand/rand_win.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ameth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_asn1.c + $(OPENSSL_PATH)/crypto/rsa/rsa_chk.c + $(OPENSSL_PATH)/crypto/rsa/rsa_crpt.c + $(OPENSSL_PATH)/crypto/rsa/rsa_depr.c + $(OPENSSL_PATH)/crypto/rsa/rsa_err.c + $(OPENSSL_PATH)/crypto/rsa/rsa_gen.c + $(OPENSSL_PATH)/crypto/rsa/rsa_lib.c + $(OPENSSL_PATH)/crypto/rsa/rsa_meth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_mp.c + $(OPENSSL_PATH)/crypto/rsa/rsa_none.c + $(OPENSSL_PATH)/crypto/rsa/rsa_oaep.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ossl.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pk1.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pmeth.c + $(OPENSSL_PATH)/crypto/rsa/rsa_prn.c + $(OPENSSL_PATH)/crypto/rsa/rsa_pss.c + $(OPENSSL_PATH)/crypto/rsa/rsa_saos.c + $(OPENSSL_PATH)/crypto/rsa/rsa_sign.c + $(OPENSSL_PATH)/crypto/rsa/rsa_ssl.c + $(OPENSSL_PATH)/crypto/rsa/rsa_x931.c + $(OPENSSL_PATH)/crypto/rsa/rsa_x931g.c + $(OPENSSL_PATH)/crypto/sha/keccak1600.c + $(OPENSSL_PATH)/crypto/sha/sha1_one.c + $(OPENSSL_PATH)/crypto/sha/sha1dgst.c + $(OPENSSL_PATH)/crypto/sha/sha256.c + $(OPENSSL_PATH)/crypto/sha/sha512.c + $(OPENSSL_PATH)/crypto/siphash/siphash.c + $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c + $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm3/m_sm3.c + $(OPENSSL_PATH)/crypto/sm3/sm3.c + $(OPENSSL_PATH)/crypto/sm4/sm4.c + $(OPENSSL_PATH)/crypto/stack/stack.c + $(OPENSSL_PATH)/crypto/threads_none.c + $(OPENSSL_PATH)/crypto/threads_pthread.c + $(OPENSSL_PATH)/crypto/threads_win.c + $(OPENSSL_PATH)/crypto/txt_db/txt_db.c + $(OPENSSL_PATH)/crypto/ui/ui_err.c + $(OPENSSL_PATH)/crypto/ui/ui_lib.c + $(OPENSSL_PATH)/crypto/ui/ui_null.c + $(OPENSSL_PATH)/crypto/ui/ui_openssl.c + $(OPENSSL_PATH)/crypto/ui/ui_util.c + $(OPENSSL_PATH)/crypto/uid.c + $(OPENSSL_PATH)/crypto/x509/by_dir.c + $(OPENSSL_PATH)/crypto/x509/by_file.c + $(OPENSSL_PATH)/crypto/x509/t_crl.c + $(OPENSSL_PATH)/crypto/x509/t_req.c + $(OPENSSL_PATH)/crypto/x509/t_x509.c + $(OPENSSL_PATH)/crypto/x509/x509_att.c + $(OPENSSL_PATH)/crypto/x509/x509_cmp.c + $(OPENSSL_PATH)/crypto/x509/x509_d2.c + $(OPENSSL_PATH)/crypto/x509/x509_def.c + $(OPENSSL_PATH)/crypto/x509/x509_err.c + $(OPENSSL_PATH)/crypto/x509/x509_ext.c + $(OPENSSL_PATH)/crypto/x509/x509_lu.c + $(OPENSSL_PATH)/crypto/x509/x509_meth.c + $(OPENSSL_PATH)/crypto/x509/x509_obj.c + $(OPENSSL_PATH)/crypto/x509/x509_r2x.c + $(OPENSSL_PATH)/crypto/x509/x509_req.c + $(OPENSSL_PATH)/crypto/x509/x509_set.c + $(OPENSSL_PATH)/crypto/x509/x509_trs.c + $(OPENSSL_PATH)/crypto/x509/x509_txt.c + $(OPENSSL_PATH)/crypto/x509/x509_v3.c + $(OPENSSL_PATH)/crypto/x509/x509_vfy.c + $(OPENSSL_PATH)/crypto/x509/x509_vpm.c + $(OPENSSL_PATH)/crypto/x509/x509cset.c + $(OPENSSL_PATH)/crypto/x509/x509name.c + $(OPENSSL_PATH)/crypto/x509/x509rset.c + $(OPENSSL_PATH)/crypto/x509/x509spki.c + $(OPENSSL_PATH)/crypto/x509/x509type.c + $(OPENSSL_PATH)/crypto/x509/x_all.c + $(OPENSSL_PATH)/crypto/x509/x_attrib.c + $(OPENSSL_PATH)/crypto/x509/x_crl.c + $(OPENSSL_PATH)/crypto/x509/x_exten.c + $(OPENSSL_PATH)/crypto/x509/x_name.c + $(OPENSSL_PATH)/crypto/x509/x_pubkey.c + $(OPENSSL_PATH)/crypto/x509/x_req.c + $(OPENSSL_PATH)/crypto/x509/x_x509.c + $(OPENSSL_PATH)/crypto/x509/x_x509a.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_cache.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_data.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_lib.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_map.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_node.c + $(OPENSSL_PATH)/crypto/x509v3/pcy_tree.c + $(OPENSSL_PATH)/crypto/x509v3/v3_addr.c + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.c + $(OPENSSL_PATH)/crypto/x509v3/v3_akey.c + $(OPENSSL_PATH)/crypto/x509v3/v3_akeya.c + $(OPENSSL_PATH)/crypto/x509v3/v3_alt.c + $(OPENSSL_PATH)/crypto/x509v3/v3_asid.c + $(OPENSSL_PATH)/crypto/x509v3/v3_bcons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_bitst.c + $(OPENSSL_PATH)/crypto/x509v3/v3_conf.c + $(OPENSSL_PATH)/crypto/x509v3/v3_cpols.c + $(OPENSSL_PATH)/crypto/x509v3/v3_crld.c + $(OPENSSL_PATH)/crypto/x509v3/v3_enum.c + $(OPENSSL_PATH)/crypto/x509v3/v3_extku.c + $(OPENSSL_PATH)/crypto/x509v3/v3_genn.c + $(OPENSSL_PATH)/crypto/x509v3/v3_ia5.c + $(OPENSSL_PATH)/crypto/x509v3/v3_info.c + $(OPENSSL_PATH)/crypto/x509v3/v3_int.c + $(OPENSSL_PATH)/crypto/x509v3/v3_lib.c + $(OPENSSL_PATH)/crypto/x509v3/v3_ncons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pci.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pcia.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pcons.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pku.c + $(OPENSSL_PATH)/crypto/x509v3/v3_pmaps.c + $(OPENSSL_PATH)/crypto/x509v3/v3_prn.c + $(OPENSSL_PATH)/crypto/x509v3/v3_purp.c + $(OPENSSL_PATH)/crypto/x509v3/v3_skey.c + $(OPENSSL_PATH)/crypto/x509v3/v3_sxnet.c + $(OPENSSL_PATH)/crypto/x509v3/v3_tlsf.c + $(OPENSSL_PATH)/crypto/x509v3/v3_utl.c + $(OPENSSL_PATH)/crypto/x509v3/v3err.c + $(OPENSSL_PATH)/crypto/arm_arch.h + $(OPENSSL_PATH)/crypto/mips_arch.h + $(OPENSSL_PATH)/crypto/ppc_arch.h + $(OPENSSL_PATH)/crypto/s390x_arch.h + $(OPENSSL_PATH)/crypto/sparc_arch.h + $(OPENSSL_PATH)/crypto/vms_rms.h + $(OPENSSL_PATH)/crypto/aes/aes_local.h + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h + $(OPENSSL_PATH)/crypto/asn1/asn1_local.h + $(OPENSSL_PATH)/crypto/asn1/charmap.h + $(OPENSSL_PATH)/crypto/asn1/standard_methods.h + $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h + $(OPENSSL_PATH)/crypto/async/async_local.h + $(OPENSSL_PATH)/crypto/async/arch/async_null.h + $(OPENSSL_PATH)/crypto/async/arch/async_posix.h + $(OPENSSL_PATH)/crypto/async/arch/async_win.h + $(OPENSSL_PATH)/crypto/bio/bio_local.h + $(OPENSSL_PATH)/crypto/bn/bn_local.h + $(OPENSSL_PATH)/crypto/bn/bn_prime.h + $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h + $(OPENSSL_PATH)/crypto/comp/comp_local.h + $(OPENSSL_PATH)/crypto/conf/conf_def.h + $(OPENSSL_PATH)/crypto/conf/conf_local.h + $(OPENSSL_PATH)/crypto/dh/dh_local.h + $(OPENSSL_PATH)/crypto/dso/dso_local.h + $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/evp/evp_local.h + $(OPENSSL_PATH)/crypto/hmac/hmac_local.h + $(OPENSSL_PATH)/crypto/lhash/lhash_local.h + $(OPENSSL_PATH)/crypto/md5/md5_local.h + $(OPENSSL_PATH)/crypto/modes/modes_local.h + $(OPENSSL_PATH)/crypto/objects/obj_dat.h + $(OPENSSL_PATH)/crypto/objects/obj_local.h + $(OPENSSL_PATH)/crypto/objects/obj_xref.h + $(OPENSSL_PATH)/crypto/ocsp/ocsp_local.h + $(OPENSSL_PATH)/crypto/pkcs12/p12_local.h + $(OPENSSL_PATH)/crypto/rand/rand_local.h + $(OPENSSL_PATH)/crypto/rsa/rsa_local.h + $(OPENSSL_PATH)/crypto/sha/sha_local.h + $(OPENSSL_PATH)/crypto/siphash/siphash_local.h + $(OPENSSL_PATH)/crypto/sm3/sm3_local.h + $(OPENSSL_PATH)/crypto/store/store_local.h + $(OPENSSL_PATH)/crypto/ui/ui_local.h + $(OPENSSL_PATH)/crypto/x509/x509_local.h + $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h + $(OPENSSL_PATH)/crypto/x509v3/pcy_local.h + $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h + $(OPENSSL_PATH)/ssl/bio_ssl.c + $(OPENSSL_PATH)/ssl/d1_lib.c + $(OPENSSL_PATH)/ssl/d1_msg.c + $(OPENSSL_PATH)/ssl/d1_srtp.c + $(OPENSSL_PATH)/ssl/methods.c + $(OPENSSL_PATH)/ssl/packet.c + $(OPENSSL_PATH)/ssl/pqueue.c + $(OPENSSL_PATH)/ssl/record/dtls1_bitmap.c + $(OPENSSL_PATH)/ssl/record/rec_layer_d1.c + $(OPENSSL_PATH)/ssl/record/rec_layer_s3.c + $(OPENSSL_PATH)/ssl/record/ssl3_buffer.c + $(OPENSSL_PATH)/ssl/record/ssl3_record.c + $(OPENSSL_PATH)/ssl/record/ssl3_record_tls13.c + $(OPENSSL_PATH)/ssl/s3_cbc.c + $(OPENSSL_PATH)/ssl/s3_enc.c + $(OPENSSL_PATH)/ssl/s3_lib.c + $(OPENSSL_PATH)/ssl/s3_msg.c + $(OPENSSL_PATH)/ssl/ssl_asn1.c + $(OPENSSL_PATH)/ssl/ssl_cert.c + $(OPENSSL_PATH)/ssl/ssl_ciph.c + $(OPENSSL_PATH)/ssl/ssl_conf.c + $(OPENSSL_PATH)/ssl/ssl_err.c + $(OPENSSL_PATH)/ssl/ssl_init.c + $(OPENSSL_PATH)/ssl/ssl_lib.c + $(OPENSSL_PATH)/ssl/ssl_mcnf.c + $(OPENSSL_PATH)/ssl/ssl_rsa.c + $(OPENSSL_PATH)/ssl/ssl_sess.c + $(OPENSSL_PATH)/ssl/ssl_stat.c + $(OPENSSL_PATH)/ssl/ssl_txt.c + $(OPENSSL_PATH)/ssl/ssl_utst.c + $(OPENSSL_PATH)/ssl/statem/extensions.c + $(OPENSSL_PATH)/ssl/statem/extensions_clnt.c + $(OPENSSL_PATH)/ssl/statem/extensions_cust.c + $(OPENSSL_PATH)/ssl/statem/extensions_srvr.c + $(OPENSSL_PATH)/ssl/statem/statem.c + $(OPENSSL_PATH)/ssl/statem/statem_clnt.c + $(OPENSSL_PATH)/ssl/statem/statem_dtls.c + $(OPENSSL_PATH)/ssl/statem/statem_lib.c + $(OPENSSL_PATH)/ssl/statem/statem_srvr.c + $(OPENSSL_PATH)/ssl/t1_enc.c + $(OPENSSL_PATH)/ssl/t1_lib.c + $(OPENSSL_PATH)/ssl/t1_trce.c + $(OPENSSL_PATH)/ssl/tls13_enc.c + $(OPENSSL_PATH)/ssl/tls_srp.c + $(OPENSSL_PATH)/ssl/packet_local.h + $(OPENSSL_PATH)/ssl/ssl_cert_table.h + $(OPENSSL_PATH)/ssl/ssl_local.h + $(OPENSSL_PATH)/ssl/record/record.h + $(OPENSSL_PATH)/ssl/record/record_local.h + $(OPENSSL_PATH)/ssl/statem/statem.h + $(OPENSSL_PATH)/ssl/statem/statem_local.h +# Autogenerated files list ends here + buildinf.h + ossl_store.c + rand_pool.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + RngLib + PrintLib + +[FixedPcd] + gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES + +[BuildOptions] + # + # Disables the following Visual Studio compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4090: 'function' : different 'const' qualifiers + # C4132: 'object' : const object should be initialized (tls13_enc.c) + # C4210: nonstandard extension used: function given file scope + # C4244: conversion from type1 to type2, possible loss of data + # C4245: conversion from type1 to type2, signed/unsigned mismatch + # C4267: conversion from size_t to type, possible loss of data + # C4306: 'identifier' : conversion from 'type1' to 'type2' of greater size + # C4310: cast truncates constant value + # C4389: 'operator' : signed/unsigned mismatch (xxxx) + # C4700: uninitialized local variable 'name' used. (conf_sap.c(71)) + # C4702: unreachable code + # C4706: assignment within conditional expression + # C4819: The file contains a character that cannot be represented in the current code page + # + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 + + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w + + # + # Suppress the following build warnings in openssl so we don't break the build with -Werror + # -Werror=maybe-uninitialized: there exist some other paths for which the variable is not initialized. + # -Werror=format: Check calls to printf and scanf, etc., to make sure that the arguments supplied have + # types appropriate to the format string specified. + # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). + # + GCC:*_*_IA32_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + + # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: + # 1295: Deprecated declaration - give arg types + # 550: was set but never used + # 1293: assignment in condition + # 111: statement is unreachable (invariably "break;" after "return X;" in case statement) + # 68: integer conversion resulted in a change of sign ("if (Status == -1)") + # 177: was declared but never referenced + # 223: function declared implicitly + # 144: a value of type cannot be used to initialize an entity of type + # 513: a value of type cannot be assigned to an entity of type + # 188: enumerated type mixed with another type (i.e. passing an integer as an enum without a cast) + # 1296: Extended constant initialiser used + # 128: loop is not reachable - may be emitted inappropriately if code follows a conditional return + # from the function that evaluates to true at compile time + # 546: transfer of control bypasses initialization - may be emitted inappropriately if the uninitialized + # variable is never referenced after the jump + # 1: ignore "#1-D: last line of file ends without a newline" + # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with + # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized diff --git a/CryptoPkg/Library/OpensslLib/UefiAsm.conf b/CryptoPkg/Library/OpensslLib/UefiAsm.conf index 2c2978d696..c3940b5886 100644 --- a/CryptoPkg/Library/OpensslLib/UefiAsm.conf +++ b/CryptoPkg/Library/OpensslLib/UefiAsm.conf @@ -9,6 +9,24 @@ my %targets = ( #### UEFI + "UEFI-x86" => { + perlasm_scheme => "win32n", + # inherit_from => [ "UEFI", asm("x86_asm") ], + inherit_from => [ "UEFI" ], + cpuid_asm_src => "x86cpuid.s", + aes_asm_src => "aes_core.c aes_cbc.c vpaes-x86.s aesni-x86.s", + sha1_asm_src => "sha1-586.s sha256-586.s sha512-586.s", + modes_asm_src => "ghash-x86.s", + }, + "UEFI-x86-GCC" => { + perlasm_scheme => "elf", + # inherit_from => [ "UEFI", asm("x86_asm") ], + inherit_from => [ "UEFI" ], + cpuid_asm_src => "x86cpuid.s", + aes_asm_src => "aes_core.c aes_cbc.c vpaes-x86.s aesni-x86.s", + sha1_asm_src => "sha1-586.s sha256-586.s sha512-586.s", + modes_asm_src => "ghash-x86.s", + }, "UEFI-x86_64" => { perlasm_scheme => "nasm", # inherit_from => [ "UEFI", asm("x86_64_asm") ], diff --git a/CryptoPkg/Library/OpensslLib/process_files.pl b/CryptoPkg/Library/OpensslLib/process_files.pl index 545f218284..82e5176b39 100755 --- a/CryptoPkg/Library/OpensslLib/process_files.pl +++ b/CryptoPkg/Library/OpensslLib/process_files.pl @@ -113,6 +113,18 @@ BEGIN $uefi_config = "UEFI-x86_64-GCC"; $extension = "S"; $comment_character = "#"; + } elsif (uc ($arch) eq "IA32") { + $arch = "IA32"; + $inf_file = "OpensslLibIa32.inf"; + $uefi_config = "UEFI-x86"; + $extension = "nasm"; + $comment_character = ";"; + } elsif (uc ($arch) eq "IA32GCC") { + $arch = "IA32Gcc"; + $inf_file = "OpensslLibIa32Gcc.inf"; + $uefi_config = "UEFI-x86-GCC"; + $extension = "S"; + $comment_character = "#"; } else { die "Unsupported architecture \"" . $arch . "\"!"; } From 961b675db7cf352ea61e38adba16f5bc71543c73 Mon Sep 17 00:00:00 2001 From: Christopher Zurcher Date: Thu, 22 Sep 2022 04:25:40 +0800 Subject: [PATCH 0055/1529] CryptoPkg/OpensslLib: Commit the auto-generated assembly files for IA32 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3654 Adding the auto-generated assembly files for IA32 architectures. Cc: Yi Li Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Christopher Zurcher Reviewed-by: Jiewen Yao --- .../OpensslLib/IA32/crypto/aes/aesni-x86.nasm | 3212 ++++++++++++++++ .../OpensslLib/IA32/crypto/aes/vpaes-x86.nasm | 651 ++++ .../IA32/crypto/modes/ghash-x86.nasm | 700 ++++ .../OpensslLib/IA32/crypto/sha/sha1-586.nasm | 1394 +++++++ .../IA32/crypto/sha/sha256-586.nasm | 3364 +++++++++++++++++ .../IA32/crypto/sha/sha512-586.nasm | 579 +++ .../OpensslLib/IA32/crypto/x86cpuid.nasm | 433 +++ .../OpensslLib/IA32Gcc/crypto/aes/aesni-x86.S | 3247 ++++++++++++++++ .../OpensslLib/IA32Gcc/crypto/aes/vpaes-x86.S | 670 ++++ .../IA32Gcc/crypto/modes/ghash-x86.S | 703 ++++ .../OpensslLib/IA32Gcc/crypto/sha/sha1-586.S | 1389 +++++++ .../IA32Gcc/crypto/sha/sha256-586.S | 3356 ++++++++++++++++ .../IA32Gcc/crypto/sha/sha512-586.S | 574 +++ .../OpensslLib/IA32Gcc/crypto/x86cpuid.S | 449 +++ 14 files changed, 20721 insertions(+) create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/aes/aesni-x86.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/aes/vpaes-x86.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/modes/ghash-x86.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha1-586.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha256-586.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha512-586.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32/crypto/x86cpuid.nasm create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/aesni-x86.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/vpaes-x86.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/modes/ghash-x86.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha1-586.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha256-586.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha512-586.S create mode 100644 CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/x86cpuid.S diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/aesni-x86.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/aesni-x86.nasm new file mode 100644 index 0000000000..e0b5058273 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/aesni-x86.nasm @@ -0,0 +1,3212 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/aes/asm/aesni-x86.pl +; +; Copyright 2009-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +;extern _OPENSSL_ia32cap_P +global _aesni_encrypt +align 16 +_aesni_encrypt: +L$_aesni_encrypt_begin: + mov eax,DWORD [4+esp] + mov edx,DWORD [12+esp] + movups xmm2,[eax] + mov ecx,DWORD [240+edx] + mov eax,DWORD [8+esp] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$000enc1_loop_1: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$000enc1_loop_1 +db 102,15,56,221,209 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + movups [eax],xmm2 + pxor xmm2,xmm2 + ret +global _aesni_decrypt +align 16 +_aesni_decrypt: +L$_aesni_decrypt_begin: + mov eax,DWORD [4+esp] + mov edx,DWORD [12+esp] + movups xmm2,[eax] + mov ecx,DWORD [240+edx] + mov eax,DWORD [8+esp] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$001dec1_loop_2: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$001dec1_loop_2 +db 102,15,56,223,209 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + movups [eax],xmm2 + pxor xmm2,xmm2 + ret +align 16 +__aesni_encrypt2: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx + add ecx,16 +L$002enc2_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$002enc2_loop +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,221,208 +db 102,15,56,221,216 + ret +align 16 +__aesni_decrypt2: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx + add ecx,16 +L$003dec2_loop: +db 102,15,56,222,209 +db 102,15,56,222,217 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,222,208 +db 102,15,56,222,216 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$003dec2_loop +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,223,208 +db 102,15,56,223,216 + ret +align 16 +__aesni_encrypt3: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx + add ecx,16 +L$004enc3_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 +db 102,15,56,220,224 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$004enc3_loop +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,221,208 +db 102,15,56,221,216 +db 102,15,56,221,224 + ret +align 16 +__aesni_decrypt3: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx + add ecx,16 +L$005dec3_loop: +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,222,208 +db 102,15,56,222,216 +db 102,15,56,222,224 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$005dec3_loop +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,223,208 +db 102,15,56,223,216 +db 102,15,56,223,224 + ret +align 16 +__aesni_encrypt4: + movups xmm0,[edx] + movups xmm1,[16+edx] + shl ecx,4 + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + pxor xmm5,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx +db 15,31,64,0 + add ecx,16 +L$006enc4_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,220,233 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 +db 102,15,56,220,224 +db 102,15,56,220,232 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$006enc4_loop +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,221,208 +db 102,15,56,221,216 +db 102,15,56,221,224 +db 102,15,56,221,232 + ret +align 16 +__aesni_decrypt4: + movups xmm0,[edx] + movups xmm1,[16+edx] + shl ecx,4 + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + pxor xmm5,xmm0 + movups xmm0,[32+edx] + lea edx,[32+ecx*1+edx] + neg ecx +db 15,31,64,0 + add ecx,16 +L$007dec4_loop: +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,222,233 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,222,208 +db 102,15,56,222,216 +db 102,15,56,222,224 +db 102,15,56,222,232 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$007dec4_loop +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,222,233 +db 102,15,56,223,208 +db 102,15,56,223,216 +db 102,15,56,223,224 +db 102,15,56,223,232 + ret +align 16 +__aesni_encrypt6: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 +db 102,15,56,220,209 + pxor xmm5,xmm0 + pxor xmm6,xmm0 +db 102,15,56,220,217 + lea edx,[32+ecx*1+edx] + neg ecx +db 102,15,56,220,225 + pxor xmm7,xmm0 + movups xmm0,[ecx*1+edx] + add ecx,16 + jmp NEAR L$008_aesni_encrypt6_inner +align 16 +L$009enc6_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +L$008_aesni_encrypt6_inner: +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 +L$_aesni_encrypt6_enter: + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 +db 102,15,56,220,224 +db 102,15,56,220,232 +db 102,15,56,220,240 +db 102,15,56,220,248 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$009enc6_loop +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 +db 102,15,56,221,208 +db 102,15,56,221,216 +db 102,15,56,221,224 +db 102,15,56,221,232 +db 102,15,56,221,240 +db 102,15,56,221,248 + ret +align 16 +__aesni_decrypt6: + movups xmm0,[edx] + shl ecx,4 + movups xmm1,[16+edx] + xorps xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 +db 102,15,56,222,209 + pxor xmm5,xmm0 + pxor xmm6,xmm0 +db 102,15,56,222,217 + lea edx,[32+ecx*1+edx] + neg ecx +db 102,15,56,222,225 + pxor xmm7,xmm0 + movups xmm0,[ecx*1+edx] + add ecx,16 + jmp NEAR L$010_aesni_decrypt6_inner +align 16 +L$011dec6_loop: +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +L$010_aesni_decrypt6_inner: +db 102,15,56,222,233 +db 102,15,56,222,241 +db 102,15,56,222,249 +L$_aesni_decrypt6_enter: + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,222,208 +db 102,15,56,222,216 +db 102,15,56,222,224 +db 102,15,56,222,232 +db 102,15,56,222,240 +db 102,15,56,222,248 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$011dec6_loop +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,222,233 +db 102,15,56,222,241 +db 102,15,56,222,249 +db 102,15,56,223,208 +db 102,15,56,223,216 +db 102,15,56,223,224 +db 102,15,56,223,232 +db 102,15,56,223,240 +db 102,15,56,223,248 + ret +global _aesni_ecb_encrypt +align 16 +_aesni_ecb_encrypt: +L$_aesni_ecb_encrypt_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebx,DWORD [36+esp] + and eax,-16 + jz NEAR L$012ecb_ret + mov ecx,DWORD [240+edx] + test ebx,ebx + jz NEAR L$013ecb_decrypt + mov ebp,edx + mov ebx,ecx + cmp eax,96 + jb NEAR L$014ecb_enc_tail + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] + sub eax,96 + jmp NEAR L$015ecb_enc_loop6_enter +align 16 +L$016ecb_enc_loop6: + movups [edi],xmm2 + movdqu xmm2,[esi] + movups [16+edi],xmm3 + movdqu xmm3,[16+esi] + movups [32+edi],xmm4 + movdqu xmm4,[32+esi] + movups [48+edi],xmm5 + movdqu xmm5,[48+esi] + movups [64+edi],xmm6 + movdqu xmm6,[64+esi] + movups [80+edi],xmm7 + lea edi,[96+edi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] +L$015ecb_enc_loop6_enter: + call __aesni_encrypt6 + mov edx,ebp + mov ecx,ebx + sub eax,96 + jnc NEAR L$016ecb_enc_loop6 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + movups [80+edi],xmm7 + lea edi,[96+edi] + add eax,96 + jz NEAR L$012ecb_ret +L$014ecb_enc_tail: + movups xmm2,[esi] + cmp eax,32 + jb NEAR L$017ecb_enc_one + movups xmm3,[16+esi] + je NEAR L$018ecb_enc_two + movups xmm4,[32+esi] + cmp eax,64 + jb NEAR L$019ecb_enc_three + movups xmm5,[48+esi] + je NEAR L$020ecb_enc_four + movups xmm6,[64+esi] + xorps xmm7,xmm7 + call __aesni_encrypt6 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + jmp NEAR L$012ecb_ret +align 16 +L$017ecb_enc_one: + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$021enc1_loop_3: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$021enc1_loop_3 +db 102,15,56,221,209 + movups [edi],xmm2 + jmp NEAR L$012ecb_ret +align 16 +L$018ecb_enc_two: + call __aesni_encrypt2 + movups [edi],xmm2 + movups [16+edi],xmm3 + jmp NEAR L$012ecb_ret +align 16 +L$019ecb_enc_three: + call __aesni_encrypt3 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + jmp NEAR L$012ecb_ret +align 16 +L$020ecb_enc_four: + call __aesni_encrypt4 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + jmp NEAR L$012ecb_ret +align 16 +L$013ecb_decrypt: + mov ebp,edx + mov ebx,ecx + cmp eax,96 + jb NEAR L$022ecb_dec_tail + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] + sub eax,96 + jmp NEAR L$023ecb_dec_loop6_enter +align 16 +L$024ecb_dec_loop6: + movups [edi],xmm2 + movdqu xmm2,[esi] + movups [16+edi],xmm3 + movdqu xmm3,[16+esi] + movups [32+edi],xmm4 + movdqu xmm4,[32+esi] + movups [48+edi],xmm5 + movdqu xmm5,[48+esi] + movups [64+edi],xmm6 + movdqu xmm6,[64+esi] + movups [80+edi],xmm7 + lea edi,[96+edi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] +L$023ecb_dec_loop6_enter: + call __aesni_decrypt6 + mov edx,ebp + mov ecx,ebx + sub eax,96 + jnc NEAR L$024ecb_dec_loop6 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + movups [80+edi],xmm7 + lea edi,[96+edi] + add eax,96 + jz NEAR L$012ecb_ret +L$022ecb_dec_tail: + movups xmm2,[esi] + cmp eax,32 + jb NEAR L$025ecb_dec_one + movups xmm3,[16+esi] + je NEAR L$026ecb_dec_two + movups xmm4,[32+esi] + cmp eax,64 + jb NEAR L$027ecb_dec_three + movups xmm5,[48+esi] + je NEAR L$028ecb_dec_four + movups xmm6,[64+esi] + xorps xmm7,xmm7 + call __aesni_decrypt6 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + jmp NEAR L$012ecb_ret +align 16 +L$025ecb_dec_one: + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$029dec1_loop_4: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$029dec1_loop_4 +db 102,15,56,223,209 + movups [edi],xmm2 + jmp NEAR L$012ecb_ret +align 16 +L$026ecb_dec_two: + call __aesni_decrypt2 + movups [edi],xmm2 + movups [16+edi],xmm3 + jmp NEAR L$012ecb_ret +align 16 +L$027ecb_dec_three: + call __aesni_decrypt3 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + jmp NEAR L$012ecb_ret +align 16 +L$028ecb_dec_four: + call __aesni_decrypt4 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 +L$012ecb_ret: + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pxor xmm7,xmm7 + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_ccm64_encrypt_blocks +align 16 +_aesni_ccm64_encrypt_blocks: +L$_aesni_ccm64_encrypt_blocks_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebx,DWORD [36+esp] + mov ecx,DWORD [40+esp] + mov ebp,esp + sub esp,60 + and esp,-16 + mov DWORD [48+esp],ebp + movdqu xmm7,[ebx] + movdqu xmm3,[ecx] + mov ecx,DWORD [240+edx] + mov DWORD [esp],202182159 + mov DWORD [4+esp],134810123 + mov DWORD [8+esp],67438087 + mov DWORD [12+esp],66051 + mov ebx,1 + xor ebp,ebp + mov DWORD [16+esp],ebx + mov DWORD [20+esp],ebp + mov DWORD [24+esp],ebp + mov DWORD [28+esp],ebp + shl ecx,4 + mov ebx,16 + lea ebp,[edx] + movdqa xmm5,[esp] + movdqa xmm2,xmm7 + lea edx,[32+ecx*1+edx] + sub ebx,ecx +db 102,15,56,0,253 +L$030ccm64_enc_outer: + movups xmm0,[ebp] + mov ecx,ebx + movups xmm6,[esi] + xorps xmm2,xmm0 + movups xmm1,[16+ebp] + xorps xmm0,xmm6 + xorps xmm3,xmm0 + movups xmm0,[32+ebp] +L$031ccm64_enc2_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$031ccm64_enc2_loop +db 102,15,56,220,209 +db 102,15,56,220,217 + paddq xmm7,[16+esp] + dec eax +db 102,15,56,221,208 +db 102,15,56,221,216 + lea esi,[16+esi] + xorps xmm6,xmm2 + movdqa xmm2,xmm7 + movups [edi],xmm6 +db 102,15,56,0,213 + lea edi,[16+edi] + jnz NEAR L$030ccm64_enc_outer + mov esp,DWORD [48+esp] + mov edi,DWORD [40+esp] + movups [edi],xmm3 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pxor xmm7,xmm7 + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_ccm64_decrypt_blocks +align 16 +_aesni_ccm64_decrypt_blocks: +L$_aesni_ccm64_decrypt_blocks_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebx,DWORD [36+esp] + mov ecx,DWORD [40+esp] + mov ebp,esp + sub esp,60 + and esp,-16 + mov DWORD [48+esp],ebp + movdqu xmm7,[ebx] + movdqu xmm3,[ecx] + mov ecx,DWORD [240+edx] + mov DWORD [esp],202182159 + mov DWORD [4+esp],134810123 + mov DWORD [8+esp],67438087 + mov DWORD [12+esp],66051 + mov ebx,1 + xor ebp,ebp + mov DWORD [16+esp],ebx + mov DWORD [20+esp],ebp + mov DWORD [24+esp],ebp + mov DWORD [28+esp],ebp + movdqa xmm5,[esp] + movdqa xmm2,xmm7 + mov ebp,edx + mov ebx,ecx +db 102,15,56,0,253 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$032enc1_loop_5: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$032enc1_loop_5 +db 102,15,56,221,209 + shl ebx,4 + mov ecx,16 + movups xmm6,[esi] + paddq xmm7,[16+esp] + lea esi,[16+esi] + sub ecx,ebx + lea edx,[32+ebx*1+ebp] + mov ebx,ecx + jmp NEAR L$033ccm64_dec_outer +align 16 +L$033ccm64_dec_outer: + xorps xmm6,xmm2 + movdqa xmm2,xmm7 + movups [edi],xmm6 + lea edi,[16+edi] +db 102,15,56,0,213 + sub eax,1 + jz NEAR L$034ccm64_dec_break + movups xmm0,[ebp] + mov ecx,ebx + movups xmm1,[16+ebp] + xorps xmm6,xmm0 + xorps xmm2,xmm0 + xorps xmm3,xmm6 + movups xmm0,[32+ebp] +L$035ccm64_dec2_loop: +db 102,15,56,220,209 +db 102,15,56,220,217 + movups xmm1,[ecx*1+edx] + add ecx,32 +db 102,15,56,220,208 +db 102,15,56,220,216 + movups xmm0,[ecx*1+edx-16] + jnz NEAR L$035ccm64_dec2_loop + movups xmm6,[esi] + paddq xmm7,[16+esp] +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,221,208 +db 102,15,56,221,216 + lea esi,[16+esi] + jmp NEAR L$033ccm64_dec_outer +align 16 +L$034ccm64_dec_break: + mov ecx,DWORD [240+ebp] + mov edx,ebp + movups xmm0,[edx] + movups xmm1,[16+edx] + xorps xmm6,xmm0 + lea edx,[32+edx] + xorps xmm3,xmm6 +L$036enc1_loop_6: +db 102,15,56,220,217 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$036enc1_loop_6 +db 102,15,56,221,217 + mov esp,DWORD [48+esp] + mov edi,DWORD [40+esp] + movups [edi],xmm3 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pxor xmm7,xmm7 + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_ctr32_encrypt_blocks +align 16 +_aesni_ctr32_encrypt_blocks: +L$_aesni_ctr32_encrypt_blocks_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebx,DWORD [36+esp] + mov ebp,esp + sub esp,88 + and esp,-16 + mov DWORD [80+esp],ebp + cmp eax,1 + je NEAR L$037ctr32_one_shortcut + movdqu xmm7,[ebx] + mov DWORD [esp],202182159 + mov DWORD [4+esp],134810123 + mov DWORD [8+esp],67438087 + mov DWORD [12+esp],66051 + mov ecx,6 + xor ebp,ebp + mov DWORD [16+esp],ecx + mov DWORD [20+esp],ecx + mov DWORD [24+esp],ecx + mov DWORD [28+esp],ebp +db 102,15,58,22,251,3 +db 102,15,58,34,253,3 + mov ecx,DWORD [240+edx] + bswap ebx + pxor xmm0,xmm0 + pxor xmm1,xmm1 + movdqa xmm2,[esp] +db 102,15,58,34,195,0 + lea ebp,[3+ebx] +db 102,15,58,34,205,0 + inc ebx +db 102,15,58,34,195,1 + inc ebp +db 102,15,58,34,205,1 + inc ebx +db 102,15,58,34,195,2 + inc ebp +db 102,15,58,34,205,2 + movdqa [48+esp],xmm0 +db 102,15,56,0,194 + movdqu xmm6,[edx] + movdqa [64+esp],xmm1 +db 102,15,56,0,202 + pshufd xmm2,xmm0,192 + pshufd xmm3,xmm0,128 + cmp eax,6 + jb NEAR L$038ctr32_tail + pxor xmm7,xmm6 + shl ecx,4 + mov ebx,16 + movdqa [32+esp],xmm7 + mov ebp,edx + sub ebx,ecx + lea edx,[32+ecx*1+edx] + sub eax,6 + jmp NEAR L$039ctr32_loop6 +align 16 +L$039ctr32_loop6: + pshufd xmm4,xmm0,64 + movdqa xmm0,[32+esp] + pshufd xmm5,xmm1,192 + pxor xmm2,xmm0 + pshufd xmm6,xmm1,128 + pxor xmm3,xmm0 + pshufd xmm7,xmm1,64 + movups xmm1,[16+ebp] + pxor xmm4,xmm0 + pxor xmm5,xmm0 +db 102,15,56,220,209 + pxor xmm6,xmm0 + pxor xmm7,xmm0 +db 102,15,56,220,217 + movups xmm0,[32+ebp] + mov ecx,ebx +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 + call L$_aesni_encrypt6_enter + movups xmm1,[esi] + movups xmm0,[16+esi] + xorps xmm2,xmm1 + movups xmm1,[32+esi] + xorps xmm3,xmm0 + movups [edi],xmm2 + movdqa xmm0,[16+esp] + xorps xmm4,xmm1 + movdqa xmm1,[64+esp] + movups [16+edi],xmm3 + movups [32+edi],xmm4 + paddd xmm1,xmm0 + paddd xmm0,[48+esp] + movdqa xmm2,[esp] + movups xmm3,[48+esi] + movups xmm4,[64+esi] + xorps xmm5,xmm3 + movups xmm3,[80+esi] + lea esi,[96+esi] + movdqa [48+esp],xmm0 +db 102,15,56,0,194 + xorps xmm6,xmm4 + movups [48+edi],xmm5 + xorps xmm7,xmm3 + movdqa [64+esp],xmm1 +db 102,15,56,0,202 + movups [64+edi],xmm6 + pshufd xmm2,xmm0,192 + movups [80+edi],xmm7 + lea edi,[96+edi] + pshufd xmm3,xmm0,128 + sub eax,6 + jnc NEAR L$039ctr32_loop6 + add eax,6 + jz NEAR L$040ctr32_ret + movdqu xmm7,[ebp] + mov edx,ebp + pxor xmm7,[32+esp] + mov ecx,DWORD [240+ebp] +L$038ctr32_tail: + por xmm2,xmm7 + cmp eax,2 + jb NEAR L$041ctr32_one + pshufd xmm4,xmm0,64 + por xmm3,xmm7 + je NEAR L$042ctr32_two + pshufd xmm5,xmm1,192 + por xmm4,xmm7 + cmp eax,4 + jb NEAR L$043ctr32_three + pshufd xmm6,xmm1,128 + por xmm5,xmm7 + je NEAR L$044ctr32_four + por xmm6,xmm7 + call __aesni_encrypt6 + movups xmm1,[esi] + movups xmm0,[16+esi] + xorps xmm2,xmm1 + movups xmm1,[32+esi] + xorps xmm3,xmm0 + movups xmm0,[48+esi] + xorps xmm4,xmm1 + movups xmm1,[64+esi] + xorps xmm5,xmm0 + movups [edi],xmm2 + xorps xmm6,xmm1 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + jmp NEAR L$040ctr32_ret +align 16 +L$037ctr32_one_shortcut: + movups xmm2,[ebx] + mov ecx,DWORD [240+edx] +L$041ctr32_one: + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$045enc1_loop_7: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$045enc1_loop_7 +db 102,15,56,221,209 + movups xmm6,[esi] + xorps xmm6,xmm2 + movups [edi],xmm6 + jmp NEAR L$040ctr32_ret +align 16 +L$042ctr32_two: + call __aesni_encrypt2 + movups xmm5,[esi] + movups xmm6,[16+esi] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + movups [edi],xmm2 + movups [16+edi],xmm3 + jmp NEAR L$040ctr32_ret +align 16 +L$043ctr32_three: + call __aesni_encrypt3 + movups xmm5,[esi] + movups xmm6,[16+esi] + xorps xmm2,xmm5 + movups xmm7,[32+esi] + xorps xmm3,xmm6 + movups [edi],xmm2 + xorps xmm4,xmm7 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + jmp NEAR L$040ctr32_ret +align 16 +L$044ctr32_four: + call __aesni_encrypt4 + movups xmm6,[esi] + movups xmm7,[16+esi] + movups xmm1,[32+esi] + xorps xmm2,xmm6 + movups xmm0,[48+esi] + xorps xmm3,xmm7 + movups [edi],xmm2 + xorps xmm4,xmm1 + movups [16+edi],xmm3 + xorps xmm5,xmm0 + movups [32+edi],xmm4 + movups [48+edi],xmm5 +L$040ctr32_ret: + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + movdqa [32+esp],xmm0 + pxor xmm5,xmm5 + movdqa [48+esp],xmm0 + pxor xmm6,xmm6 + movdqa [64+esp],xmm0 + pxor xmm7,xmm7 + mov esp,DWORD [80+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_xts_encrypt +align 16 +_aesni_xts_encrypt: +L$_aesni_xts_encrypt_begin: + push ebp + push ebx + push esi + push edi + mov edx,DWORD [36+esp] + mov esi,DWORD [40+esp] + mov ecx,DWORD [240+edx] + movups xmm2,[esi] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$046enc1_loop_8: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$046enc1_loop_8 +db 102,15,56,221,209 + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebp,esp + sub esp,120 + mov ecx,DWORD [240+edx] + and esp,-16 + mov DWORD [96+esp],135 + mov DWORD [100+esp],0 + mov DWORD [104+esp],1 + mov DWORD [108+esp],0 + mov DWORD [112+esp],eax + mov DWORD [116+esp],ebp + movdqa xmm1,xmm2 + pxor xmm0,xmm0 + movdqa xmm3,[96+esp] + pcmpgtd xmm0,xmm1 + and eax,-16 + mov ebp,edx + mov ebx,ecx + sub eax,96 + jc NEAR L$047xts_enc_short + shl ecx,4 + mov ebx,16 + sub ebx,ecx + lea edx,[32+ecx*1+edx] + jmp NEAR L$048xts_enc_loop6 +align 16 +L$048xts_enc_loop6: + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [16+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [32+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [48+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm7,xmm0,19 + movdqa [64+esp],xmm1 + paddq xmm1,xmm1 + movups xmm0,[ebp] + pand xmm7,xmm3 + movups xmm2,[esi] + pxor xmm7,xmm1 + mov ecx,ebx + movdqu xmm3,[16+esi] + xorps xmm2,xmm0 + movdqu xmm4,[32+esi] + pxor xmm3,xmm0 + movdqu xmm5,[48+esi] + pxor xmm4,xmm0 + movdqu xmm6,[64+esi] + pxor xmm5,xmm0 + movdqu xmm1,[80+esi] + pxor xmm6,xmm0 + lea esi,[96+esi] + pxor xmm2,[esp] + movdqa [80+esp],xmm7 + pxor xmm7,xmm1 + movups xmm1,[16+ebp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] +db 102,15,56,220,209 + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] +db 102,15,56,220,217 + pxor xmm7,xmm0 + movups xmm0,[32+ebp] +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 + call L$_aesni_encrypt6_enter + movdqa xmm1,[80+esp] + pxor xmm0,xmm0 + xorps xmm2,[esp] + pcmpgtd xmm0,xmm1 + xorps xmm3,[16+esp] + movups [edi],xmm2 + xorps xmm4,[32+esp] + movups [16+edi],xmm3 + xorps xmm5,[48+esp] + movups [32+edi],xmm4 + xorps xmm6,[64+esp] + movups [48+edi],xmm5 + xorps xmm7,xmm1 + movups [64+edi],xmm6 + pshufd xmm2,xmm0,19 + movups [80+edi],xmm7 + lea edi,[96+edi] + movdqa xmm3,[96+esp] + pxor xmm0,xmm0 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + sub eax,96 + jnc NEAR L$048xts_enc_loop6 + mov ecx,DWORD [240+ebp] + mov edx,ebp + mov ebx,ecx +L$047xts_enc_short: + add eax,96 + jz NEAR L$049xts_enc_done6x + movdqa xmm5,xmm1 + cmp eax,32 + jb NEAR L$050xts_enc_one + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + je NEAR L$051xts_enc_two + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa xmm6,xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + cmp eax,64 + jb NEAR L$052xts_enc_three + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa xmm7,xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + movdqa [esp],xmm5 + movdqa [16+esp],xmm6 + je NEAR L$053xts_enc_four + movdqa [32+esp],xmm7 + pshufd xmm7,xmm0,19 + movdqa [48+esp],xmm1 + paddq xmm1,xmm1 + pand xmm7,xmm3 + pxor xmm7,xmm1 + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + pxor xmm2,[esp] + movdqu xmm5,[48+esi] + pxor xmm3,[16+esp] + movdqu xmm6,[64+esi] + pxor xmm4,[32+esp] + lea esi,[80+esi] + pxor xmm5,[48+esp] + movdqa [64+esp],xmm7 + pxor xmm6,xmm7 + call __aesni_encrypt6 + movaps xmm1,[64+esp] + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,[32+esp] + movups [edi],xmm2 + xorps xmm5,[48+esp] + movups [16+edi],xmm3 + xorps xmm6,xmm1 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + lea edi,[80+edi] + jmp NEAR L$054xts_enc_done +align 16 +L$050xts_enc_one: + movups xmm2,[esi] + lea esi,[16+esi] + xorps xmm2,xmm5 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$055enc1_loop_9: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$055enc1_loop_9 +db 102,15,56,221,209 + xorps xmm2,xmm5 + movups [edi],xmm2 + lea edi,[16+edi] + movdqa xmm1,xmm5 + jmp NEAR L$054xts_enc_done +align 16 +L$051xts_enc_two: + movaps xmm6,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + lea esi,[32+esi] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + call __aesni_encrypt2 + xorps xmm2,xmm5 + xorps xmm3,xmm6 + movups [edi],xmm2 + movups [16+edi],xmm3 + lea edi,[32+edi] + movdqa xmm1,xmm6 + jmp NEAR L$054xts_enc_done +align 16 +L$052xts_enc_three: + movaps xmm7,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + movups xmm4,[32+esi] + lea esi,[48+esi] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + call __aesni_encrypt3 + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + lea edi,[48+edi] + movdqa xmm1,xmm7 + jmp NEAR L$054xts_enc_done +align 16 +L$053xts_enc_four: + movaps xmm6,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + movups xmm4,[32+esi] + xorps xmm2,[esp] + movups xmm5,[48+esi] + lea esi,[64+esi] + xorps xmm3,[16+esp] + xorps xmm4,xmm7 + xorps xmm5,xmm6 + call __aesni_encrypt4 + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,xmm7 + movups [edi],xmm2 + xorps xmm5,xmm6 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + lea edi,[64+edi] + movdqa xmm1,xmm6 + jmp NEAR L$054xts_enc_done +align 16 +L$049xts_enc_done6x: + mov eax,DWORD [112+esp] + and eax,15 + jz NEAR L$056xts_enc_ret + movdqa xmm5,xmm1 + mov DWORD [112+esp],eax + jmp NEAR L$057xts_enc_steal +align 16 +L$054xts_enc_done: + mov eax,DWORD [112+esp] + pxor xmm0,xmm0 + and eax,15 + jz NEAR L$056xts_enc_ret + pcmpgtd xmm0,xmm1 + mov DWORD [112+esp],eax + pshufd xmm5,xmm0,19 + paddq xmm1,xmm1 + pand xmm5,[96+esp] + pxor xmm5,xmm1 +L$057xts_enc_steal: + movzx ecx,BYTE [esi] + movzx edx,BYTE [edi-16] + lea esi,[1+esi] + mov BYTE [edi-16],cl + mov BYTE [edi],dl + lea edi,[1+edi] + sub eax,1 + jnz NEAR L$057xts_enc_steal + sub edi,DWORD [112+esp] + mov edx,ebp + mov ecx,ebx + movups xmm2,[edi-16] + xorps xmm2,xmm5 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$058enc1_loop_10: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$058enc1_loop_10 +db 102,15,56,221,209 + xorps xmm2,xmm5 + movups [edi-16],xmm2 +L$056xts_enc_ret: + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + movdqa [esp],xmm0 + pxor xmm3,xmm3 + movdqa [16+esp],xmm0 + pxor xmm4,xmm4 + movdqa [32+esp],xmm0 + pxor xmm5,xmm5 + movdqa [48+esp],xmm0 + pxor xmm6,xmm6 + movdqa [64+esp],xmm0 + pxor xmm7,xmm7 + movdqa [80+esp],xmm0 + mov esp,DWORD [116+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_xts_decrypt +align 16 +_aesni_xts_decrypt: +L$_aesni_xts_decrypt_begin: + push ebp + push ebx + push esi + push edi + mov edx,DWORD [36+esp] + mov esi,DWORD [40+esp] + mov ecx,DWORD [240+edx] + movups xmm2,[esi] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$059enc1_loop_11: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$059enc1_loop_11 +db 102,15,56,221,209 + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + mov ebp,esp + sub esp,120 + and esp,-16 + xor ebx,ebx + test eax,15 + setnz bl + shl ebx,4 + sub eax,ebx + mov DWORD [96+esp],135 + mov DWORD [100+esp],0 + mov DWORD [104+esp],1 + mov DWORD [108+esp],0 + mov DWORD [112+esp],eax + mov DWORD [116+esp],ebp + mov ecx,DWORD [240+edx] + mov ebp,edx + mov ebx,ecx + movdqa xmm1,xmm2 + pxor xmm0,xmm0 + movdqa xmm3,[96+esp] + pcmpgtd xmm0,xmm1 + and eax,-16 + sub eax,96 + jc NEAR L$060xts_dec_short + shl ecx,4 + mov ebx,16 + sub ebx,ecx + lea edx,[32+ecx*1+edx] + jmp NEAR L$061xts_dec_loop6 +align 16 +L$061xts_dec_loop6: + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [16+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [32+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa [48+esp],xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + pshufd xmm7,xmm0,19 + movdqa [64+esp],xmm1 + paddq xmm1,xmm1 + movups xmm0,[ebp] + pand xmm7,xmm3 + movups xmm2,[esi] + pxor xmm7,xmm1 + mov ecx,ebx + movdqu xmm3,[16+esi] + xorps xmm2,xmm0 + movdqu xmm4,[32+esi] + pxor xmm3,xmm0 + movdqu xmm5,[48+esi] + pxor xmm4,xmm0 + movdqu xmm6,[64+esi] + pxor xmm5,xmm0 + movdqu xmm1,[80+esi] + pxor xmm6,xmm0 + lea esi,[96+esi] + pxor xmm2,[esp] + movdqa [80+esp],xmm7 + pxor xmm7,xmm1 + movups xmm1,[16+ebp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] +db 102,15,56,222,209 + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] +db 102,15,56,222,217 + pxor xmm7,xmm0 + movups xmm0,[32+ebp] +db 102,15,56,222,225 +db 102,15,56,222,233 +db 102,15,56,222,241 +db 102,15,56,222,249 + call L$_aesni_decrypt6_enter + movdqa xmm1,[80+esp] + pxor xmm0,xmm0 + xorps xmm2,[esp] + pcmpgtd xmm0,xmm1 + xorps xmm3,[16+esp] + movups [edi],xmm2 + xorps xmm4,[32+esp] + movups [16+edi],xmm3 + xorps xmm5,[48+esp] + movups [32+edi],xmm4 + xorps xmm6,[64+esp] + movups [48+edi],xmm5 + xorps xmm7,xmm1 + movups [64+edi],xmm6 + pshufd xmm2,xmm0,19 + movups [80+edi],xmm7 + lea edi,[96+edi] + movdqa xmm3,[96+esp] + pxor xmm0,xmm0 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + sub eax,96 + jnc NEAR L$061xts_dec_loop6 + mov ecx,DWORD [240+ebp] + mov edx,ebp + mov ebx,ecx +L$060xts_dec_short: + add eax,96 + jz NEAR L$062xts_dec_done6x + movdqa xmm5,xmm1 + cmp eax,32 + jb NEAR L$063xts_dec_one + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + je NEAR L$064xts_dec_two + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa xmm6,xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + cmp eax,64 + jb NEAR L$065xts_dec_three + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa xmm7,xmm1 + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 + movdqa [esp],xmm5 + movdqa [16+esp],xmm6 + je NEAR L$066xts_dec_four + movdqa [32+esp],xmm7 + pshufd xmm7,xmm0,19 + movdqa [48+esp],xmm1 + paddq xmm1,xmm1 + pand xmm7,xmm3 + pxor xmm7,xmm1 + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + pxor xmm2,[esp] + movdqu xmm5,[48+esi] + pxor xmm3,[16+esp] + movdqu xmm6,[64+esi] + pxor xmm4,[32+esp] + lea esi,[80+esi] + pxor xmm5,[48+esp] + movdqa [64+esp],xmm7 + pxor xmm6,xmm7 + call __aesni_decrypt6 + movaps xmm1,[64+esp] + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,[32+esp] + movups [edi],xmm2 + xorps xmm5,[48+esp] + movups [16+edi],xmm3 + xorps xmm6,xmm1 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + movups [64+edi],xmm6 + lea edi,[80+edi] + jmp NEAR L$067xts_dec_done +align 16 +L$063xts_dec_one: + movups xmm2,[esi] + lea esi,[16+esi] + xorps xmm2,xmm5 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$068dec1_loop_12: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$068dec1_loop_12 +db 102,15,56,223,209 + xorps xmm2,xmm5 + movups [edi],xmm2 + lea edi,[16+edi] + movdqa xmm1,xmm5 + jmp NEAR L$067xts_dec_done +align 16 +L$064xts_dec_two: + movaps xmm6,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + lea esi,[32+esi] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + call __aesni_decrypt2 + xorps xmm2,xmm5 + xorps xmm3,xmm6 + movups [edi],xmm2 + movups [16+edi],xmm3 + lea edi,[32+edi] + movdqa xmm1,xmm6 + jmp NEAR L$067xts_dec_done +align 16 +L$065xts_dec_three: + movaps xmm7,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + movups xmm4,[32+esi] + lea esi,[48+esi] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + call __aesni_decrypt3 + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + movups [edi],xmm2 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + lea edi,[48+edi] + movdqa xmm1,xmm7 + jmp NEAR L$067xts_dec_done +align 16 +L$066xts_dec_four: + movaps xmm6,xmm1 + movups xmm2,[esi] + movups xmm3,[16+esi] + movups xmm4,[32+esi] + xorps xmm2,[esp] + movups xmm5,[48+esi] + lea esi,[64+esi] + xorps xmm3,[16+esp] + xorps xmm4,xmm7 + xorps xmm5,xmm6 + call __aesni_decrypt4 + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,xmm7 + movups [edi],xmm2 + xorps xmm5,xmm6 + movups [16+edi],xmm3 + movups [32+edi],xmm4 + movups [48+edi],xmm5 + lea edi,[64+edi] + movdqa xmm1,xmm6 + jmp NEAR L$067xts_dec_done +align 16 +L$062xts_dec_done6x: + mov eax,DWORD [112+esp] + and eax,15 + jz NEAR L$069xts_dec_ret + mov DWORD [112+esp],eax + jmp NEAR L$070xts_dec_only_one_more +align 16 +L$067xts_dec_done: + mov eax,DWORD [112+esp] + pxor xmm0,xmm0 + and eax,15 + jz NEAR L$069xts_dec_ret + pcmpgtd xmm0,xmm1 + mov DWORD [112+esp],eax + pshufd xmm2,xmm0,19 + pxor xmm0,xmm0 + movdqa xmm3,[96+esp] + paddq xmm1,xmm1 + pand xmm2,xmm3 + pcmpgtd xmm0,xmm1 + pxor xmm1,xmm2 +L$070xts_dec_only_one_more: + pshufd xmm5,xmm0,19 + movdqa xmm6,xmm1 + paddq xmm1,xmm1 + pand xmm5,xmm3 + pxor xmm5,xmm1 + mov edx,ebp + mov ecx,ebx + movups xmm2,[esi] + xorps xmm2,xmm5 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$071dec1_loop_13: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$071dec1_loop_13 +db 102,15,56,223,209 + xorps xmm2,xmm5 + movups [edi],xmm2 +L$072xts_dec_steal: + movzx ecx,BYTE [16+esi] + movzx edx,BYTE [edi] + lea esi,[1+esi] + mov BYTE [edi],cl + mov BYTE [16+edi],dl + lea edi,[1+edi] + sub eax,1 + jnz NEAR L$072xts_dec_steal + sub edi,DWORD [112+esp] + mov edx,ebp + mov ecx,ebx + movups xmm2,[edi] + xorps xmm2,xmm6 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$073dec1_loop_14: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$073dec1_loop_14 +db 102,15,56,223,209 + xorps xmm2,xmm6 + movups [edi],xmm2 +L$069xts_dec_ret: + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + movdqa [esp],xmm0 + pxor xmm3,xmm3 + movdqa [16+esp],xmm0 + pxor xmm4,xmm4 + movdqa [32+esp],xmm0 + pxor xmm5,xmm5 + movdqa [48+esp],xmm0 + pxor xmm6,xmm6 + movdqa [64+esp],xmm0 + pxor xmm7,xmm7 + movdqa [80+esp],xmm0 + mov esp,DWORD [116+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_ocb_encrypt +align 16 +_aesni_ocb_encrypt: +L$_aesni_ocb_encrypt_begin: + push ebp + push ebx + push esi + push edi + mov ecx,DWORD [40+esp] + mov ebx,DWORD [48+esp] + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + movdqu xmm0,[ecx] + mov ebp,DWORD [36+esp] + movdqu xmm1,[ebx] + mov ebx,DWORD [44+esp] + mov ecx,esp + sub esp,132 + and esp,-16 + sub edi,esi + shl eax,4 + lea eax,[eax*1+esi-96] + mov DWORD [120+esp],edi + mov DWORD [124+esp],eax + mov DWORD [128+esp],ecx + mov ecx,DWORD [240+edx] + test ebp,1 + jnz NEAR L$074odd + bsf eax,ebp + add ebp,1 + shl eax,4 + movdqu xmm7,[eax*1+ebx] + mov eax,edx + movdqu xmm2,[esi] + lea esi,[16+esi] + pxor xmm7,xmm0 + pxor xmm1,xmm2 + pxor xmm2,xmm7 + movdqa xmm6,xmm1 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$075enc1_loop_15: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$075enc1_loop_15 +db 102,15,56,221,209 + xorps xmm2,xmm7 + movdqa xmm0,xmm7 + movdqa xmm1,xmm6 + movups [esi*1+edi-16],xmm2 + mov ecx,DWORD [240+eax] + mov edx,eax + mov eax,DWORD [124+esp] +L$074odd: + shl ecx,4 + mov edi,16 + sub edi,ecx + mov DWORD [112+esp],edx + lea edx,[32+ecx*1+edx] + mov DWORD [116+esp],edi + cmp esi,eax + ja NEAR L$076short + jmp NEAR L$077grandloop +align 32 +L$077grandloop: + lea ecx,[1+ebp] + lea eax,[3+ebp] + lea edi,[5+ebp] + add ebp,6 + bsf ecx,ecx + bsf eax,eax + bsf edi,edi + shl ecx,4 + shl eax,4 + shl edi,4 + movdqu xmm2,[ebx] + movdqu xmm3,[ecx*1+ebx] + mov ecx,DWORD [116+esp] + movdqa xmm4,xmm2 + movdqu xmm5,[eax*1+ebx] + movdqa xmm6,xmm2 + movdqu xmm7,[edi*1+ebx] + pxor xmm2,xmm0 + pxor xmm3,xmm2 + movdqa [esp],xmm2 + pxor xmm4,xmm3 + movdqa [16+esp],xmm3 + pxor xmm5,xmm4 + movdqa [32+esp],xmm4 + pxor xmm6,xmm5 + movdqa [48+esp],xmm5 + pxor xmm7,xmm6 + movdqa [64+esp],xmm6 + movdqa [80+esp],xmm7 + movups xmm0,[ecx*1+edx-48] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] + pxor xmm1,xmm2 + pxor xmm2,xmm0 + pxor xmm1,xmm3 + pxor xmm3,xmm0 + pxor xmm1,xmm4 + pxor xmm4,xmm0 + pxor xmm1,xmm5 + pxor xmm5,xmm0 + pxor xmm1,xmm6 + pxor xmm6,xmm0 + pxor xmm1,xmm7 + pxor xmm7,xmm0 + movdqa [96+esp],xmm1 + movups xmm1,[ecx*1+edx-32] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + pxor xmm7,[80+esp] + movups xmm0,[ecx*1+edx-16] +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 + mov edi,DWORD [120+esp] + mov eax,DWORD [124+esp] + call L$_aesni_encrypt6_enter + movdqa xmm0,[80+esp] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + pxor xmm7,xmm0 + movdqa xmm1,[96+esp] + movdqu [esi*1+edi-96],xmm2 + movdqu [esi*1+edi-80],xmm3 + movdqu [esi*1+edi-64],xmm4 + movdqu [esi*1+edi-48],xmm5 + movdqu [esi*1+edi-32],xmm6 + movdqu [esi*1+edi-16],xmm7 + cmp esi,eax + jb NEAR L$077grandloop +L$076short: + add eax,96 + sub eax,esi + jz NEAR L$078done + cmp eax,32 + jb NEAR L$079one + je NEAR L$080two + cmp eax,64 + jb NEAR L$081three + je NEAR L$082four + lea ecx,[1+ebp] + lea eax,[3+ebp] + bsf ecx,ecx + bsf eax,eax + shl ecx,4 + shl eax,4 + movdqu xmm2,[ebx] + movdqu xmm3,[ecx*1+ebx] + mov ecx,DWORD [116+esp] + movdqa xmm4,xmm2 + movdqu xmm5,[eax*1+ebx] + movdqa xmm6,xmm2 + pxor xmm2,xmm0 + pxor xmm3,xmm2 + movdqa [esp],xmm2 + pxor xmm4,xmm3 + movdqa [16+esp],xmm3 + pxor xmm5,xmm4 + movdqa [32+esp],xmm4 + pxor xmm6,xmm5 + movdqa [48+esp],xmm5 + pxor xmm7,xmm6 + movdqa [64+esp],xmm6 + movups xmm0,[ecx*1+edx-48] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + pxor xmm7,xmm7 + pxor xmm1,xmm2 + pxor xmm2,xmm0 + pxor xmm1,xmm3 + pxor xmm3,xmm0 + pxor xmm1,xmm4 + pxor xmm4,xmm0 + pxor xmm1,xmm5 + pxor xmm5,xmm0 + pxor xmm1,xmm6 + pxor xmm6,xmm0 + movdqa [96+esp],xmm1 + movups xmm1,[ecx*1+edx-32] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + movups xmm0,[ecx*1+edx-16] +db 102,15,56,220,209 +db 102,15,56,220,217 +db 102,15,56,220,225 +db 102,15,56,220,233 +db 102,15,56,220,241 +db 102,15,56,220,249 + mov edi,DWORD [120+esp] + call L$_aesni_encrypt6_enter + movdqa xmm0,[64+esp] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,xmm0 + movdqa xmm1,[96+esp] + movdqu [esi*1+edi],xmm2 + movdqu [16+esi*1+edi],xmm3 + movdqu [32+esi*1+edi],xmm4 + movdqu [48+esi*1+edi],xmm5 + movdqu [64+esi*1+edi],xmm6 + jmp NEAR L$078done +align 16 +L$079one: + movdqu xmm7,[ebx] + mov edx,DWORD [112+esp] + movdqu xmm2,[esi] + mov ecx,DWORD [240+edx] + pxor xmm7,xmm0 + pxor xmm1,xmm2 + pxor xmm2,xmm7 + movdqa xmm6,xmm1 + mov edi,DWORD [120+esp] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$083enc1_loop_16: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$083enc1_loop_16 +db 102,15,56,221,209 + xorps xmm2,xmm7 + movdqa xmm0,xmm7 + movdqa xmm1,xmm6 + movups [esi*1+edi],xmm2 + jmp NEAR L$078done +align 16 +L$080two: + lea ecx,[1+ebp] + mov edx,DWORD [112+esp] + bsf ecx,ecx + shl ecx,4 + movdqu xmm6,[ebx] + movdqu xmm7,[ecx*1+ebx] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + mov ecx,DWORD [240+edx] + pxor xmm6,xmm0 + pxor xmm7,xmm6 + pxor xmm1,xmm2 + pxor xmm2,xmm6 + pxor xmm1,xmm3 + pxor xmm3,xmm7 + movdqa xmm5,xmm1 + mov edi,DWORD [120+esp] + call __aesni_encrypt2 + xorps xmm2,xmm6 + xorps xmm3,xmm7 + movdqa xmm0,xmm7 + movdqa xmm1,xmm5 + movups [esi*1+edi],xmm2 + movups [16+esi*1+edi],xmm3 + jmp NEAR L$078done +align 16 +L$081three: + lea ecx,[1+ebp] + mov edx,DWORD [112+esp] + bsf ecx,ecx + shl ecx,4 + movdqu xmm5,[ebx] + movdqu xmm6,[ecx*1+ebx] + movdqa xmm7,xmm5 + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + mov ecx,DWORD [240+edx] + pxor xmm5,xmm0 + pxor xmm6,xmm5 + pxor xmm7,xmm6 + pxor xmm1,xmm2 + pxor xmm2,xmm5 + pxor xmm1,xmm3 + pxor xmm3,xmm6 + pxor xmm1,xmm4 + pxor xmm4,xmm7 + movdqa [96+esp],xmm1 + mov edi,DWORD [120+esp] + call __aesni_encrypt3 + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + movdqa xmm0,xmm7 + movdqa xmm1,[96+esp] + movups [esi*1+edi],xmm2 + movups [16+esi*1+edi],xmm3 + movups [32+esi*1+edi],xmm4 + jmp NEAR L$078done +align 16 +L$082four: + lea ecx,[1+ebp] + lea eax,[3+ebp] + bsf ecx,ecx + bsf eax,eax + mov edx,DWORD [112+esp] + shl ecx,4 + shl eax,4 + movdqu xmm4,[ebx] + movdqu xmm5,[ecx*1+ebx] + movdqa xmm6,xmm4 + movdqu xmm7,[eax*1+ebx] + pxor xmm4,xmm0 + movdqu xmm2,[esi] + pxor xmm5,xmm4 + movdqu xmm3,[16+esi] + pxor xmm6,xmm5 + movdqa [esp],xmm4 + pxor xmm7,xmm6 + movdqa [16+esp],xmm5 + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + mov ecx,DWORD [240+edx] + pxor xmm1,xmm2 + pxor xmm2,[esp] + pxor xmm1,xmm3 + pxor xmm3,[16+esp] + pxor xmm1,xmm4 + pxor xmm4,xmm6 + pxor xmm1,xmm5 + pxor xmm5,xmm7 + movdqa [96+esp],xmm1 + mov edi,DWORD [120+esp] + call __aesni_encrypt4 + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,xmm6 + movups [esi*1+edi],xmm2 + xorps xmm5,xmm7 + movups [16+esi*1+edi],xmm3 + movdqa xmm0,xmm7 + movups [32+esi*1+edi],xmm4 + movdqa xmm1,[96+esp] + movups [48+esi*1+edi],xmm5 +L$078done: + mov edx,DWORD [128+esp] + pxor xmm2,xmm2 + pxor xmm3,xmm3 + movdqa [esp],xmm2 + pxor xmm4,xmm4 + movdqa [16+esp],xmm2 + pxor xmm5,xmm5 + movdqa [32+esp],xmm2 + pxor xmm6,xmm6 + movdqa [48+esp],xmm2 + pxor xmm7,xmm7 + movdqa [64+esp],xmm2 + movdqa [80+esp],xmm2 + movdqa [96+esp],xmm2 + lea esp,[edx] + mov ecx,DWORD [40+esp] + mov ebx,DWORD [48+esp] + movdqu [ecx],xmm0 + pxor xmm0,xmm0 + movdqu [ebx],xmm1 + pxor xmm1,xmm1 + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_ocb_decrypt +align 16 +_aesni_ocb_decrypt: +L$_aesni_ocb_decrypt_begin: + push ebp + push ebx + push esi + push edi + mov ecx,DWORD [40+esp] + mov ebx,DWORD [48+esp] + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + movdqu xmm0,[ecx] + mov ebp,DWORD [36+esp] + movdqu xmm1,[ebx] + mov ebx,DWORD [44+esp] + mov ecx,esp + sub esp,132 + and esp,-16 + sub edi,esi + shl eax,4 + lea eax,[eax*1+esi-96] + mov DWORD [120+esp],edi + mov DWORD [124+esp],eax + mov DWORD [128+esp],ecx + mov ecx,DWORD [240+edx] + test ebp,1 + jnz NEAR L$084odd + bsf eax,ebp + add ebp,1 + shl eax,4 + movdqu xmm7,[eax*1+ebx] + mov eax,edx + movdqu xmm2,[esi] + lea esi,[16+esi] + pxor xmm7,xmm0 + pxor xmm2,xmm7 + movdqa xmm6,xmm1 + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$085dec1_loop_17: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$085dec1_loop_17 +db 102,15,56,223,209 + xorps xmm2,xmm7 + movaps xmm1,xmm6 + movdqa xmm0,xmm7 + xorps xmm1,xmm2 + movups [esi*1+edi-16],xmm2 + mov ecx,DWORD [240+eax] + mov edx,eax + mov eax,DWORD [124+esp] +L$084odd: + shl ecx,4 + mov edi,16 + sub edi,ecx + mov DWORD [112+esp],edx + lea edx,[32+ecx*1+edx] + mov DWORD [116+esp],edi + cmp esi,eax + ja NEAR L$086short + jmp NEAR L$087grandloop +align 32 +L$087grandloop: + lea ecx,[1+ebp] + lea eax,[3+ebp] + lea edi,[5+ebp] + add ebp,6 + bsf ecx,ecx + bsf eax,eax + bsf edi,edi + shl ecx,4 + shl eax,4 + shl edi,4 + movdqu xmm2,[ebx] + movdqu xmm3,[ecx*1+ebx] + mov ecx,DWORD [116+esp] + movdqa xmm4,xmm2 + movdqu xmm5,[eax*1+ebx] + movdqa xmm6,xmm2 + movdqu xmm7,[edi*1+ebx] + pxor xmm2,xmm0 + pxor xmm3,xmm2 + movdqa [esp],xmm2 + pxor xmm4,xmm3 + movdqa [16+esp],xmm3 + pxor xmm5,xmm4 + movdqa [32+esp],xmm4 + pxor xmm6,xmm5 + movdqa [48+esp],xmm5 + pxor xmm7,xmm6 + movdqa [64+esp],xmm6 + movdqa [80+esp],xmm7 + movups xmm0,[ecx*1+edx-48] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + movdqu xmm7,[80+esi] + lea esi,[96+esi] + movdqa [96+esp],xmm1 + pxor xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + pxor xmm5,xmm0 + pxor xmm6,xmm0 + pxor xmm7,xmm0 + movups xmm1,[ecx*1+edx-32] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + pxor xmm7,[80+esp] + movups xmm0,[ecx*1+edx-16] +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,222,233 +db 102,15,56,222,241 +db 102,15,56,222,249 + mov edi,DWORD [120+esp] + mov eax,DWORD [124+esp] + call L$_aesni_decrypt6_enter + movdqa xmm0,[80+esp] + pxor xmm2,[esp] + movdqa xmm1,[96+esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + pxor xmm7,xmm0 + pxor xmm1,xmm2 + movdqu [esi*1+edi-96],xmm2 + pxor xmm1,xmm3 + movdqu [esi*1+edi-80],xmm3 + pxor xmm1,xmm4 + movdqu [esi*1+edi-64],xmm4 + pxor xmm1,xmm5 + movdqu [esi*1+edi-48],xmm5 + pxor xmm1,xmm6 + movdqu [esi*1+edi-32],xmm6 + pxor xmm1,xmm7 + movdqu [esi*1+edi-16],xmm7 + cmp esi,eax + jb NEAR L$087grandloop +L$086short: + add eax,96 + sub eax,esi + jz NEAR L$088done + cmp eax,32 + jb NEAR L$089one + je NEAR L$090two + cmp eax,64 + jb NEAR L$091three + je NEAR L$092four + lea ecx,[1+ebp] + lea eax,[3+ebp] + bsf ecx,ecx + bsf eax,eax + shl ecx,4 + shl eax,4 + movdqu xmm2,[ebx] + movdqu xmm3,[ecx*1+ebx] + mov ecx,DWORD [116+esp] + movdqa xmm4,xmm2 + movdqu xmm5,[eax*1+ebx] + movdqa xmm6,xmm2 + pxor xmm2,xmm0 + pxor xmm3,xmm2 + movdqa [esp],xmm2 + pxor xmm4,xmm3 + movdqa [16+esp],xmm3 + pxor xmm5,xmm4 + movdqa [32+esp],xmm4 + pxor xmm6,xmm5 + movdqa [48+esp],xmm5 + pxor xmm7,xmm6 + movdqa [64+esp],xmm6 + movups xmm0,[ecx*1+edx-48] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + pxor xmm7,xmm7 + movdqa [96+esp],xmm1 + pxor xmm2,xmm0 + pxor xmm3,xmm0 + pxor xmm4,xmm0 + pxor xmm5,xmm0 + pxor xmm6,xmm0 + movups xmm1,[ecx*1+edx-32] + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,[64+esp] + movups xmm0,[ecx*1+edx-16] +db 102,15,56,222,209 +db 102,15,56,222,217 +db 102,15,56,222,225 +db 102,15,56,222,233 +db 102,15,56,222,241 +db 102,15,56,222,249 + mov edi,DWORD [120+esp] + call L$_aesni_decrypt6_enter + movdqa xmm0,[64+esp] + pxor xmm2,[esp] + movdqa xmm1,[96+esp] + pxor xmm3,[16+esp] + pxor xmm4,[32+esp] + pxor xmm5,[48+esp] + pxor xmm6,xmm0 + pxor xmm1,xmm2 + movdqu [esi*1+edi],xmm2 + pxor xmm1,xmm3 + movdqu [16+esi*1+edi],xmm3 + pxor xmm1,xmm4 + movdqu [32+esi*1+edi],xmm4 + pxor xmm1,xmm5 + movdqu [48+esi*1+edi],xmm5 + pxor xmm1,xmm6 + movdqu [64+esi*1+edi],xmm6 + jmp NEAR L$088done +align 16 +L$089one: + movdqu xmm7,[ebx] + mov edx,DWORD [112+esp] + movdqu xmm2,[esi] + mov ecx,DWORD [240+edx] + pxor xmm7,xmm0 + pxor xmm2,xmm7 + movdqa xmm6,xmm1 + mov edi,DWORD [120+esp] + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$093dec1_loop_18: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$093dec1_loop_18 +db 102,15,56,223,209 + xorps xmm2,xmm7 + movaps xmm1,xmm6 + movdqa xmm0,xmm7 + xorps xmm1,xmm2 + movups [esi*1+edi],xmm2 + jmp NEAR L$088done +align 16 +L$090two: + lea ecx,[1+ebp] + mov edx,DWORD [112+esp] + bsf ecx,ecx + shl ecx,4 + movdqu xmm6,[ebx] + movdqu xmm7,[ecx*1+ebx] + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + mov ecx,DWORD [240+edx] + movdqa xmm5,xmm1 + pxor xmm6,xmm0 + pxor xmm7,xmm6 + pxor xmm2,xmm6 + pxor xmm3,xmm7 + mov edi,DWORD [120+esp] + call __aesni_decrypt2 + xorps xmm2,xmm6 + xorps xmm3,xmm7 + movdqa xmm0,xmm7 + xorps xmm5,xmm2 + movups [esi*1+edi],xmm2 + xorps xmm5,xmm3 + movups [16+esi*1+edi],xmm3 + movaps xmm1,xmm5 + jmp NEAR L$088done +align 16 +L$091three: + lea ecx,[1+ebp] + mov edx,DWORD [112+esp] + bsf ecx,ecx + shl ecx,4 + movdqu xmm5,[ebx] + movdqu xmm6,[ecx*1+ebx] + movdqa xmm7,xmm5 + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + mov ecx,DWORD [240+edx] + movdqa [96+esp],xmm1 + pxor xmm5,xmm0 + pxor xmm6,xmm5 + pxor xmm7,xmm6 + pxor xmm2,xmm5 + pxor xmm3,xmm6 + pxor xmm4,xmm7 + mov edi,DWORD [120+esp] + call __aesni_decrypt3 + movdqa xmm1,[96+esp] + xorps xmm2,xmm5 + xorps xmm3,xmm6 + xorps xmm4,xmm7 + movups [esi*1+edi],xmm2 + pxor xmm1,xmm2 + movdqa xmm0,xmm7 + movups [16+esi*1+edi],xmm3 + pxor xmm1,xmm3 + movups [32+esi*1+edi],xmm4 + pxor xmm1,xmm4 + jmp NEAR L$088done +align 16 +L$092four: + lea ecx,[1+ebp] + lea eax,[3+ebp] + bsf ecx,ecx + bsf eax,eax + mov edx,DWORD [112+esp] + shl ecx,4 + shl eax,4 + movdqu xmm4,[ebx] + movdqu xmm5,[ecx*1+ebx] + movdqa xmm6,xmm4 + movdqu xmm7,[eax*1+ebx] + pxor xmm4,xmm0 + movdqu xmm2,[esi] + pxor xmm5,xmm4 + movdqu xmm3,[16+esi] + pxor xmm6,xmm5 + movdqa [esp],xmm4 + pxor xmm7,xmm6 + movdqa [16+esp],xmm5 + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + mov ecx,DWORD [240+edx] + movdqa [96+esp],xmm1 + pxor xmm2,[esp] + pxor xmm3,[16+esp] + pxor xmm4,xmm6 + pxor xmm5,xmm7 + mov edi,DWORD [120+esp] + call __aesni_decrypt4 + movdqa xmm1,[96+esp] + xorps xmm2,[esp] + xorps xmm3,[16+esp] + xorps xmm4,xmm6 + movups [esi*1+edi],xmm2 + pxor xmm1,xmm2 + xorps xmm5,xmm7 + movups [16+esi*1+edi],xmm3 + pxor xmm1,xmm3 + movdqa xmm0,xmm7 + movups [32+esi*1+edi],xmm4 + pxor xmm1,xmm4 + movups [48+esi*1+edi],xmm5 + pxor xmm1,xmm5 +L$088done: + mov edx,DWORD [128+esp] + pxor xmm2,xmm2 + pxor xmm3,xmm3 + movdqa [esp],xmm2 + pxor xmm4,xmm4 + movdqa [16+esp],xmm2 + pxor xmm5,xmm5 + movdqa [32+esp],xmm2 + pxor xmm6,xmm6 + movdqa [48+esp],xmm2 + pxor xmm7,xmm7 + movdqa [64+esp],xmm2 + movdqa [80+esp],xmm2 + movdqa [96+esp],xmm2 + lea esp,[edx] + mov ecx,DWORD [40+esp] + mov ebx,DWORD [48+esp] + movdqu [ecx],xmm0 + pxor xmm0,xmm0 + movdqu [ebx],xmm1 + pxor xmm1,xmm1 + pop edi + pop esi + pop ebx + pop ebp + ret +global _aesni_cbc_encrypt +align 16 +_aesni_cbc_encrypt: +L$_aesni_cbc_encrypt_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov ebx,esp + mov edi,DWORD [24+esp] + sub ebx,24 + mov eax,DWORD [28+esp] + and ebx,-16 + mov edx,DWORD [32+esp] + mov ebp,DWORD [36+esp] + test eax,eax + jz NEAR L$094cbc_abort + cmp DWORD [40+esp],0 + xchg ebx,esp + movups xmm7,[ebp] + mov ecx,DWORD [240+edx] + mov ebp,edx + mov DWORD [16+esp],ebx + mov ebx,ecx + je NEAR L$095cbc_decrypt + movaps xmm2,xmm7 + cmp eax,16 + jb NEAR L$096cbc_enc_tail + sub eax,16 + jmp NEAR L$097cbc_enc_loop +align 16 +L$097cbc_enc_loop: + movups xmm7,[esi] + lea esi,[16+esi] + movups xmm0,[edx] + movups xmm1,[16+edx] + xorps xmm7,xmm0 + lea edx,[32+edx] + xorps xmm2,xmm7 +L$098enc1_loop_19: +db 102,15,56,220,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$098enc1_loop_19 +db 102,15,56,221,209 + mov ecx,ebx + mov edx,ebp + movups [edi],xmm2 + lea edi,[16+edi] + sub eax,16 + jnc NEAR L$097cbc_enc_loop + add eax,16 + jnz NEAR L$096cbc_enc_tail + movaps xmm7,xmm2 + pxor xmm2,xmm2 + jmp NEAR L$099cbc_ret +L$096cbc_enc_tail: + mov ecx,eax +dd 2767451785 + mov ecx,16 + sub ecx,eax + xor eax,eax +dd 2868115081 + lea edi,[edi-16] + mov ecx,ebx + mov esi,edi + mov edx,ebp + jmp NEAR L$097cbc_enc_loop +align 16 +L$095cbc_decrypt: + cmp eax,80 + jbe NEAR L$100cbc_dec_tail + movaps [esp],xmm7 + sub eax,80 + jmp NEAR L$101cbc_dec_loop6_enter +align 16 +L$102cbc_dec_loop6: + movaps [esp],xmm0 + movups [edi],xmm7 + lea edi,[16+edi] +L$101cbc_dec_loop6_enter: + movdqu xmm2,[esi] + movdqu xmm3,[16+esi] + movdqu xmm4,[32+esi] + movdqu xmm5,[48+esi] + movdqu xmm6,[64+esi] + movdqu xmm7,[80+esi] + call __aesni_decrypt6 + movups xmm1,[esi] + movups xmm0,[16+esi] + xorps xmm2,[esp] + xorps xmm3,xmm1 + movups xmm1,[32+esi] + xorps xmm4,xmm0 + movups xmm0,[48+esi] + xorps xmm5,xmm1 + movups xmm1,[64+esi] + xorps xmm6,xmm0 + movups xmm0,[80+esi] + xorps xmm7,xmm1 + movups [edi],xmm2 + movups [16+edi],xmm3 + lea esi,[96+esi] + movups [32+edi],xmm4 + mov ecx,ebx + movups [48+edi],xmm5 + mov edx,ebp + movups [64+edi],xmm6 + lea edi,[80+edi] + sub eax,96 + ja NEAR L$102cbc_dec_loop6 + movaps xmm2,xmm7 + movaps xmm7,xmm0 + add eax,80 + jle NEAR L$103cbc_dec_clear_tail_collected + movups [edi],xmm2 + lea edi,[16+edi] +L$100cbc_dec_tail: + movups xmm2,[esi] + movaps xmm6,xmm2 + cmp eax,16 + jbe NEAR L$104cbc_dec_one + movups xmm3,[16+esi] + movaps xmm5,xmm3 + cmp eax,32 + jbe NEAR L$105cbc_dec_two + movups xmm4,[32+esi] + cmp eax,48 + jbe NEAR L$106cbc_dec_three + movups xmm5,[48+esi] + cmp eax,64 + jbe NEAR L$107cbc_dec_four + movups xmm6,[64+esi] + movaps [esp],xmm7 + movups xmm2,[esi] + xorps xmm7,xmm7 + call __aesni_decrypt6 + movups xmm1,[esi] + movups xmm0,[16+esi] + xorps xmm2,[esp] + xorps xmm3,xmm1 + movups xmm1,[32+esi] + xorps xmm4,xmm0 + movups xmm0,[48+esi] + xorps xmm5,xmm1 + movups xmm7,[64+esi] + xorps xmm6,xmm0 + movups [edi],xmm2 + movups [16+edi],xmm3 + pxor xmm3,xmm3 + movups [32+edi],xmm4 + pxor xmm4,xmm4 + movups [48+edi],xmm5 + pxor xmm5,xmm5 + lea edi,[64+edi] + movaps xmm2,xmm6 + pxor xmm6,xmm6 + sub eax,80 + jmp NEAR L$108cbc_dec_tail_collected +align 16 +L$104cbc_dec_one: + movups xmm0,[edx] + movups xmm1,[16+edx] + lea edx,[32+edx] + xorps xmm2,xmm0 +L$109dec1_loop_20: +db 102,15,56,222,209 + dec ecx + movups xmm1,[edx] + lea edx,[16+edx] + jnz NEAR L$109dec1_loop_20 +db 102,15,56,223,209 + xorps xmm2,xmm7 + movaps xmm7,xmm6 + sub eax,16 + jmp NEAR L$108cbc_dec_tail_collected +align 16 +L$105cbc_dec_two: + call __aesni_decrypt2 + xorps xmm2,xmm7 + xorps xmm3,xmm6 + movups [edi],xmm2 + movaps xmm2,xmm3 + pxor xmm3,xmm3 + lea edi,[16+edi] + movaps xmm7,xmm5 + sub eax,32 + jmp NEAR L$108cbc_dec_tail_collected +align 16 +L$106cbc_dec_three: + call __aesni_decrypt3 + xorps xmm2,xmm7 + xorps xmm3,xmm6 + xorps xmm4,xmm5 + movups [edi],xmm2 + movaps xmm2,xmm4 + pxor xmm4,xmm4 + movups [16+edi],xmm3 + pxor xmm3,xmm3 + lea edi,[32+edi] + movups xmm7,[32+esi] + sub eax,48 + jmp NEAR L$108cbc_dec_tail_collected +align 16 +L$107cbc_dec_four: + call __aesni_decrypt4 + movups xmm1,[16+esi] + movups xmm0,[32+esi] + xorps xmm2,xmm7 + movups xmm7,[48+esi] + xorps xmm3,xmm6 + movups [edi],xmm2 + xorps xmm4,xmm1 + movups [16+edi],xmm3 + pxor xmm3,xmm3 + xorps xmm5,xmm0 + movups [32+edi],xmm4 + pxor xmm4,xmm4 + lea edi,[48+edi] + movaps xmm2,xmm5 + pxor xmm5,xmm5 + sub eax,64 + jmp NEAR L$108cbc_dec_tail_collected +align 16 +L$103cbc_dec_clear_tail_collected: + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 +L$108cbc_dec_tail_collected: + and eax,15 + jnz NEAR L$110cbc_dec_tail_partial + movups [edi],xmm2 + pxor xmm0,xmm0 + jmp NEAR L$099cbc_ret +align 16 +L$110cbc_dec_tail_partial: + movaps [esp],xmm2 + pxor xmm0,xmm0 + mov ecx,16 + mov esi,esp + sub ecx,eax +dd 2767451785 + movdqa [esp],xmm2 +L$099cbc_ret: + mov esp,DWORD [16+esp] + mov ebp,DWORD [36+esp] + pxor xmm2,xmm2 + pxor xmm1,xmm1 + movups [ebp],xmm7 + pxor xmm7,xmm7 +L$094cbc_abort: + pop edi + pop esi + pop ebx + pop ebp + ret +align 16 +__aesni_set_encrypt_key: + push ebp + push ebx + test eax,eax + jz NEAR L$111bad_pointer + test edx,edx + jz NEAR L$111bad_pointer + call L$112pic +L$112pic: + pop ebx + lea ebx,[(L$key_const-L$112pic)+ebx] + lea ebp,[_OPENSSL_ia32cap_P] + movups xmm0,[eax] + xorps xmm4,xmm4 + mov ebp,DWORD [4+ebp] + lea edx,[16+edx] + and ebp,268437504 + cmp ecx,256 + je NEAR L$11314rounds + cmp ecx,192 + je NEAR L$11412rounds + cmp ecx,128 + jne NEAR L$115bad_keybits +align 16 +L$11610rounds: + cmp ebp,268435456 + je NEAR L$11710rounds_alt + mov ecx,9 + movups [edx-16],xmm0 +db 102,15,58,223,200,1 + call L$118key_128_cold +db 102,15,58,223,200,2 + call L$119key_128 +db 102,15,58,223,200,4 + call L$119key_128 +db 102,15,58,223,200,8 + call L$119key_128 +db 102,15,58,223,200,16 + call L$119key_128 +db 102,15,58,223,200,32 + call L$119key_128 +db 102,15,58,223,200,64 + call L$119key_128 +db 102,15,58,223,200,128 + call L$119key_128 +db 102,15,58,223,200,27 + call L$119key_128 +db 102,15,58,223,200,54 + call L$119key_128 + movups [edx],xmm0 + mov DWORD [80+edx],ecx + jmp NEAR L$120good_key +align 16 +L$119key_128: + movups [edx],xmm0 + lea edx,[16+edx] +L$118key_128_cold: + shufps xmm4,xmm0,16 + xorps xmm0,xmm4 + shufps xmm4,xmm0,140 + xorps xmm0,xmm4 + shufps xmm1,xmm1,255 + xorps xmm0,xmm1 + ret +align 16 +L$11710rounds_alt: + movdqa xmm5,[ebx] + mov ecx,8 + movdqa xmm4,[32+ebx] + movdqa xmm2,xmm0 + movdqu [edx-16],xmm0 +L$121loop_key128: +db 102,15,56,0,197 +db 102,15,56,221,196 + pslld xmm4,1 + lea edx,[16+edx] + movdqa xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm2,xmm3 + pxor xmm0,xmm2 + movdqu [edx-16],xmm0 + movdqa xmm2,xmm0 + dec ecx + jnz NEAR L$121loop_key128 + movdqa xmm4,[48+ebx] +db 102,15,56,0,197 +db 102,15,56,221,196 + pslld xmm4,1 + movdqa xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm2,xmm3 + pxor xmm0,xmm2 + movdqu [edx],xmm0 + movdqa xmm2,xmm0 +db 102,15,56,0,197 +db 102,15,56,221,196 + movdqa xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm3,xmm2 + pslldq xmm2,4 + pxor xmm2,xmm3 + pxor xmm0,xmm2 + movdqu [16+edx],xmm0 + mov ecx,9 + mov DWORD [96+edx],ecx + jmp NEAR L$120good_key +align 16 +L$11412rounds: + movq xmm2,[16+eax] + cmp ebp,268435456 + je NEAR L$12212rounds_alt + mov ecx,11 + movups [edx-16],xmm0 +db 102,15,58,223,202,1 + call L$123key_192a_cold +db 102,15,58,223,202,2 + call L$124key_192b +db 102,15,58,223,202,4 + call L$125key_192a +db 102,15,58,223,202,8 + call L$124key_192b +db 102,15,58,223,202,16 + call L$125key_192a +db 102,15,58,223,202,32 + call L$124key_192b +db 102,15,58,223,202,64 + call L$125key_192a +db 102,15,58,223,202,128 + call L$124key_192b + movups [edx],xmm0 + mov DWORD [48+edx],ecx + jmp NEAR L$120good_key +align 16 +L$125key_192a: + movups [edx],xmm0 + lea edx,[16+edx] +align 16 +L$123key_192a_cold: + movaps xmm5,xmm2 +L$126key_192b_warm: + shufps xmm4,xmm0,16 + movdqa xmm3,xmm2 + xorps xmm0,xmm4 + shufps xmm4,xmm0,140 + pslldq xmm3,4 + xorps xmm0,xmm4 + pshufd xmm1,xmm1,85 + pxor xmm2,xmm3 + pxor xmm0,xmm1 + pshufd xmm3,xmm0,255 + pxor xmm2,xmm3 + ret +align 16 +L$124key_192b: + movaps xmm3,xmm0 + shufps xmm5,xmm0,68 + movups [edx],xmm5 + shufps xmm3,xmm2,78 + movups [16+edx],xmm3 + lea edx,[32+edx] + jmp NEAR L$126key_192b_warm +align 16 +L$12212rounds_alt: + movdqa xmm5,[16+ebx] + movdqa xmm4,[32+ebx] + mov ecx,8 + movdqu [edx-16],xmm0 +L$127loop_key192: + movq [edx],xmm2 + movdqa xmm1,xmm2 +db 102,15,56,0,213 +db 102,15,56,221,212 + pslld xmm4,1 + lea edx,[24+edx] + movdqa xmm3,xmm0 + pslldq xmm0,4 + pxor xmm3,xmm0 + pslldq xmm0,4 + pxor xmm3,xmm0 + pslldq xmm0,4 + pxor xmm0,xmm3 + pshufd xmm3,xmm0,255 + pxor xmm3,xmm1 + pslldq xmm1,4 + pxor xmm3,xmm1 + pxor xmm0,xmm2 + pxor xmm2,xmm3 + movdqu [edx-16],xmm0 + dec ecx + jnz NEAR L$127loop_key192 + mov ecx,11 + mov DWORD [32+edx],ecx + jmp NEAR L$120good_key +align 16 +L$11314rounds: + movups xmm2,[16+eax] + lea edx,[16+edx] + cmp ebp,268435456 + je NEAR L$12814rounds_alt + mov ecx,13 + movups [edx-32],xmm0 + movups [edx-16],xmm2 +db 102,15,58,223,202,1 + call L$129key_256a_cold +db 102,15,58,223,200,1 + call L$130key_256b +db 102,15,58,223,202,2 + call L$131key_256a +db 102,15,58,223,200,2 + call L$130key_256b +db 102,15,58,223,202,4 + call L$131key_256a +db 102,15,58,223,200,4 + call L$130key_256b +db 102,15,58,223,202,8 + call L$131key_256a +db 102,15,58,223,200,8 + call L$130key_256b +db 102,15,58,223,202,16 + call L$131key_256a +db 102,15,58,223,200,16 + call L$130key_256b +db 102,15,58,223,202,32 + call L$131key_256a +db 102,15,58,223,200,32 + call L$130key_256b +db 102,15,58,223,202,64 + call L$131key_256a + movups [edx],xmm0 + mov DWORD [16+edx],ecx + xor eax,eax + jmp NEAR L$120good_key +align 16 +L$131key_256a: + movups [edx],xmm2 + lea edx,[16+edx] +L$129key_256a_cold: + shufps xmm4,xmm0,16 + xorps xmm0,xmm4 + shufps xmm4,xmm0,140 + xorps xmm0,xmm4 + shufps xmm1,xmm1,255 + xorps xmm0,xmm1 + ret +align 16 +L$130key_256b: + movups [edx],xmm0 + lea edx,[16+edx] + shufps xmm4,xmm2,16 + xorps xmm2,xmm4 + shufps xmm4,xmm2,140 + xorps xmm2,xmm4 + shufps xmm1,xmm1,170 + xorps xmm2,xmm1 + ret +align 16 +L$12814rounds_alt: + movdqa xmm5,[ebx] + movdqa xmm4,[32+ebx] + mov ecx,7 + movdqu [edx-32],xmm0 + movdqa xmm1,xmm2 + movdqu [edx-16],xmm2 +L$132loop_key256: +db 102,15,56,0,213 +db 102,15,56,221,212 + movdqa xmm3,xmm0 + pslldq xmm0,4 + pxor xmm3,xmm0 + pslldq xmm0,4 + pxor xmm3,xmm0 + pslldq xmm0,4 + pxor xmm0,xmm3 + pslld xmm4,1 + pxor xmm0,xmm2 + movdqu [edx],xmm0 + dec ecx + jz NEAR L$133done_key256 + pshufd xmm2,xmm0,255 + pxor xmm3,xmm3 +db 102,15,56,221,211 + movdqa xmm3,xmm1 + pslldq xmm1,4 + pxor xmm3,xmm1 + pslldq xmm1,4 + pxor xmm3,xmm1 + pslldq xmm1,4 + pxor xmm1,xmm3 + pxor xmm2,xmm1 + movdqu [16+edx],xmm2 + lea edx,[32+edx] + movdqa xmm1,xmm2 + jmp NEAR L$132loop_key256 +L$133done_key256: + mov ecx,13 + mov DWORD [16+edx],ecx +L$120good_key: + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + xor eax,eax + pop ebx + pop ebp + ret +align 4 +L$111bad_pointer: + mov eax,-1 + pop ebx + pop ebp + ret +align 4 +L$115bad_keybits: + pxor xmm0,xmm0 + mov eax,-2 + pop ebx + pop ebp + ret +global _aesni_set_encrypt_key +align 16 +_aesni_set_encrypt_key: +L$_aesni_set_encrypt_key_begin: + mov eax,DWORD [4+esp] + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + call __aesni_set_encrypt_key + ret +global _aesni_set_decrypt_key +align 16 +_aesni_set_decrypt_key: +L$_aesni_set_decrypt_key_begin: + mov eax,DWORD [4+esp] + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + call __aesni_set_encrypt_key + mov edx,DWORD [12+esp] + shl ecx,4 + test eax,eax + jnz NEAR L$134dec_key_ret + lea eax,[16+ecx*1+edx] + movups xmm0,[edx] + movups xmm1,[eax] + movups [eax],xmm0 + movups [edx],xmm1 + lea edx,[16+edx] + lea eax,[eax-16] +L$135dec_key_inverse: + movups xmm0,[edx] + movups xmm1,[eax] +db 102,15,56,219,192 +db 102,15,56,219,201 + lea edx,[16+edx] + lea eax,[eax-16] + movups [16+eax],xmm0 + movups [edx-16],xmm1 + cmp eax,edx + ja NEAR L$135dec_key_inverse + movups xmm0,[edx] +db 102,15,56,219,192 + movups [edx],xmm0 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + xor eax,eax +L$134dec_key_ret: + ret +align 64 +L$key_const: +dd 202313229,202313229,202313229,202313229 +dd 67569157,67569157,67569157,67569157 +dd 1,1,1,1 +dd 27,27,27,27 +db 65,69,83,32,102,111,114,32,73,110,116,101,108,32,65,69 +db 83,45,78,73,44,32,67,82,89,80,84,79,71,65,77,83 +db 32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115 +db 115,108,46,111,114,103,62,0 +segment .bss +common _OPENSSL_ia32cap_P 16 diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/vpaes-x86.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/vpaes-x86.nasm new file mode 100644 index 0000000000..cf2e13f620 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/aes/vpaes-x86.nasm @@ -0,0 +1,651 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/aes/asm/vpaes-x86.pl +; +; Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +align 64 +L$_vpaes_consts: +dd 218628480,235210255,168496130,67568393 +dd 252381056,17041926,33884169,51187212 +dd 252645135,252645135,252645135,252645135 +dd 1512730624,3266504856,1377990664,3401244816 +dd 830229760,1275146365,2969422977,3447763452 +dd 3411033600,2979783055,338359620,2782886510 +dd 4209124096,907596821,221174255,1006095553 +dd 191964160,3799684038,3164090317,1589111125 +dd 182528256,1777043520,2877432650,3265356744 +dd 1874708224,3503451415,3305285752,363511674 +dd 1606117888,3487855781,1093350906,2384367825 +dd 197121,67569157,134941193,202313229 +dd 67569157,134941193,202313229,197121 +dd 134941193,202313229,197121,67569157 +dd 202313229,197121,67569157,134941193 +dd 33619971,100992007,168364043,235736079 +dd 235736079,33619971,100992007,168364043 +dd 168364043,235736079,33619971,100992007 +dd 100992007,168364043,235736079,33619971 +dd 50462976,117835012,185207048,252579084 +dd 252314880,51251460,117574920,184942860 +dd 184682752,252054788,50987272,118359308 +dd 118099200,185467140,251790600,50727180 +dd 2946363062,528716217,1300004225,1881839624 +dd 1532713819,1532713819,1532713819,1532713819 +dd 3602276352,4288629033,3737020424,4153884961 +dd 1354558464,32357713,2958822624,3775749553 +dd 1201988352,132424512,1572796698,503232858 +dd 2213177600,1597421020,4103937655,675398315 +dd 2749646592,4273543773,1511898873,121693092 +dd 3040248576,1103263732,2871565598,1608280554 +dd 2236667136,2588920351,482954393,64377734 +dd 3069987328,291237287,2117370568,3650299247 +dd 533321216,3573750986,2572112006,1401264716 +dd 1339849704,2721158661,548607111,3445553514 +dd 2128193280,3054596040,2183486460,1257083700 +dd 655635200,1165381986,3923443150,2344132524 +dd 190078720,256924420,290342170,357187870 +dd 1610966272,2263057382,4103205268,309794674 +dd 2592527872,2233205587,1335446729,3402964816 +dd 3973531904,3225098121,3002836325,1918774430 +dd 3870401024,2102906079,2284471353,4117666579 +dd 617007872,1021508343,366931923,691083277 +dd 2528395776,3491914898,2968704004,1613121270 +dd 3445188352,3247741094,844474987,4093578302 +dd 651481088,1190302358,1689581232,574775300 +dd 4289380608,206939853,2555985458,2489840491 +dd 2130264064,327674451,3566485037,3349835193 +dd 2470714624,316102159,3636825756,3393945945 +db 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105 +db 111,110,32,65,69,83,32,102,111,114,32,120,56,54,47,83 +db 83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117 +db 114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105 +db 118,101,114,115,105,116,121,41,0 +align 64 +align 16 +__vpaes_preheat: + add ebp,DWORD [esp] + movdqa xmm7,[ebp-48] + movdqa xmm6,[ebp-16] + ret +align 16 +__vpaes_encrypt_core: + mov ecx,16 + mov eax,DWORD [240+edx] + movdqa xmm1,xmm6 + movdqa xmm2,[ebp] + pandn xmm1,xmm0 + pand xmm0,xmm6 + movdqu xmm5,[edx] +db 102,15,56,0,208 + movdqa xmm0,[16+ebp] + pxor xmm2,xmm5 + psrld xmm1,4 + add edx,16 +db 102,15,56,0,193 + lea ebx,[192+ebp] + pxor xmm0,xmm2 + jmp NEAR L$000enc_entry +align 16 +L$001enc_loop: + movdqa xmm4,[32+ebp] + movdqa xmm0,[48+ebp] +db 102,15,56,0,226 +db 102,15,56,0,195 + pxor xmm4,xmm5 + movdqa xmm5,[64+ebp] + pxor xmm0,xmm4 + movdqa xmm1,[ecx*1+ebx-64] +db 102,15,56,0,234 + movdqa xmm2,[80+ebp] + movdqa xmm4,[ecx*1+ebx] +db 102,15,56,0,211 + movdqa xmm3,xmm0 + pxor xmm2,xmm5 +db 102,15,56,0,193 + add edx,16 + pxor xmm0,xmm2 +db 102,15,56,0,220 + add ecx,16 + pxor xmm3,xmm0 +db 102,15,56,0,193 + and ecx,48 + sub eax,1 + pxor xmm0,xmm3 +L$000enc_entry: + movdqa xmm1,xmm6 + movdqa xmm5,[ebp-32] + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm6 +db 102,15,56,0,232 + movdqa xmm3,xmm7 + pxor xmm0,xmm1 +db 102,15,56,0,217 + movdqa xmm4,xmm7 + pxor xmm3,xmm5 +db 102,15,56,0,224 + movdqa xmm2,xmm7 + pxor xmm4,xmm5 +db 102,15,56,0,211 + movdqa xmm3,xmm7 + pxor xmm2,xmm0 +db 102,15,56,0,220 + movdqu xmm5,[edx] + pxor xmm3,xmm1 + jnz NEAR L$001enc_loop + movdqa xmm4,[96+ebp] + movdqa xmm0,[112+ebp] +db 102,15,56,0,226 + pxor xmm4,xmm5 +db 102,15,56,0,195 + movdqa xmm1,[64+ecx*1+ebx] + pxor xmm0,xmm4 +db 102,15,56,0,193 + ret +align 16 +__vpaes_decrypt_core: + lea ebx,[608+ebp] + mov eax,DWORD [240+edx] + movdqa xmm1,xmm6 + movdqa xmm2,[ebx-64] + pandn xmm1,xmm0 + mov ecx,eax + psrld xmm1,4 + movdqu xmm5,[edx] + shl ecx,4 + pand xmm0,xmm6 +db 102,15,56,0,208 + movdqa xmm0,[ebx-48] + xor ecx,48 +db 102,15,56,0,193 + and ecx,48 + pxor xmm2,xmm5 + movdqa xmm5,[176+ebp] + pxor xmm0,xmm2 + add edx,16 + lea ecx,[ecx*1+ebx-352] + jmp NEAR L$002dec_entry +align 16 +L$003dec_loop: + movdqa xmm4,[ebx-32] + movdqa xmm1,[ebx-16] +db 102,15,56,0,226 +db 102,15,56,0,203 + pxor xmm0,xmm4 + movdqa xmm4,[ebx] + pxor xmm0,xmm1 + movdqa xmm1,[16+ebx] +db 102,15,56,0,226 +db 102,15,56,0,197 +db 102,15,56,0,203 + pxor xmm0,xmm4 + movdqa xmm4,[32+ebx] + pxor xmm0,xmm1 + movdqa xmm1,[48+ebx] +db 102,15,56,0,226 +db 102,15,56,0,197 +db 102,15,56,0,203 + pxor xmm0,xmm4 + movdqa xmm4,[64+ebx] + pxor xmm0,xmm1 + movdqa xmm1,[80+ebx] +db 102,15,56,0,226 +db 102,15,56,0,197 +db 102,15,56,0,203 + pxor xmm0,xmm4 + add edx,16 +db 102,15,58,15,237,12 + pxor xmm0,xmm1 + sub eax,1 +L$002dec_entry: + movdqa xmm1,xmm6 + movdqa xmm2,[ebp-32] + pandn xmm1,xmm0 + pand xmm0,xmm6 + psrld xmm1,4 +db 102,15,56,0,208 + movdqa xmm3,xmm7 + pxor xmm0,xmm1 +db 102,15,56,0,217 + movdqa xmm4,xmm7 + pxor xmm3,xmm2 +db 102,15,56,0,224 + pxor xmm4,xmm2 + movdqa xmm2,xmm7 +db 102,15,56,0,211 + movdqa xmm3,xmm7 + pxor xmm2,xmm0 +db 102,15,56,0,220 + movdqu xmm0,[edx] + pxor xmm3,xmm1 + jnz NEAR L$003dec_loop + movdqa xmm4,[96+ebx] +db 102,15,56,0,226 + pxor xmm4,xmm0 + movdqa xmm0,[112+ebx] + movdqa xmm2,[ecx] +db 102,15,56,0,195 + pxor xmm0,xmm4 +db 102,15,56,0,194 + ret +align 16 +__vpaes_schedule_core: + add ebp,DWORD [esp] + movdqu xmm0,[esi] + movdqa xmm2,[320+ebp] + movdqa xmm3,xmm0 + lea ebx,[ebp] + movdqa [4+esp],xmm2 + call __vpaes_schedule_transform + movdqa xmm7,xmm0 + test edi,edi + jnz NEAR L$004schedule_am_decrypting + movdqu [edx],xmm0 + jmp NEAR L$005schedule_go +L$004schedule_am_decrypting: + movdqa xmm1,[256+ecx*1+ebp] +db 102,15,56,0,217 + movdqu [edx],xmm3 + xor ecx,48 +L$005schedule_go: + cmp eax,192 + ja NEAR L$006schedule_256 + je NEAR L$007schedule_192 +L$008schedule_128: + mov eax,10 +L$009loop_schedule_128: + call __vpaes_schedule_round + dec eax + jz NEAR L$010schedule_mangle_last + call __vpaes_schedule_mangle + jmp NEAR L$009loop_schedule_128 +align 16 +L$007schedule_192: + movdqu xmm0,[8+esi] + call __vpaes_schedule_transform + movdqa xmm6,xmm0 + pxor xmm4,xmm4 + movhlps xmm6,xmm4 + mov eax,4 +L$011loop_schedule_192: + call __vpaes_schedule_round +db 102,15,58,15,198,8 + call __vpaes_schedule_mangle + call __vpaes_schedule_192_smear + call __vpaes_schedule_mangle + call __vpaes_schedule_round + dec eax + jz NEAR L$010schedule_mangle_last + call __vpaes_schedule_mangle + call __vpaes_schedule_192_smear + jmp NEAR L$011loop_schedule_192 +align 16 +L$006schedule_256: + movdqu xmm0,[16+esi] + call __vpaes_schedule_transform + mov eax,7 +L$012loop_schedule_256: + call __vpaes_schedule_mangle + movdqa xmm6,xmm0 + call __vpaes_schedule_round + dec eax + jz NEAR L$010schedule_mangle_last + call __vpaes_schedule_mangle + pshufd xmm0,xmm0,255 + movdqa [20+esp],xmm7 + movdqa xmm7,xmm6 + call L$_vpaes_schedule_low_round + movdqa xmm7,[20+esp] + jmp NEAR L$012loop_schedule_256 +align 16 +L$010schedule_mangle_last: + lea ebx,[384+ebp] + test edi,edi + jnz NEAR L$013schedule_mangle_last_dec + movdqa xmm1,[256+ecx*1+ebp] +db 102,15,56,0,193 + lea ebx,[352+ebp] + add edx,32 +L$013schedule_mangle_last_dec: + add edx,-16 + pxor xmm0,[336+ebp] + call __vpaes_schedule_transform + movdqu [edx],xmm0 + pxor xmm0,xmm0 + pxor xmm1,xmm1 + pxor xmm2,xmm2 + pxor xmm3,xmm3 + pxor xmm4,xmm4 + pxor xmm5,xmm5 + pxor xmm6,xmm6 + pxor xmm7,xmm7 + ret +align 16 +__vpaes_schedule_192_smear: + pshufd xmm1,xmm6,128 + pshufd xmm0,xmm7,254 + pxor xmm6,xmm1 + pxor xmm1,xmm1 + pxor xmm6,xmm0 + movdqa xmm0,xmm6 + movhlps xmm6,xmm1 + ret +align 16 +__vpaes_schedule_round: + movdqa xmm2,[8+esp] + pxor xmm1,xmm1 +db 102,15,58,15,202,15 +db 102,15,58,15,210,15 + pxor xmm7,xmm1 + pshufd xmm0,xmm0,255 +db 102,15,58,15,192,1 + movdqa [8+esp],xmm2 +L$_vpaes_schedule_low_round: + movdqa xmm1,xmm7 + pslldq xmm7,4 + pxor xmm7,xmm1 + movdqa xmm1,xmm7 + pslldq xmm7,8 + pxor xmm7,xmm1 + pxor xmm7,[336+ebp] + movdqa xmm4,[ebp-16] + movdqa xmm5,[ebp-48] + movdqa xmm1,xmm4 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm4 + movdqa xmm2,[ebp-32] +db 102,15,56,0,208 + pxor xmm0,xmm1 + movdqa xmm3,xmm5 +db 102,15,56,0,217 + pxor xmm3,xmm2 + movdqa xmm4,xmm5 +db 102,15,56,0,224 + pxor xmm4,xmm2 + movdqa xmm2,xmm5 +db 102,15,56,0,211 + pxor xmm2,xmm0 + movdqa xmm3,xmm5 +db 102,15,56,0,220 + pxor xmm3,xmm1 + movdqa xmm4,[32+ebp] +db 102,15,56,0,226 + movdqa xmm0,[48+ebp] +db 102,15,56,0,195 + pxor xmm0,xmm4 + pxor xmm0,xmm7 + movdqa xmm7,xmm0 + ret +align 16 +__vpaes_schedule_transform: + movdqa xmm2,[ebp-16] + movdqa xmm1,xmm2 + pandn xmm1,xmm0 + psrld xmm1,4 + pand xmm0,xmm2 + movdqa xmm2,[ebx] +db 102,15,56,0,208 + movdqa xmm0,[16+ebx] +db 102,15,56,0,193 + pxor xmm0,xmm2 + ret +align 16 +__vpaes_schedule_mangle: + movdqa xmm4,xmm0 + movdqa xmm5,[128+ebp] + test edi,edi + jnz NEAR L$014schedule_mangle_dec + add edx,16 + pxor xmm4,[336+ebp] +db 102,15,56,0,229 + movdqa xmm3,xmm4 +db 102,15,56,0,229 + pxor xmm3,xmm4 +db 102,15,56,0,229 + pxor xmm3,xmm4 + jmp NEAR L$015schedule_mangle_both +align 16 +L$014schedule_mangle_dec: + movdqa xmm2,[ebp-16] + lea esi,[416+ebp] + movdqa xmm1,xmm2 + pandn xmm1,xmm4 + psrld xmm1,4 + pand xmm4,xmm2 + movdqa xmm2,[esi] +db 102,15,56,0,212 + movdqa xmm3,[16+esi] +db 102,15,56,0,217 + pxor xmm3,xmm2 +db 102,15,56,0,221 + movdqa xmm2,[32+esi] +db 102,15,56,0,212 + pxor xmm2,xmm3 + movdqa xmm3,[48+esi] +db 102,15,56,0,217 + pxor xmm3,xmm2 +db 102,15,56,0,221 + movdqa xmm2,[64+esi] +db 102,15,56,0,212 + pxor xmm2,xmm3 + movdqa xmm3,[80+esi] +db 102,15,56,0,217 + pxor xmm3,xmm2 +db 102,15,56,0,221 + movdqa xmm2,[96+esi] +db 102,15,56,0,212 + pxor xmm2,xmm3 + movdqa xmm3,[112+esi] +db 102,15,56,0,217 + pxor xmm3,xmm2 + add edx,-16 +L$015schedule_mangle_both: + movdqa xmm1,[256+ecx*1+ebp] +db 102,15,56,0,217 + add ecx,-16 + and ecx,48 + movdqu [edx],xmm3 + ret +global _vpaes_set_encrypt_key +align 16 +_vpaes_set_encrypt_key: +L$_vpaes_set_encrypt_key_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + lea ebx,[esp-56] + mov eax,DWORD [24+esp] + and ebx,-16 + mov edx,DWORD [28+esp] + xchg ebx,esp + mov DWORD [48+esp],ebx + mov ebx,eax + shr ebx,5 + add ebx,5 + mov DWORD [240+edx],ebx + mov ecx,48 + mov edi,0 + lea ebp,[(L$_vpaes_consts+0x30-L$016pic_point)] + call __vpaes_schedule_core +L$016pic_point: + mov esp,DWORD [48+esp] + xor eax,eax + pop edi + pop esi + pop ebx + pop ebp + ret +global _vpaes_set_decrypt_key +align 16 +_vpaes_set_decrypt_key: +L$_vpaes_set_decrypt_key_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + lea ebx,[esp-56] + mov eax,DWORD [24+esp] + and ebx,-16 + mov edx,DWORD [28+esp] + xchg ebx,esp + mov DWORD [48+esp],ebx + mov ebx,eax + shr ebx,5 + add ebx,5 + mov DWORD [240+edx],ebx + shl ebx,4 + lea edx,[16+ebx*1+edx] + mov edi,1 + mov ecx,eax + shr ecx,1 + and ecx,32 + xor ecx,32 + lea ebp,[(L$_vpaes_consts+0x30-L$017pic_point)] + call __vpaes_schedule_core +L$017pic_point: + mov esp,DWORD [48+esp] + xor eax,eax + pop edi + pop esi + pop ebx + pop ebp + ret +global _vpaes_encrypt +align 16 +_vpaes_encrypt: +L$_vpaes_encrypt_begin: + push ebp + push ebx + push esi + push edi + lea ebp,[(L$_vpaes_consts+0x30-L$018pic_point)] + call __vpaes_preheat +L$018pic_point: + mov esi,DWORD [20+esp] + lea ebx,[esp-56] + mov edi,DWORD [24+esp] + and ebx,-16 + mov edx,DWORD [28+esp] + xchg ebx,esp + mov DWORD [48+esp],ebx + movdqu xmm0,[esi] + call __vpaes_encrypt_core + movdqu [edi],xmm0 + mov esp,DWORD [48+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +global _vpaes_decrypt +align 16 +_vpaes_decrypt: +L$_vpaes_decrypt_begin: + push ebp + push ebx + push esi + push edi + lea ebp,[(L$_vpaes_consts+0x30-L$019pic_point)] + call __vpaes_preheat +L$019pic_point: + mov esi,DWORD [20+esp] + lea ebx,[esp-56] + mov edi,DWORD [24+esp] + and ebx,-16 + mov edx,DWORD [28+esp] + xchg ebx,esp + mov DWORD [48+esp],ebx + movdqu xmm0,[esi] + call __vpaes_decrypt_core + movdqu [edi],xmm0 + mov esp,DWORD [48+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +global _vpaes_cbc_encrypt +align 16 +_vpaes_cbc_encrypt: +L$_vpaes_cbc_encrypt_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov edx,DWORD [32+esp] + sub eax,16 + jc NEAR L$020cbc_abort + lea ebx,[esp-56] + mov ebp,DWORD [36+esp] + and ebx,-16 + mov ecx,DWORD [40+esp] + xchg ebx,esp + movdqu xmm1,[ebp] + sub edi,esi + mov DWORD [48+esp],ebx + mov DWORD [esp],edi + mov DWORD [4+esp],edx + mov DWORD [8+esp],ebp + mov edi,eax + lea ebp,[(L$_vpaes_consts+0x30-L$021pic_point)] + call __vpaes_preheat +L$021pic_point: + cmp ecx,0 + je NEAR L$022cbc_dec_loop + jmp NEAR L$023cbc_enc_loop +align 16 +L$023cbc_enc_loop: + movdqu xmm0,[esi] + pxor xmm0,xmm1 + call __vpaes_encrypt_core + mov ebx,DWORD [esp] + mov edx,DWORD [4+esp] + movdqa xmm1,xmm0 + movdqu [esi*1+ebx],xmm0 + lea esi,[16+esi] + sub edi,16 + jnc NEAR L$023cbc_enc_loop + jmp NEAR L$024cbc_done +align 16 +L$022cbc_dec_loop: + movdqu xmm0,[esi] + movdqa [16+esp],xmm1 + movdqa [32+esp],xmm0 + call __vpaes_decrypt_core + mov ebx,DWORD [esp] + mov edx,DWORD [4+esp] + pxor xmm0,[16+esp] + movdqa xmm1,[32+esp] + movdqu [esi*1+ebx],xmm0 + lea esi,[16+esi] + sub edi,16 + jnc NEAR L$022cbc_dec_loop +L$024cbc_done: + mov ebx,DWORD [8+esp] + mov esp,DWORD [48+esp] + movdqu [ebx],xmm1 +L$020cbc_abort: + pop edi + pop esi + pop ebx + pop ebp + ret diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/modes/ghash-x86.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/modes/ghash-x86.nasm new file mode 100644 index 0000000000..88c52f746c --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/modes/ghash-x86.nasm @@ -0,0 +1,700 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/modes/asm/ghash-x86.pl +; +; Copyright 2010-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +global _gcm_gmult_4bit_x86 +align 16 +_gcm_gmult_4bit_x86: +L$_gcm_gmult_4bit_x86_begin: + push ebp + push ebx + push esi + push edi + sub esp,84 + mov edi,DWORD [104+esp] + mov esi,DWORD [108+esp] + mov ebp,DWORD [edi] + mov edx,DWORD [4+edi] + mov ecx,DWORD [8+edi] + mov ebx,DWORD [12+edi] + mov DWORD [16+esp],0 + mov DWORD [20+esp],471859200 + mov DWORD [24+esp],943718400 + mov DWORD [28+esp],610271232 + mov DWORD [32+esp],1887436800 + mov DWORD [36+esp],1822425088 + mov DWORD [40+esp],1220542464 + mov DWORD [44+esp],1423966208 + mov DWORD [48+esp],3774873600 + mov DWORD [52+esp],4246732800 + mov DWORD [56+esp],3644850176 + mov DWORD [60+esp],3311403008 + mov DWORD [64+esp],2441084928 + mov DWORD [68+esp],2376073216 + mov DWORD [72+esp],2847932416 + mov DWORD [76+esp],3051356160 + mov DWORD [esp],ebp + mov DWORD [4+esp],edx + mov DWORD [8+esp],ecx + mov DWORD [12+esp],ebx + shr ebx,20 + and ebx,240 + mov ebp,DWORD [4+ebx*1+esi] + mov edx,DWORD [ebx*1+esi] + mov ecx,DWORD [12+ebx*1+esi] + mov ebx,DWORD [8+ebx*1+esi] + xor eax,eax + mov edi,15 + jmp NEAR L$000x86_loop +align 16 +L$000x86_loop: + mov al,bl + shrd ebx,ecx,4 + and al,15 + shrd ecx,edx,4 + shrd edx,ebp,4 + shr ebp,4 + xor ebp,DWORD [16+eax*4+esp] + mov al,BYTE [edi*1+esp] + and al,240 + xor ebx,DWORD [8+eax*1+esi] + xor ecx,DWORD [12+eax*1+esi] + xor edx,DWORD [eax*1+esi] + xor ebp,DWORD [4+eax*1+esi] + dec edi + js NEAR L$001x86_break + mov al,bl + shrd ebx,ecx,4 + and al,15 + shrd ecx,edx,4 + shrd edx,ebp,4 + shr ebp,4 + xor ebp,DWORD [16+eax*4+esp] + mov al,BYTE [edi*1+esp] + shl al,4 + xor ebx,DWORD [8+eax*1+esi] + xor ecx,DWORD [12+eax*1+esi] + xor edx,DWORD [eax*1+esi] + xor ebp,DWORD [4+eax*1+esi] + jmp NEAR L$000x86_loop +align 16 +L$001x86_break: + bswap ebx + bswap ecx + bswap edx + bswap ebp + mov edi,DWORD [104+esp] + mov DWORD [12+edi],ebx + mov DWORD [8+edi],ecx + mov DWORD [4+edi],edx + mov DWORD [edi],ebp + add esp,84 + pop edi + pop esi + pop ebx + pop ebp + ret +global _gcm_ghash_4bit_x86 +align 16 +_gcm_ghash_4bit_x86: +L$_gcm_ghash_4bit_x86_begin: + push ebp + push ebx + push esi + push edi + sub esp,84 + mov ebx,DWORD [104+esp] + mov esi,DWORD [108+esp] + mov edi,DWORD [112+esp] + mov ecx,DWORD [116+esp] + add ecx,edi + mov DWORD [116+esp],ecx + mov ebp,DWORD [ebx] + mov edx,DWORD [4+ebx] + mov ecx,DWORD [8+ebx] + mov ebx,DWORD [12+ebx] + mov DWORD [16+esp],0 + mov DWORD [20+esp],471859200 + mov DWORD [24+esp],943718400 + mov DWORD [28+esp],610271232 + mov DWORD [32+esp],1887436800 + mov DWORD [36+esp],1822425088 + mov DWORD [40+esp],1220542464 + mov DWORD [44+esp],1423966208 + mov DWORD [48+esp],3774873600 + mov DWORD [52+esp],4246732800 + mov DWORD [56+esp],3644850176 + mov DWORD [60+esp],3311403008 + mov DWORD [64+esp],2441084928 + mov DWORD [68+esp],2376073216 + mov DWORD [72+esp],2847932416 + mov DWORD [76+esp],3051356160 +align 16 +L$002x86_outer_loop: + xor ebx,DWORD [12+edi] + xor ecx,DWORD [8+edi] + xor edx,DWORD [4+edi] + xor ebp,DWORD [edi] + mov DWORD [12+esp],ebx + mov DWORD [8+esp],ecx + mov DWORD [4+esp],edx + mov DWORD [esp],ebp + shr ebx,20 + and ebx,240 + mov ebp,DWORD [4+ebx*1+esi] + mov edx,DWORD [ebx*1+esi] + mov ecx,DWORD [12+ebx*1+esi] + mov ebx,DWORD [8+ebx*1+esi] + xor eax,eax + mov edi,15 + jmp NEAR L$003x86_loop +align 16 +L$003x86_loop: + mov al,bl + shrd ebx,ecx,4 + and al,15 + shrd ecx,edx,4 + shrd edx,ebp,4 + shr ebp,4 + xor ebp,DWORD [16+eax*4+esp] + mov al,BYTE [edi*1+esp] + and al,240 + xor ebx,DWORD [8+eax*1+esi] + xor ecx,DWORD [12+eax*1+esi] + xor edx,DWORD [eax*1+esi] + xor ebp,DWORD [4+eax*1+esi] + dec edi + js NEAR L$004x86_break + mov al,bl + shrd ebx,ecx,4 + and al,15 + shrd ecx,edx,4 + shrd edx,ebp,4 + shr ebp,4 + xor ebp,DWORD [16+eax*4+esp] + mov al,BYTE [edi*1+esp] + shl al,4 + xor ebx,DWORD [8+eax*1+esi] + xor ecx,DWORD [12+eax*1+esi] + xor edx,DWORD [eax*1+esi] + xor ebp,DWORD [4+eax*1+esi] + jmp NEAR L$003x86_loop +align 16 +L$004x86_break: + bswap ebx + bswap ecx + bswap edx + bswap ebp + mov edi,DWORD [112+esp] + lea edi,[16+edi] + cmp edi,DWORD [116+esp] + mov DWORD [112+esp],edi + jb NEAR L$002x86_outer_loop + mov edi,DWORD [104+esp] + mov DWORD [12+edi],ebx + mov DWORD [8+edi],ecx + mov DWORD [4+edi],edx + mov DWORD [edi],ebp + add esp,84 + pop edi + pop esi + pop ebx + pop ebp + ret +align 16 +__mmx_gmult_4bit_inner: + xor ecx,ecx + mov edx,ebx + mov cl,dl + shl cl,4 + and edx,240 + movq mm0,[8+ecx*1+esi] + movq mm1,[ecx*1+esi] + movd ebp,mm0 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [14+edi] + psllq mm2,60 + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [13+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [12+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [11+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [10+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [9+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [8+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [7+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [6+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [5+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [4+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [3+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [2+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [1+edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + mov cl,BYTE [edi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + mov edx,ecx + movd ebx,mm0 + pxor mm0,mm2 + shl cl,4 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+ecx*1+esi] + psllq mm2,60 + and edx,240 + pxor mm1,[ebp*8+eax] + and ebx,15 + pxor mm1,[ecx*1+esi] + movd ebp,mm0 + pxor mm0,mm2 + psrlq mm0,4 + movq mm2,mm1 + psrlq mm1,4 + pxor mm0,[8+edx*1+esi] + psllq mm2,60 + pxor mm1,[ebx*8+eax] + and ebp,15 + pxor mm1,[edx*1+esi] + movd ebx,mm0 + pxor mm0,mm2 + mov edi,DWORD [4+ebp*8+eax] + psrlq mm0,32 + movd edx,mm1 + psrlq mm1,32 + movd ecx,mm0 + movd ebp,mm1 + shl edi,4 + bswap ebx + bswap edx + bswap ecx + xor ebp,edi + bswap ebp + ret +global _gcm_gmult_4bit_mmx +align 16 +_gcm_gmult_4bit_mmx: +L$_gcm_gmult_4bit_mmx_begin: + push ebp + push ebx + push esi + push edi + mov edi,DWORD [20+esp] + mov esi,DWORD [24+esp] + call L$005pic_point +L$005pic_point: + pop eax + lea eax,[(L$rem_4bit-L$005pic_point)+eax] + movzx ebx,BYTE [15+edi] + call __mmx_gmult_4bit_inner + mov edi,DWORD [20+esp] + emms + mov DWORD [12+edi],ebx + mov DWORD [4+edi],edx + mov DWORD [8+edi],ecx + mov DWORD [edi],ebp + pop edi + pop esi + pop ebx + pop ebp + ret +global _gcm_ghash_4bit_mmx +align 16 +_gcm_ghash_4bit_mmx: +L$_gcm_ghash_4bit_mmx_begin: + push ebp + push ebx + push esi + push edi + mov ebp,DWORD [20+esp] + mov esi,DWORD [24+esp] + mov edi,DWORD [28+esp] + mov ecx,DWORD [32+esp] + call L$006pic_point +L$006pic_point: + pop eax + lea eax,[(L$rem_4bit-L$006pic_point)+eax] + add ecx,edi + mov DWORD [32+esp],ecx + sub esp,20 + mov ebx,DWORD [12+ebp] + mov edx,DWORD [4+ebp] + mov ecx,DWORD [8+ebp] + mov ebp,DWORD [ebp] + jmp NEAR L$007mmx_outer_loop +align 16 +L$007mmx_outer_loop: + xor ebx,DWORD [12+edi] + xor edx,DWORD [4+edi] + xor ecx,DWORD [8+edi] + xor ebp,DWORD [edi] + mov DWORD [48+esp],edi + mov DWORD [12+esp],ebx + mov DWORD [4+esp],edx + mov DWORD [8+esp],ecx + mov DWORD [esp],ebp + mov edi,esp + shr ebx,24 + call __mmx_gmult_4bit_inner + mov edi,DWORD [48+esp] + lea edi,[16+edi] + cmp edi,DWORD [52+esp] + jb NEAR L$007mmx_outer_loop + mov edi,DWORD [40+esp] + emms + mov DWORD [12+edi],ebx + mov DWORD [4+edi],edx + mov DWORD [8+edi],ecx + mov DWORD [edi],ebp + add esp,20 + pop edi + pop esi + pop ebx + pop ebp + ret +align 64 +L$rem_4bit: +dd 0,0,0,29491200,0,58982400,0,38141952 +dd 0,117964800,0,113901568,0,76283904,0,88997888 +dd 0,235929600,0,265420800,0,227803136,0,206962688 +dd 0,152567808,0,148504576,0,177995776,0,190709760 +db 71,72,65,83,72,32,102,111,114,32,120,56,54,44,32,67 +db 82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112 +db 112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62 +db 0 diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha1-586.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha1-586.nasm new file mode 100644 index 0000000000..bf2831e5ea --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha1-586.nasm @@ -0,0 +1,1394 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/sha/asm/sha1-586.pl +; +; Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +global _sha1_block_data_order +align 16 +_sha1_block_data_order: +L$_sha1_block_data_order_begin: + push ebp + push ebx + push esi + push edi + mov ebp,DWORD [20+esp] + mov esi,DWORD [24+esp] + mov eax,DWORD [28+esp] + sub esp,76 + shl eax,6 + add eax,esi + mov DWORD [104+esp],eax + mov edi,DWORD [16+ebp] + jmp NEAR L$000loop +align 16 +L$000loop: + mov eax,DWORD [esi] + mov ebx,DWORD [4+esi] + mov ecx,DWORD [8+esi] + mov edx,DWORD [12+esi] + bswap eax + bswap ebx + bswap ecx + bswap edx + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + mov DWORD [8+esp],ecx + mov DWORD [12+esp],edx + mov eax,DWORD [16+esi] + mov ebx,DWORD [20+esi] + mov ecx,DWORD [24+esi] + mov edx,DWORD [28+esi] + bswap eax + bswap ebx + bswap ecx + bswap edx + mov DWORD [16+esp],eax + mov DWORD [20+esp],ebx + mov DWORD [24+esp],ecx + mov DWORD [28+esp],edx + mov eax,DWORD [32+esi] + mov ebx,DWORD [36+esi] + mov ecx,DWORD [40+esi] + mov edx,DWORD [44+esi] + bswap eax + bswap ebx + bswap ecx + bswap edx + mov DWORD [32+esp],eax + mov DWORD [36+esp],ebx + mov DWORD [40+esp],ecx + mov DWORD [44+esp],edx + mov eax,DWORD [48+esi] + mov ebx,DWORD [52+esi] + mov ecx,DWORD [56+esi] + mov edx,DWORD [60+esi] + bswap eax + bswap ebx + bswap ecx + bswap edx + mov DWORD [48+esp],eax + mov DWORD [52+esp],ebx + mov DWORD [56+esp],ecx + mov DWORD [60+esp],edx + mov DWORD [100+esp],esi + mov eax,DWORD [ebp] + mov ebx,DWORD [4+ebp] + mov ecx,DWORD [8+ebp] + mov edx,DWORD [12+ebp] + ; 00_15 0 + mov esi,ecx + mov ebp,eax + rol ebp,5 + xor esi,edx + add ebp,edi + mov edi,DWORD [esp] + and esi,ebx + ror ebx,2 + xor esi,edx + lea ebp,[1518500249+edi*1+ebp] + add ebp,esi + ; 00_15 1 + mov edi,ebx + mov esi,ebp + rol ebp,5 + xor edi,ecx + add ebp,edx + mov edx,DWORD [4+esp] + and edi,eax + ror eax,2 + xor edi,ecx + lea ebp,[1518500249+edx*1+ebp] + add ebp,edi + ; 00_15 2 + mov edx,eax + mov edi,ebp + rol ebp,5 + xor edx,ebx + add ebp,ecx + mov ecx,DWORD [8+esp] + and edx,esi + ror esi,2 + xor edx,ebx + lea ebp,[1518500249+ecx*1+ebp] + add ebp,edx + ; 00_15 3 + mov ecx,esi + mov edx,ebp + rol ebp,5 + xor ecx,eax + add ebp,ebx + mov ebx,DWORD [12+esp] + and ecx,edi + ror edi,2 + xor ecx,eax + lea ebp,[1518500249+ebx*1+ebp] + add ebp,ecx + ; 00_15 4 + mov ebx,edi + mov ecx,ebp + rol ebp,5 + xor ebx,esi + add ebp,eax + mov eax,DWORD [16+esp] + and ebx,edx + ror edx,2 + xor ebx,esi + lea ebp,[1518500249+eax*1+ebp] + add ebp,ebx + ; 00_15 5 + mov eax,edx + mov ebx,ebp + rol ebp,5 + xor eax,edi + add ebp,esi + mov esi,DWORD [20+esp] + and eax,ecx + ror ecx,2 + xor eax,edi + lea ebp,[1518500249+esi*1+ebp] + add ebp,eax + ; 00_15 6 + mov esi,ecx + mov eax,ebp + rol ebp,5 + xor esi,edx + add ebp,edi + mov edi,DWORD [24+esp] + and esi,ebx + ror ebx,2 + xor esi,edx + lea ebp,[1518500249+edi*1+ebp] + add ebp,esi + ; 00_15 7 + mov edi,ebx + mov esi,ebp + rol ebp,5 + xor edi,ecx + add ebp,edx + mov edx,DWORD [28+esp] + and edi,eax + ror eax,2 + xor edi,ecx + lea ebp,[1518500249+edx*1+ebp] + add ebp,edi + ; 00_15 8 + mov edx,eax + mov edi,ebp + rol ebp,5 + xor edx,ebx + add ebp,ecx + mov ecx,DWORD [32+esp] + and edx,esi + ror esi,2 + xor edx,ebx + lea ebp,[1518500249+ecx*1+ebp] + add ebp,edx + ; 00_15 9 + mov ecx,esi + mov edx,ebp + rol ebp,5 + xor ecx,eax + add ebp,ebx + mov ebx,DWORD [36+esp] + and ecx,edi + ror edi,2 + xor ecx,eax + lea ebp,[1518500249+ebx*1+ebp] + add ebp,ecx + ; 00_15 10 + mov ebx,edi + mov ecx,ebp + rol ebp,5 + xor ebx,esi + add ebp,eax + mov eax,DWORD [40+esp] + and ebx,edx + ror edx,2 + xor ebx,esi + lea ebp,[1518500249+eax*1+ebp] + add ebp,ebx + ; 00_15 11 + mov eax,edx + mov ebx,ebp + rol ebp,5 + xor eax,edi + add ebp,esi + mov esi,DWORD [44+esp] + and eax,ecx + ror ecx,2 + xor eax,edi + lea ebp,[1518500249+esi*1+ebp] + add ebp,eax + ; 00_15 12 + mov esi,ecx + mov eax,ebp + rol ebp,5 + xor esi,edx + add ebp,edi + mov edi,DWORD [48+esp] + and esi,ebx + ror ebx,2 + xor esi,edx + lea ebp,[1518500249+edi*1+ebp] + add ebp,esi + ; 00_15 13 + mov edi,ebx + mov esi,ebp + rol ebp,5 + xor edi,ecx + add ebp,edx + mov edx,DWORD [52+esp] + and edi,eax + ror eax,2 + xor edi,ecx + lea ebp,[1518500249+edx*1+ebp] + add ebp,edi + ; 00_15 14 + mov edx,eax + mov edi,ebp + rol ebp,5 + xor edx,ebx + add ebp,ecx + mov ecx,DWORD [56+esp] + and edx,esi + ror esi,2 + xor edx,ebx + lea ebp,[1518500249+ecx*1+ebp] + add ebp,edx + ; 00_15 15 + mov ecx,esi + mov edx,ebp + rol ebp,5 + xor ecx,eax + add ebp,ebx + mov ebx,DWORD [60+esp] + and ecx,edi + ror edi,2 + xor ecx,eax + lea ebp,[1518500249+ebx*1+ebp] + mov ebx,DWORD [esp] + add ecx,ebp + ; 16_19 16 + mov ebp,edi + xor ebx,DWORD [8+esp] + xor ebp,esi + xor ebx,DWORD [32+esp] + and ebp,edx + xor ebx,DWORD [52+esp] + rol ebx,1 + xor ebp,esi + add eax,ebp + mov ebp,ecx + ror edx,2 + mov DWORD [esp],ebx + rol ebp,5 + lea ebx,[1518500249+eax*1+ebx] + mov eax,DWORD [4+esp] + add ebx,ebp + ; 16_19 17 + mov ebp,edx + xor eax,DWORD [12+esp] + xor ebp,edi + xor eax,DWORD [36+esp] + and ebp,ecx + xor eax,DWORD [56+esp] + rol eax,1 + xor ebp,edi + add esi,ebp + mov ebp,ebx + ror ecx,2 + mov DWORD [4+esp],eax + rol ebp,5 + lea eax,[1518500249+esi*1+eax] + mov esi,DWORD [8+esp] + add eax,ebp + ; 16_19 18 + mov ebp,ecx + xor esi,DWORD [16+esp] + xor ebp,edx + xor esi,DWORD [40+esp] + and ebp,ebx + xor esi,DWORD [60+esp] + rol esi,1 + xor ebp,edx + add edi,ebp + mov ebp,eax + ror ebx,2 + mov DWORD [8+esp],esi + rol ebp,5 + lea esi,[1518500249+edi*1+esi] + mov edi,DWORD [12+esp] + add esi,ebp + ; 16_19 19 + mov ebp,ebx + xor edi,DWORD [20+esp] + xor ebp,ecx + xor edi,DWORD [44+esp] + and ebp,eax + xor edi,DWORD [esp] + rol edi,1 + xor ebp,ecx + add edx,ebp + mov ebp,esi + ror eax,2 + mov DWORD [12+esp],edi + rol ebp,5 + lea edi,[1518500249+edx*1+edi] + mov edx,DWORD [16+esp] + add edi,ebp + ; 20_39 20 + mov ebp,esi + xor edx,DWORD [24+esp] + xor ebp,eax + xor edx,DWORD [48+esp] + xor ebp,ebx + xor edx,DWORD [4+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [16+esp],edx + lea edx,[1859775393+ecx*1+edx] + mov ecx,DWORD [20+esp] + add edx,ebp + ; 20_39 21 + mov ebp,edi + xor ecx,DWORD [28+esp] + xor ebp,esi + xor ecx,DWORD [52+esp] + xor ebp,eax + xor ecx,DWORD [8+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [20+esp],ecx + lea ecx,[1859775393+ebx*1+ecx] + mov ebx,DWORD [24+esp] + add ecx,ebp + ; 20_39 22 + mov ebp,edx + xor ebx,DWORD [32+esp] + xor ebp,edi + xor ebx,DWORD [56+esp] + xor ebp,esi + xor ebx,DWORD [12+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [24+esp],ebx + lea ebx,[1859775393+eax*1+ebx] + mov eax,DWORD [28+esp] + add ebx,ebp + ; 20_39 23 + mov ebp,ecx + xor eax,DWORD [36+esp] + xor ebp,edx + xor eax,DWORD [60+esp] + xor ebp,edi + xor eax,DWORD [16+esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + mov DWORD [28+esp],eax + lea eax,[1859775393+esi*1+eax] + mov esi,DWORD [32+esp] + add eax,ebp + ; 20_39 24 + mov ebp,ebx + xor esi,DWORD [40+esp] + xor ebp,ecx + xor esi,DWORD [esp] + xor ebp,edx + xor esi,DWORD [20+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [32+esp],esi + lea esi,[1859775393+edi*1+esi] + mov edi,DWORD [36+esp] + add esi,ebp + ; 20_39 25 + mov ebp,eax + xor edi,DWORD [44+esp] + xor ebp,ebx + xor edi,DWORD [4+esp] + xor ebp,ecx + xor edi,DWORD [24+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [36+esp],edi + lea edi,[1859775393+edx*1+edi] + mov edx,DWORD [40+esp] + add edi,ebp + ; 20_39 26 + mov ebp,esi + xor edx,DWORD [48+esp] + xor ebp,eax + xor edx,DWORD [8+esp] + xor ebp,ebx + xor edx,DWORD [28+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [40+esp],edx + lea edx,[1859775393+ecx*1+edx] + mov ecx,DWORD [44+esp] + add edx,ebp + ; 20_39 27 + mov ebp,edi + xor ecx,DWORD [52+esp] + xor ebp,esi + xor ecx,DWORD [12+esp] + xor ebp,eax + xor ecx,DWORD [32+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [44+esp],ecx + lea ecx,[1859775393+ebx*1+ecx] + mov ebx,DWORD [48+esp] + add ecx,ebp + ; 20_39 28 + mov ebp,edx + xor ebx,DWORD [56+esp] + xor ebp,edi + xor ebx,DWORD [16+esp] + xor ebp,esi + xor ebx,DWORD [36+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [48+esp],ebx + lea ebx,[1859775393+eax*1+ebx] + mov eax,DWORD [52+esp] + add ebx,ebp + ; 20_39 29 + mov ebp,ecx + xor eax,DWORD [60+esp] + xor ebp,edx + xor eax,DWORD [20+esp] + xor ebp,edi + xor eax,DWORD [40+esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + mov DWORD [52+esp],eax + lea eax,[1859775393+esi*1+eax] + mov esi,DWORD [56+esp] + add eax,ebp + ; 20_39 30 + mov ebp,ebx + xor esi,DWORD [esp] + xor ebp,ecx + xor esi,DWORD [24+esp] + xor ebp,edx + xor esi,DWORD [44+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [56+esp],esi + lea esi,[1859775393+edi*1+esi] + mov edi,DWORD [60+esp] + add esi,ebp + ; 20_39 31 + mov ebp,eax + xor edi,DWORD [4+esp] + xor ebp,ebx + xor edi,DWORD [28+esp] + xor ebp,ecx + xor edi,DWORD [48+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [60+esp],edi + lea edi,[1859775393+edx*1+edi] + mov edx,DWORD [esp] + add edi,ebp + ; 20_39 32 + mov ebp,esi + xor edx,DWORD [8+esp] + xor ebp,eax + xor edx,DWORD [32+esp] + xor ebp,ebx + xor edx,DWORD [52+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [esp],edx + lea edx,[1859775393+ecx*1+edx] + mov ecx,DWORD [4+esp] + add edx,ebp + ; 20_39 33 + mov ebp,edi + xor ecx,DWORD [12+esp] + xor ebp,esi + xor ecx,DWORD [36+esp] + xor ebp,eax + xor ecx,DWORD [56+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [4+esp],ecx + lea ecx,[1859775393+ebx*1+ecx] + mov ebx,DWORD [8+esp] + add ecx,ebp + ; 20_39 34 + mov ebp,edx + xor ebx,DWORD [16+esp] + xor ebp,edi + xor ebx,DWORD [40+esp] + xor ebp,esi + xor ebx,DWORD [60+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [8+esp],ebx + lea ebx,[1859775393+eax*1+ebx] + mov eax,DWORD [12+esp] + add ebx,ebp + ; 20_39 35 + mov ebp,ecx + xor eax,DWORD [20+esp] + xor ebp,edx + xor eax,DWORD [44+esp] + xor ebp,edi + xor eax,DWORD [esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + mov DWORD [12+esp],eax + lea eax,[1859775393+esi*1+eax] + mov esi,DWORD [16+esp] + add eax,ebp + ; 20_39 36 + mov ebp,ebx + xor esi,DWORD [24+esp] + xor ebp,ecx + xor esi,DWORD [48+esp] + xor ebp,edx + xor esi,DWORD [4+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [16+esp],esi + lea esi,[1859775393+edi*1+esi] + mov edi,DWORD [20+esp] + add esi,ebp + ; 20_39 37 + mov ebp,eax + xor edi,DWORD [28+esp] + xor ebp,ebx + xor edi,DWORD [52+esp] + xor ebp,ecx + xor edi,DWORD [8+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [20+esp],edi + lea edi,[1859775393+edx*1+edi] + mov edx,DWORD [24+esp] + add edi,ebp + ; 20_39 38 + mov ebp,esi + xor edx,DWORD [32+esp] + xor ebp,eax + xor edx,DWORD [56+esp] + xor ebp,ebx + xor edx,DWORD [12+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [24+esp],edx + lea edx,[1859775393+ecx*1+edx] + mov ecx,DWORD [28+esp] + add edx,ebp + ; 20_39 39 + mov ebp,edi + xor ecx,DWORD [36+esp] + xor ebp,esi + xor ecx,DWORD [60+esp] + xor ebp,eax + xor ecx,DWORD [16+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [28+esp],ecx + lea ecx,[1859775393+ebx*1+ecx] + mov ebx,DWORD [32+esp] + add ecx,ebp + ; 40_59 40 + mov ebp,edi + xor ebx,DWORD [40+esp] + xor ebp,esi + xor ebx,DWORD [esp] + and ebp,edx + xor ebx,DWORD [20+esp] + rol ebx,1 + add ebp,eax + ror edx,2 + mov eax,ecx + rol eax,5 + mov DWORD [32+esp],ebx + lea ebx,[2400959708+ebp*1+ebx] + mov ebp,edi + add ebx,eax + and ebp,esi + mov eax,DWORD [36+esp] + add ebx,ebp + ; 40_59 41 + mov ebp,edx + xor eax,DWORD [44+esp] + xor ebp,edi + xor eax,DWORD [4+esp] + and ebp,ecx + xor eax,DWORD [24+esp] + rol eax,1 + add ebp,esi + ror ecx,2 + mov esi,ebx + rol esi,5 + mov DWORD [36+esp],eax + lea eax,[2400959708+ebp*1+eax] + mov ebp,edx + add eax,esi + and ebp,edi + mov esi,DWORD [40+esp] + add eax,ebp + ; 40_59 42 + mov ebp,ecx + xor esi,DWORD [48+esp] + xor ebp,edx + xor esi,DWORD [8+esp] + and ebp,ebx + xor esi,DWORD [28+esp] + rol esi,1 + add ebp,edi + ror ebx,2 + mov edi,eax + rol edi,5 + mov DWORD [40+esp],esi + lea esi,[2400959708+ebp*1+esi] + mov ebp,ecx + add esi,edi + and ebp,edx + mov edi,DWORD [44+esp] + add esi,ebp + ; 40_59 43 + mov ebp,ebx + xor edi,DWORD [52+esp] + xor ebp,ecx + xor edi,DWORD [12+esp] + and ebp,eax + xor edi,DWORD [32+esp] + rol edi,1 + add ebp,edx + ror eax,2 + mov edx,esi + rol edx,5 + mov DWORD [44+esp],edi + lea edi,[2400959708+ebp*1+edi] + mov ebp,ebx + add edi,edx + and ebp,ecx + mov edx,DWORD [48+esp] + add edi,ebp + ; 40_59 44 + mov ebp,eax + xor edx,DWORD [56+esp] + xor ebp,ebx + xor edx,DWORD [16+esp] + and ebp,esi + xor edx,DWORD [36+esp] + rol edx,1 + add ebp,ecx + ror esi,2 + mov ecx,edi + rol ecx,5 + mov DWORD [48+esp],edx + lea edx,[2400959708+ebp*1+edx] + mov ebp,eax + add edx,ecx + and ebp,ebx + mov ecx,DWORD [52+esp] + add edx,ebp + ; 40_59 45 + mov ebp,esi + xor ecx,DWORD [60+esp] + xor ebp,eax + xor ecx,DWORD [20+esp] + and ebp,edi + xor ecx,DWORD [40+esp] + rol ecx,1 + add ebp,ebx + ror edi,2 + mov ebx,edx + rol ebx,5 + mov DWORD [52+esp],ecx + lea ecx,[2400959708+ebp*1+ecx] + mov ebp,esi + add ecx,ebx + and ebp,eax + mov ebx,DWORD [56+esp] + add ecx,ebp + ; 40_59 46 + mov ebp,edi + xor ebx,DWORD [esp] + xor ebp,esi + xor ebx,DWORD [24+esp] + and ebp,edx + xor ebx,DWORD [44+esp] + rol ebx,1 + add ebp,eax + ror edx,2 + mov eax,ecx + rol eax,5 + mov DWORD [56+esp],ebx + lea ebx,[2400959708+ebp*1+ebx] + mov ebp,edi + add ebx,eax + and ebp,esi + mov eax,DWORD [60+esp] + add ebx,ebp + ; 40_59 47 + mov ebp,edx + xor eax,DWORD [4+esp] + xor ebp,edi + xor eax,DWORD [28+esp] + and ebp,ecx + xor eax,DWORD [48+esp] + rol eax,1 + add ebp,esi + ror ecx,2 + mov esi,ebx + rol esi,5 + mov DWORD [60+esp],eax + lea eax,[2400959708+ebp*1+eax] + mov ebp,edx + add eax,esi + and ebp,edi + mov esi,DWORD [esp] + add eax,ebp + ; 40_59 48 + mov ebp,ecx + xor esi,DWORD [8+esp] + xor ebp,edx + xor esi,DWORD [32+esp] + and ebp,ebx + xor esi,DWORD [52+esp] + rol esi,1 + add ebp,edi + ror ebx,2 + mov edi,eax + rol edi,5 + mov DWORD [esp],esi + lea esi,[2400959708+ebp*1+esi] + mov ebp,ecx + add esi,edi + and ebp,edx + mov edi,DWORD [4+esp] + add esi,ebp + ; 40_59 49 + mov ebp,ebx + xor edi,DWORD [12+esp] + xor ebp,ecx + xor edi,DWORD [36+esp] + and ebp,eax + xor edi,DWORD [56+esp] + rol edi,1 + add ebp,edx + ror eax,2 + mov edx,esi + rol edx,5 + mov DWORD [4+esp],edi + lea edi,[2400959708+ebp*1+edi] + mov ebp,ebx + add edi,edx + and ebp,ecx + mov edx,DWORD [8+esp] + add edi,ebp + ; 40_59 50 + mov ebp,eax + xor edx,DWORD [16+esp] + xor ebp,ebx + xor edx,DWORD [40+esp] + and ebp,esi + xor edx,DWORD [60+esp] + rol edx,1 + add ebp,ecx + ror esi,2 + mov ecx,edi + rol ecx,5 + mov DWORD [8+esp],edx + lea edx,[2400959708+ebp*1+edx] + mov ebp,eax + add edx,ecx + and ebp,ebx + mov ecx,DWORD [12+esp] + add edx,ebp + ; 40_59 51 + mov ebp,esi + xor ecx,DWORD [20+esp] + xor ebp,eax + xor ecx,DWORD [44+esp] + and ebp,edi + xor ecx,DWORD [esp] + rol ecx,1 + add ebp,ebx + ror edi,2 + mov ebx,edx + rol ebx,5 + mov DWORD [12+esp],ecx + lea ecx,[2400959708+ebp*1+ecx] + mov ebp,esi + add ecx,ebx + and ebp,eax + mov ebx,DWORD [16+esp] + add ecx,ebp + ; 40_59 52 + mov ebp,edi + xor ebx,DWORD [24+esp] + xor ebp,esi + xor ebx,DWORD [48+esp] + and ebp,edx + xor ebx,DWORD [4+esp] + rol ebx,1 + add ebp,eax + ror edx,2 + mov eax,ecx + rol eax,5 + mov DWORD [16+esp],ebx + lea ebx,[2400959708+ebp*1+ebx] + mov ebp,edi + add ebx,eax + and ebp,esi + mov eax,DWORD [20+esp] + add ebx,ebp + ; 40_59 53 + mov ebp,edx + xor eax,DWORD [28+esp] + xor ebp,edi + xor eax,DWORD [52+esp] + and ebp,ecx + xor eax,DWORD [8+esp] + rol eax,1 + add ebp,esi + ror ecx,2 + mov esi,ebx + rol esi,5 + mov DWORD [20+esp],eax + lea eax,[2400959708+ebp*1+eax] + mov ebp,edx + add eax,esi + and ebp,edi + mov esi,DWORD [24+esp] + add eax,ebp + ; 40_59 54 + mov ebp,ecx + xor esi,DWORD [32+esp] + xor ebp,edx + xor esi,DWORD [56+esp] + and ebp,ebx + xor esi,DWORD [12+esp] + rol esi,1 + add ebp,edi + ror ebx,2 + mov edi,eax + rol edi,5 + mov DWORD [24+esp],esi + lea esi,[2400959708+ebp*1+esi] + mov ebp,ecx + add esi,edi + and ebp,edx + mov edi,DWORD [28+esp] + add esi,ebp + ; 40_59 55 + mov ebp,ebx + xor edi,DWORD [36+esp] + xor ebp,ecx + xor edi,DWORD [60+esp] + and ebp,eax + xor edi,DWORD [16+esp] + rol edi,1 + add ebp,edx + ror eax,2 + mov edx,esi + rol edx,5 + mov DWORD [28+esp],edi + lea edi,[2400959708+ebp*1+edi] + mov ebp,ebx + add edi,edx + and ebp,ecx + mov edx,DWORD [32+esp] + add edi,ebp + ; 40_59 56 + mov ebp,eax + xor edx,DWORD [40+esp] + xor ebp,ebx + xor edx,DWORD [esp] + and ebp,esi + xor edx,DWORD [20+esp] + rol edx,1 + add ebp,ecx + ror esi,2 + mov ecx,edi + rol ecx,5 + mov DWORD [32+esp],edx + lea edx,[2400959708+ebp*1+edx] + mov ebp,eax + add edx,ecx + and ebp,ebx + mov ecx,DWORD [36+esp] + add edx,ebp + ; 40_59 57 + mov ebp,esi + xor ecx,DWORD [44+esp] + xor ebp,eax + xor ecx,DWORD [4+esp] + and ebp,edi + xor ecx,DWORD [24+esp] + rol ecx,1 + add ebp,ebx + ror edi,2 + mov ebx,edx + rol ebx,5 + mov DWORD [36+esp],ecx + lea ecx,[2400959708+ebp*1+ecx] + mov ebp,esi + add ecx,ebx + and ebp,eax + mov ebx,DWORD [40+esp] + add ecx,ebp + ; 40_59 58 + mov ebp,edi + xor ebx,DWORD [48+esp] + xor ebp,esi + xor ebx,DWORD [8+esp] + and ebp,edx + xor ebx,DWORD [28+esp] + rol ebx,1 + add ebp,eax + ror edx,2 + mov eax,ecx + rol eax,5 + mov DWORD [40+esp],ebx + lea ebx,[2400959708+ebp*1+ebx] + mov ebp,edi + add ebx,eax + and ebp,esi + mov eax,DWORD [44+esp] + add ebx,ebp + ; 40_59 59 + mov ebp,edx + xor eax,DWORD [52+esp] + xor ebp,edi + xor eax,DWORD [12+esp] + and ebp,ecx + xor eax,DWORD [32+esp] + rol eax,1 + add ebp,esi + ror ecx,2 + mov esi,ebx + rol esi,5 + mov DWORD [44+esp],eax + lea eax,[2400959708+ebp*1+eax] + mov ebp,edx + add eax,esi + and ebp,edi + mov esi,DWORD [48+esp] + add eax,ebp + ; 20_39 60 + mov ebp,ebx + xor esi,DWORD [56+esp] + xor ebp,ecx + xor esi,DWORD [16+esp] + xor ebp,edx + xor esi,DWORD [36+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [48+esp],esi + lea esi,[3395469782+edi*1+esi] + mov edi,DWORD [52+esp] + add esi,ebp + ; 20_39 61 + mov ebp,eax + xor edi,DWORD [60+esp] + xor ebp,ebx + xor edi,DWORD [20+esp] + xor ebp,ecx + xor edi,DWORD [40+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [52+esp],edi + lea edi,[3395469782+edx*1+edi] + mov edx,DWORD [56+esp] + add edi,ebp + ; 20_39 62 + mov ebp,esi + xor edx,DWORD [esp] + xor ebp,eax + xor edx,DWORD [24+esp] + xor ebp,ebx + xor edx,DWORD [44+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [56+esp],edx + lea edx,[3395469782+ecx*1+edx] + mov ecx,DWORD [60+esp] + add edx,ebp + ; 20_39 63 + mov ebp,edi + xor ecx,DWORD [4+esp] + xor ebp,esi + xor ecx,DWORD [28+esp] + xor ebp,eax + xor ecx,DWORD [48+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [60+esp],ecx + lea ecx,[3395469782+ebx*1+ecx] + mov ebx,DWORD [esp] + add ecx,ebp + ; 20_39 64 + mov ebp,edx + xor ebx,DWORD [8+esp] + xor ebp,edi + xor ebx,DWORD [32+esp] + xor ebp,esi + xor ebx,DWORD [52+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [esp],ebx + lea ebx,[3395469782+eax*1+ebx] + mov eax,DWORD [4+esp] + add ebx,ebp + ; 20_39 65 + mov ebp,ecx + xor eax,DWORD [12+esp] + xor ebp,edx + xor eax,DWORD [36+esp] + xor ebp,edi + xor eax,DWORD [56+esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + mov DWORD [4+esp],eax + lea eax,[3395469782+esi*1+eax] + mov esi,DWORD [8+esp] + add eax,ebp + ; 20_39 66 + mov ebp,ebx + xor esi,DWORD [16+esp] + xor ebp,ecx + xor esi,DWORD [40+esp] + xor ebp,edx + xor esi,DWORD [60+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [8+esp],esi + lea esi,[3395469782+edi*1+esi] + mov edi,DWORD [12+esp] + add esi,ebp + ; 20_39 67 + mov ebp,eax + xor edi,DWORD [20+esp] + xor ebp,ebx + xor edi,DWORD [44+esp] + xor ebp,ecx + xor edi,DWORD [esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [12+esp],edi + lea edi,[3395469782+edx*1+edi] + mov edx,DWORD [16+esp] + add edi,ebp + ; 20_39 68 + mov ebp,esi + xor edx,DWORD [24+esp] + xor ebp,eax + xor edx,DWORD [48+esp] + xor ebp,ebx + xor edx,DWORD [4+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [16+esp],edx + lea edx,[3395469782+ecx*1+edx] + mov ecx,DWORD [20+esp] + add edx,ebp + ; 20_39 69 + mov ebp,edi + xor ecx,DWORD [28+esp] + xor ebp,esi + xor ecx,DWORD [52+esp] + xor ebp,eax + xor ecx,DWORD [8+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [20+esp],ecx + lea ecx,[3395469782+ebx*1+ecx] + mov ebx,DWORD [24+esp] + add ecx,ebp + ; 20_39 70 + mov ebp,edx + xor ebx,DWORD [32+esp] + xor ebp,edi + xor ebx,DWORD [56+esp] + xor ebp,esi + xor ebx,DWORD [12+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [24+esp],ebx + lea ebx,[3395469782+eax*1+ebx] + mov eax,DWORD [28+esp] + add ebx,ebp + ; 20_39 71 + mov ebp,ecx + xor eax,DWORD [36+esp] + xor ebp,edx + xor eax,DWORD [60+esp] + xor ebp,edi + xor eax,DWORD [16+esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + mov DWORD [28+esp],eax + lea eax,[3395469782+esi*1+eax] + mov esi,DWORD [32+esp] + add eax,ebp + ; 20_39 72 + mov ebp,ebx + xor esi,DWORD [40+esp] + xor ebp,ecx + xor esi,DWORD [esp] + xor ebp,edx + xor esi,DWORD [20+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + mov DWORD [32+esp],esi + lea esi,[3395469782+edi*1+esi] + mov edi,DWORD [36+esp] + add esi,ebp + ; 20_39 73 + mov ebp,eax + xor edi,DWORD [44+esp] + xor ebp,ebx + xor edi,DWORD [4+esp] + xor ebp,ecx + xor edi,DWORD [24+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + mov DWORD [36+esp],edi + lea edi,[3395469782+edx*1+edi] + mov edx,DWORD [40+esp] + add edi,ebp + ; 20_39 74 + mov ebp,esi + xor edx,DWORD [48+esp] + xor ebp,eax + xor edx,DWORD [8+esp] + xor ebp,ebx + xor edx,DWORD [28+esp] + rol edx,1 + add ecx,ebp + ror esi,2 + mov ebp,edi + rol ebp,5 + mov DWORD [40+esp],edx + lea edx,[3395469782+ecx*1+edx] + mov ecx,DWORD [44+esp] + add edx,ebp + ; 20_39 75 + mov ebp,edi + xor ecx,DWORD [52+esp] + xor ebp,esi + xor ecx,DWORD [12+esp] + xor ebp,eax + xor ecx,DWORD [32+esp] + rol ecx,1 + add ebx,ebp + ror edi,2 + mov ebp,edx + rol ebp,5 + mov DWORD [44+esp],ecx + lea ecx,[3395469782+ebx*1+ecx] + mov ebx,DWORD [48+esp] + add ecx,ebp + ; 20_39 76 + mov ebp,edx + xor ebx,DWORD [56+esp] + xor ebp,edi + xor ebx,DWORD [16+esp] + xor ebp,esi + xor ebx,DWORD [36+esp] + rol ebx,1 + add eax,ebp + ror edx,2 + mov ebp,ecx + rol ebp,5 + mov DWORD [48+esp],ebx + lea ebx,[3395469782+eax*1+ebx] + mov eax,DWORD [52+esp] + add ebx,ebp + ; 20_39 77 + mov ebp,ecx + xor eax,DWORD [60+esp] + xor ebp,edx + xor eax,DWORD [20+esp] + xor ebp,edi + xor eax,DWORD [40+esp] + rol eax,1 + add esi,ebp + ror ecx,2 + mov ebp,ebx + rol ebp,5 + lea eax,[3395469782+esi*1+eax] + mov esi,DWORD [56+esp] + add eax,ebp + ; 20_39 78 + mov ebp,ebx + xor esi,DWORD [esp] + xor ebp,ecx + xor esi,DWORD [24+esp] + xor ebp,edx + xor esi,DWORD [44+esp] + rol esi,1 + add edi,ebp + ror ebx,2 + mov ebp,eax + rol ebp,5 + lea esi,[3395469782+edi*1+esi] + mov edi,DWORD [60+esp] + add esi,ebp + ; 20_39 79 + mov ebp,eax + xor edi,DWORD [4+esp] + xor ebp,ebx + xor edi,DWORD [28+esp] + xor ebp,ecx + xor edi,DWORD [48+esp] + rol edi,1 + add edx,ebp + ror eax,2 + mov ebp,esi + rol ebp,5 + lea edi,[3395469782+edx*1+edi] + add edi,ebp + mov ebp,DWORD [96+esp] + mov edx,DWORD [100+esp] + add edi,DWORD [ebp] + add esi,DWORD [4+ebp] + add eax,DWORD [8+ebp] + add ebx,DWORD [12+ebp] + add ecx,DWORD [16+ebp] + mov DWORD [ebp],edi + add edx,64 + mov DWORD [4+ebp],esi + cmp edx,DWORD [104+esp] + mov DWORD [8+ebp],eax + mov edi,ecx + mov DWORD [12+ebp],ebx + mov esi,edx + mov DWORD [16+ebp],ecx + jb NEAR L$000loop + add esp,76 + pop edi + pop esi + pop ebx + pop ebp + ret +db 83,72,65,49,32,98,108,111,99,107,32,116,114,97,110,115 +db 102,111,114,109,32,102,111,114,32,120,56,54,44,32,67,82 +db 89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112 +db 114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0 diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha256-586.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha256-586.nasm new file mode 100644 index 0000000000..4598dae75a --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha256-586.nasm @@ -0,0 +1,3364 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/sha/asm/sha256-586.pl +; +; Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +;extern _OPENSSL_ia32cap_P +global _sha256_block_data_order +align 16 +_sha256_block_data_order: +L$_sha256_block_data_order_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov ebx,esp + call L$000pic_point +L$000pic_point: + pop ebp + lea ebp,[(L$001K256-L$000pic_point)+ebp] + sub esp,16 + and esp,-64 + shl eax,6 + add eax,edi + mov DWORD [esp],esi + mov DWORD [4+esp],edi + mov DWORD [8+esp],eax + mov DWORD [12+esp],ebx + jmp NEAR L$002loop +align 16 +L$002loop: + mov eax,DWORD [edi] + mov ebx,DWORD [4+edi] + mov ecx,DWORD [8+edi] + bswap eax + mov edx,DWORD [12+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [16+edi] + mov ebx,DWORD [20+edi] + mov ecx,DWORD [24+edi] + bswap eax + mov edx,DWORD [28+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [32+edi] + mov ebx,DWORD [36+edi] + mov ecx,DWORD [40+edi] + bswap eax + mov edx,DWORD [44+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [48+edi] + mov ebx,DWORD [52+edi] + mov ecx,DWORD [56+edi] + bswap eax + mov edx,DWORD [60+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + add edi,64 + lea esp,[esp-36] + mov DWORD [104+esp],edi + mov eax,DWORD [esi] + mov ebx,DWORD [4+esi] + mov ecx,DWORD [8+esi] + mov edi,DWORD [12+esi] + mov DWORD [8+esp],ebx + xor ebx,ecx + mov DWORD [12+esp],ecx + mov DWORD [16+esp],edi + mov DWORD [esp],ebx + mov edx,DWORD [16+esi] + mov ebx,DWORD [20+esi] + mov ecx,DWORD [24+esi] + mov edi,DWORD [28+esi] + mov DWORD [24+esp],ebx + mov DWORD [28+esp],ecx + mov DWORD [32+esp],edi +align 16 +L$00300_15: + mov ecx,edx + mov esi,DWORD [24+esp] + ror ecx,14 + mov edi,DWORD [28+esp] + xor ecx,edx + xor esi,edi + mov ebx,DWORD [96+esp] + ror ecx,5 + and esi,edx + mov DWORD [20+esp],edx + xor edx,ecx + add ebx,DWORD [32+esp] + xor esi,edi + ror edx,6 + mov ecx,eax + add ebx,esi + ror ecx,9 + add ebx,edx + mov edi,DWORD [8+esp] + xor ecx,eax + mov DWORD [4+esp],eax + lea esp,[esp-4] + ror ecx,11 + mov esi,DWORD [ebp] + xor ecx,eax + mov edx,DWORD [20+esp] + xor eax,edi + ror ecx,2 + add ebx,esi + mov DWORD [esp],eax + add edx,ebx + and eax,DWORD [4+esp] + add ebx,ecx + xor eax,edi + add ebp,4 + add eax,ebx + cmp esi,3248222580 + jne NEAR L$00300_15 + mov ecx,DWORD [156+esp] + jmp NEAR L$00416_63 +align 16 +L$00416_63: + mov ebx,ecx + mov esi,DWORD [104+esp] + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [160+esp] + shr edi,10 + add ebx,DWORD [124+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [24+esp] + ror ecx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor ecx,edx + xor esi,edi + mov DWORD [96+esp],ebx + ror ecx,5 + and esi,edx + mov DWORD [20+esp],edx + xor edx,ecx + add ebx,DWORD [32+esp] + xor esi,edi + ror edx,6 + mov ecx,eax + add ebx,esi + ror ecx,9 + add ebx,edx + mov edi,DWORD [8+esp] + xor ecx,eax + mov DWORD [4+esp],eax + lea esp,[esp-4] + ror ecx,11 + mov esi,DWORD [ebp] + xor ecx,eax + mov edx,DWORD [20+esp] + xor eax,edi + ror ecx,2 + add ebx,esi + mov DWORD [esp],eax + add edx,ebx + and eax,DWORD [4+esp] + add ebx,ecx + xor eax,edi + mov ecx,DWORD [156+esp] + add ebp,4 + add eax,ebx + cmp esi,3329325298 + jne NEAR L$00416_63 + mov esi,DWORD [356+esp] + mov ebx,DWORD [8+esp] + mov ecx,DWORD [16+esp] + add eax,DWORD [esi] + add ebx,DWORD [4+esi] + add edi,DWORD [8+esi] + add ecx,DWORD [12+esi] + mov DWORD [esi],eax + mov DWORD [4+esi],ebx + mov DWORD [8+esi],edi + mov DWORD [12+esi],ecx + mov eax,DWORD [24+esp] + mov ebx,DWORD [28+esp] + mov ecx,DWORD [32+esp] + mov edi,DWORD [360+esp] + add edx,DWORD [16+esi] + add eax,DWORD [20+esi] + add ebx,DWORD [24+esi] + add ecx,DWORD [28+esi] + mov DWORD [16+esi],edx + mov DWORD [20+esi],eax + mov DWORD [24+esi],ebx + mov DWORD [28+esi],ecx + lea esp,[356+esp] + sub ebp,256 + cmp edi,DWORD [8+esp] + jb NEAR L$002loop + mov esp,DWORD [12+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +align 32 +L$005loop_shrd: + mov eax,DWORD [edi] + mov ebx,DWORD [4+edi] + mov ecx,DWORD [8+edi] + bswap eax + mov edx,DWORD [12+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [16+edi] + mov ebx,DWORD [20+edi] + mov ecx,DWORD [24+edi] + bswap eax + mov edx,DWORD [28+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [32+edi] + mov ebx,DWORD [36+edi] + mov ecx,DWORD [40+edi] + bswap eax + mov edx,DWORD [44+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + mov eax,DWORD [48+edi] + mov ebx,DWORD [52+edi] + mov ecx,DWORD [56+edi] + bswap eax + mov edx,DWORD [60+edi] + bswap ebx + push eax + bswap ecx + push ebx + bswap edx + push ecx + push edx + add edi,64 + lea esp,[esp-36] + mov DWORD [104+esp],edi + mov eax,DWORD [esi] + mov ebx,DWORD [4+esi] + mov ecx,DWORD [8+esi] + mov edi,DWORD [12+esi] + mov DWORD [8+esp],ebx + xor ebx,ecx + mov DWORD [12+esp],ecx + mov DWORD [16+esp],edi + mov DWORD [esp],ebx + mov edx,DWORD [16+esi] + mov ebx,DWORD [20+esi] + mov ecx,DWORD [24+esi] + mov edi,DWORD [28+esi] + mov DWORD [24+esp],ebx + mov DWORD [28+esp],ecx + mov DWORD [32+esp],edi +align 16 +L$00600_15_shrd: + mov ecx,edx + mov esi,DWORD [24+esp] + shrd ecx,ecx,14 + mov edi,DWORD [28+esp] + xor ecx,edx + xor esi,edi + mov ebx,DWORD [96+esp] + shrd ecx,ecx,5 + and esi,edx + mov DWORD [20+esp],edx + xor edx,ecx + add ebx,DWORD [32+esp] + xor esi,edi + shrd edx,edx,6 + mov ecx,eax + add ebx,esi + shrd ecx,ecx,9 + add ebx,edx + mov edi,DWORD [8+esp] + xor ecx,eax + mov DWORD [4+esp],eax + lea esp,[esp-4] + shrd ecx,ecx,11 + mov esi,DWORD [ebp] + xor ecx,eax + mov edx,DWORD [20+esp] + xor eax,edi + shrd ecx,ecx,2 + add ebx,esi + mov DWORD [esp],eax + add edx,ebx + and eax,DWORD [4+esp] + add ebx,ecx + xor eax,edi + add ebp,4 + add eax,ebx + cmp esi,3248222580 + jne NEAR L$00600_15_shrd + mov ecx,DWORD [156+esp] + jmp NEAR L$00716_63_shrd +align 16 +L$00716_63_shrd: + mov ebx,ecx + mov esi,DWORD [104+esp] + shrd ecx,ecx,11 + mov edi,esi + shrd esi,esi,2 + xor ecx,ebx + shr ebx,3 + shrd ecx,ecx,7 + xor esi,edi + xor ebx,ecx + shrd esi,esi,17 + add ebx,DWORD [160+esp] + shr edi,10 + add ebx,DWORD [124+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [24+esp] + shrd ecx,ecx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor ecx,edx + xor esi,edi + mov DWORD [96+esp],ebx + shrd ecx,ecx,5 + and esi,edx + mov DWORD [20+esp],edx + xor edx,ecx + add ebx,DWORD [32+esp] + xor esi,edi + shrd edx,edx,6 + mov ecx,eax + add ebx,esi + shrd ecx,ecx,9 + add ebx,edx + mov edi,DWORD [8+esp] + xor ecx,eax + mov DWORD [4+esp],eax + lea esp,[esp-4] + shrd ecx,ecx,11 + mov esi,DWORD [ebp] + xor ecx,eax + mov edx,DWORD [20+esp] + xor eax,edi + shrd ecx,ecx,2 + add ebx,esi + mov DWORD [esp],eax + add edx,ebx + and eax,DWORD [4+esp] + add ebx,ecx + xor eax,edi + mov ecx,DWORD [156+esp] + add ebp,4 + add eax,ebx + cmp esi,3329325298 + jne NEAR L$00716_63_shrd + mov esi,DWORD [356+esp] + mov ebx,DWORD [8+esp] + mov ecx,DWORD [16+esp] + add eax,DWORD [esi] + add ebx,DWORD [4+esi] + add edi,DWORD [8+esi] + add ecx,DWORD [12+esi] + mov DWORD [esi],eax + mov DWORD [4+esi],ebx + mov DWORD [8+esi],edi + mov DWORD [12+esi],ecx + mov eax,DWORD [24+esp] + mov ebx,DWORD [28+esp] + mov ecx,DWORD [32+esp] + mov edi,DWORD [360+esp] + add edx,DWORD [16+esi] + add eax,DWORD [20+esi] + add ebx,DWORD [24+esi] + add ecx,DWORD [28+esi] + mov DWORD [16+esi],edx + mov DWORD [20+esi],eax + mov DWORD [24+esi],ebx + mov DWORD [28+esi],ecx + lea esp,[356+esp] + sub ebp,256 + cmp edi,DWORD [8+esp] + jb NEAR L$005loop_shrd + mov esp,DWORD [12+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +align 64 +L$001K256: +dd 1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298 +dd 66051,67438087,134810123,202182159 +db 83,72,65,50,53,54,32,98,108,111,99,107,32,116,114,97 +db 110,115,102,111,114,109,32,102,111,114,32,120,56,54,44,32 +db 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 +db 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 +db 62,0 +align 16 +L$008unrolled: + lea esp,[esp-96] + mov eax,DWORD [esi] + mov ebp,DWORD [4+esi] + mov ecx,DWORD [8+esi] + mov ebx,DWORD [12+esi] + mov DWORD [4+esp],ebp + xor ebp,ecx + mov DWORD [8+esp],ecx + mov DWORD [12+esp],ebx + mov edx,DWORD [16+esi] + mov ebx,DWORD [20+esi] + mov ecx,DWORD [24+esi] + mov esi,DWORD [28+esi] + mov DWORD [20+esp],ebx + mov DWORD [24+esp],ecx + mov DWORD [28+esp],esi + jmp NEAR L$009grand_loop +align 16 +L$009grand_loop: + mov ebx,DWORD [edi] + mov ecx,DWORD [4+edi] + bswap ebx + mov esi,DWORD [8+edi] + bswap ecx + mov DWORD [32+esp],ebx + bswap esi + mov DWORD [36+esp],ecx + mov DWORD [40+esp],esi + mov ebx,DWORD [12+edi] + mov ecx,DWORD [16+edi] + bswap ebx + mov esi,DWORD [20+edi] + bswap ecx + mov DWORD [44+esp],ebx + bswap esi + mov DWORD [48+esp],ecx + mov DWORD [52+esp],esi + mov ebx,DWORD [24+edi] + mov ecx,DWORD [28+edi] + bswap ebx + mov esi,DWORD [32+edi] + bswap ecx + mov DWORD [56+esp],ebx + bswap esi + mov DWORD [60+esp],ecx + mov DWORD [64+esp],esi + mov ebx,DWORD [36+edi] + mov ecx,DWORD [40+edi] + bswap ebx + mov esi,DWORD [44+edi] + bswap ecx + mov DWORD [68+esp],ebx + bswap esi + mov DWORD [72+esp],ecx + mov DWORD [76+esp],esi + mov ebx,DWORD [48+edi] + mov ecx,DWORD [52+edi] + bswap ebx + mov esi,DWORD [56+edi] + bswap ecx + mov DWORD [80+esp],ebx + bswap esi + mov DWORD [84+esp],ecx + mov DWORD [88+esp],esi + mov ebx,DWORD [60+edi] + add edi,64 + bswap ebx + mov DWORD [100+esp],edi + mov DWORD [92+esp],ebx + mov ecx,edx + mov esi,DWORD [20+esp] + ror edx,14 + mov edi,DWORD [24+esp] + xor edx,ecx + mov ebx,DWORD [32+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1116352408+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [16+esp] + ror edx,14 + mov edi,DWORD [20+esp] + xor edx,esi + mov ebx,DWORD [36+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1899447441+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [12+esp] + ror edx,14 + mov edi,DWORD [16+esp] + xor edx,ecx + mov ebx,DWORD [40+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3049323471+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [8+esp] + ror edx,14 + mov edi,DWORD [12+esp] + xor edx,esi + mov ebx,DWORD [44+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3921009573+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [4+esp] + ror edx,14 + mov edi,DWORD [8+esp] + xor edx,ecx + mov ebx,DWORD [48+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[961987163+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [esp] + ror edx,14 + mov edi,DWORD [4+esp] + xor edx,esi + mov ebx,DWORD [52+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1508970993+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [28+esp] + ror edx,14 + mov edi,DWORD [esp] + xor edx,ecx + mov ebx,DWORD [56+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2453635748+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [24+esp] + ror edx,14 + mov edi,DWORD [28+esp] + xor edx,esi + mov ebx,DWORD [60+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2870763221+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [20+esp] + ror edx,14 + mov edi,DWORD [24+esp] + xor edx,ecx + mov ebx,DWORD [64+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3624381080+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [16+esp] + ror edx,14 + mov edi,DWORD [20+esp] + xor edx,esi + mov ebx,DWORD [68+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[310598401+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [12+esp] + ror edx,14 + mov edi,DWORD [16+esp] + xor edx,ecx + mov ebx,DWORD [72+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[607225278+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [8+esp] + ror edx,14 + mov edi,DWORD [12+esp] + xor edx,esi + mov ebx,DWORD [76+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1426881987+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [4+esp] + ror edx,14 + mov edi,DWORD [8+esp] + xor edx,ecx + mov ebx,DWORD [80+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1925078388+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [esp] + ror edx,14 + mov edi,DWORD [4+esp] + xor edx,esi + mov ebx,DWORD [84+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2162078206+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov ecx,edx + mov esi,DWORD [28+esp] + ror edx,14 + mov edi,DWORD [esp] + xor edx,ecx + mov ebx,DWORD [88+esp] + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2614888103+edx*1+ebx] + xor ecx,esi + xor ebp,edi + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov esi,edx + mov ecx,DWORD [24+esp] + ror edx,14 + mov edi,DWORD [28+esp] + xor edx,esi + mov ebx,DWORD [92+esp] + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3248222580+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [36+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [88+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [32+esp] + shr edi,10 + add ebx,DWORD [68+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [32+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3835390401+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [40+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [92+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [36+esp] + shr edi,10 + add ebx,DWORD [72+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [36+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[4022224774+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [44+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [32+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [40+esp] + shr edi,10 + add ebx,DWORD [76+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [40+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[264347078+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [48+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [36+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [44+esp] + shr edi,10 + add ebx,DWORD [80+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [44+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[604807628+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [52+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [40+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [48+esp] + shr edi,10 + add ebx,DWORD [84+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [48+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[770255983+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [56+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [44+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [52+esp] + shr edi,10 + add ebx,DWORD [88+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [52+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1249150122+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [60+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [48+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [56+esp] + shr edi,10 + add ebx,DWORD [92+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + mov DWORD [56+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1555081692+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [64+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [52+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [60+esp] + shr edi,10 + add ebx,DWORD [32+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + mov DWORD [60+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1996064986+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [68+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [56+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [64+esp] + shr edi,10 + add ebx,DWORD [36+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [64+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2554220882+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [72+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [60+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [68+esp] + shr edi,10 + add ebx,DWORD [40+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [68+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2821834349+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [76+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [64+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [72+esp] + shr edi,10 + add ebx,DWORD [44+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [72+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2952996808+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [80+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [68+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [76+esp] + shr edi,10 + add ebx,DWORD [48+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [76+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3210313671+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [84+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [72+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [80+esp] + shr edi,10 + add ebx,DWORD [52+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [80+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3336571891+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [88+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [76+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [84+esp] + shr edi,10 + add ebx,DWORD [56+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [84+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3584528711+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [92+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [80+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [88+esp] + shr edi,10 + add ebx,DWORD [60+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + mov DWORD [88+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[113926993+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [32+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [84+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [92+esp] + shr edi,10 + add ebx,DWORD [64+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + mov DWORD [92+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[338241895+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [36+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [88+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [32+esp] + shr edi,10 + add ebx,DWORD [68+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [32+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[666307205+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [40+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [92+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [36+esp] + shr edi,10 + add ebx,DWORD [72+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [36+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[773529912+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [44+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [32+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [40+esp] + shr edi,10 + add ebx,DWORD [76+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [40+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1294757372+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [48+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [36+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [44+esp] + shr edi,10 + add ebx,DWORD [80+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [44+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1396182291+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [52+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [40+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [48+esp] + shr edi,10 + add ebx,DWORD [84+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [48+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1695183700+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [56+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [44+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [52+esp] + shr edi,10 + add ebx,DWORD [88+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [52+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1986661051+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [60+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [48+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [56+esp] + shr edi,10 + add ebx,DWORD [92+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + mov DWORD [56+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2177026350+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [64+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [52+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [60+esp] + shr edi,10 + add ebx,DWORD [32+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + mov DWORD [60+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2456956037+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [68+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [56+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [64+esp] + shr edi,10 + add ebx,DWORD [36+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [64+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2730485921+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [72+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [60+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [68+esp] + shr edi,10 + add ebx,DWORD [40+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [68+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2820302411+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [76+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [64+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [72+esp] + shr edi,10 + add ebx,DWORD [44+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [72+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3259730800+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [80+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [68+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [76+esp] + shr edi,10 + add ebx,DWORD [48+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [76+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3345764771+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [84+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [72+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [80+esp] + shr edi,10 + add ebx,DWORD [52+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [80+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3516065817+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [88+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [76+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [84+esp] + shr edi,10 + add ebx,DWORD [56+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [84+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3600352804+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [92+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [80+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [88+esp] + shr edi,10 + add ebx,DWORD [60+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + mov DWORD [88+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[4094571909+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [32+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [84+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [92+esp] + shr edi,10 + add ebx,DWORD [64+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + mov DWORD [92+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[275423344+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [36+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [88+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [32+esp] + shr edi,10 + add ebx,DWORD [68+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [32+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[430227734+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [40+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [92+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [36+esp] + shr edi,10 + add ebx,DWORD [72+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [36+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[506948616+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [44+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [32+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [40+esp] + shr edi,10 + add ebx,DWORD [76+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [40+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[659060556+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [48+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [36+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [44+esp] + shr edi,10 + add ebx,DWORD [80+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [44+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[883997877+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [52+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [40+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [48+esp] + shr edi,10 + add ebx,DWORD [84+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [48+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[958139571+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [56+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [44+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [52+esp] + shr edi,10 + add ebx,DWORD [88+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [52+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1322822218+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [60+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [48+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [56+esp] + shr edi,10 + add ebx,DWORD [92+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + mov DWORD [56+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1537002063+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [64+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [52+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [60+esp] + shr edi,10 + add ebx,DWORD [32+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + mov DWORD [60+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[1747873779+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [68+esp] + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [56+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [64+esp] + shr edi,10 + add ebx,DWORD [36+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [20+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [24+esp] + xor edx,ecx + mov DWORD [64+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [16+esp],ecx + xor edx,ecx + add ebx,DWORD [28+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [4+esp] + xor ecx,eax + mov DWORD [esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[1955562222+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [72+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [12+esp] + add ebp,ecx + mov ecx,DWORD [60+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [68+esp] + shr edi,10 + add ebx,DWORD [40+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [16+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [20+esp] + xor edx,esi + mov DWORD [68+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [12+esp],esi + xor edx,esi + add ebx,DWORD [24+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [esp] + xor esi,ebp + mov DWORD [28+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2024104815+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [76+esp] + ror esi,2 + add eax,edx + add edx,DWORD [8+esp] + add eax,esi + mov esi,DWORD [64+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [72+esp] + shr edi,10 + add ebx,DWORD [44+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [12+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [16+esp] + xor edx,ecx + mov DWORD [72+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [8+esp],ecx + xor edx,ecx + add ebx,DWORD [20+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [28+esp] + xor ecx,eax + mov DWORD [24+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2227730452+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [80+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [4+esp] + add ebp,ecx + mov ecx,DWORD [68+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [76+esp] + shr edi,10 + add ebx,DWORD [48+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [8+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [12+esp] + xor edx,esi + mov DWORD [76+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [4+esp],esi + xor edx,esi + add ebx,DWORD [16+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [24+esp] + xor esi,ebp + mov DWORD [20+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2361852424+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [84+esp] + ror esi,2 + add eax,edx + add edx,DWORD [esp] + add eax,esi + mov esi,DWORD [72+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [80+esp] + shr edi,10 + add ebx,DWORD [52+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [4+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [8+esp] + xor edx,ecx + mov DWORD [80+esp],ebx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [esp],ecx + xor edx,ecx + add ebx,DWORD [12+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [20+esp] + xor ecx,eax + mov DWORD [16+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[2428436474+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [88+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [28+esp] + add ebp,ecx + mov ecx,DWORD [76+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [84+esp] + shr edi,10 + add ebx,DWORD [56+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [4+esp] + xor edx,esi + mov DWORD [84+esp],ebx + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [28+esp],esi + xor edx,esi + add ebx,DWORD [8+esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [16+esp] + xor esi,ebp + mov DWORD [12+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[2756734187+edx*1+ebx] + xor esi,ecx + xor eax,edi + mov ecx,DWORD [92+esp] + ror esi,2 + add eax,edx + add edx,DWORD [24+esp] + add eax,esi + mov esi,DWORD [80+esp] + mov ebx,ecx + ror ecx,11 + mov edi,esi + ror esi,2 + xor ecx,ebx + shr ebx,3 + ror ecx,7 + xor esi,edi + xor ebx,ecx + ror esi,17 + add ebx,DWORD [88+esp] + shr edi,10 + add ebx,DWORD [60+esp] + mov ecx,edx + xor edi,esi + mov esi,DWORD [28+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [esp] + xor edx,ecx + xor esi,edi + ror edx,5 + and esi,ecx + mov DWORD [24+esp],ecx + xor edx,ecx + add ebx,DWORD [4+esp] + xor edi,esi + ror edx,6 + mov ecx,eax + add ebx,edi + ror ecx,9 + mov esi,eax + mov edi,DWORD [12+esp] + xor ecx,eax + mov DWORD [8+esp],eax + xor eax,edi + ror ecx,11 + and ebp,eax + lea edx,[3204031479+edx*1+ebx] + xor ecx,esi + xor ebp,edi + mov esi,DWORD [32+esp] + ror ecx,2 + add ebp,edx + add edx,DWORD [20+esp] + add ebp,ecx + mov ecx,DWORD [84+esp] + mov ebx,esi + ror esi,11 + mov edi,ecx + ror ecx,2 + xor esi,ebx + shr ebx,3 + ror esi,7 + xor ecx,edi + xor ebx,esi + ror ecx,17 + add ebx,DWORD [92+esp] + shr edi,10 + add ebx,DWORD [64+esp] + mov esi,edx + xor edi,ecx + mov ecx,DWORD [24+esp] + ror edx,14 + add ebx,edi + mov edi,DWORD [28+esp] + xor edx,esi + xor ecx,edi + ror edx,5 + and ecx,esi + mov DWORD [20+esp],esi + xor edx,esi + add ebx,DWORD [esp] + xor edi,ecx + ror edx,6 + mov esi,ebp + add ebx,edi + ror esi,9 + mov ecx,ebp + mov edi,DWORD [8+esp] + xor esi,ebp + mov DWORD [4+esp],ebp + xor ebp,edi + ror esi,11 + and eax,ebp + lea edx,[3329325298+edx*1+ebx] + xor esi,ecx + xor eax,edi + ror esi,2 + add eax,edx + add edx,DWORD [16+esp] + add eax,esi + mov esi,DWORD [96+esp] + xor ebp,edi + mov ecx,DWORD [12+esp] + add eax,DWORD [esi] + add ebp,DWORD [4+esi] + add edi,DWORD [8+esi] + add ecx,DWORD [12+esi] + mov DWORD [esi],eax + mov DWORD [4+esi],ebp + mov DWORD [8+esi],edi + mov DWORD [12+esi],ecx + mov DWORD [4+esp],ebp + xor ebp,edi + mov DWORD [8+esp],edi + mov DWORD [12+esp],ecx + mov edi,DWORD [20+esp] + mov ebx,DWORD [24+esp] + mov ecx,DWORD [28+esp] + add edx,DWORD [16+esi] + add edi,DWORD [20+esi] + add ebx,DWORD [24+esi] + add ecx,DWORD [28+esi] + mov DWORD [16+esi],edx + mov DWORD [20+esi],edi + mov DWORD [24+esi],ebx + mov DWORD [28+esi],ecx + mov DWORD [20+esp],edi + mov edi,DWORD [100+esp] + mov DWORD [24+esp],ebx + mov DWORD [28+esp],ecx + cmp edi,DWORD [104+esp] + jb NEAR L$009grand_loop + mov esp,DWORD [108+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +segment .bss +common _OPENSSL_ia32cap_P 16 diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha512-586.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha512-586.nasm new file mode 100644 index 0000000000..a168b4a799 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/sha/sha512-586.nasm @@ -0,0 +1,579 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/sha/asm/sha512-586.pl +; +; Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +global _sha512_block_data_order +align 16 +_sha512_block_data_order: +L$_sha512_block_data_order_begin: + push ebp + push ebx + push esi + push edi + mov esi,DWORD [20+esp] + mov edi,DWORD [24+esp] + mov eax,DWORD [28+esp] + mov ebx,esp + call L$000pic_point +L$000pic_point: + pop ebp + lea ebp,[(L$001K512-L$000pic_point)+ebp] + sub esp,16 + and esp,-64 + shl eax,7 + add eax,edi + mov DWORD [esp],esi + mov DWORD [4+esp],edi + mov DWORD [8+esp],eax + mov DWORD [12+esp],ebx +align 16 +L$002loop_x86: + mov eax,DWORD [edi] + mov ebx,DWORD [4+edi] + mov ecx,DWORD [8+edi] + mov edx,DWORD [12+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [16+edi] + mov ebx,DWORD [20+edi] + mov ecx,DWORD [24+edi] + mov edx,DWORD [28+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [32+edi] + mov ebx,DWORD [36+edi] + mov ecx,DWORD [40+edi] + mov edx,DWORD [44+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [48+edi] + mov ebx,DWORD [52+edi] + mov ecx,DWORD [56+edi] + mov edx,DWORD [60+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [64+edi] + mov ebx,DWORD [68+edi] + mov ecx,DWORD [72+edi] + mov edx,DWORD [76+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [80+edi] + mov ebx,DWORD [84+edi] + mov ecx,DWORD [88+edi] + mov edx,DWORD [92+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [96+edi] + mov ebx,DWORD [100+edi] + mov ecx,DWORD [104+edi] + mov edx,DWORD [108+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + mov eax,DWORD [112+edi] + mov ebx,DWORD [116+edi] + mov ecx,DWORD [120+edi] + mov edx,DWORD [124+edi] + bswap eax + bswap ebx + bswap ecx + bswap edx + push eax + push ebx + push ecx + push edx + add edi,128 + sub esp,72 + mov DWORD [204+esp],edi + lea edi,[8+esp] + mov ecx,16 +dd 2784229001 +align 16 +L$00300_15_x86: + mov ecx,DWORD [40+esp] + mov edx,DWORD [44+esp] + mov esi,ecx + shr ecx,9 + mov edi,edx + shr edx,9 + mov ebx,ecx + shl esi,14 + mov eax,edx + shl edi,14 + xor ebx,esi + shr ecx,5 + xor eax,edi + shr edx,5 + xor eax,ecx + shl esi,4 + xor ebx,edx + shl edi,4 + xor ebx,esi + shr ecx,4 + xor eax,edi + shr edx,4 + xor eax,ecx + shl esi,5 + xor ebx,edx + shl edi,5 + xor eax,esi + xor ebx,edi + mov ecx,DWORD [48+esp] + mov edx,DWORD [52+esp] + mov esi,DWORD [56+esp] + mov edi,DWORD [60+esp] + add eax,DWORD [64+esp] + adc ebx,DWORD [68+esp] + xor ecx,esi + xor edx,edi + and ecx,DWORD [40+esp] + and edx,DWORD [44+esp] + add eax,DWORD [192+esp] + adc ebx,DWORD [196+esp] + xor ecx,esi + xor edx,edi + mov esi,DWORD [ebp] + mov edi,DWORD [4+ebp] + add eax,ecx + adc ebx,edx + mov ecx,DWORD [32+esp] + mov edx,DWORD [36+esp] + add eax,esi + adc ebx,edi + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + add eax,ecx + adc ebx,edx + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + mov DWORD [32+esp],eax + mov DWORD [36+esp],ebx + mov esi,ecx + shr ecx,2 + mov edi,edx + shr edx,2 + mov ebx,ecx + shl esi,4 + mov eax,edx + shl edi,4 + xor ebx,esi + shr ecx,5 + xor eax,edi + shr edx,5 + xor ebx,ecx + shl esi,21 + xor eax,edx + shl edi,21 + xor eax,esi + shr ecx,21 + xor ebx,edi + shr edx,21 + xor eax,ecx + shl esi,5 + xor ebx,edx + shl edi,5 + xor eax,esi + xor ebx,edi + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + mov esi,DWORD [16+esp] + mov edi,DWORD [20+esp] + add eax,DWORD [esp] + adc ebx,DWORD [4+esp] + or ecx,esi + or edx,edi + and ecx,DWORD [24+esp] + and edx,DWORD [28+esp] + and esi,DWORD [8+esp] + and edi,DWORD [12+esp] + or ecx,esi + or edx,edi + add eax,ecx + adc ebx,edx + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + mov dl,BYTE [ebp] + sub esp,8 + lea ebp,[8+ebp] + cmp dl,148 + jne NEAR L$00300_15_x86 +align 16 +L$00416_79_x86: + mov ecx,DWORD [312+esp] + mov edx,DWORD [316+esp] + mov esi,ecx + shr ecx,1 + mov edi,edx + shr edx,1 + mov eax,ecx + shl esi,24 + mov ebx,edx + shl edi,24 + xor ebx,esi + shr ecx,6 + xor eax,edi + shr edx,6 + xor eax,ecx + shl esi,7 + xor ebx,edx + shl edi,1 + xor ebx,esi + shr ecx,1 + xor eax,edi + shr edx,1 + xor eax,ecx + shl edi,6 + xor ebx,edx + xor eax,edi + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + mov ecx,DWORD [208+esp] + mov edx,DWORD [212+esp] + mov esi,ecx + shr ecx,6 + mov edi,edx + shr edx,6 + mov eax,ecx + shl esi,3 + mov ebx,edx + shl edi,3 + xor eax,esi + shr ecx,13 + xor ebx,edi + shr edx,13 + xor eax,ecx + shl esi,10 + xor ebx,edx + shl edi,10 + xor ebx,esi + shr ecx,10 + xor eax,edi + shr edx,10 + xor ebx,ecx + shl edi,13 + xor eax,edx + xor eax,edi + mov ecx,DWORD [320+esp] + mov edx,DWORD [324+esp] + add eax,DWORD [esp] + adc ebx,DWORD [4+esp] + mov esi,DWORD [248+esp] + mov edi,DWORD [252+esp] + add eax,ecx + adc ebx,edx + add eax,esi + adc ebx,edi + mov DWORD [192+esp],eax + mov DWORD [196+esp],ebx + mov ecx,DWORD [40+esp] + mov edx,DWORD [44+esp] + mov esi,ecx + shr ecx,9 + mov edi,edx + shr edx,9 + mov ebx,ecx + shl esi,14 + mov eax,edx + shl edi,14 + xor ebx,esi + shr ecx,5 + xor eax,edi + shr edx,5 + xor eax,ecx + shl esi,4 + xor ebx,edx + shl edi,4 + xor ebx,esi + shr ecx,4 + xor eax,edi + shr edx,4 + xor eax,ecx + shl esi,5 + xor ebx,edx + shl edi,5 + xor eax,esi + xor ebx,edi + mov ecx,DWORD [48+esp] + mov edx,DWORD [52+esp] + mov esi,DWORD [56+esp] + mov edi,DWORD [60+esp] + add eax,DWORD [64+esp] + adc ebx,DWORD [68+esp] + xor ecx,esi + xor edx,edi + and ecx,DWORD [40+esp] + and edx,DWORD [44+esp] + add eax,DWORD [192+esp] + adc ebx,DWORD [196+esp] + xor ecx,esi + xor edx,edi + mov esi,DWORD [ebp] + mov edi,DWORD [4+ebp] + add eax,ecx + adc ebx,edx + mov ecx,DWORD [32+esp] + mov edx,DWORD [36+esp] + add eax,esi + adc ebx,edi + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + add eax,ecx + adc ebx,edx + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + mov DWORD [32+esp],eax + mov DWORD [36+esp],ebx + mov esi,ecx + shr ecx,2 + mov edi,edx + shr edx,2 + mov ebx,ecx + shl esi,4 + mov eax,edx + shl edi,4 + xor ebx,esi + shr ecx,5 + xor eax,edi + shr edx,5 + xor ebx,ecx + shl esi,21 + xor eax,edx + shl edi,21 + xor eax,esi + shr ecx,21 + xor ebx,edi + shr edx,21 + xor eax,ecx + shl esi,5 + xor ebx,edx + shl edi,5 + xor eax,esi + xor ebx,edi + mov ecx,DWORD [8+esp] + mov edx,DWORD [12+esp] + mov esi,DWORD [16+esp] + mov edi,DWORD [20+esp] + add eax,DWORD [esp] + adc ebx,DWORD [4+esp] + or ecx,esi + or edx,edi + and ecx,DWORD [24+esp] + and edx,DWORD [28+esp] + and esi,DWORD [8+esp] + and edi,DWORD [12+esp] + or ecx,esi + or edx,edi + add eax,ecx + adc ebx,edx + mov DWORD [esp],eax + mov DWORD [4+esp],ebx + mov dl,BYTE [ebp] + sub esp,8 + lea ebp,[8+ebp] + cmp dl,23 + jne NEAR L$00416_79_x86 + mov esi,DWORD [840+esp] + mov edi,DWORD [844+esp] + mov eax,DWORD [esi] + mov ebx,DWORD [4+esi] + mov ecx,DWORD [8+esi] + mov edx,DWORD [12+esi] + add eax,DWORD [8+esp] + adc ebx,DWORD [12+esp] + mov DWORD [esi],eax + mov DWORD [4+esi],ebx + add ecx,DWORD [16+esp] + adc edx,DWORD [20+esp] + mov DWORD [8+esi],ecx + mov DWORD [12+esi],edx + mov eax,DWORD [16+esi] + mov ebx,DWORD [20+esi] + mov ecx,DWORD [24+esi] + mov edx,DWORD [28+esi] + add eax,DWORD [24+esp] + adc ebx,DWORD [28+esp] + mov DWORD [16+esi],eax + mov DWORD [20+esi],ebx + add ecx,DWORD [32+esp] + adc edx,DWORD [36+esp] + mov DWORD [24+esi],ecx + mov DWORD [28+esi],edx + mov eax,DWORD [32+esi] + mov ebx,DWORD [36+esi] + mov ecx,DWORD [40+esi] + mov edx,DWORD [44+esi] + add eax,DWORD [40+esp] + adc ebx,DWORD [44+esp] + mov DWORD [32+esi],eax + mov DWORD [36+esi],ebx + add ecx,DWORD [48+esp] + adc edx,DWORD [52+esp] + mov DWORD [40+esi],ecx + mov DWORD [44+esi],edx + mov eax,DWORD [48+esi] + mov ebx,DWORD [52+esi] + mov ecx,DWORD [56+esi] + mov edx,DWORD [60+esi] + add eax,DWORD [56+esp] + adc ebx,DWORD [60+esp] + mov DWORD [48+esi],eax + mov DWORD [52+esi],ebx + add ecx,DWORD [64+esp] + adc edx,DWORD [68+esp] + mov DWORD [56+esi],ecx + mov DWORD [60+esi],edx + add esp,840 + sub ebp,640 + cmp edi,DWORD [8+esp] + jb NEAR L$002loop_x86 + mov esp,DWORD [12+esp] + pop edi + pop esi + pop ebx + pop ebp + ret +align 64 +L$001K512: +dd 3609767458,1116352408 +dd 602891725,1899447441 +dd 3964484399,3049323471 +dd 2173295548,3921009573 +dd 4081628472,961987163 +dd 3053834265,1508970993 +dd 2937671579,2453635748 +dd 3664609560,2870763221 +dd 2734883394,3624381080 +dd 1164996542,310598401 +dd 1323610764,607225278 +dd 3590304994,1426881987 +dd 4068182383,1925078388 +dd 991336113,2162078206 +dd 633803317,2614888103 +dd 3479774868,3248222580 +dd 2666613458,3835390401 +dd 944711139,4022224774 +dd 2341262773,264347078 +dd 2007800933,604807628 +dd 1495990901,770255983 +dd 1856431235,1249150122 +dd 3175218132,1555081692 +dd 2198950837,1996064986 +dd 3999719339,2554220882 +dd 766784016,2821834349 +dd 2566594879,2952996808 +dd 3203337956,3210313671 +dd 1034457026,3336571891 +dd 2466948901,3584528711 +dd 3758326383,113926993 +dd 168717936,338241895 +dd 1188179964,666307205 +dd 1546045734,773529912 +dd 1522805485,1294757372 +dd 2643833823,1396182291 +dd 2343527390,1695183700 +dd 1014477480,1986661051 +dd 1206759142,2177026350 +dd 344077627,2456956037 +dd 1290863460,2730485921 +dd 3158454273,2820302411 +dd 3505952657,3259730800 +dd 106217008,3345764771 +dd 3606008344,3516065817 +dd 1432725776,3600352804 +dd 1467031594,4094571909 +dd 851169720,275423344 +dd 3100823752,430227734 +dd 1363258195,506948616 +dd 3750685593,659060556 +dd 3785050280,883997877 +dd 3318307427,958139571 +dd 3812723403,1322822218 +dd 2003034995,1537002063 +dd 3602036899,1747873779 +dd 1575990012,1955562222 +dd 1125592928,2024104815 +dd 2716904306,2227730452 +dd 442776044,2361852424 +dd 593698344,2428436474 +dd 3733110249,2756734187 +dd 2999351573,3204031479 +dd 3815920427,3329325298 +dd 3928383900,3391569614 +dd 566280711,3515267271 +dd 3454069534,3940187606 +dd 4000239992,4118630271 +dd 1914138554,116418474 +dd 2731055270,174292421 +dd 3203993006,289380356 +dd 320620315,460393269 +dd 587496836,685471733 +dd 1086792851,852142971 +dd 365543100,1017036298 +dd 2618297676,1126000580 +dd 3409855158,1288033470 +dd 4234509866,1501505948 +dd 987167468,1607167915 +dd 1246189591,1816402316 +dd 67438087,66051 +dd 202182159,134810123 +db 83,72,65,53,49,50,32,98,108,111,99,107,32,116,114,97 +db 110,115,102,111,114,109,32,102,111,114,32,120,56,54,44,32 +db 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 +db 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 +db 62,0 diff --git a/CryptoPkg/Library/OpensslLib/IA32/crypto/x86cpuid.nasm b/CryptoPkg/Library/OpensslLib/IA32/crypto/x86cpuid.nasm new file mode 100644 index 0000000000..542e759ecd --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32/crypto/x86cpuid.nasm @@ -0,0 +1,433 @@ +; WARNING: do not edit! +; Generated from openssl/crypto/x86cpuid.pl +; +; Copyright 2004-2020 The OpenSSL Project Authors. All Rights Reserved. +; +; Licensed under the OpenSSL license (the "License"). You may not use +; this file except in compliance with the License. You can obtain a copy +; in the file LICENSE in the source distribution or at +; https://www.openssl.org/source/license.html + +%ifidn __OUTPUT_FORMAT__,obj +section code use32 class=code align=64 +%elifidn __OUTPUT_FORMAT__,win32 +$@feat.00 equ 1 +section .text code align=64 +%else +section .text code +%endif +global _OPENSSL_ia32_cpuid +align 16 +_OPENSSL_ia32_cpuid: +L$_OPENSSL_ia32_cpuid_begin: + push ebp + push ebx + push esi + push edi + xor edx,edx + pushfd + pop eax + mov ecx,eax + xor eax,2097152 + push eax + popfd + pushfd + pop eax + xor ecx,eax + xor eax,eax + mov esi,DWORD [20+esp] + mov DWORD [8+esi],eax + bt ecx,21 + jnc NEAR L$000nocpuid + cpuid + mov edi,eax + xor eax,eax + cmp ebx,1970169159 + setne al + mov ebp,eax + cmp edx,1231384169 + setne al + or ebp,eax + cmp ecx,1818588270 + setne al + or ebp,eax + jz NEAR L$001intel + cmp ebx,1752462657 + setne al + mov esi,eax + cmp edx,1769238117 + setne al + or esi,eax + cmp ecx,1145913699 + setne al + or esi,eax + jnz NEAR L$001intel + mov eax,2147483648 + cpuid + cmp eax,2147483649 + jb NEAR L$001intel + mov esi,eax + mov eax,2147483649 + cpuid + or ebp,ecx + and ebp,2049 + cmp esi,2147483656 + jb NEAR L$001intel + mov eax,2147483656 + cpuid + movzx esi,cl + inc esi + mov eax,1 + xor ecx,ecx + cpuid + bt edx,28 + jnc NEAR L$002generic + shr ebx,16 + and ebx,255 + cmp ebx,esi + ja NEAR L$002generic + and edx,4026531839 + jmp NEAR L$002generic +L$001intel: + cmp edi,4 + mov esi,-1 + jb NEAR L$003nocacheinfo + mov eax,4 + mov ecx,0 + cpuid + mov esi,eax + shr esi,14 + and esi,4095 +L$003nocacheinfo: + mov eax,1 + xor ecx,ecx + cpuid + and edx,3220176895 + cmp ebp,0 + jne NEAR L$004notintel + or edx,1073741824 + and ah,15 + cmp ah,15 + jne NEAR L$004notintel + or edx,1048576 +L$004notintel: + bt edx,28 + jnc NEAR L$002generic + and edx,4026531839 + cmp esi,0 + je NEAR L$002generic + or edx,268435456 + shr ebx,16 + cmp bl,1 + ja NEAR L$002generic + and edx,4026531839 +L$002generic: + and ebp,2048 + and ecx,4294965247 + mov esi,edx + or ebp,ecx + cmp edi,7 + mov edi,DWORD [20+esp] + jb NEAR L$005no_extended_info + mov eax,7 + xor ecx,ecx + cpuid + mov DWORD [8+edi],ebx +L$005no_extended_info: + bt ebp,27 + jnc NEAR L$006clear_avx + xor ecx,ecx +db 15,1,208 + and eax,6 + cmp eax,6 + je NEAR L$007done + cmp eax,2 + je NEAR L$006clear_avx +L$008clear_xmm: + and ebp,4261412861 + and esi,4278190079 +L$006clear_avx: + and ebp,4026525695 + and DWORD [8+edi],4294967263 +L$007done: + mov eax,esi + mov edx,ebp +L$000nocpuid: + pop edi + pop esi + pop ebx + pop ebp + ret +;extern _OPENSSL_ia32cap_P +global _OPENSSL_rdtsc +align 16 +_OPENSSL_rdtsc: +L$_OPENSSL_rdtsc_begin: + xor eax,eax + xor edx,edx + lea ecx,[_OPENSSL_ia32cap_P] + bt DWORD [ecx],4 + jnc NEAR L$009notsc + rdtsc +L$009notsc: + ret +global _OPENSSL_instrument_halt +align 16 +_OPENSSL_instrument_halt: +L$_OPENSSL_instrument_halt_begin: + lea ecx,[_OPENSSL_ia32cap_P] + bt DWORD [ecx],4 + jnc NEAR L$010nohalt +dd 2421723150 + and eax,3 + jnz NEAR L$010nohalt + pushfd + pop eax + bt eax,9 + jnc NEAR L$010nohalt + rdtsc + push edx + push eax + hlt + rdtsc + sub eax,DWORD [esp] + sbb edx,DWORD [4+esp] + add esp,8 + ret +L$010nohalt: + xor eax,eax + xor edx,edx + ret +global _OPENSSL_far_spin +align 16 +_OPENSSL_far_spin: +L$_OPENSSL_far_spin_begin: + pushfd + pop eax + bt eax,9 + jnc NEAR L$011nospin + mov eax,DWORD [4+esp] + mov ecx,DWORD [8+esp] +dd 2430111262 + xor eax,eax + mov edx,DWORD [ecx] + jmp NEAR L$012spin +align 16 +L$012spin: + inc eax + cmp edx,DWORD [ecx] + je NEAR L$012spin +dd 529567888 + ret +L$011nospin: + xor eax,eax + xor edx,edx + ret +global _OPENSSL_wipe_cpu +align 16 +_OPENSSL_wipe_cpu: +L$_OPENSSL_wipe_cpu_begin: + xor eax,eax + xor edx,edx + lea ecx,[_OPENSSL_ia32cap_P] + mov ecx,DWORD [ecx] + bt DWORD [ecx],1 + jnc NEAR L$013no_x87 +dd 4007259865,4007259865,4007259865,4007259865,2430851995 +L$013no_x87: + lea eax,[4+esp] + ret +global _OPENSSL_atomic_add +align 16 +_OPENSSL_atomic_add: +L$_OPENSSL_atomic_add_begin: + mov edx,DWORD [4+esp] + mov ecx,DWORD [8+esp] + push ebx + nop + mov eax,DWORD [edx] +L$014spin: + lea ebx,[ecx*1+eax] + nop +dd 447811568 + jne NEAR L$014spin + mov eax,ebx + pop ebx + ret +global _OPENSSL_cleanse +align 16 +_OPENSSL_cleanse: +L$_OPENSSL_cleanse_begin: + mov edx,DWORD [4+esp] + mov ecx,DWORD [8+esp] + xor eax,eax + cmp ecx,7 + jae NEAR L$015lot + cmp ecx,0 + je NEAR L$016ret +L$017little: + mov BYTE [edx],al + sub ecx,1 + lea edx,[1+edx] + jnz NEAR L$017little +L$016ret: + ret +align 16 +L$015lot: + test edx,3 + jz NEAR L$018aligned + mov BYTE [edx],al + lea ecx,[ecx-1] + lea edx,[1+edx] + jmp NEAR L$015lot +L$018aligned: + mov DWORD [edx],eax + lea ecx,[ecx-4] + test ecx,-4 + lea edx,[4+edx] + jnz NEAR L$018aligned + cmp ecx,0 + jne NEAR L$017little + ret +global _CRYPTO_memcmp +align 16 +_CRYPTO_memcmp: +L$_CRYPTO_memcmp_begin: + push esi + push edi + mov esi,DWORD [12+esp] + mov edi,DWORD [16+esp] + mov ecx,DWORD [20+esp] + xor eax,eax + xor edx,edx + cmp ecx,0 + je NEAR L$019no_data +L$020loop: + mov dl,BYTE [esi] + lea esi,[1+esi] + xor dl,BYTE [edi] + lea edi,[1+edi] + or al,dl + dec ecx + jnz NEAR L$020loop + neg eax + shr eax,31 +L$019no_data: + pop edi + pop esi + ret +global _OPENSSL_instrument_bus +align 16 +_OPENSSL_instrument_bus: +L$_OPENSSL_instrument_bus_begin: + push ebp + push ebx + push esi + push edi + mov eax,0 + pop edi + pop esi + pop ebx + pop ebp + ret +global _OPENSSL_instrument_bus2 +align 16 +_OPENSSL_instrument_bus2: +L$_OPENSSL_instrument_bus2_begin: + push ebp + push ebx + push esi + push edi + mov eax,0 + pop edi + pop esi + pop ebx + pop ebp + ret +global _OPENSSL_ia32_rdrand_bytes +align 16 +_OPENSSL_ia32_rdrand_bytes: +L$_OPENSSL_ia32_rdrand_bytes_begin: + push edi + push ebx + xor eax,eax + mov edi,DWORD [12+esp] + mov ebx,DWORD [16+esp] + cmp ebx,0 + je NEAR L$021done + mov ecx,8 +L$022loop: +db 15,199,242 + jc NEAR L$023break + loop L$022loop + jmp NEAR L$021done +align 16 +L$023break: + cmp ebx,4 + jb NEAR L$024tail + mov DWORD [edi],edx + lea edi,[4+edi] + add eax,4 + sub ebx,4 + jz NEAR L$021done + mov ecx,8 + jmp NEAR L$022loop +align 16 +L$024tail: + mov BYTE [edi],dl + lea edi,[1+edi] + inc eax + shr edx,8 + dec ebx + jnz NEAR L$024tail +L$021done: + xor edx,edx + pop ebx + pop edi + ret +global _OPENSSL_ia32_rdseed_bytes +align 16 +_OPENSSL_ia32_rdseed_bytes: +L$_OPENSSL_ia32_rdseed_bytes_begin: + push edi + push ebx + xor eax,eax + mov edi,DWORD [12+esp] + mov ebx,DWORD [16+esp] + cmp ebx,0 + je NEAR L$025done + mov ecx,8 +L$026loop: +db 15,199,250 + jc NEAR L$027break + loop L$026loop + jmp NEAR L$025done +align 16 +L$027break: + cmp ebx,4 + jb NEAR L$028tail + mov DWORD [edi],edx + lea edi,[4+edi] + add eax,4 + sub ebx,4 + jz NEAR L$025done + mov ecx,8 + jmp NEAR L$026loop +align 16 +L$028tail: + mov BYTE [edi],dl + lea edi,[1+edi] + inc eax + shr edx,8 + dec ebx + jnz NEAR L$028tail +L$025done: + xor edx,edx + pop ebx + pop edi + ret +segment .bss +common _OPENSSL_ia32cap_P 16 +segment .CRT$XCU data align=4 +extern _OPENSSL_cpuid_setup +dd _OPENSSL_cpuid_setup diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/aesni-x86.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/aesni-x86.S new file mode 100644 index 0000000000..836e831b18 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/aesni-x86.S @@ -0,0 +1,3247 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/aes/asm/aesni-x86.pl +# +# Copyright 2009-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl aesni_encrypt +.type aesni_encrypt,@function +.align 16 +aesni_encrypt: +.L_aesni_encrypt_begin: + movl 4(%esp),%eax + movl 12(%esp),%edx + movups (%eax),%xmm2 + movl 240(%edx),%ecx + movl 8(%esp),%eax + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L000enc1_loop_1: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L000enc1_loop_1 +.byte 102,15,56,221,209 + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + movups %xmm2,(%eax) + pxor %xmm2,%xmm2 + ret +.size aesni_encrypt,.-.L_aesni_encrypt_begin +.globl aesni_decrypt +.type aesni_decrypt,@function +.align 16 +aesni_decrypt: +.L_aesni_decrypt_begin: + movl 4(%esp),%eax + movl 12(%esp),%edx + movups (%eax),%xmm2 + movl 240(%edx),%ecx + movl 8(%esp),%eax + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L001dec1_loop_2: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L001dec1_loop_2 +.byte 102,15,56,223,209 + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + movups %xmm2,(%eax) + pxor %xmm2,%xmm2 + ret +.size aesni_decrypt,.-.L_aesni_decrypt_begin +.type _aesni_encrypt2,@function +.align 16 +_aesni_encrypt2: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx + addl $16,%ecx +.L002enc2_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L002enc2_loop +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 + ret +.size _aesni_encrypt2,.-_aesni_encrypt2 +.type _aesni_decrypt2,@function +.align 16 +_aesni_decrypt2: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx + addl $16,%ecx +.L003dec2_loop: +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,222,208 +.byte 102,15,56,222,216 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L003dec2_loop +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,223,208 +.byte 102,15,56,223,216 + ret +.size _aesni_decrypt2,.-_aesni_decrypt2 +.type _aesni_encrypt3,@function +.align 16 +_aesni_encrypt3: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx + addl $16,%ecx +.L004enc3_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 +.byte 102,15,56,220,224 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L004enc3_loop +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 +.byte 102,15,56,221,224 + ret +.size _aesni_encrypt3,.-_aesni_encrypt3 +.type _aesni_decrypt3,@function +.align 16 +_aesni_decrypt3: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx + addl $16,%ecx +.L005dec3_loop: +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,222,208 +.byte 102,15,56,222,216 +.byte 102,15,56,222,224 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L005dec3_loop +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,223,208 +.byte 102,15,56,223,216 +.byte 102,15,56,223,224 + ret +.size _aesni_decrypt3,.-_aesni_decrypt3 +.type _aesni_encrypt4,@function +.align 16 +_aesni_encrypt4: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + shll $4,%ecx + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + pxor %xmm0,%xmm5 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx +.byte 15,31,64,0 + addl $16,%ecx +.L006enc4_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 +.byte 102,15,56,220,224 +.byte 102,15,56,220,232 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L006enc4_loop +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 +.byte 102,15,56,221,224 +.byte 102,15,56,221,232 + ret +.size _aesni_encrypt4,.-_aesni_encrypt4 +.type _aesni_decrypt4,@function +.align 16 +_aesni_decrypt4: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + shll $4,%ecx + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + pxor %xmm0,%xmm5 + movups 32(%edx),%xmm0 + leal 32(%edx,%ecx,1),%edx + negl %ecx +.byte 15,31,64,0 + addl $16,%ecx +.L007dec4_loop: +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,222,208 +.byte 102,15,56,222,216 +.byte 102,15,56,222,224 +.byte 102,15,56,222,232 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L007dec4_loop +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 +.byte 102,15,56,223,208 +.byte 102,15,56,223,216 +.byte 102,15,56,223,224 +.byte 102,15,56,223,232 + ret +.size _aesni_decrypt4,.-_aesni_decrypt4 +.type _aesni_encrypt6,@function +.align 16 +_aesni_encrypt6: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 +.byte 102,15,56,220,209 + pxor %xmm0,%xmm5 + pxor %xmm0,%xmm6 +.byte 102,15,56,220,217 + leal 32(%edx,%ecx,1),%edx + negl %ecx +.byte 102,15,56,220,225 + pxor %xmm0,%xmm7 + movups (%edx,%ecx,1),%xmm0 + addl $16,%ecx + jmp .L008_aesni_encrypt6_inner +.align 16 +.L009enc6_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.L008_aesni_encrypt6_inner: +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 +.L_aesni_encrypt6_enter: + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 +.byte 102,15,56,220,224 +.byte 102,15,56,220,232 +.byte 102,15,56,220,240 +.byte 102,15,56,220,248 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L009enc6_loop +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 +.byte 102,15,56,221,224 +.byte 102,15,56,221,232 +.byte 102,15,56,221,240 +.byte 102,15,56,221,248 + ret +.size _aesni_encrypt6,.-_aesni_encrypt6 +.type _aesni_decrypt6,@function +.align 16 +_aesni_decrypt6: + movups (%edx),%xmm0 + shll $4,%ecx + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 +.byte 102,15,56,222,209 + pxor %xmm0,%xmm5 + pxor %xmm0,%xmm6 +.byte 102,15,56,222,217 + leal 32(%edx,%ecx,1),%edx + negl %ecx +.byte 102,15,56,222,225 + pxor %xmm0,%xmm7 + movups (%edx,%ecx,1),%xmm0 + addl $16,%ecx + jmp .L010_aesni_decrypt6_inner +.align 16 +.L011dec6_loop: +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.L010_aesni_decrypt6_inner: +.byte 102,15,56,222,233 +.byte 102,15,56,222,241 +.byte 102,15,56,222,249 +.L_aesni_decrypt6_enter: + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,222,208 +.byte 102,15,56,222,216 +.byte 102,15,56,222,224 +.byte 102,15,56,222,232 +.byte 102,15,56,222,240 +.byte 102,15,56,222,248 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L011dec6_loop +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 +.byte 102,15,56,222,241 +.byte 102,15,56,222,249 +.byte 102,15,56,223,208 +.byte 102,15,56,223,216 +.byte 102,15,56,223,224 +.byte 102,15,56,223,232 +.byte 102,15,56,223,240 +.byte 102,15,56,223,248 + ret +.size _aesni_decrypt6,.-_aesni_decrypt6 +.globl aesni_ecb_encrypt +.type aesni_ecb_encrypt,@function +.align 16 +aesni_ecb_encrypt: +.L_aesni_ecb_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl 36(%esp),%ebx + andl $-16,%eax + jz .L012ecb_ret + movl 240(%edx),%ecx + testl %ebx,%ebx + jz .L013ecb_decrypt + movl %edx,%ebp + movl %ecx,%ebx + cmpl $96,%eax + jb .L014ecb_enc_tail + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi + subl $96,%eax + jmp .L015ecb_enc_loop6_enter +.align 16 +.L016ecb_enc_loop6: + movups %xmm2,(%edi) + movdqu (%esi),%xmm2 + movups %xmm3,16(%edi) + movdqu 16(%esi),%xmm3 + movups %xmm4,32(%edi) + movdqu 32(%esi),%xmm4 + movups %xmm5,48(%edi) + movdqu 48(%esi),%xmm5 + movups %xmm6,64(%edi) + movdqu 64(%esi),%xmm6 + movups %xmm7,80(%edi) + leal 96(%edi),%edi + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi +.L015ecb_enc_loop6_enter: + call _aesni_encrypt6 + movl %ebp,%edx + movl %ebx,%ecx + subl $96,%eax + jnc .L016ecb_enc_loop6 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + movups %xmm7,80(%edi) + leal 96(%edi),%edi + addl $96,%eax + jz .L012ecb_ret +.L014ecb_enc_tail: + movups (%esi),%xmm2 + cmpl $32,%eax + jb .L017ecb_enc_one + movups 16(%esi),%xmm3 + je .L018ecb_enc_two + movups 32(%esi),%xmm4 + cmpl $64,%eax + jb .L019ecb_enc_three + movups 48(%esi),%xmm5 + je .L020ecb_enc_four + movups 64(%esi),%xmm6 + xorps %xmm7,%xmm7 + call _aesni_encrypt6 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + jmp .L012ecb_ret +.align 16 +.L017ecb_enc_one: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L021enc1_loop_3: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L021enc1_loop_3 +.byte 102,15,56,221,209 + movups %xmm2,(%edi) + jmp .L012ecb_ret +.align 16 +.L018ecb_enc_two: + call _aesni_encrypt2 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + jmp .L012ecb_ret +.align 16 +.L019ecb_enc_three: + call _aesni_encrypt3 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + jmp .L012ecb_ret +.align 16 +.L020ecb_enc_four: + call _aesni_encrypt4 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + jmp .L012ecb_ret +.align 16 +.L013ecb_decrypt: + movl %edx,%ebp + movl %ecx,%ebx + cmpl $96,%eax + jb .L022ecb_dec_tail + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi + subl $96,%eax + jmp .L023ecb_dec_loop6_enter +.align 16 +.L024ecb_dec_loop6: + movups %xmm2,(%edi) + movdqu (%esi),%xmm2 + movups %xmm3,16(%edi) + movdqu 16(%esi),%xmm3 + movups %xmm4,32(%edi) + movdqu 32(%esi),%xmm4 + movups %xmm5,48(%edi) + movdqu 48(%esi),%xmm5 + movups %xmm6,64(%edi) + movdqu 64(%esi),%xmm6 + movups %xmm7,80(%edi) + leal 96(%edi),%edi + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi +.L023ecb_dec_loop6_enter: + call _aesni_decrypt6 + movl %ebp,%edx + movl %ebx,%ecx + subl $96,%eax + jnc .L024ecb_dec_loop6 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + movups %xmm7,80(%edi) + leal 96(%edi),%edi + addl $96,%eax + jz .L012ecb_ret +.L022ecb_dec_tail: + movups (%esi),%xmm2 + cmpl $32,%eax + jb .L025ecb_dec_one + movups 16(%esi),%xmm3 + je .L026ecb_dec_two + movups 32(%esi),%xmm4 + cmpl $64,%eax + jb .L027ecb_dec_three + movups 48(%esi),%xmm5 + je .L028ecb_dec_four + movups 64(%esi),%xmm6 + xorps %xmm7,%xmm7 + call _aesni_decrypt6 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + jmp .L012ecb_ret +.align 16 +.L025ecb_dec_one: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L029dec1_loop_4: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L029dec1_loop_4 +.byte 102,15,56,223,209 + movups %xmm2,(%edi) + jmp .L012ecb_ret +.align 16 +.L026ecb_dec_two: + call _aesni_decrypt2 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + jmp .L012ecb_ret +.align 16 +.L027ecb_dec_three: + call _aesni_decrypt3 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + jmp .L012ecb_ret +.align 16 +.L028ecb_dec_four: + call _aesni_decrypt4 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) +.L012ecb_ret: + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + pxor %xmm7,%xmm7 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ecb_encrypt,.-.L_aesni_ecb_encrypt_begin +.globl aesni_ccm64_encrypt_blocks +.type aesni_ccm64_encrypt_blocks,@function +.align 16 +aesni_ccm64_encrypt_blocks: +.L_aesni_ccm64_encrypt_blocks_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl 36(%esp),%ebx + movl 40(%esp),%ecx + movl %esp,%ebp + subl $60,%esp + andl $-16,%esp + movl %ebp,48(%esp) + movdqu (%ebx),%xmm7 + movdqu (%ecx),%xmm3 + movl 240(%edx),%ecx + movl $202182159,(%esp) + movl $134810123,4(%esp) + movl $67438087,8(%esp) + movl $66051,12(%esp) + movl $1,%ebx + xorl %ebp,%ebp + movl %ebx,16(%esp) + movl %ebp,20(%esp) + movl %ebp,24(%esp) + movl %ebp,28(%esp) + shll $4,%ecx + movl $16,%ebx + leal (%edx),%ebp + movdqa (%esp),%xmm5 + movdqa %xmm7,%xmm2 + leal 32(%edx,%ecx,1),%edx + subl %ecx,%ebx +.byte 102,15,56,0,253 +.L030ccm64_enc_outer: + movups (%ebp),%xmm0 + movl %ebx,%ecx + movups (%esi),%xmm6 + xorps %xmm0,%xmm2 + movups 16(%ebp),%xmm1 + xorps %xmm6,%xmm0 + xorps %xmm0,%xmm3 + movups 32(%ebp),%xmm0 +.L031ccm64_enc2_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L031ccm64_enc2_loop +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 + paddq 16(%esp),%xmm7 + decl %eax +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 + leal 16(%esi),%esi + xorps %xmm2,%xmm6 + movdqa %xmm7,%xmm2 + movups %xmm6,(%edi) +.byte 102,15,56,0,213 + leal 16(%edi),%edi + jnz .L030ccm64_enc_outer + movl 48(%esp),%esp + movl 40(%esp),%edi + movups %xmm3,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + pxor %xmm7,%xmm7 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ccm64_encrypt_blocks,.-.L_aesni_ccm64_encrypt_blocks_begin +.globl aesni_ccm64_decrypt_blocks +.type aesni_ccm64_decrypt_blocks,@function +.align 16 +aesni_ccm64_decrypt_blocks: +.L_aesni_ccm64_decrypt_blocks_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl 36(%esp),%ebx + movl 40(%esp),%ecx + movl %esp,%ebp + subl $60,%esp + andl $-16,%esp + movl %ebp,48(%esp) + movdqu (%ebx),%xmm7 + movdqu (%ecx),%xmm3 + movl 240(%edx),%ecx + movl $202182159,(%esp) + movl $134810123,4(%esp) + movl $67438087,8(%esp) + movl $66051,12(%esp) + movl $1,%ebx + xorl %ebp,%ebp + movl %ebx,16(%esp) + movl %ebp,20(%esp) + movl %ebp,24(%esp) + movl %ebp,28(%esp) + movdqa (%esp),%xmm5 + movdqa %xmm7,%xmm2 + movl %edx,%ebp + movl %ecx,%ebx +.byte 102,15,56,0,253 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L032enc1_loop_5: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L032enc1_loop_5 +.byte 102,15,56,221,209 + shll $4,%ebx + movl $16,%ecx + movups (%esi),%xmm6 + paddq 16(%esp),%xmm7 + leal 16(%esi),%esi + subl %ebx,%ecx + leal 32(%ebp,%ebx,1),%edx + movl %ecx,%ebx + jmp .L033ccm64_dec_outer +.align 16 +.L033ccm64_dec_outer: + xorps %xmm2,%xmm6 + movdqa %xmm7,%xmm2 + movups %xmm6,(%edi) + leal 16(%edi),%edi +.byte 102,15,56,0,213 + subl $1,%eax + jz .L034ccm64_dec_break + movups (%ebp),%xmm0 + movl %ebx,%ecx + movups 16(%ebp),%xmm1 + xorps %xmm0,%xmm6 + xorps %xmm0,%xmm2 + xorps %xmm6,%xmm3 + movups 32(%ebp),%xmm0 +.L035ccm64_dec2_loop: +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 + movups (%edx,%ecx,1),%xmm1 + addl $32,%ecx +.byte 102,15,56,220,208 +.byte 102,15,56,220,216 + movups -16(%edx,%ecx,1),%xmm0 + jnz .L035ccm64_dec2_loop + movups (%esi),%xmm6 + paddq 16(%esp),%xmm7 +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,221,208 +.byte 102,15,56,221,216 + leal 16(%esi),%esi + jmp .L033ccm64_dec_outer +.align 16 +.L034ccm64_dec_break: + movl 240(%ebp),%ecx + movl %ebp,%edx + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm6 + leal 32(%edx),%edx + xorps %xmm6,%xmm3 +.L036enc1_loop_6: +.byte 102,15,56,220,217 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L036enc1_loop_6 +.byte 102,15,56,221,217 + movl 48(%esp),%esp + movl 40(%esp),%edi + movups %xmm3,(%edi) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + pxor %xmm7,%xmm7 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ccm64_decrypt_blocks,.-.L_aesni_ccm64_decrypt_blocks_begin +.globl aesni_ctr32_encrypt_blocks +.type aesni_ctr32_encrypt_blocks,@function +.align 16 +aesni_ctr32_encrypt_blocks: +.L_aesni_ctr32_encrypt_blocks_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl 36(%esp),%ebx + movl %esp,%ebp + subl $88,%esp + andl $-16,%esp + movl %ebp,80(%esp) + cmpl $1,%eax + je .L037ctr32_one_shortcut + movdqu (%ebx),%xmm7 + movl $202182159,(%esp) + movl $134810123,4(%esp) + movl $67438087,8(%esp) + movl $66051,12(%esp) + movl $6,%ecx + xorl %ebp,%ebp + movl %ecx,16(%esp) + movl %ecx,20(%esp) + movl %ecx,24(%esp) + movl %ebp,28(%esp) +.byte 102,15,58,22,251,3 +.byte 102,15,58,34,253,3 + movl 240(%edx),%ecx + bswap %ebx + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + movdqa (%esp),%xmm2 +.byte 102,15,58,34,195,0 + leal 3(%ebx),%ebp +.byte 102,15,58,34,205,0 + incl %ebx +.byte 102,15,58,34,195,1 + incl %ebp +.byte 102,15,58,34,205,1 + incl %ebx +.byte 102,15,58,34,195,2 + incl %ebp +.byte 102,15,58,34,205,2 + movdqa %xmm0,48(%esp) +.byte 102,15,56,0,194 + movdqu (%edx),%xmm6 + movdqa %xmm1,64(%esp) +.byte 102,15,56,0,202 + pshufd $192,%xmm0,%xmm2 + pshufd $128,%xmm0,%xmm3 + cmpl $6,%eax + jb .L038ctr32_tail + pxor %xmm6,%xmm7 + shll $4,%ecx + movl $16,%ebx + movdqa %xmm7,32(%esp) + movl %edx,%ebp + subl %ecx,%ebx + leal 32(%edx,%ecx,1),%edx + subl $6,%eax + jmp .L039ctr32_loop6 +.align 16 +.L039ctr32_loop6: + pshufd $64,%xmm0,%xmm4 + movdqa 32(%esp),%xmm0 + pshufd $192,%xmm1,%xmm5 + pxor %xmm0,%xmm2 + pshufd $128,%xmm1,%xmm6 + pxor %xmm0,%xmm3 + pshufd $64,%xmm1,%xmm7 + movups 16(%ebp),%xmm1 + pxor %xmm0,%xmm4 + pxor %xmm0,%xmm5 +.byte 102,15,56,220,209 + pxor %xmm0,%xmm6 + pxor %xmm0,%xmm7 +.byte 102,15,56,220,217 + movups 32(%ebp),%xmm0 + movl %ebx,%ecx +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 + call .L_aesni_encrypt6_enter + movups (%esi),%xmm1 + movups 16(%esi),%xmm0 + xorps %xmm1,%xmm2 + movups 32(%esi),%xmm1 + xorps %xmm0,%xmm3 + movups %xmm2,(%edi) + movdqa 16(%esp),%xmm0 + xorps %xmm1,%xmm4 + movdqa 64(%esp),%xmm1 + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + paddd %xmm0,%xmm1 + paddd 48(%esp),%xmm0 + movdqa (%esp),%xmm2 + movups 48(%esi),%xmm3 + movups 64(%esi),%xmm4 + xorps %xmm3,%xmm5 + movups 80(%esi),%xmm3 + leal 96(%esi),%esi + movdqa %xmm0,48(%esp) +.byte 102,15,56,0,194 + xorps %xmm4,%xmm6 + movups %xmm5,48(%edi) + xorps %xmm3,%xmm7 + movdqa %xmm1,64(%esp) +.byte 102,15,56,0,202 + movups %xmm6,64(%edi) + pshufd $192,%xmm0,%xmm2 + movups %xmm7,80(%edi) + leal 96(%edi),%edi + pshufd $128,%xmm0,%xmm3 + subl $6,%eax + jnc .L039ctr32_loop6 + addl $6,%eax + jz .L040ctr32_ret + movdqu (%ebp),%xmm7 + movl %ebp,%edx + pxor 32(%esp),%xmm7 + movl 240(%ebp),%ecx +.L038ctr32_tail: + por %xmm7,%xmm2 + cmpl $2,%eax + jb .L041ctr32_one + pshufd $64,%xmm0,%xmm4 + por %xmm7,%xmm3 + je .L042ctr32_two + pshufd $192,%xmm1,%xmm5 + por %xmm7,%xmm4 + cmpl $4,%eax + jb .L043ctr32_three + pshufd $128,%xmm1,%xmm6 + por %xmm7,%xmm5 + je .L044ctr32_four + por %xmm7,%xmm6 + call _aesni_encrypt6 + movups (%esi),%xmm1 + movups 16(%esi),%xmm0 + xorps %xmm1,%xmm2 + movups 32(%esi),%xmm1 + xorps %xmm0,%xmm3 + movups 48(%esi),%xmm0 + xorps %xmm1,%xmm4 + movups 64(%esi),%xmm1 + xorps %xmm0,%xmm5 + movups %xmm2,(%edi) + xorps %xmm1,%xmm6 + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + jmp .L040ctr32_ret +.align 16 +.L037ctr32_one_shortcut: + movups (%ebx),%xmm2 + movl 240(%edx),%ecx +.L041ctr32_one: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L045enc1_loop_7: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L045enc1_loop_7 +.byte 102,15,56,221,209 + movups (%esi),%xmm6 + xorps %xmm2,%xmm6 + movups %xmm6,(%edi) + jmp .L040ctr32_ret +.align 16 +.L042ctr32_two: + call _aesni_encrypt2 + movups (%esi),%xmm5 + movups 16(%esi),%xmm6 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + jmp .L040ctr32_ret +.align 16 +.L043ctr32_three: + call _aesni_encrypt3 + movups (%esi),%xmm5 + movups 16(%esi),%xmm6 + xorps %xmm5,%xmm2 + movups 32(%esi),%xmm7 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + xorps %xmm7,%xmm4 + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + jmp .L040ctr32_ret +.align 16 +.L044ctr32_four: + call _aesni_encrypt4 + movups (%esi),%xmm6 + movups 16(%esi),%xmm7 + movups 32(%esi),%xmm1 + xorps %xmm6,%xmm2 + movups 48(%esi),%xmm0 + xorps %xmm7,%xmm3 + movups %xmm2,(%edi) + xorps %xmm1,%xmm4 + movups %xmm3,16(%edi) + xorps %xmm0,%xmm5 + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) +.L040ctr32_ret: + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + movdqa %xmm0,32(%esp) + pxor %xmm5,%xmm5 + movdqa %xmm0,48(%esp) + pxor %xmm6,%xmm6 + movdqa %xmm0,64(%esp) + pxor %xmm7,%xmm7 + movl 80(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ctr32_encrypt_blocks,.-.L_aesni_ctr32_encrypt_blocks_begin +.globl aesni_xts_encrypt +.type aesni_xts_encrypt,@function +.align 16 +aesni_xts_encrypt: +.L_aesni_xts_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 36(%esp),%edx + movl 40(%esp),%esi + movl 240(%edx),%ecx + movups (%esi),%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L046enc1_loop_8: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L046enc1_loop_8 +.byte 102,15,56,221,209 + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl %esp,%ebp + subl $120,%esp + movl 240(%edx),%ecx + andl $-16,%esp + movl $135,96(%esp) + movl $0,100(%esp) + movl $1,104(%esp) + movl $0,108(%esp) + movl %eax,112(%esp) + movl %ebp,116(%esp) + movdqa %xmm2,%xmm1 + pxor %xmm0,%xmm0 + movdqa 96(%esp),%xmm3 + pcmpgtd %xmm1,%xmm0 + andl $-16,%eax + movl %edx,%ebp + movl %ecx,%ebx + subl $96,%eax + jc .L047xts_enc_short + shll $4,%ecx + movl $16,%ebx + subl %ecx,%ebx + leal 32(%edx,%ecx,1),%edx + jmp .L048xts_enc_loop6 +.align 16 +.L048xts_enc_loop6: + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,16(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,32(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,48(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm7 + movdqa %xmm1,64(%esp) + paddq %xmm1,%xmm1 + movups (%ebp),%xmm0 + pand %xmm3,%xmm7 + movups (%esi),%xmm2 + pxor %xmm1,%xmm7 + movl %ebx,%ecx + movdqu 16(%esi),%xmm3 + xorps %xmm0,%xmm2 + movdqu 32(%esi),%xmm4 + pxor %xmm0,%xmm3 + movdqu 48(%esi),%xmm5 + pxor %xmm0,%xmm4 + movdqu 64(%esi),%xmm6 + pxor %xmm0,%xmm5 + movdqu 80(%esi),%xmm1 + pxor %xmm0,%xmm6 + leal 96(%esi),%esi + pxor (%esp),%xmm2 + movdqa %xmm7,80(%esp) + pxor %xmm1,%xmm7 + movups 16(%ebp),%xmm1 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 +.byte 102,15,56,220,209 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 +.byte 102,15,56,220,217 + pxor %xmm0,%xmm7 + movups 32(%ebp),%xmm0 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 + call .L_aesni_encrypt6_enter + movdqa 80(%esp),%xmm1 + pxor %xmm0,%xmm0 + xorps (%esp),%xmm2 + pcmpgtd %xmm1,%xmm0 + xorps 16(%esp),%xmm3 + movups %xmm2,(%edi) + xorps 32(%esp),%xmm4 + movups %xmm3,16(%edi) + xorps 48(%esp),%xmm5 + movups %xmm4,32(%edi) + xorps 64(%esp),%xmm6 + movups %xmm5,48(%edi) + xorps %xmm1,%xmm7 + movups %xmm6,64(%edi) + pshufd $19,%xmm0,%xmm2 + movups %xmm7,80(%edi) + leal 96(%edi),%edi + movdqa 96(%esp),%xmm3 + pxor %xmm0,%xmm0 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + subl $96,%eax + jnc .L048xts_enc_loop6 + movl 240(%ebp),%ecx + movl %ebp,%edx + movl %ecx,%ebx +.L047xts_enc_short: + addl $96,%eax + jz .L049xts_enc_done6x + movdqa %xmm1,%xmm5 + cmpl $32,%eax + jb .L050xts_enc_one + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + je .L051xts_enc_two + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,%xmm6 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + cmpl $64,%eax + jb .L052xts_enc_three + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,%xmm7 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + movdqa %xmm5,(%esp) + movdqa %xmm6,16(%esp) + je .L053xts_enc_four + movdqa %xmm7,32(%esp) + pshufd $19,%xmm0,%xmm7 + movdqa %xmm1,48(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm7 + pxor %xmm1,%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + pxor (%esp),%xmm2 + movdqu 48(%esi),%xmm5 + pxor 16(%esp),%xmm3 + movdqu 64(%esi),%xmm6 + pxor 32(%esp),%xmm4 + leal 80(%esi),%esi + pxor 48(%esp),%xmm5 + movdqa %xmm7,64(%esp) + pxor %xmm7,%xmm6 + call _aesni_encrypt6 + movaps 64(%esp),%xmm1 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps 32(%esp),%xmm4 + movups %xmm2,(%edi) + xorps 48(%esp),%xmm5 + movups %xmm3,16(%edi) + xorps %xmm1,%xmm6 + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + leal 80(%edi),%edi + jmp .L054xts_enc_done +.align 16 +.L050xts_enc_one: + movups (%esi),%xmm2 + leal 16(%esi),%esi + xorps %xmm5,%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L055enc1_loop_9: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L055enc1_loop_9 +.byte 102,15,56,221,209 + xorps %xmm5,%xmm2 + movups %xmm2,(%edi) + leal 16(%edi),%edi + movdqa %xmm5,%xmm1 + jmp .L054xts_enc_done +.align 16 +.L051xts_enc_two: + movaps %xmm1,%xmm6 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + leal 32(%esi),%esi + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + call _aesni_encrypt2 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + leal 32(%edi),%edi + movdqa %xmm6,%xmm1 + jmp .L054xts_enc_done +.align 16 +.L052xts_enc_three: + movaps %xmm1,%xmm7 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + movups 32(%esi),%xmm4 + leal 48(%esi),%esi + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + call _aesni_encrypt3 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + leal 48(%edi),%edi + movdqa %xmm7,%xmm1 + jmp .L054xts_enc_done +.align 16 +.L053xts_enc_four: + movaps %xmm1,%xmm6 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + movups 32(%esi),%xmm4 + xorps (%esp),%xmm2 + movups 48(%esi),%xmm5 + leal 64(%esi),%esi + xorps 16(%esp),%xmm3 + xorps %xmm7,%xmm4 + xorps %xmm6,%xmm5 + call _aesni_encrypt4 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps %xmm7,%xmm4 + movups %xmm2,(%edi) + xorps %xmm6,%xmm5 + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + leal 64(%edi),%edi + movdqa %xmm6,%xmm1 + jmp .L054xts_enc_done +.align 16 +.L049xts_enc_done6x: + movl 112(%esp),%eax + andl $15,%eax + jz .L056xts_enc_ret + movdqa %xmm1,%xmm5 + movl %eax,112(%esp) + jmp .L057xts_enc_steal +.align 16 +.L054xts_enc_done: + movl 112(%esp),%eax + pxor %xmm0,%xmm0 + andl $15,%eax + jz .L056xts_enc_ret + pcmpgtd %xmm1,%xmm0 + movl %eax,112(%esp) + pshufd $19,%xmm0,%xmm5 + paddq %xmm1,%xmm1 + pand 96(%esp),%xmm5 + pxor %xmm1,%xmm5 +.L057xts_enc_steal: + movzbl (%esi),%ecx + movzbl -16(%edi),%edx + leal 1(%esi),%esi + movb %cl,-16(%edi) + movb %dl,(%edi) + leal 1(%edi),%edi + subl $1,%eax + jnz .L057xts_enc_steal + subl 112(%esp),%edi + movl %ebp,%edx + movl %ebx,%ecx + movups -16(%edi),%xmm2 + xorps %xmm5,%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L058enc1_loop_10: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L058enc1_loop_10 +.byte 102,15,56,221,209 + xorps %xmm5,%xmm2 + movups %xmm2,-16(%edi) +.L056xts_enc_ret: + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + movdqa %xmm0,(%esp) + pxor %xmm3,%xmm3 + movdqa %xmm0,16(%esp) + pxor %xmm4,%xmm4 + movdqa %xmm0,32(%esp) + pxor %xmm5,%xmm5 + movdqa %xmm0,48(%esp) + pxor %xmm6,%xmm6 + movdqa %xmm0,64(%esp) + pxor %xmm7,%xmm7 + movdqa %xmm0,80(%esp) + movl 116(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_xts_encrypt,.-.L_aesni_xts_encrypt_begin +.globl aesni_xts_decrypt +.type aesni_xts_decrypt,@function +.align 16 +aesni_xts_decrypt: +.L_aesni_xts_decrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 36(%esp),%edx + movl 40(%esp),%esi + movl 240(%edx),%ecx + movups (%esi),%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L059enc1_loop_11: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L059enc1_loop_11 +.byte 102,15,56,221,209 + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movl %esp,%ebp + subl $120,%esp + andl $-16,%esp + xorl %ebx,%ebx + testl $15,%eax + setnz %bl + shll $4,%ebx + subl %ebx,%eax + movl $135,96(%esp) + movl $0,100(%esp) + movl $1,104(%esp) + movl $0,108(%esp) + movl %eax,112(%esp) + movl %ebp,116(%esp) + movl 240(%edx),%ecx + movl %edx,%ebp + movl %ecx,%ebx + movdqa %xmm2,%xmm1 + pxor %xmm0,%xmm0 + movdqa 96(%esp),%xmm3 + pcmpgtd %xmm1,%xmm0 + andl $-16,%eax + subl $96,%eax + jc .L060xts_dec_short + shll $4,%ecx + movl $16,%ebx + subl %ecx,%ebx + leal 32(%edx,%ecx,1),%edx + jmp .L061xts_dec_loop6 +.align 16 +.L061xts_dec_loop6: + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,16(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,32(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,48(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + pshufd $19,%xmm0,%xmm7 + movdqa %xmm1,64(%esp) + paddq %xmm1,%xmm1 + movups (%ebp),%xmm0 + pand %xmm3,%xmm7 + movups (%esi),%xmm2 + pxor %xmm1,%xmm7 + movl %ebx,%ecx + movdqu 16(%esi),%xmm3 + xorps %xmm0,%xmm2 + movdqu 32(%esi),%xmm4 + pxor %xmm0,%xmm3 + movdqu 48(%esi),%xmm5 + pxor %xmm0,%xmm4 + movdqu 64(%esi),%xmm6 + pxor %xmm0,%xmm5 + movdqu 80(%esi),%xmm1 + pxor %xmm0,%xmm6 + leal 96(%esi),%esi + pxor (%esp),%xmm2 + movdqa %xmm7,80(%esp) + pxor %xmm1,%xmm7 + movups 16(%ebp),%xmm1 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 +.byte 102,15,56,222,209 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 +.byte 102,15,56,222,217 + pxor %xmm0,%xmm7 + movups 32(%ebp),%xmm0 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 +.byte 102,15,56,222,241 +.byte 102,15,56,222,249 + call .L_aesni_decrypt6_enter + movdqa 80(%esp),%xmm1 + pxor %xmm0,%xmm0 + xorps (%esp),%xmm2 + pcmpgtd %xmm1,%xmm0 + xorps 16(%esp),%xmm3 + movups %xmm2,(%edi) + xorps 32(%esp),%xmm4 + movups %xmm3,16(%edi) + xorps 48(%esp),%xmm5 + movups %xmm4,32(%edi) + xorps 64(%esp),%xmm6 + movups %xmm5,48(%edi) + xorps %xmm1,%xmm7 + movups %xmm6,64(%edi) + pshufd $19,%xmm0,%xmm2 + movups %xmm7,80(%edi) + leal 96(%edi),%edi + movdqa 96(%esp),%xmm3 + pxor %xmm0,%xmm0 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + subl $96,%eax + jnc .L061xts_dec_loop6 + movl 240(%ebp),%ecx + movl %ebp,%edx + movl %ecx,%ebx +.L060xts_dec_short: + addl $96,%eax + jz .L062xts_dec_done6x + movdqa %xmm1,%xmm5 + cmpl $32,%eax + jb .L063xts_dec_one + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + je .L064xts_dec_two + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,%xmm6 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + cmpl $64,%eax + jb .L065xts_dec_three + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa %xmm1,%xmm7 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 + movdqa %xmm5,(%esp) + movdqa %xmm6,16(%esp) + je .L066xts_dec_four + movdqa %xmm7,32(%esp) + pshufd $19,%xmm0,%xmm7 + movdqa %xmm1,48(%esp) + paddq %xmm1,%xmm1 + pand %xmm3,%xmm7 + pxor %xmm1,%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + pxor (%esp),%xmm2 + movdqu 48(%esi),%xmm5 + pxor 16(%esp),%xmm3 + movdqu 64(%esi),%xmm6 + pxor 32(%esp),%xmm4 + leal 80(%esi),%esi + pxor 48(%esp),%xmm5 + movdqa %xmm7,64(%esp) + pxor %xmm7,%xmm6 + call _aesni_decrypt6 + movaps 64(%esp),%xmm1 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps 32(%esp),%xmm4 + movups %xmm2,(%edi) + xorps 48(%esp),%xmm5 + movups %xmm3,16(%edi) + xorps %xmm1,%xmm6 + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + movups %xmm6,64(%edi) + leal 80(%edi),%edi + jmp .L067xts_dec_done +.align 16 +.L063xts_dec_one: + movups (%esi),%xmm2 + leal 16(%esi),%esi + xorps %xmm5,%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L068dec1_loop_12: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L068dec1_loop_12 +.byte 102,15,56,223,209 + xorps %xmm5,%xmm2 + movups %xmm2,(%edi) + leal 16(%edi),%edi + movdqa %xmm5,%xmm1 + jmp .L067xts_dec_done +.align 16 +.L064xts_dec_two: + movaps %xmm1,%xmm6 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + leal 32(%esi),%esi + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + call _aesni_decrypt2 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + leal 32(%edi),%edi + movdqa %xmm6,%xmm1 + jmp .L067xts_dec_done +.align 16 +.L065xts_dec_three: + movaps %xmm1,%xmm7 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + movups 32(%esi),%xmm4 + leal 48(%esi),%esi + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + call _aesni_decrypt3 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + leal 48(%edi),%edi + movdqa %xmm7,%xmm1 + jmp .L067xts_dec_done +.align 16 +.L066xts_dec_four: + movaps %xmm1,%xmm6 + movups (%esi),%xmm2 + movups 16(%esi),%xmm3 + movups 32(%esi),%xmm4 + xorps (%esp),%xmm2 + movups 48(%esi),%xmm5 + leal 64(%esi),%esi + xorps 16(%esp),%xmm3 + xorps %xmm7,%xmm4 + xorps %xmm6,%xmm5 + call _aesni_decrypt4 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps %xmm7,%xmm4 + movups %xmm2,(%edi) + xorps %xmm6,%xmm5 + movups %xmm3,16(%edi) + movups %xmm4,32(%edi) + movups %xmm5,48(%edi) + leal 64(%edi),%edi + movdqa %xmm6,%xmm1 + jmp .L067xts_dec_done +.align 16 +.L062xts_dec_done6x: + movl 112(%esp),%eax + andl $15,%eax + jz .L069xts_dec_ret + movl %eax,112(%esp) + jmp .L070xts_dec_only_one_more +.align 16 +.L067xts_dec_done: + movl 112(%esp),%eax + pxor %xmm0,%xmm0 + andl $15,%eax + jz .L069xts_dec_ret + pcmpgtd %xmm1,%xmm0 + movl %eax,112(%esp) + pshufd $19,%xmm0,%xmm2 + pxor %xmm0,%xmm0 + movdqa 96(%esp),%xmm3 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm2 + pcmpgtd %xmm1,%xmm0 + pxor %xmm2,%xmm1 +.L070xts_dec_only_one_more: + pshufd $19,%xmm0,%xmm5 + movdqa %xmm1,%xmm6 + paddq %xmm1,%xmm1 + pand %xmm3,%xmm5 + pxor %xmm1,%xmm5 + movl %ebp,%edx + movl %ebx,%ecx + movups (%esi),%xmm2 + xorps %xmm5,%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L071dec1_loop_13: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L071dec1_loop_13 +.byte 102,15,56,223,209 + xorps %xmm5,%xmm2 + movups %xmm2,(%edi) +.L072xts_dec_steal: + movzbl 16(%esi),%ecx + movzbl (%edi),%edx + leal 1(%esi),%esi + movb %cl,(%edi) + movb %dl,16(%edi) + leal 1(%edi),%edi + subl $1,%eax + jnz .L072xts_dec_steal + subl 112(%esp),%edi + movl %ebp,%edx + movl %ebx,%ecx + movups (%edi),%xmm2 + xorps %xmm6,%xmm2 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L073dec1_loop_14: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L073dec1_loop_14 +.byte 102,15,56,223,209 + xorps %xmm6,%xmm2 + movups %xmm2,(%edi) +.L069xts_dec_ret: + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + movdqa %xmm0,(%esp) + pxor %xmm3,%xmm3 + movdqa %xmm0,16(%esp) + pxor %xmm4,%xmm4 + movdqa %xmm0,32(%esp) + pxor %xmm5,%xmm5 + movdqa %xmm0,48(%esp) + pxor %xmm6,%xmm6 + movdqa %xmm0,64(%esp) + pxor %xmm7,%xmm7 + movdqa %xmm0,80(%esp) + movl 116(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_xts_decrypt,.-.L_aesni_xts_decrypt_begin +.globl aesni_ocb_encrypt +.type aesni_ocb_encrypt,@function +.align 16 +aesni_ocb_encrypt: +.L_aesni_ocb_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 40(%esp),%ecx + movl 48(%esp),%ebx + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movdqu (%ecx),%xmm0 + movl 36(%esp),%ebp + movdqu (%ebx),%xmm1 + movl 44(%esp),%ebx + movl %esp,%ecx + subl $132,%esp + andl $-16,%esp + subl %esi,%edi + shll $4,%eax + leal -96(%esi,%eax,1),%eax + movl %edi,120(%esp) + movl %eax,124(%esp) + movl %ecx,128(%esp) + movl 240(%edx),%ecx + testl $1,%ebp + jnz .L074odd + bsfl %ebp,%eax + addl $1,%ebp + shll $4,%eax + movdqu (%ebx,%eax,1),%xmm7 + movl %edx,%eax + movdqu (%esi),%xmm2 + leal 16(%esi),%esi + pxor %xmm0,%xmm7 + pxor %xmm2,%xmm1 + pxor %xmm7,%xmm2 + movdqa %xmm1,%xmm6 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L075enc1_loop_15: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L075enc1_loop_15 +.byte 102,15,56,221,209 + xorps %xmm7,%xmm2 + movdqa %xmm7,%xmm0 + movdqa %xmm6,%xmm1 + movups %xmm2,-16(%edi,%esi,1) + movl 240(%eax),%ecx + movl %eax,%edx + movl 124(%esp),%eax +.L074odd: + shll $4,%ecx + movl $16,%edi + subl %ecx,%edi + movl %edx,112(%esp) + leal 32(%edx,%ecx,1),%edx + movl %edi,116(%esp) + cmpl %eax,%esi + ja .L076short + jmp .L077grandloop +.align 32 +.L077grandloop: + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + leal 5(%ebp),%edi + addl $6,%ebp + bsfl %ecx,%ecx + bsfl %eax,%eax + bsfl %edi,%edi + shll $4,%ecx + shll $4,%eax + shll $4,%edi + movdqu (%ebx),%xmm2 + movdqu (%ebx,%ecx,1),%xmm3 + movl 116(%esp),%ecx + movdqa %xmm2,%xmm4 + movdqu (%ebx,%eax,1),%xmm5 + movdqa %xmm2,%xmm6 + movdqu (%ebx,%edi,1),%xmm7 + pxor %xmm0,%xmm2 + pxor %xmm2,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm3,%xmm4 + movdqa %xmm3,16(%esp) + pxor %xmm4,%xmm5 + movdqa %xmm4,32(%esp) + pxor %xmm5,%xmm6 + movdqa %xmm5,48(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm6,64(%esp) + movdqa %xmm7,80(%esp) + movups -48(%edx,%ecx,1),%xmm0 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi + pxor %xmm2,%xmm1 + pxor %xmm0,%xmm2 + pxor %xmm3,%xmm1 + pxor %xmm0,%xmm3 + pxor %xmm4,%xmm1 + pxor %xmm0,%xmm4 + pxor %xmm5,%xmm1 + pxor %xmm0,%xmm5 + pxor %xmm6,%xmm1 + pxor %xmm0,%xmm6 + pxor %xmm7,%xmm1 + pxor %xmm0,%xmm7 + movdqa %xmm1,96(%esp) + movups -32(%edx,%ecx,1),%xmm1 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + pxor 80(%esp),%xmm7 + movups -16(%edx,%ecx,1),%xmm0 +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 + movl 120(%esp),%edi + movl 124(%esp),%eax + call .L_aesni_encrypt6_enter + movdqa 80(%esp),%xmm0 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + pxor %xmm0,%xmm7 + movdqa 96(%esp),%xmm1 + movdqu %xmm2,-96(%edi,%esi,1) + movdqu %xmm3,-80(%edi,%esi,1) + movdqu %xmm4,-64(%edi,%esi,1) + movdqu %xmm5,-48(%edi,%esi,1) + movdqu %xmm6,-32(%edi,%esi,1) + movdqu %xmm7,-16(%edi,%esi,1) + cmpl %eax,%esi + jb .L077grandloop +.L076short: + addl $96,%eax + subl %esi,%eax + jz .L078done + cmpl $32,%eax + jb .L079one + je .L080two + cmpl $64,%eax + jb .L081three + je .L082four + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + bsfl %ecx,%ecx + bsfl %eax,%eax + shll $4,%ecx + shll $4,%eax + movdqu (%ebx),%xmm2 + movdqu (%ebx,%ecx,1),%xmm3 + movl 116(%esp),%ecx + movdqa %xmm2,%xmm4 + movdqu (%ebx,%eax,1),%xmm5 + movdqa %xmm2,%xmm6 + pxor %xmm0,%xmm2 + pxor %xmm2,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm3,%xmm4 + movdqa %xmm3,16(%esp) + pxor %xmm4,%xmm5 + movdqa %xmm4,32(%esp) + pxor %xmm5,%xmm6 + movdqa %xmm5,48(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm6,64(%esp) + movups -48(%edx,%ecx,1),%xmm0 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + pxor %xmm7,%xmm7 + pxor %xmm2,%xmm1 + pxor %xmm0,%xmm2 + pxor %xmm3,%xmm1 + pxor %xmm0,%xmm3 + pxor %xmm4,%xmm1 + pxor %xmm0,%xmm4 + pxor %xmm5,%xmm1 + pxor %xmm0,%xmm5 + pxor %xmm6,%xmm1 + pxor %xmm0,%xmm6 + movdqa %xmm1,96(%esp) + movups -32(%edx,%ecx,1),%xmm1 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + movups -16(%edx,%ecx,1),%xmm0 +.byte 102,15,56,220,209 +.byte 102,15,56,220,217 +.byte 102,15,56,220,225 +.byte 102,15,56,220,233 +.byte 102,15,56,220,241 +.byte 102,15,56,220,249 + movl 120(%esp),%edi + call .L_aesni_encrypt6_enter + movdqa 64(%esp),%xmm0 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor %xmm0,%xmm6 + movdqa 96(%esp),%xmm1 + movdqu %xmm2,(%edi,%esi,1) + movdqu %xmm3,16(%edi,%esi,1) + movdqu %xmm4,32(%edi,%esi,1) + movdqu %xmm5,48(%edi,%esi,1) + movdqu %xmm6,64(%edi,%esi,1) + jmp .L078done +.align 16 +.L079one: + movdqu (%ebx),%xmm7 + movl 112(%esp),%edx + movdqu (%esi),%xmm2 + movl 240(%edx),%ecx + pxor %xmm0,%xmm7 + pxor %xmm2,%xmm1 + pxor %xmm7,%xmm2 + movdqa %xmm1,%xmm6 + movl 120(%esp),%edi + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L083enc1_loop_16: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L083enc1_loop_16 +.byte 102,15,56,221,209 + xorps %xmm7,%xmm2 + movdqa %xmm7,%xmm0 + movdqa %xmm6,%xmm1 + movups %xmm2,(%edi,%esi,1) + jmp .L078done +.align 16 +.L080two: + leal 1(%ebp),%ecx + movl 112(%esp),%edx + bsfl %ecx,%ecx + shll $4,%ecx + movdqu (%ebx),%xmm6 + movdqu (%ebx,%ecx,1),%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movl 240(%edx),%ecx + pxor %xmm0,%xmm6 + pxor %xmm6,%xmm7 + pxor %xmm2,%xmm1 + pxor %xmm6,%xmm2 + pxor %xmm3,%xmm1 + pxor %xmm7,%xmm3 + movdqa %xmm1,%xmm5 + movl 120(%esp),%edi + call _aesni_encrypt2 + xorps %xmm6,%xmm2 + xorps %xmm7,%xmm3 + movdqa %xmm7,%xmm0 + movdqa %xmm5,%xmm1 + movups %xmm2,(%edi,%esi,1) + movups %xmm3,16(%edi,%esi,1) + jmp .L078done +.align 16 +.L081three: + leal 1(%ebp),%ecx + movl 112(%esp),%edx + bsfl %ecx,%ecx + shll $4,%ecx + movdqu (%ebx),%xmm5 + movdqu (%ebx,%ecx,1),%xmm6 + movdqa %xmm5,%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movl 240(%edx),%ecx + pxor %xmm0,%xmm5 + pxor %xmm5,%xmm6 + pxor %xmm6,%xmm7 + pxor %xmm2,%xmm1 + pxor %xmm5,%xmm2 + pxor %xmm3,%xmm1 + pxor %xmm6,%xmm3 + pxor %xmm4,%xmm1 + pxor %xmm7,%xmm4 + movdqa %xmm1,96(%esp) + movl 120(%esp),%edi + call _aesni_encrypt3 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + movdqa %xmm7,%xmm0 + movdqa 96(%esp),%xmm1 + movups %xmm2,(%edi,%esi,1) + movups %xmm3,16(%edi,%esi,1) + movups %xmm4,32(%edi,%esi,1) + jmp .L078done +.align 16 +.L082four: + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + bsfl %ecx,%ecx + bsfl %eax,%eax + movl 112(%esp),%edx + shll $4,%ecx + shll $4,%eax + movdqu (%ebx),%xmm4 + movdqu (%ebx,%ecx,1),%xmm5 + movdqa %xmm4,%xmm6 + movdqu (%ebx,%eax,1),%xmm7 + pxor %xmm0,%xmm4 + movdqu (%esi),%xmm2 + pxor %xmm4,%xmm5 + movdqu 16(%esi),%xmm3 + pxor %xmm5,%xmm6 + movdqa %xmm4,(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm5,16(%esp) + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movl 240(%edx),%ecx + pxor %xmm2,%xmm1 + pxor (%esp),%xmm2 + pxor %xmm3,%xmm1 + pxor 16(%esp),%xmm3 + pxor %xmm4,%xmm1 + pxor %xmm6,%xmm4 + pxor %xmm5,%xmm1 + pxor %xmm7,%xmm5 + movdqa %xmm1,96(%esp) + movl 120(%esp),%edi + call _aesni_encrypt4 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps %xmm6,%xmm4 + movups %xmm2,(%edi,%esi,1) + xorps %xmm7,%xmm5 + movups %xmm3,16(%edi,%esi,1) + movdqa %xmm7,%xmm0 + movups %xmm4,32(%edi,%esi,1) + movdqa 96(%esp),%xmm1 + movups %xmm5,48(%edi,%esi,1) +.L078done: + movl 128(%esp),%edx + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm4,%xmm4 + movdqa %xmm2,16(%esp) + pxor %xmm5,%xmm5 + movdqa %xmm2,32(%esp) + pxor %xmm6,%xmm6 + movdqa %xmm2,48(%esp) + pxor %xmm7,%xmm7 + movdqa %xmm2,64(%esp) + movdqa %xmm2,80(%esp) + movdqa %xmm2,96(%esp) + leal (%edx),%esp + movl 40(%esp),%ecx + movl 48(%esp),%ebx + movdqu %xmm0,(%ecx) + pxor %xmm0,%xmm0 + movdqu %xmm1,(%ebx) + pxor %xmm1,%xmm1 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ocb_encrypt,.-.L_aesni_ocb_encrypt_begin +.globl aesni_ocb_decrypt +.type aesni_ocb_decrypt,@function +.align 16 +aesni_ocb_decrypt: +.L_aesni_ocb_decrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 40(%esp),%ecx + movl 48(%esp),%ebx + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + movdqu (%ecx),%xmm0 + movl 36(%esp),%ebp + movdqu (%ebx),%xmm1 + movl 44(%esp),%ebx + movl %esp,%ecx + subl $132,%esp + andl $-16,%esp + subl %esi,%edi + shll $4,%eax + leal -96(%esi,%eax,1),%eax + movl %edi,120(%esp) + movl %eax,124(%esp) + movl %ecx,128(%esp) + movl 240(%edx),%ecx + testl $1,%ebp + jnz .L084odd + bsfl %ebp,%eax + addl $1,%ebp + shll $4,%eax + movdqu (%ebx,%eax,1),%xmm7 + movl %edx,%eax + movdqu (%esi),%xmm2 + leal 16(%esi),%esi + pxor %xmm0,%xmm7 + pxor %xmm7,%xmm2 + movdqa %xmm1,%xmm6 + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L085dec1_loop_17: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L085dec1_loop_17 +.byte 102,15,56,223,209 + xorps %xmm7,%xmm2 + movaps %xmm6,%xmm1 + movdqa %xmm7,%xmm0 + xorps %xmm2,%xmm1 + movups %xmm2,-16(%edi,%esi,1) + movl 240(%eax),%ecx + movl %eax,%edx + movl 124(%esp),%eax +.L084odd: + shll $4,%ecx + movl $16,%edi + subl %ecx,%edi + movl %edx,112(%esp) + leal 32(%edx,%ecx,1),%edx + movl %edi,116(%esp) + cmpl %eax,%esi + ja .L086short + jmp .L087grandloop +.align 32 +.L087grandloop: + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + leal 5(%ebp),%edi + addl $6,%ebp + bsfl %ecx,%ecx + bsfl %eax,%eax + bsfl %edi,%edi + shll $4,%ecx + shll $4,%eax + shll $4,%edi + movdqu (%ebx),%xmm2 + movdqu (%ebx,%ecx,1),%xmm3 + movl 116(%esp),%ecx + movdqa %xmm2,%xmm4 + movdqu (%ebx,%eax,1),%xmm5 + movdqa %xmm2,%xmm6 + movdqu (%ebx,%edi,1),%xmm7 + pxor %xmm0,%xmm2 + pxor %xmm2,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm3,%xmm4 + movdqa %xmm3,16(%esp) + pxor %xmm4,%xmm5 + movdqa %xmm4,32(%esp) + pxor %xmm5,%xmm6 + movdqa %xmm5,48(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm6,64(%esp) + movdqa %xmm7,80(%esp) + movups -48(%edx,%ecx,1),%xmm0 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + movdqu 80(%esi),%xmm7 + leal 96(%esi),%esi + movdqa %xmm1,96(%esp) + pxor %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + pxor %xmm0,%xmm5 + pxor %xmm0,%xmm6 + pxor %xmm0,%xmm7 + movups -32(%edx,%ecx,1),%xmm1 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + pxor 80(%esp),%xmm7 + movups -16(%edx,%ecx,1),%xmm0 +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 +.byte 102,15,56,222,241 +.byte 102,15,56,222,249 + movl 120(%esp),%edi + movl 124(%esp),%eax + call .L_aesni_decrypt6_enter + movdqa 80(%esp),%xmm0 + pxor (%esp),%xmm2 + movdqa 96(%esp),%xmm1 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + pxor %xmm0,%xmm7 + pxor %xmm2,%xmm1 + movdqu %xmm2,-96(%edi,%esi,1) + pxor %xmm3,%xmm1 + movdqu %xmm3,-80(%edi,%esi,1) + pxor %xmm4,%xmm1 + movdqu %xmm4,-64(%edi,%esi,1) + pxor %xmm5,%xmm1 + movdqu %xmm5,-48(%edi,%esi,1) + pxor %xmm6,%xmm1 + movdqu %xmm6,-32(%edi,%esi,1) + pxor %xmm7,%xmm1 + movdqu %xmm7,-16(%edi,%esi,1) + cmpl %eax,%esi + jb .L087grandloop +.L086short: + addl $96,%eax + subl %esi,%eax + jz .L088done + cmpl $32,%eax + jb .L089one + je .L090two + cmpl $64,%eax + jb .L091three + je .L092four + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + bsfl %ecx,%ecx + bsfl %eax,%eax + shll $4,%ecx + shll $4,%eax + movdqu (%ebx),%xmm2 + movdqu (%ebx,%ecx,1),%xmm3 + movl 116(%esp),%ecx + movdqa %xmm2,%xmm4 + movdqu (%ebx,%eax,1),%xmm5 + movdqa %xmm2,%xmm6 + pxor %xmm0,%xmm2 + pxor %xmm2,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm3,%xmm4 + movdqa %xmm3,16(%esp) + pxor %xmm4,%xmm5 + movdqa %xmm4,32(%esp) + pxor %xmm5,%xmm6 + movdqa %xmm5,48(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm6,64(%esp) + movups -48(%edx,%ecx,1),%xmm0 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + pxor %xmm7,%xmm7 + movdqa %xmm1,96(%esp) + pxor %xmm0,%xmm2 + pxor %xmm0,%xmm3 + pxor %xmm0,%xmm4 + pxor %xmm0,%xmm5 + pxor %xmm0,%xmm6 + movups -32(%edx,%ecx,1),%xmm1 + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor 64(%esp),%xmm6 + movups -16(%edx,%ecx,1),%xmm0 +.byte 102,15,56,222,209 +.byte 102,15,56,222,217 +.byte 102,15,56,222,225 +.byte 102,15,56,222,233 +.byte 102,15,56,222,241 +.byte 102,15,56,222,249 + movl 120(%esp),%edi + call .L_aesni_decrypt6_enter + movdqa 64(%esp),%xmm0 + pxor (%esp),%xmm2 + movdqa 96(%esp),%xmm1 + pxor 16(%esp),%xmm3 + pxor 32(%esp),%xmm4 + pxor 48(%esp),%xmm5 + pxor %xmm0,%xmm6 + pxor %xmm2,%xmm1 + movdqu %xmm2,(%edi,%esi,1) + pxor %xmm3,%xmm1 + movdqu %xmm3,16(%edi,%esi,1) + pxor %xmm4,%xmm1 + movdqu %xmm4,32(%edi,%esi,1) + pxor %xmm5,%xmm1 + movdqu %xmm5,48(%edi,%esi,1) + pxor %xmm6,%xmm1 + movdqu %xmm6,64(%edi,%esi,1) + jmp .L088done +.align 16 +.L089one: + movdqu (%ebx),%xmm7 + movl 112(%esp),%edx + movdqu (%esi),%xmm2 + movl 240(%edx),%ecx + pxor %xmm0,%xmm7 + pxor %xmm7,%xmm2 + movdqa %xmm1,%xmm6 + movl 120(%esp),%edi + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L093dec1_loop_18: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L093dec1_loop_18 +.byte 102,15,56,223,209 + xorps %xmm7,%xmm2 + movaps %xmm6,%xmm1 + movdqa %xmm7,%xmm0 + xorps %xmm2,%xmm1 + movups %xmm2,(%edi,%esi,1) + jmp .L088done +.align 16 +.L090two: + leal 1(%ebp),%ecx + movl 112(%esp),%edx + bsfl %ecx,%ecx + shll $4,%ecx + movdqu (%ebx),%xmm6 + movdqu (%ebx,%ecx,1),%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movl 240(%edx),%ecx + movdqa %xmm1,%xmm5 + pxor %xmm0,%xmm6 + pxor %xmm6,%xmm7 + pxor %xmm6,%xmm2 + pxor %xmm7,%xmm3 + movl 120(%esp),%edi + call _aesni_decrypt2 + xorps %xmm6,%xmm2 + xorps %xmm7,%xmm3 + movdqa %xmm7,%xmm0 + xorps %xmm2,%xmm5 + movups %xmm2,(%edi,%esi,1) + xorps %xmm3,%xmm5 + movups %xmm3,16(%edi,%esi,1) + movaps %xmm5,%xmm1 + jmp .L088done +.align 16 +.L091three: + leal 1(%ebp),%ecx + movl 112(%esp),%edx + bsfl %ecx,%ecx + shll $4,%ecx + movdqu (%ebx),%xmm5 + movdqu (%ebx,%ecx,1),%xmm6 + movdqa %xmm5,%xmm7 + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movl 240(%edx),%ecx + movdqa %xmm1,96(%esp) + pxor %xmm0,%xmm5 + pxor %xmm5,%xmm6 + pxor %xmm6,%xmm7 + pxor %xmm5,%xmm2 + pxor %xmm6,%xmm3 + pxor %xmm7,%xmm4 + movl 120(%esp),%edi + call _aesni_decrypt3 + movdqa 96(%esp),%xmm1 + xorps %xmm5,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm7,%xmm4 + movups %xmm2,(%edi,%esi,1) + pxor %xmm2,%xmm1 + movdqa %xmm7,%xmm0 + movups %xmm3,16(%edi,%esi,1) + pxor %xmm3,%xmm1 + movups %xmm4,32(%edi,%esi,1) + pxor %xmm4,%xmm1 + jmp .L088done +.align 16 +.L092four: + leal 1(%ebp),%ecx + leal 3(%ebp),%eax + bsfl %ecx,%ecx + bsfl %eax,%eax + movl 112(%esp),%edx + shll $4,%ecx + shll $4,%eax + movdqu (%ebx),%xmm4 + movdqu (%ebx,%ecx,1),%xmm5 + movdqa %xmm4,%xmm6 + movdqu (%ebx,%eax,1),%xmm7 + pxor %xmm0,%xmm4 + movdqu (%esi),%xmm2 + pxor %xmm4,%xmm5 + movdqu 16(%esi),%xmm3 + pxor %xmm5,%xmm6 + movdqa %xmm4,(%esp) + pxor %xmm6,%xmm7 + movdqa %xmm5,16(%esp) + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movl 240(%edx),%ecx + movdqa %xmm1,96(%esp) + pxor (%esp),%xmm2 + pxor 16(%esp),%xmm3 + pxor %xmm6,%xmm4 + pxor %xmm7,%xmm5 + movl 120(%esp),%edi + call _aesni_decrypt4 + movdqa 96(%esp),%xmm1 + xorps (%esp),%xmm2 + xorps 16(%esp),%xmm3 + xorps %xmm6,%xmm4 + movups %xmm2,(%edi,%esi,1) + pxor %xmm2,%xmm1 + xorps %xmm7,%xmm5 + movups %xmm3,16(%edi,%esi,1) + pxor %xmm3,%xmm1 + movdqa %xmm7,%xmm0 + movups %xmm4,32(%edi,%esi,1) + pxor %xmm4,%xmm1 + movups %xmm5,48(%edi,%esi,1) + pxor %xmm5,%xmm1 +.L088done: + movl 128(%esp),%edx + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + movdqa %xmm2,(%esp) + pxor %xmm4,%xmm4 + movdqa %xmm2,16(%esp) + pxor %xmm5,%xmm5 + movdqa %xmm2,32(%esp) + pxor %xmm6,%xmm6 + movdqa %xmm2,48(%esp) + pxor %xmm7,%xmm7 + movdqa %xmm2,64(%esp) + movdqa %xmm2,80(%esp) + movdqa %xmm2,96(%esp) + leal (%edx),%esp + movl 40(%esp),%ecx + movl 48(%esp),%ebx + movdqu %xmm0,(%ecx) + pxor %xmm0,%xmm0 + movdqu %xmm1,(%ebx) + pxor %xmm1,%xmm1 + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_ocb_decrypt,.-.L_aesni_ocb_decrypt_begin +.globl aesni_cbc_encrypt +.type aesni_cbc_encrypt,@function +.align 16 +aesni_cbc_encrypt: +.L_aesni_cbc_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl %esp,%ebx + movl 24(%esp),%edi + subl $24,%ebx + movl 28(%esp),%eax + andl $-16,%ebx + movl 32(%esp),%edx + movl 36(%esp),%ebp + testl %eax,%eax + jz .L094cbc_abort + cmpl $0,40(%esp) + xchgl %esp,%ebx + movups (%ebp),%xmm7 + movl 240(%edx),%ecx + movl %edx,%ebp + movl %ebx,16(%esp) + movl %ecx,%ebx + je .L095cbc_decrypt + movaps %xmm7,%xmm2 + cmpl $16,%eax + jb .L096cbc_enc_tail + subl $16,%eax + jmp .L097cbc_enc_loop +.align 16 +.L097cbc_enc_loop: + movups (%esi),%xmm7 + leal 16(%esi),%esi + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + xorps %xmm0,%xmm7 + leal 32(%edx),%edx + xorps %xmm7,%xmm2 +.L098enc1_loop_19: +.byte 102,15,56,220,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L098enc1_loop_19 +.byte 102,15,56,221,209 + movl %ebx,%ecx + movl %ebp,%edx + movups %xmm2,(%edi) + leal 16(%edi),%edi + subl $16,%eax + jnc .L097cbc_enc_loop + addl $16,%eax + jnz .L096cbc_enc_tail + movaps %xmm2,%xmm7 + pxor %xmm2,%xmm2 + jmp .L099cbc_ret +.L096cbc_enc_tail: + movl %eax,%ecx +.long 2767451785 + movl $16,%ecx + subl %eax,%ecx + xorl %eax,%eax +.long 2868115081 + leal -16(%edi),%edi + movl %ebx,%ecx + movl %edi,%esi + movl %ebp,%edx + jmp .L097cbc_enc_loop +.align 16 +.L095cbc_decrypt: + cmpl $80,%eax + jbe .L100cbc_dec_tail + movaps %xmm7,(%esp) + subl $80,%eax + jmp .L101cbc_dec_loop6_enter +.align 16 +.L102cbc_dec_loop6: + movaps %xmm0,(%esp) + movups %xmm7,(%edi) + leal 16(%edi),%edi +.L101cbc_dec_loop6_enter: + movdqu (%esi),%xmm2 + movdqu 16(%esi),%xmm3 + movdqu 32(%esi),%xmm4 + movdqu 48(%esi),%xmm5 + movdqu 64(%esi),%xmm6 + movdqu 80(%esi),%xmm7 + call _aesni_decrypt6 + movups (%esi),%xmm1 + movups 16(%esi),%xmm0 + xorps (%esp),%xmm2 + xorps %xmm1,%xmm3 + movups 32(%esi),%xmm1 + xorps %xmm0,%xmm4 + movups 48(%esi),%xmm0 + xorps %xmm1,%xmm5 + movups 64(%esi),%xmm1 + xorps %xmm0,%xmm6 + movups 80(%esi),%xmm0 + xorps %xmm1,%xmm7 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + leal 96(%esi),%esi + movups %xmm4,32(%edi) + movl %ebx,%ecx + movups %xmm5,48(%edi) + movl %ebp,%edx + movups %xmm6,64(%edi) + leal 80(%edi),%edi + subl $96,%eax + ja .L102cbc_dec_loop6 + movaps %xmm7,%xmm2 + movaps %xmm0,%xmm7 + addl $80,%eax + jle .L103cbc_dec_clear_tail_collected + movups %xmm2,(%edi) + leal 16(%edi),%edi +.L100cbc_dec_tail: + movups (%esi),%xmm2 + movaps %xmm2,%xmm6 + cmpl $16,%eax + jbe .L104cbc_dec_one + movups 16(%esi),%xmm3 + movaps %xmm3,%xmm5 + cmpl $32,%eax + jbe .L105cbc_dec_two + movups 32(%esi),%xmm4 + cmpl $48,%eax + jbe .L106cbc_dec_three + movups 48(%esi),%xmm5 + cmpl $64,%eax + jbe .L107cbc_dec_four + movups 64(%esi),%xmm6 + movaps %xmm7,(%esp) + movups (%esi),%xmm2 + xorps %xmm7,%xmm7 + call _aesni_decrypt6 + movups (%esi),%xmm1 + movups 16(%esi),%xmm0 + xorps (%esp),%xmm2 + xorps %xmm1,%xmm3 + movups 32(%esi),%xmm1 + xorps %xmm0,%xmm4 + movups 48(%esi),%xmm0 + xorps %xmm1,%xmm5 + movups 64(%esi),%xmm7 + xorps %xmm0,%xmm6 + movups %xmm2,(%edi) + movups %xmm3,16(%edi) + pxor %xmm3,%xmm3 + movups %xmm4,32(%edi) + pxor %xmm4,%xmm4 + movups %xmm5,48(%edi) + pxor %xmm5,%xmm5 + leal 64(%edi),%edi + movaps %xmm6,%xmm2 + pxor %xmm6,%xmm6 + subl $80,%eax + jmp .L108cbc_dec_tail_collected +.align 16 +.L104cbc_dec_one: + movups (%edx),%xmm0 + movups 16(%edx),%xmm1 + leal 32(%edx),%edx + xorps %xmm0,%xmm2 +.L109dec1_loop_20: +.byte 102,15,56,222,209 + decl %ecx + movups (%edx),%xmm1 + leal 16(%edx),%edx + jnz .L109dec1_loop_20 +.byte 102,15,56,223,209 + xorps %xmm7,%xmm2 + movaps %xmm6,%xmm7 + subl $16,%eax + jmp .L108cbc_dec_tail_collected +.align 16 +.L105cbc_dec_two: + call _aesni_decrypt2 + xorps %xmm7,%xmm2 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + movaps %xmm3,%xmm2 + pxor %xmm3,%xmm3 + leal 16(%edi),%edi + movaps %xmm5,%xmm7 + subl $32,%eax + jmp .L108cbc_dec_tail_collected +.align 16 +.L106cbc_dec_three: + call _aesni_decrypt3 + xorps %xmm7,%xmm2 + xorps %xmm6,%xmm3 + xorps %xmm5,%xmm4 + movups %xmm2,(%edi) + movaps %xmm4,%xmm2 + pxor %xmm4,%xmm4 + movups %xmm3,16(%edi) + pxor %xmm3,%xmm3 + leal 32(%edi),%edi + movups 32(%esi),%xmm7 + subl $48,%eax + jmp .L108cbc_dec_tail_collected +.align 16 +.L107cbc_dec_four: + call _aesni_decrypt4 + movups 16(%esi),%xmm1 + movups 32(%esi),%xmm0 + xorps %xmm7,%xmm2 + movups 48(%esi),%xmm7 + xorps %xmm6,%xmm3 + movups %xmm2,(%edi) + xorps %xmm1,%xmm4 + movups %xmm3,16(%edi) + pxor %xmm3,%xmm3 + xorps %xmm0,%xmm5 + movups %xmm4,32(%edi) + pxor %xmm4,%xmm4 + leal 48(%edi),%edi + movaps %xmm5,%xmm2 + pxor %xmm5,%xmm5 + subl $64,%eax + jmp .L108cbc_dec_tail_collected +.align 16 +.L103cbc_dec_clear_tail_collected: + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 +.L108cbc_dec_tail_collected: + andl $15,%eax + jnz .L110cbc_dec_tail_partial + movups %xmm2,(%edi) + pxor %xmm0,%xmm0 + jmp .L099cbc_ret +.align 16 +.L110cbc_dec_tail_partial: + movaps %xmm2,(%esp) + pxor %xmm0,%xmm0 + movl $16,%ecx + movl %esp,%esi + subl %eax,%ecx +.long 2767451785 + movdqa %xmm2,(%esp) +.L099cbc_ret: + movl 16(%esp),%esp + movl 36(%esp),%ebp + pxor %xmm2,%xmm2 + pxor %xmm1,%xmm1 + movups %xmm7,(%ebp) + pxor %xmm7,%xmm7 +.L094cbc_abort: + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size aesni_cbc_encrypt,.-.L_aesni_cbc_encrypt_begin +.type _aesni_set_encrypt_key,@function +.align 16 +_aesni_set_encrypt_key: + pushl %ebp + pushl %ebx + testl %eax,%eax + jz .L111bad_pointer + testl %edx,%edx + jz .L111bad_pointer + call .L112pic +.L112pic: + popl %ebx + leal .Lkey_const-.L112pic(%ebx),%ebx + leal OPENSSL_ia32cap_P,%ebp + movups (%eax),%xmm0 + xorps %xmm4,%xmm4 + movl 4(%ebp),%ebp + leal 16(%edx),%edx + andl $268437504,%ebp + cmpl $256,%ecx + je .L11314rounds + cmpl $192,%ecx + je .L11412rounds + cmpl $128,%ecx + jne .L115bad_keybits +.align 16 +.L11610rounds: + cmpl $268435456,%ebp + je .L11710rounds_alt + movl $9,%ecx + movups %xmm0,-16(%edx) +.byte 102,15,58,223,200,1 + call .L118key_128_cold +.byte 102,15,58,223,200,2 + call .L119key_128 +.byte 102,15,58,223,200,4 + call .L119key_128 +.byte 102,15,58,223,200,8 + call .L119key_128 +.byte 102,15,58,223,200,16 + call .L119key_128 +.byte 102,15,58,223,200,32 + call .L119key_128 +.byte 102,15,58,223,200,64 + call .L119key_128 +.byte 102,15,58,223,200,128 + call .L119key_128 +.byte 102,15,58,223,200,27 + call .L119key_128 +.byte 102,15,58,223,200,54 + call .L119key_128 + movups %xmm0,(%edx) + movl %ecx,80(%edx) + jmp .L120good_key +.align 16 +.L119key_128: + movups %xmm0,(%edx) + leal 16(%edx),%edx +.L118key_128_cold: + shufps $16,%xmm0,%xmm4 + xorps %xmm4,%xmm0 + shufps $140,%xmm0,%xmm4 + xorps %xmm4,%xmm0 + shufps $255,%xmm1,%xmm1 + xorps %xmm1,%xmm0 + ret +.align 16 +.L11710rounds_alt: + movdqa (%ebx),%xmm5 + movl $8,%ecx + movdqa 32(%ebx),%xmm4 + movdqa %xmm0,%xmm2 + movdqu %xmm0,-16(%edx) +.L121loop_key128: +.byte 102,15,56,0,197 +.byte 102,15,56,221,196 + pslld $1,%xmm4 + leal 16(%edx),%edx + movdqa %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm3,%xmm2 + pxor %xmm2,%xmm0 + movdqu %xmm0,-16(%edx) + movdqa %xmm0,%xmm2 + decl %ecx + jnz .L121loop_key128 + movdqa 48(%ebx),%xmm4 +.byte 102,15,56,0,197 +.byte 102,15,56,221,196 + pslld $1,%xmm4 + movdqa %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm3,%xmm2 + pxor %xmm2,%xmm0 + movdqu %xmm0,(%edx) + movdqa %xmm0,%xmm2 +.byte 102,15,56,0,197 +.byte 102,15,56,221,196 + movdqa %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm2,%xmm3 + pslldq $4,%xmm2 + pxor %xmm3,%xmm2 + pxor %xmm2,%xmm0 + movdqu %xmm0,16(%edx) + movl $9,%ecx + movl %ecx,96(%edx) + jmp .L120good_key +.align 16 +.L11412rounds: + movq 16(%eax),%xmm2 + cmpl $268435456,%ebp + je .L12212rounds_alt + movl $11,%ecx + movups %xmm0,-16(%edx) +.byte 102,15,58,223,202,1 + call .L123key_192a_cold +.byte 102,15,58,223,202,2 + call .L124key_192b +.byte 102,15,58,223,202,4 + call .L125key_192a +.byte 102,15,58,223,202,8 + call .L124key_192b +.byte 102,15,58,223,202,16 + call .L125key_192a +.byte 102,15,58,223,202,32 + call .L124key_192b +.byte 102,15,58,223,202,64 + call .L125key_192a +.byte 102,15,58,223,202,128 + call .L124key_192b + movups %xmm0,(%edx) + movl %ecx,48(%edx) + jmp .L120good_key +.align 16 +.L125key_192a: + movups %xmm0,(%edx) + leal 16(%edx),%edx +.align 16 +.L123key_192a_cold: + movaps %xmm2,%xmm5 +.L126key_192b_warm: + shufps $16,%xmm0,%xmm4 + movdqa %xmm2,%xmm3 + xorps %xmm4,%xmm0 + shufps $140,%xmm0,%xmm4 + pslldq $4,%xmm3 + xorps %xmm4,%xmm0 + pshufd $85,%xmm1,%xmm1 + pxor %xmm3,%xmm2 + pxor %xmm1,%xmm0 + pshufd $255,%xmm0,%xmm3 + pxor %xmm3,%xmm2 + ret +.align 16 +.L124key_192b: + movaps %xmm0,%xmm3 + shufps $68,%xmm0,%xmm5 + movups %xmm5,(%edx) + shufps $78,%xmm2,%xmm3 + movups %xmm3,16(%edx) + leal 32(%edx),%edx + jmp .L126key_192b_warm +.align 16 +.L12212rounds_alt: + movdqa 16(%ebx),%xmm5 + movdqa 32(%ebx),%xmm4 + movl $8,%ecx + movdqu %xmm0,-16(%edx) +.L127loop_key192: + movq %xmm2,(%edx) + movdqa %xmm2,%xmm1 +.byte 102,15,56,0,213 +.byte 102,15,56,221,212 + pslld $1,%xmm4 + leal 24(%edx),%edx + movdqa %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm3,%xmm0 + pshufd $255,%xmm0,%xmm3 + pxor %xmm1,%xmm3 + pslldq $4,%xmm1 + pxor %xmm1,%xmm3 + pxor %xmm2,%xmm0 + pxor %xmm3,%xmm2 + movdqu %xmm0,-16(%edx) + decl %ecx + jnz .L127loop_key192 + movl $11,%ecx + movl %ecx,32(%edx) + jmp .L120good_key +.align 16 +.L11314rounds: + movups 16(%eax),%xmm2 + leal 16(%edx),%edx + cmpl $268435456,%ebp + je .L12814rounds_alt + movl $13,%ecx + movups %xmm0,-32(%edx) + movups %xmm2,-16(%edx) +.byte 102,15,58,223,202,1 + call .L129key_256a_cold +.byte 102,15,58,223,200,1 + call .L130key_256b +.byte 102,15,58,223,202,2 + call .L131key_256a +.byte 102,15,58,223,200,2 + call .L130key_256b +.byte 102,15,58,223,202,4 + call .L131key_256a +.byte 102,15,58,223,200,4 + call .L130key_256b +.byte 102,15,58,223,202,8 + call .L131key_256a +.byte 102,15,58,223,200,8 + call .L130key_256b +.byte 102,15,58,223,202,16 + call .L131key_256a +.byte 102,15,58,223,200,16 + call .L130key_256b +.byte 102,15,58,223,202,32 + call .L131key_256a +.byte 102,15,58,223,200,32 + call .L130key_256b +.byte 102,15,58,223,202,64 + call .L131key_256a + movups %xmm0,(%edx) + movl %ecx,16(%edx) + xorl %eax,%eax + jmp .L120good_key +.align 16 +.L131key_256a: + movups %xmm2,(%edx) + leal 16(%edx),%edx +.L129key_256a_cold: + shufps $16,%xmm0,%xmm4 + xorps %xmm4,%xmm0 + shufps $140,%xmm0,%xmm4 + xorps %xmm4,%xmm0 + shufps $255,%xmm1,%xmm1 + xorps %xmm1,%xmm0 + ret +.align 16 +.L130key_256b: + movups %xmm0,(%edx) + leal 16(%edx),%edx + shufps $16,%xmm2,%xmm4 + xorps %xmm4,%xmm2 + shufps $140,%xmm2,%xmm4 + xorps %xmm4,%xmm2 + shufps $170,%xmm1,%xmm1 + xorps %xmm1,%xmm2 + ret +.align 16 +.L12814rounds_alt: + movdqa (%ebx),%xmm5 + movdqa 32(%ebx),%xmm4 + movl $7,%ecx + movdqu %xmm0,-32(%edx) + movdqa %xmm2,%xmm1 + movdqu %xmm2,-16(%edx) +.L132loop_key256: +.byte 102,15,56,0,213 +.byte 102,15,56,221,212 + movdqa %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm0,%xmm3 + pslldq $4,%xmm0 + pxor %xmm3,%xmm0 + pslld $1,%xmm4 + pxor %xmm2,%xmm0 + movdqu %xmm0,(%edx) + decl %ecx + jz .L133done_key256 + pshufd $255,%xmm0,%xmm2 + pxor %xmm3,%xmm3 +.byte 102,15,56,221,211 + movdqa %xmm1,%xmm3 + pslldq $4,%xmm1 + pxor %xmm1,%xmm3 + pslldq $4,%xmm1 + pxor %xmm1,%xmm3 + pslldq $4,%xmm1 + pxor %xmm3,%xmm1 + pxor %xmm1,%xmm2 + movdqu %xmm2,16(%edx) + leal 32(%edx),%edx + movdqa %xmm2,%xmm1 + jmp .L132loop_key256 +.L133done_key256: + movl $13,%ecx + movl %ecx,16(%edx) +.L120good_key: + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + xorl %eax,%eax + popl %ebx + popl %ebp + ret +.align 4 +.L111bad_pointer: + movl $-1,%eax + popl %ebx + popl %ebp + ret +.align 4 +.L115bad_keybits: + pxor %xmm0,%xmm0 + movl $-2,%eax + popl %ebx + popl %ebp + ret +.size _aesni_set_encrypt_key,.-_aesni_set_encrypt_key +.globl aesni_set_encrypt_key +.type aesni_set_encrypt_key,@function +.align 16 +aesni_set_encrypt_key: +.L_aesni_set_encrypt_key_begin: + movl 4(%esp),%eax + movl 8(%esp),%ecx + movl 12(%esp),%edx + call _aesni_set_encrypt_key + ret +.size aesni_set_encrypt_key,.-.L_aesni_set_encrypt_key_begin +.globl aesni_set_decrypt_key +.type aesni_set_decrypt_key,@function +.align 16 +aesni_set_decrypt_key: +.L_aesni_set_decrypt_key_begin: + movl 4(%esp),%eax + movl 8(%esp),%ecx + movl 12(%esp),%edx + call _aesni_set_encrypt_key + movl 12(%esp),%edx + shll $4,%ecx + testl %eax,%eax + jnz .L134dec_key_ret + leal 16(%edx,%ecx,1),%eax + movups (%edx),%xmm0 + movups (%eax),%xmm1 + movups %xmm0,(%eax) + movups %xmm1,(%edx) + leal 16(%edx),%edx + leal -16(%eax),%eax +.L135dec_key_inverse: + movups (%edx),%xmm0 + movups (%eax),%xmm1 +.byte 102,15,56,219,192 +.byte 102,15,56,219,201 + leal 16(%edx),%edx + leal -16(%eax),%eax + movups %xmm0,16(%eax) + movups %xmm1,-16(%edx) + cmpl %edx,%eax + ja .L135dec_key_inverse + movups (%edx),%xmm0 +.byte 102,15,56,219,192 + movups %xmm0,(%edx) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + xorl %eax,%eax +.L134dec_key_ret: + ret +.size aesni_set_decrypt_key,.-.L_aesni_set_decrypt_key_begin +.align 64 +.Lkey_const: +.long 202313229,202313229,202313229,202313229 +.long 67569157,67569157,67569157,67569157 +.long 1,1,1,1 +.long 27,27,27,27 +.byte 65,69,83,32,102,111,114,32,73,110,116,101,108,32,65,69 +.byte 83,45,78,73,44,32,67,82,89,80,84,79,71,65,77,83 +.byte 32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115 +.byte 115,108,46,111,114,103,62,0 +.comm OPENSSL_ia32cap_P,16,4 diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/vpaes-x86.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/vpaes-x86.S new file mode 100644 index 0000000000..6f62534682 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/aes/vpaes-x86.S @@ -0,0 +1,670 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/aes/asm/vpaes-x86.pl +# +# Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.align 64 +.L_vpaes_consts: +.long 218628480,235210255,168496130,67568393 +.long 252381056,17041926,33884169,51187212 +.long 252645135,252645135,252645135,252645135 +.long 1512730624,3266504856,1377990664,3401244816 +.long 830229760,1275146365,2969422977,3447763452 +.long 3411033600,2979783055,338359620,2782886510 +.long 4209124096,907596821,221174255,1006095553 +.long 191964160,3799684038,3164090317,1589111125 +.long 182528256,1777043520,2877432650,3265356744 +.long 1874708224,3503451415,3305285752,363511674 +.long 1606117888,3487855781,1093350906,2384367825 +.long 197121,67569157,134941193,202313229 +.long 67569157,134941193,202313229,197121 +.long 134941193,202313229,197121,67569157 +.long 202313229,197121,67569157,134941193 +.long 33619971,100992007,168364043,235736079 +.long 235736079,33619971,100992007,168364043 +.long 168364043,235736079,33619971,100992007 +.long 100992007,168364043,235736079,33619971 +.long 50462976,117835012,185207048,252579084 +.long 252314880,51251460,117574920,184942860 +.long 184682752,252054788,50987272,118359308 +.long 118099200,185467140,251790600,50727180 +.long 2946363062,528716217,1300004225,1881839624 +.long 1532713819,1532713819,1532713819,1532713819 +.long 3602276352,4288629033,3737020424,4153884961 +.long 1354558464,32357713,2958822624,3775749553 +.long 1201988352,132424512,1572796698,503232858 +.long 2213177600,1597421020,4103937655,675398315 +.long 2749646592,4273543773,1511898873,121693092 +.long 3040248576,1103263732,2871565598,1608280554 +.long 2236667136,2588920351,482954393,64377734 +.long 3069987328,291237287,2117370568,3650299247 +.long 533321216,3573750986,2572112006,1401264716 +.long 1339849704,2721158661,548607111,3445553514 +.long 2128193280,3054596040,2183486460,1257083700 +.long 655635200,1165381986,3923443150,2344132524 +.long 190078720,256924420,290342170,357187870 +.long 1610966272,2263057382,4103205268,309794674 +.long 2592527872,2233205587,1335446729,3402964816 +.long 3973531904,3225098121,3002836325,1918774430 +.long 3870401024,2102906079,2284471353,4117666579 +.long 617007872,1021508343,366931923,691083277 +.long 2528395776,3491914898,2968704004,1613121270 +.long 3445188352,3247741094,844474987,4093578302 +.long 651481088,1190302358,1689581232,574775300 +.long 4289380608,206939853,2555985458,2489840491 +.long 2130264064,327674451,3566485037,3349835193 +.long 2470714624,316102159,3636825756,3393945945 +.byte 86,101,99,116,111,114,32,80,101,114,109,117,116,97,116,105 +.byte 111,110,32,65,69,83,32,102,111,114,32,120,56,54,47,83 +.byte 83,83,69,51,44,32,77,105,107,101,32,72,97,109,98,117 +.byte 114,103,32,40,83,116,97,110,102,111,114,100,32,85,110,105 +.byte 118,101,114,115,105,116,121,41,0 +.align 64 +.type _vpaes_preheat,@function +.align 16 +_vpaes_preheat: + addl (%esp),%ebp + movdqa -48(%ebp),%xmm7 + movdqa -16(%ebp),%xmm6 + ret +.size _vpaes_preheat,.-_vpaes_preheat +.type _vpaes_encrypt_core,@function +.align 16 +_vpaes_encrypt_core: + movl $16,%ecx + movl 240(%edx),%eax + movdqa %xmm6,%xmm1 + movdqa (%ebp),%xmm2 + pandn %xmm0,%xmm1 + pand %xmm6,%xmm0 + movdqu (%edx),%xmm5 +.byte 102,15,56,0,208 + movdqa 16(%ebp),%xmm0 + pxor %xmm5,%xmm2 + psrld $4,%xmm1 + addl $16,%edx +.byte 102,15,56,0,193 + leal 192(%ebp),%ebx + pxor %xmm2,%xmm0 + jmp .L000enc_entry +.align 16 +.L001enc_loop: + movdqa 32(%ebp),%xmm4 + movdqa 48(%ebp),%xmm0 +.byte 102,15,56,0,226 +.byte 102,15,56,0,195 + pxor %xmm5,%xmm4 + movdqa 64(%ebp),%xmm5 + pxor %xmm4,%xmm0 + movdqa -64(%ebx,%ecx,1),%xmm1 +.byte 102,15,56,0,234 + movdqa 80(%ebp),%xmm2 + movdqa (%ebx,%ecx,1),%xmm4 +.byte 102,15,56,0,211 + movdqa %xmm0,%xmm3 + pxor %xmm5,%xmm2 +.byte 102,15,56,0,193 + addl $16,%edx + pxor %xmm2,%xmm0 +.byte 102,15,56,0,220 + addl $16,%ecx + pxor %xmm0,%xmm3 +.byte 102,15,56,0,193 + andl $48,%ecx + subl $1,%eax + pxor %xmm3,%xmm0 +.L000enc_entry: + movdqa %xmm6,%xmm1 + movdqa -32(%ebp),%xmm5 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm6,%xmm0 +.byte 102,15,56,0,232 + movdqa %xmm7,%xmm3 + pxor %xmm1,%xmm0 +.byte 102,15,56,0,217 + movdqa %xmm7,%xmm4 + pxor %xmm5,%xmm3 +.byte 102,15,56,0,224 + movdqa %xmm7,%xmm2 + pxor %xmm5,%xmm4 +.byte 102,15,56,0,211 + movdqa %xmm7,%xmm3 + pxor %xmm0,%xmm2 +.byte 102,15,56,0,220 + movdqu (%edx),%xmm5 + pxor %xmm1,%xmm3 + jnz .L001enc_loop + movdqa 96(%ebp),%xmm4 + movdqa 112(%ebp),%xmm0 +.byte 102,15,56,0,226 + pxor %xmm5,%xmm4 +.byte 102,15,56,0,195 + movdqa 64(%ebx,%ecx,1),%xmm1 + pxor %xmm4,%xmm0 +.byte 102,15,56,0,193 + ret +.size _vpaes_encrypt_core,.-_vpaes_encrypt_core +.type _vpaes_decrypt_core,@function +.align 16 +_vpaes_decrypt_core: + leal 608(%ebp),%ebx + movl 240(%edx),%eax + movdqa %xmm6,%xmm1 + movdqa -64(%ebx),%xmm2 + pandn %xmm0,%xmm1 + movl %eax,%ecx + psrld $4,%xmm1 + movdqu (%edx),%xmm5 + shll $4,%ecx + pand %xmm6,%xmm0 +.byte 102,15,56,0,208 + movdqa -48(%ebx),%xmm0 + xorl $48,%ecx +.byte 102,15,56,0,193 + andl $48,%ecx + pxor %xmm5,%xmm2 + movdqa 176(%ebp),%xmm5 + pxor %xmm2,%xmm0 + addl $16,%edx + leal -352(%ebx,%ecx,1),%ecx + jmp .L002dec_entry +.align 16 +.L003dec_loop: + movdqa -32(%ebx),%xmm4 + movdqa -16(%ebx),%xmm1 +.byte 102,15,56,0,226 +.byte 102,15,56,0,203 + pxor %xmm4,%xmm0 + movdqa (%ebx),%xmm4 + pxor %xmm1,%xmm0 + movdqa 16(%ebx),%xmm1 +.byte 102,15,56,0,226 +.byte 102,15,56,0,197 +.byte 102,15,56,0,203 + pxor %xmm4,%xmm0 + movdqa 32(%ebx),%xmm4 + pxor %xmm1,%xmm0 + movdqa 48(%ebx),%xmm1 +.byte 102,15,56,0,226 +.byte 102,15,56,0,197 +.byte 102,15,56,0,203 + pxor %xmm4,%xmm0 + movdqa 64(%ebx),%xmm4 + pxor %xmm1,%xmm0 + movdqa 80(%ebx),%xmm1 +.byte 102,15,56,0,226 +.byte 102,15,56,0,197 +.byte 102,15,56,0,203 + pxor %xmm4,%xmm0 + addl $16,%edx +.byte 102,15,58,15,237,12 + pxor %xmm1,%xmm0 + subl $1,%eax +.L002dec_entry: + movdqa %xmm6,%xmm1 + movdqa -32(%ebp),%xmm2 + pandn %xmm0,%xmm1 + pand %xmm6,%xmm0 + psrld $4,%xmm1 +.byte 102,15,56,0,208 + movdqa %xmm7,%xmm3 + pxor %xmm1,%xmm0 +.byte 102,15,56,0,217 + movdqa %xmm7,%xmm4 + pxor %xmm2,%xmm3 +.byte 102,15,56,0,224 + pxor %xmm2,%xmm4 + movdqa %xmm7,%xmm2 +.byte 102,15,56,0,211 + movdqa %xmm7,%xmm3 + pxor %xmm0,%xmm2 +.byte 102,15,56,0,220 + movdqu (%edx),%xmm0 + pxor %xmm1,%xmm3 + jnz .L003dec_loop + movdqa 96(%ebx),%xmm4 +.byte 102,15,56,0,226 + pxor %xmm0,%xmm4 + movdqa 112(%ebx),%xmm0 + movdqa (%ecx),%xmm2 +.byte 102,15,56,0,195 + pxor %xmm4,%xmm0 +.byte 102,15,56,0,194 + ret +.size _vpaes_decrypt_core,.-_vpaes_decrypt_core +.type _vpaes_schedule_core,@function +.align 16 +_vpaes_schedule_core: + addl (%esp),%ebp + movdqu (%esi),%xmm0 + movdqa 320(%ebp),%xmm2 + movdqa %xmm0,%xmm3 + leal (%ebp),%ebx + movdqa %xmm2,4(%esp) + call _vpaes_schedule_transform + movdqa %xmm0,%xmm7 + testl %edi,%edi + jnz .L004schedule_am_decrypting + movdqu %xmm0,(%edx) + jmp .L005schedule_go +.L004schedule_am_decrypting: + movdqa 256(%ebp,%ecx,1),%xmm1 +.byte 102,15,56,0,217 + movdqu %xmm3,(%edx) + xorl $48,%ecx +.L005schedule_go: + cmpl $192,%eax + ja .L006schedule_256 + je .L007schedule_192 +.L008schedule_128: + movl $10,%eax +.L009loop_schedule_128: + call _vpaes_schedule_round + decl %eax + jz .L010schedule_mangle_last + call _vpaes_schedule_mangle + jmp .L009loop_schedule_128 +.align 16 +.L007schedule_192: + movdqu 8(%esi),%xmm0 + call _vpaes_schedule_transform + movdqa %xmm0,%xmm6 + pxor %xmm4,%xmm4 + movhlps %xmm4,%xmm6 + movl $4,%eax +.L011loop_schedule_192: + call _vpaes_schedule_round +.byte 102,15,58,15,198,8 + call _vpaes_schedule_mangle + call _vpaes_schedule_192_smear + call _vpaes_schedule_mangle + call _vpaes_schedule_round + decl %eax + jz .L010schedule_mangle_last + call _vpaes_schedule_mangle + call _vpaes_schedule_192_smear + jmp .L011loop_schedule_192 +.align 16 +.L006schedule_256: + movdqu 16(%esi),%xmm0 + call _vpaes_schedule_transform + movl $7,%eax +.L012loop_schedule_256: + call _vpaes_schedule_mangle + movdqa %xmm0,%xmm6 + call _vpaes_schedule_round + decl %eax + jz .L010schedule_mangle_last + call _vpaes_schedule_mangle + pshufd $255,%xmm0,%xmm0 + movdqa %xmm7,20(%esp) + movdqa %xmm6,%xmm7 + call .L_vpaes_schedule_low_round + movdqa 20(%esp),%xmm7 + jmp .L012loop_schedule_256 +.align 16 +.L010schedule_mangle_last: + leal 384(%ebp),%ebx + testl %edi,%edi + jnz .L013schedule_mangle_last_dec + movdqa 256(%ebp,%ecx,1),%xmm1 +.byte 102,15,56,0,193 + leal 352(%ebp),%ebx + addl $32,%edx +.L013schedule_mangle_last_dec: + addl $-16,%edx + pxor 336(%ebp),%xmm0 + call _vpaes_schedule_transform + movdqu %xmm0,(%edx) + pxor %xmm0,%xmm0 + pxor %xmm1,%xmm1 + pxor %xmm2,%xmm2 + pxor %xmm3,%xmm3 + pxor %xmm4,%xmm4 + pxor %xmm5,%xmm5 + pxor %xmm6,%xmm6 + pxor %xmm7,%xmm7 + ret +.size _vpaes_schedule_core,.-_vpaes_schedule_core +.type _vpaes_schedule_192_smear,@function +.align 16 +_vpaes_schedule_192_smear: + pshufd $128,%xmm6,%xmm1 + pshufd $254,%xmm7,%xmm0 + pxor %xmm1,%xmm6 + pxor %xmm1,%xmm1 + pxor %xmm0,%xmm6 + movdqa %xmm6,%xmm0 + movhlps %xmm1,%xmm6 + ret +.size _vpaes_schedule_192_smear,.-_vpaes_schedule_192_smear +.type _vpaes_schedule_round,@function +.align 16 +_vpaes_schedule_round: + movdqa 8(%esp),%xmm2 + pxor %xmm1,%xmm1 +.byte 102,15,58,15,202,15 +.byte 102,15,58,15,210,15 + pxor %xmm1,%xmm7 + pshufd $255,%xmm0,%xmm0 +.byte 102,15,58,15,192,1 + movdqa %xmm2,8(%esp) +.L_vpaes_schedule_low_round: + movdqa %xmm7,%xmm1 + pslldq $4,%xmm7 + pxor %xmm1,%xmm7 + movdqa %xmm7,%xmm1 + pslldq $8,%xmm7 + pxor %xmm1,%xmm7 + pxor 336(%ebp),%xmm7 + movdqa -16(%ebp),%xmm4 + movdqa -48(%ebp),%xmm5 + movdqa %xmm4,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm4,%xmm0 + movdqa -32(%ebp),%xmm2 +.byte 102,15,56,0,208 + pxor %xmm1,%xmm0 + movdqa %xmm5,%xmm3 +.byte 102,15,56,0,217 + pxor %xmm2,%xmm3 + movdqa %xmm5,%xmm4 +.byte 102,15,56,0,224 + pxor %xmm2,%xmm4 + movdqa %xmm5,%xmm2 +.byte 102,15,56,0,211 + pxor %xmm0,%xmm2 + movdqa %xmm5,%xmm3 +.byte 102,15,56,0,220 + pxor %xmm1,%xmm3 + movdqa 32(%ebp),%xmm4 +.byte 102,15,56,0,226 + movdqa 48(%ebp),%xmm0 +.byte 102,15,56,0,195 + pxor %xmm4,%xmm0 + pxor %xmm7,%xmm0 + movdqa %xmm0,%xmm7 + ret +.size _vpaes_schedule_round,.-_vpaes_schedule_round +.type _vpaes_schedule_transform,@function +.align 16 +_vpaes_schedule_transform: + movdqa -16(%ebp),%xmm2 + movdqa %xmm2,%xmm1 + pandn %xmm0,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm0 + movdqa (%ebx),%xmm2 +.byte 102,15,56,0,208 + movdqa 16(%ebx),%xmm0 +.byte 102,15,56,0,193 + pxor %xmm2,%xmm0 + ret +.size _vpaes_schedule_transform,.-_vpaes_schedule_transform +.type _vpaes_schedule_mangle,@function +.align 16 +_vpaes_schedule_mangle: + movdqa %xmm0,%xmm4 + movdqa 128(%ebp),%xmm5 + testl %edi,%edi + jnz .L014schedule_mangle_dec + addl $16,%edx + pxor 336(%ebp),%xmm4 +.byte 102,15,56,0,229 + movdqa %xmm4,%xmm3 +.byte 102,15,56,0,229 + pxor %xmm4,%xmm3 +.byte 102,15,56,0,229 + pxor %xmm4,%xmm3 + jmp .L015schedule_mangle_both +.align 16 +.L014schedule_mangle_dec: + movdqa -16(%ebp),%xmm2 + leal 416(%ebp),%esi + movdqa %xmm2,%xmm1 + pandn %xmm4,%xmm1 + psrld $4,%xmm1 + pand %xmm2,%xmm4 + movdqa (%esi),%xmm2 +.byte 102,15,56,0,212 + movdqa 16(%esi),%xmm3 +.byte 102,15,56,0,217 + pxor %xmm2,%xmm3 +.byte 102,15,56,0,221 + movdqa 32(%esi),%xmm2 +.byte 102,15,56,0,212 + pxor %xmm3,%xmm2 + movdqa 48(%esi),%xmm3 +.byte 102,15,56,0,217 + pxor %xmm2,%xmm3 +.byte 102,15,56,0,221 + movdqa 64(%esi),%xmm2 +.byte 102,15,56,0,212 + pxor %xmm3,%xmm2 + movdqa 80(%esi),%xmm3 +.byte 102,15,56,0,217 + pxor %xmm2,%xmm3 +.byte 102,15,56,0,221 + movdqa 96(%esi),%xmm2 +.byte 102,15,56,0,212 + pxor %xmm3,%xmm2 + movdqa 112(%esi),%xmm3 +.byte 102,15,56,0,217 + pxor %xmm2,%xmm3 + addl $-16,%edx +.L015schedule_mangle_both: + movdqa 256(%ebp,%ecx,1),%xmm1 +.byte 102,15,56,0,217 + addl $-16,%ecx + andl $48,%ecx + movdqu %xmm3,(%edx) + ret +.size _vpaes_schedule_mangle,.-_vpaes_schedule_mangle +.globl vpaes_set_encrypt_key +.type vpaes_set_encrypt_key,@function +.align 16 +vpaes_set_encrypt_key: +.L_vpaes_set_encrypt_key_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + leal -56(%esp),%ebx + movl 24(%esp),%eax + andl $-16,%ebx + movl 28(%esp),%edx + xchgl %esp,%ebx + movl %ebx,48(%esp) + movl %eax,%ebx + shrl $5,%ebx + addl $5,%ebx + movl %ebx,240(%edx) + movl $48,%ecx + movl $0,%edi + leal .L_vpaes_consts+0x30-.L016pic_point,%ebp + call _vpaes_schedule_core +.L016pic_point: + movl 48(%esp),%esp + xorl %eax,%eax + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size vpaes_set_encrypt_key,.-.L_vpaes_set_encrypt_key_begin +.globl vpaes_set_decrypt_key +.type vpaes_set_decrypt_key,@function +.align 16 +vpaes_set_decrypt_key: +.L_vpaes_set_decrypt_key_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + leal -56(%esp),%ebx + movl 24(%esp),%eax + andl $-16,%ebx + movl 28(%esp),%edx + xchgl %esp,%ebx + movl %ebx,48(%esp) + movl %eax,%ebx + shrl $5,%ebx + addl $5,%ebx + movl %ebx,240(%edx) + shll $4,%ebx + leal 16(%edx,%ebx,1),%edx + movl $1,%edi + movl %eax,%ecx + shrl $1,%ecx + andl $32,%ecx + xorl $32,%ecx + leal .L_vpaes_consts+0x30-.L017pic_point,%ebp + call _vpaes_schedule_core +.L017pic_point: + movl 48(%esp),%esp + xorl %eax,%eax + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size vpaes_set_decrypt_key,.-.L_vpaes_set_decrypt_key_begin +.globl vpaes_encrypt +.type vpaes_encrypt,@function +.align 16 +vpaes_encrypt: +.L_vpaes_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + leal .L_vpaes_consts+0x30-.L018pic_point,%ebp + call _vpaes_preheat +.L018pic_point: + movl 20(%esp),%esi + leal -56(%esp),%ebx + movl 24(%esp),%edi + andl $-16,%ebx + movl 28(%esp),%edx + xchgl %esp,%ebx + movl %ebx,48(%esp) + movdqu (%esi),%xmm0 + call _vpaes_encrypt_core + movdqu %xmm0,(%edi) + movl 48(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size vpaes_encrypt,.-.L_vpaes_encrypt_begin +.globl vpaes_decrypt +.type vpaes_decrypt,@function +.align 16 +vpaes_decrypt: +.L_vpaes_decrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + leal .L_vpaes_consts+0x30-.L019pic_point,%ebp + call _vpaes_preheat +.L019pic_point: + movl 20(%esp),%esi + leal -56(%esp),%ebx + movl 24(%esp),%edi + andl $-16,%ebx + movl 28(%esp),%edx + xchgl %esp,%ebx + movl %ebx,48(%esp) + movdqu (%esi),%xmm0 + call _vpaes_decrypt_core + movdqu %xmm0,(%edi) + movl 48(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size vpaes_decrypt,.-.L_vpaes_decrypt_begin +.globl vpaes_cbc_encrypt +.type vpaes_cbc_encrypt,@function +.align 16 +vpaes_cbc_encrypt: +.L_vpaes_cbc_encrypt_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl 32(%esp),%edx + subl $16,%eax + jc .L020cbc_abort + leal -56(%esp),%ebx + movl 36(%esp),%ebp + andl $-16,%ebx + movl 40(%esp),%ecx + xchgl %esp,%ebx + movdqu (%ebp),%xmm1 + subl %esi,%edi + movl %ebx,48(%esp) + movl %edi,(%esp) + movl %edx,4(%esp) + movl %ebp,8(%esp) + movl %eax,%edi + leal .L_vpaes_consts+0x30-.L021pic_point,%ebp + call _vpaes_preheat +.L021pic_point: + cmpl $0,%ecx + je .L022cbc_dec_loop + jmp .L023cbc_enc_loop +.align 16 +.L023cbc_enc_loop: + movdqu (%esi),%xmm0 + pxor %xmm1,%xmm0 + call _vpaes_encrypt_core + movl (%esp),%ebx + movl 4(%esp),%edx + movdqa %xmm0,%xmm1 + movdqu %xmm0,(%ebx,%esi,1) + leal 16(%esi),%esi + subl $16,%edi + jnc .L023cbc_enc_loop + jmp .L024cbc_done +.align 16 +.L022cbc_dec_loop: + movdqu (%esi),%xmm0 + movdqa %xmm1,16(%esp) + movdqa %xmm0,32(%esp) + call _vpaes_decrypt_core + movl (%esp),%ebx + movl 4(%esp),%edx + pxor 16(%esp),%xmm0 + movdqa 32(%esp),%xmm1 + movdqu %xmm0,(%ebx,%esi,1) + leal 16(%esi),%esi + subl $16,%edi + jnc .L022cbc_dec_loop +.L024cbc_done: + movl 8(%esp),%ebx + movl 48(%esp),%esp + movdqu %xmm1,(%ebx) +.L020cbc_abort: + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size vpaes_cbc_encrypt,.-.L_vpaes_cbc_encrypt_begin diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/modes/ghash-x86.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/modes/ghash-x86.S new file mode 100644 index 0000000000..f52b445df2 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/modes/ghash-x86.S @@ -0,0 +1,703 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/modes/asm/ghash-x86.pl +# +# Copyright 2010-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl gcm_gmult_4bit_x86 +.type gcm_gmult_4bit_x86,@function +.align 16 +gcm_gmult_4bit_x86: +.L_gcm_gmult_4bit_x86_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + subl $84,%esp + movl 104(%esp),%edi + movl 108(%esp),%esi + movl (%edi),%ebp + movl 4(%edi),%edx + movl 8(%edi),%ecx + movl 12(%edi),%ebx + movl $0,16(%esp) + movl $471859200,20(%esp) + movl $943718400,24(%esp) + movl $610271232,28(%esp) + movl $1887436800,32(%esp) + movl $1822425088,36(%esp) + movl $1220542464,40(%esp) + movl $1423966208,44(%esp) + movl $3774873600,48(%esp) + movl $4246732800,52(%esp) + movl $3644850176,56(%esp) + movl $3311403008,60(%esp) + movl $2441084928,64(%esp) + movl $2376073216,68(%esp) + movl $2847932416,72(%esp) + movl $3051356160,76(%esp) + movl %ebp,(%esp) + movl %edx,4(%esp) + movl %ecx,8(%esp) + movl %ebx,12(%esp) + shrl $20,%ebx + andl $240,%ebx + movl 4(%esi,%ebx,1),%ebp + movl (%esi,%ebx,1),%edx + movl 12(%esi,%ebx,1),%ecx + movl 8(%esi,%ebx,1),%ebx + xorl %eax,%eax + movl $15,%edi + jmp .L000x86_loop +.align 16 +.L000x86_loop: + movb %bl,%al + shrdl $4,%ecx,%ebx + andb $15,%al + shrdl $4,%edx,%ecx + shrdl $4,%ebp,%edx + shrl $4,%ebp + xorl 16(%esp,%eax,4),%ebp + movb (%esp,%edi,1),%al + andb $240,%al + xorl 8(%esi,%eax,1),%ebx + xorl 12(%esi,%eax,1),%ecx + xorl (%esi,%eax,1),%edx + xorl 4(%esi,%eax,1),%ebp + decl %edi + js .L001x86_break + movb %bl,%al + shrdl $4,%ecx,%ebx + andb $15,%al + shrdl $4,%edx,%ecx + shrdl $4,%ebp,%edx + shrl $4,%ebp + xorl 16(%esp,%eax,4),%ebp + movb (%esp,%edi,1),%al + shlb $4,%al + xorl 8(%esi,%eax,1),%ebx + xorl 12(%esi,%eax,1),%ecx + xorl (%esi,%eax,1),%edx + xorl 4(%esi,%eax,1),%ebp + jmp .L000x86_loop +.align 16 +.L001x86_break: + bswap %ebx + bswap %ecx + bswap %edx + bswap %ebp + movl 104(%esp),%edi + movl %ebx,12(%edi) + movl %ecx,8(%edi) + movl %edx,4(%edi) + movl %ebp,(%edi) + addl $84,%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_gmult_4bit_x86,.-.L_gcm_gmult_4bit_x86_begin +.globl gcm_ghash_4bit_x86 +.type gcm_ghash_4bit_x86,@function +.align 16 +gcm_ghash_4bit_x86: +.L_gcm_ghash_4bit_x86_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + subl $84,%esp + movl 104(%esp),%ebx + movl 108(%esp),%esi + movl 112(%esp),%edi + movl 116(%esp),%ecx + addl %edi,%ecx + movl %ecx,116(%esp) + movl (%ebx),%ebp + movl 4(%ebx),%edx + movl 8(%ebx),%ecx + movl 12(%ebx),%ebx + movl $0,16(%esp) + movl $471859200,20(%esp) + movl $943718400,24(%esp) + movl $610271232,28(%esp) + movl $1887436800,32(%esp) + movl $1822425088,36(%esp) + movl $1220542464,40(%esp) + movl $1423966208,44(%esp) + movl $3774873600,48(%esp) + movl $4246732800,52(%esp) + movl $3644850176,56(%esp) + movl $3311403008,60(%esp) + movl $2441084928,64(%esp) + movl $2376073216,68(%esp) + movl $2847932416,72(%esp) + movl $3051356160,76(%esp) +.align 16 +.L002x86_outer_loop: + xorl 12(%edi),%ebx + xorl 8(%edi),%ecx + xorl 4(%edi),%edx + xorl (%edi),%ebp + movl %ebx,12(%esp) + movl %ecx,8(%esp) + movl %edx,4(%esp) + movl %ebp,(%esp) + shrl $20,%ebx + andl $240,%ebx + movl 4(%esi,%ebx,1),%ebp + movl (%esi,%ebx,1),%edx + movl 12(%esi,%ebx,1),%ecx + movl 8(%esi,%ebx,1),%ebx + xorl %eax,%eax + movl $15,%edi + jmp .L003x86_loop +.align 16 +.L003x86_loop: + movb %bl,%al + shrdl $4,%ecx,%ebx + andb $15,%al + shrdl $4,%edx,%ecx + shrdl $4,%ebp,%edx + shrl $4,%ebp + xorl 16(%esp,%eax,4),%ebp + movb (%esp,%edi,1),%al + andb $240,%al + xorl 8(%esi,%eax,1),%ebx + xorl 12(%esi,%eax,1),%ecx + xorl (%esi,%eax,1),%edx + xorl 4(%esi,%eax,1),%ebp + decl %edi + js .L004x86_break + movb %bl,%al + shrdl $4,%ecx,%ebx + andb $15,%al + shrdl $4,%edx,%ecx + shrdl $4,%ebp,%edx + shrl $4,%ebp + xorl 16(%esp,%eax,4),%ebp + movb (%esp,%edi,1),%al + shlb $4,%al + xorl 8(%esi,%eax,1),%ebx + xorl 12(%esi,%eax,1),%ecx + xorl (%esi,%eax,1),%edx + xorl 4(%esi,%eax,1),%ebp + jmp .L003x86_loop +.align 16 +.L004x86_break: + bswap %ebx + bswap %ecx + bswap %edx + bswap %ebp + movl 112(%esp),%edi + leal 16(%edi),%edi + cmpl 116(%esp),%edi + movl %edi,112(%esp) + jb .L002x86_outer_loop + movl 104(%esp),%edi + movl %ebx,12(%edi) + movl %ecx,8(%edi) + movl %edx,4(%edi) + movl %ebp,(%edi) + addl $84,%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_ghash_4bit_x86,.-.L_gcm_ghash_4bit_x86_begin +.type _mmx_gmult_4bit_inner,@function +.align 16 +_mmx_gmult_4bit_inner: + xorl %ecx,%ecx + movl %ebx,%edx + movb %dl,%cl + shlb $4,%cl + andl $240,%edx + movq 8(%esi,%ecx,1),%mm0 + movq (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 14(%edi),%cl + psllq $60,%mm2 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 13(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 12(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 11(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 10(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 9(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 8(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 7(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 6(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 5(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 4(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 3(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 2(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb 1(%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + movb (%edi),%cl + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movl %ecx,%edx + movd %mm0,%ebx + pxor %mm2,%mm0 + shlb $4,%cl + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%ecx,1),%mm0 + psllq $60,%mm2 + andl $240,%edx + pxor (%eax,%ebp,8),%mm1 + andl $15,%ebx + pxor (%esi,%ecx,1),%mm1 + movd %mm0,%ebp + pxor %mm2,%mm0 + psrlq $4,%mm0 + movq %mm1,%mm2 + psrlq $4,%mm1 + pxor 8(%esi,%edx,1),%mm0 + psllq $60,%mm2 + pxor (%eax,%ebx,8),%mm1 + andl $15,%ebp + pxor (%esi,%edx,1),%mm1 + movd %mm0,%ebx + pxor %mm2,%mm0 + movl 4(%eax,%ebp,8),%edi + psrlq $32,%mm0 + movd %mm1,%edx + psrlq $32,%mm1 + movd %mm0,%ecx + movd %mm1,%ebp + shll $4,%edi + bswap %ebx + bswap %edx + bswap %ecx + xorl %edi,%ebp + bswap %ebp + ret +.size _mmx_gmult_4bit_inner,.-_mmx_gmult_4bit_inner +.globl gcm_gmult_4bit_mmx +.type gcm_gmult_4bit_mmx,@function +.align 16 +gcm_gmult_4bit_mmx: +.L_gcm_gmult_4bit_mmx_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%edi + movl 24(%esp),%esi + call .L005pic_point +.L005pic_point: + popl %eax + leal .Lrem_4bit-.L005pic_point(%eax),%eax + movzbl 15(%edi),%ebx + call _mmx_gmult_4bit_inner + movl 20(%esp),%edi + emms + movl %ebx,12(%edi) + movl %edx,4(%edi) + movl %ecx,8(%edi) + movl %ebp,(%edi) + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_gmult_4bit_mmx,.-.L_gcm_gmult_4bit_mmx_begin +.globl gcm_ghash_4bit_mmx +.type gcm_ghash_4bit_mmx,@function +.align 16 +gcm_ghash_4bit_mmx: +.L_gcm_ghash_4bit_mmx_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%ebp + movl 24(%esp),%esi + movl 28(%esp),%edi + movl 32(%esp),%ecx + call .L006pic_point +.L006pic_point: + popl %eax + leal .Lrem_4bit-.L006pic_point(%eax),%eax + addl %edi,%ecx + movl %ecx,32(%esp) + subl $20,%esp + movl 12(%ebp),%ebx + movl 4(%ebp),%edx + movl 8(%ebp),%ecx + movl (%ebp),%ebp + jmp .L007mmx_outer_loop +.align 16 +.L007mmx_outer_loop: + xorl 12(%edi),%ebx + xorl 4(%edi),%edx + xorl 8(%edi),%ecx + xorl (%edi),%ebp + movl %edi,48(%esp) + movl %ebx,12(%esp) + movl %edx,4(%esp) + movl %ecx,8(%esp) + movl %ebp,(%esp) + movl %esp,%edi + shrl $24,%ebx + call _mmx_gmult_4bit_inner + movl 48(%esp),%edi + leal 16(%edi),%edi + cmpl 52(%esp),%edi + jb .L007mmx_outer_loop + movl 40(%esp),%edi + emms + movl %ebx,12(%edi) + movl %edx,4(%edi) + movl %ecx,8(%edi) + movl %ebp,(%edi) + addl $20,%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size gcm_ghash_4bit_mmx,.-.L_gcm_ghash_4bit_mmx_begin +.align 64 +.Lrem_4bit: +.long 0,0,0,29491200,0,58982400,0,38141952 +.long 0,117964800,0,113901568,0,76283904,0,88997888 +.long 0,235929600,0,265420800,0,227803136,0,206962688 +.long 0,152567808,0,148504576,0,177995776,0,190709760 +.byte 71,72,65,83,72,32,102,111,114,32,120,56,54,44,32,67 +.byte 82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112 +.byte 112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62 +.byte 0 diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha1-586.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha1-586.S new file mode 100644 index 0000000000..0b22a3e553 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha1-586.S @@ -0,0 +1,1389 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/sha/asm/sha1-586.pl +# +# Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl sha1_block_data_order +.type sha1_block_data_order,@function +.align 16 +sha1_block_data_order: +.L_sha1_block_data_order_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%ebp + movl 24(%esp),%esi + movl 28(%esp),%eax + subl $76,%esp + shll $6,%eax + addl %esi,%eax + movl %eax,104(%esp) + movl 16(%ebp),%edi + jmp .L000loop +.align 16 +.L000loop: + movl (%esi),%eax + movl 4(%esi),%ebx + movl 8(%esi),%ecx + movl 12(%esi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + movl %eax,(%esp) + movl %ebx,4(%esp) + movl %ecx,8(%esp) + movl %edx,12(%esp) + movl 16(%esi),%eax + movl 20(%esi),%ebx + movl 24(%esi),%ecx + movl 28(%esi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + movl %eax,16(%esp) + movl %ebx,20(%esp) + movl %ecx,24(%esp) + movl %edx,28(%esp) + movl 32(%esi),%eax + movl 36(%esi),%ebx + movl 40(%esi),%ecx + movl 44(%esi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + movl %eax,32(%esp) + movl %ebx,36(%esp) + movl %ecx,40(%esp) + movl %edx,44(%esp) + movl 48(%esi),%eax + movl 52(%esi),%ebx + movl 56(%esi),%ecx + movl 60(%esi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + movl %eax,48(%esp) + movl %ebx,52(%esp) + movl %ecx,56(%esp) + movl %edx,60(%esp) + movl %esi,100(%esp) + movl (%ebp),%eax + movl 4(%ebp),%ebx + movl 8(%ebp),%ecx + movl 12(%ebp),%edx + + movl %ecx,%esi + movl %eax,%ebp + roll $5,%ebp + xorl %edx,%esi + addl %edi,%ebp + movl (%esp),%edi + andl %ebx,%esi + rorl $2,%ebx + xorl %edx,%esi + leal 1518500249(%ebp,%edi,1),%ebp + addl %esi,%ebp + + movl %ebx,%edi + movl %ebp,%esi + roll $5,%ebp + xorl %ecx,%edi + addl %edx,%ebp + movl 4(%esp),%edx + andl %eax,%edi + rorl $2,%eax + xorl %ecx,%edi + leal 1518500249(%ebp,%edx,1),%ebp + addl %edi,%ebp + + movl %eax,%edx + movl %ebp,%edi + roll $5,%ebp + xorl %ebx,%edx + addl %ecx,%ebp + movl 8(%esp),%ecx + andl %esi,%edx + rorl $2,%esi + xorl %ebx,%edx + leal 1518500249(%ebp,%ecx,1),%ebp + addl %edx,%ebp + + movl %esi,%ecx + movl %ebp,%edx + roll $5,%ebp + xorl %eax,%ecx + addl %ebx,%ebp + movl 12(%esp),%ebx + andl %edi,%ecx + rorl $2,%edi + xorl %eax,%ecx + leal 1518500249(%ebp,%ebx,1),%ebp + addl %ecx,%ebp + + movl %edi,%ebx + movl %ebp,%ecx + roll $5,%ebp + xorl %esi,%ebx + addl %eax,%ebp + movl 16(%esp),%eax + andl %edx,%ebx + rorl $2,%edx + xorl %esi,%ebx + leal 1518500249(%ebp,%eax,1),%ebp + addl %ebx,%ebp + + movl %edx,%eax + movl %ebp,%ebx + roll $5,%ebp + xorl %edi,%eax + addl %esi,%ebp + movl 20(%esp),%esi + andl %ecx,%eax + rorl $2,%ecx + xorl %edi,%eax + leal 1518500249(%ebp,%esi,1),%ebp + addl %eax,%ebp + + movl %ecx,%esi + movl %ebp,%eax + roll $5,%ebp + xorl %edx,%esi + addl %edi,%ebp + movl 24(%esp),%edi + andl %ebx,%esi + rorl $2,%ebx + xorl %edx,%esi + leal 1518500249(%ebp,%edi,1),%ebp + addl %esi,%ebp + + movl %ebx,%edi + movl %ebp,%esi + roll $5,%ebp + xorl %ecx,%edi + addl %edx,%ebp + movl 28(%esp),%edx + andl %eax,%edi + rorl $2,%eax + xorl %ecx,%edi + leal 1518500249(%ebp,%edx,1),%ebp + addl %edi,%ebp + + movl %eax,%edx + movl %ebp,%edi + roll $5,%ebp + xorl %ebx,%edx + addl %ecx,%ebp + movl 32(%esp),%ecx + andl %esi,%edx + rorl $2,%esi + xorl %ebx,%edx + leal 1518500249(%ebp,%ecx,1),%ebp + addl %edx,%ebp + + movl %esi,%ecx + movl %ebp,%edx + roll $5,%ebp + xorl %eax,%ecx + addl %ebx,%ebp + movl 36(%esp),%ebx + andl %edi,%ecx + rorl $2,%edi + xorl %eax,%ecx + leal 1518500249(%ebp,%ebx,1),%ebp + addl %ecx,%ebp + + movl %edi,%ebx + movl %ebp,%ecx + roll $5,%ebp + xorl %esi,%ebx + addl %eax,%ebp + movl 40(%esp),%eax + andl %edx,%ebx + rorl $2,%edx + xorl %esi,%ebx + leal 1518500249(%ebp,%eax,1),%ebp + addl %ebx,%ebp + + movl %edx,%eax + movl %ebp,%ebx + roll $5,%ebp + xorl %edi,%eax + addl %esi,%ebp + movl 44(%esp),%esi + andl %ecx,%eax + rorl $2,%ecx + xorl %edi,%eax + leal 1518500249(%ebp,%esi,1),%ebp + addl %eax,%ebp + + movl %ecx,%esi + movl %ebp,%eax + roll $5,%ebp + xorl %edx,%esi + addl %edi,%ebp + movl 48(%esp),%edi + andl %ebx,%esi + rorl $2,%ebx + xorl %edx,%esi + leal 1518500249(%ebp,%edi,1),%ebp + addl %esi,%ebp + + movl %ebx,%edi + movl %ebp,%esi + roll $5,%ebp + xorl %ecx,%edi + addl %edx,%ebp + movl 52(%esp),%edx + andl %eax,%edi + rorl $2,%eax + xorl %ecx,%edi + leal 1518500249(%ebp,%edx,1),%ebp + addl %edi,%ebp + + movl %eax,%edx + movl %ebp,%edi + roll $5,%ebp + xorl %ebx,%edx + addl %ecx,%ebp + movl 56(%esp),%ecx + andl %esi,%edx + rorl $2,%esi + xorl %ebx,%edx + leal 1518500249(%ebp,%ecx,1),%ebp + addl %edx,%ebp + + movl %esi,%ecx + movl %ebp,%edx + roll $5,%ebp + xorl %eax,%ecx + addl %ebx,%ebp + movl 60(%esp),%ebx + andl %edi,%ecx + rorl $2,%edi + xorl %eax,%ecx + leal 1518500249(%ebp,%ebx,1),%ebp + movl (%esp),%ebx + addl %ebp,%ecx + + movl %edi,%ebp + xorl 8(%esp),%ebx + xorl %esi,%ebp + xorl 32(%esp),%ebx + andl %edx,%ebp + xorl 52(%esp),%ebx + roll $1,%ebx + xorl %esi,%ebp + addl %ebp,%eax + movl %ecx,%ebp + rorl $2,%edx + movl %ebx,(%esp) + roll $5,%ebp + leal 1518500249(%ebx,%eax,1),%ebx + movl 4(%esp),%eax + addl %ebp,%ebx + + movl %edx,%ebp + xorl 12(%esp),%eax + xorl %edi,%ebp + xorl 36(%esp),%eax + andl %ecx,%ebp + xorl 56(%esp),%eax + roll $1,%eax + xorl %edi,%ebp + addl %ebp,%esi + movl %ebx,%ebp + rorl $2,%ecx + movl %eax,4(%esp) + roll $5,%ebp + leal 1518500249(%eax,%esi,1),%eax + movl 8(%esp),%esi + addl %ebp,%eax + + movl %ecx,%ebp + xorl 16(%esp),%esi + xorl %edx,%ebp + xorl 40(%esp),%esi + andl %ebx,%ebp + xorl 60(%esp),%esi + roll $1,%esi + xorl %edx,%ebp + addl %ebp,%edi + movl %eax,%ebp + rorl $2,%ebx + movl %esi,8(%esp) + roll $5,%ebp + leal 1518500249(%esi,%edi,1),%esi + movl 12(%esp),%edi + addl %ebp,%esi + + movl %ebx,%ebp + xorl 20(%esp),%edi + xorl %ecx,%ebp + xorl 44(%esp),%edi + andl %eax,%ebp + xorl (%esp),%edi + roll $1,%edi + xorl %ecx,%ebp + addl %ebp,%edx + movl %esi,%ebp + rorl $2,%eax + movl %edi,12(%esp) + roll $5,%ebp + leal 1518500249(%edi,%edx,1),%edi + movl 16(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 24(%esp),%edx + xorl %eax,%ebp + xorl 48(%esp),%edx + xorl %ebx,%ebp + xorl 4(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,16(%esp) + leal 1859775393(%edx,%ecx,1),%edx + movl 20(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 28(%esp),%ecx + xorl %esi,%ebp + xorl 52(%esp),%ecx + xorl %eax,%ebp + xorl 8(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,20(%esp) + leal 1859775393(%ecx,%ebx,1),%ecx + movl 24(%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 32(%esp),%ebx + xorl %edi,%ebp + xorl 56(%esp),%ebx + xorl %esi,%ebp + xorl 12(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,24(%esp) + leal 1859775393(%ebx,%eax,1),%ebx + movl 28(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 36(%esp),%eax + xorl %edx,%ebp + xorl 60(%esp),%eax + xorl %edi,%ebp + xorl 16(%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + movl %eax,28(%esp) + leal 1859775393(%eax,%esi,1),%eax + movl 32(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl 40(%esp),%esi + xorl %ecx,%ebp + xorl (%esp),%esi + xorl %edx,%ebp + xorl 20(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,32(%esp) + leal 1859775393(%esi,%edi,1),%esi + movl 36(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 44(%esp),%edi + xorl %ebx,%ebp + xorl 4(%esp),%edi + xorl %ecx,%ebp + xorl 24(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,36(%esp) + leal 1859775393(%edi,%edx,1),%edi + movl 40(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 48(%esp),%edx + xorl %eax,%ebp + xorl 8(%esp),%edx + xorl %ebx,%ebp + xorl 28(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,40(%esp) + leal 1859775393(%edx,%ecx,1),%edx + movl 44(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 52(%esp),%ecx + xorl %esi,%ebp + xorl 12(%esp),%ecx + xorl %eax,%ebp + xorl 32(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,44(%esp) + leal 1859775393(%ecx,%ebx,1),%ecx + movl 48(%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 56(%esp),%ebx + xorl %edi,%ebp + xorl 16(%esp),%ebx + xorl %esi,%ebp + xorl 36(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,48(%esp) + leal 1859775393(%ebx,%eax,1),%ebx + movl 52(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 60(%esp),%eax + xorl %edx,%ebp + xorl 20(%esp),%eax + xorl %edi,%ebp + xorl 40(%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + movl %eax,52(%esp) + leal 1859775393(%eax,%esi,1),%eax + movl 56(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl (%esp),%esi + xorl %ecx,%ebp + xorl 24(%esp),%esi + xorl %edx,%ebp + xorl 44(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,56(%esp) + leal 1859775393(%esi,%edi,1),%esi + movl 60(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 4(%esp),%edi + xorl %ebx,%ebp + xorl 28(%esp),%edi + xorl %ecx,%ebp + xorl 48(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,60(%esp) + leal 1859775393(%edi,%edx,1),%edi + movl (%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 8(%esp),%edx + xorl %eax,%ebp + xorl 32(%esp),%edx + xorl %ebx,%ebp + xorl 52(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,(%esp) + leal 1859775393(%edx,%ecx,1),%edx + movl 4(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 12(%esp),%ecx + xorl %esi,%ebp + xorl 36(%esp),%ecx + xorl %eax,%ebp + xorl 56(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,4(%esp) + leal 1859775393(%ecx,%ebx,1),%ecx + movl 8(%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 16(%esp),%ebx + xorl %edi,%ebp + xorl 40(%esp),%ebx + xorl %esi,%ebp + xorl 60(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,8(%esp) + leal 1859775393(%ebx,%eax,1),%ebx + movl 12(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 20(%esp),%eax + xorl %edx,%ebp + xorl 44(%esp),%eax + xorl %edi,%ebp + xorl (%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + movl %eax,12(%esp) + leal 1859775393(%eax,%esi,1),%eax + movl 16(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl 24(%esp),%esi + xorl %ecx,%ebp + xorl 48(%esp),%esi + xorl %edx,%ebp + xorl 4(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,16(%esp) + leal 1859775393(%esi,%edi,1),%esi + movl 20(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 28(%esp),%edi + xorl %ebx,%ebp + xorl 52(%esp),%edi + xorl %ecx,%ebp + xorl 8(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,20(%esp) + leal 1859775393(%edi,%edx,1),%edi + movl 24(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 32(%esp),%edx + xorl %eax,%ebp + xorl 56(%esp),%edx + xorl %ebx,%ebp + xorl 12(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,24(%esp) + leal 1859775393(%edx,%ecx,1),%edx + movl 28(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 36(%esp),%ecx + xorl %esi,%ebp + xorl 60(%esp),%ecx + xorl %eax,%ebp + xorl 16(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,28(%esp) + leal 1859775393(%ecx,%ebx,1),%ecx + movl 32(%esp),%ebx + addl %ebp,%ecx + + movl %edi,%ebp + xorl 40(%esp),%ebx + xorl %esi,%ebp + xorl (%esp),%ebx + andl %edx,%ebp + xorl 20(%esp),%ebx + roll $1,%ebx + addl %eax,%ebp + rorl $2,%edx + movl %ecx,%eax + roll $5,%eax + movl %ebx,32(%esp) + leal 2400959708(%ebx,%ebp,1),%ebx + movl %edi,%ebp + addl %eax,%ebx + andl %esi,%ebp + movl 36(%esp),%eax + addl %ebp,%ebx + + movl %edx,%ebp + xorl 44(%esp),%eax + xorl %edi,%ebp + xorl 4(%esp),%eax + andl %ecx,%ebp + xorl 24(%esp),%eax + roll $1,%eax + addl %esi,%ebp + rorl $2,%ecx + movl %ebx,%esi + roll $5,%esi + movl %eax,36(%esp) + leal 2400959708(%eax,%ebp,1),%eax + movl %edx,%ebp + addl %esi,%eax + andl %edi,%ebp + movl 40(%esp),%esi + addl %ebp,%eax + + movl %ecx,%ebp + xorl 48(%esp),%esi + xorl %edx,%ebp + xorl 8(%esp),%esi + andl %ebx,%ebp + xorl 28(%esp),%esi + roll $1,%esi + addl %edi,%ebp + rorl $2,%ebx + movl %eax,%edi + roll $5,%edi + movl %esi,40(%esp) + leal 2400959708(%esi,%ebp,1),%esi + movl %ecx,%ebp + addl %edi,%esi + andl %edx,%ebp + movl 44(%esp),%edi + addl %ebp,%esi + + movl %ebx,%ebp + xorl 52(%esp),%edi + xorl %ecx,%ebp + xorl 12(%esp),%edi + andl %eax,%ebp + xorl 32(%esp),%edi + roll $1,%edi + addl %edx,%ebp + rorl $2,%eax + movl %esi,%edx + roll $5,%edx + movl %edi,44(%esp) + leal 2400959708(%edi,%ebp,1),%edi + movl %ebx,%ebp + addl %edx,%edi + andl %ecx,%ebp + movl 48(%esp),%edx + addl %ebp,%edi + + movl %eax,%ebp + xorl 56(%esp),%edx + xorl %ebx,%ebp + xorl 16(%esp),%edx + andl %esi,%ebp + xorl 36(%esp),%edx + roll $1,%edx + addl %ecx,%ebp + rorl $2,%esi + movl %edi,%ecx + roll $5,%ecx + movl %edx,48(%esp) + leal 2400959708(%edx,%ebp,1),%edx + movl %eax,%ebp + addl %ecx,%edx + andl %ebx,%ebp + movl 52(%esp),%ecx + addl %ebp,%edx + + movl %esi,%ebp + xorl 60(%esp),%ecx + xorl %eax,%ebp + xorl 20(%esp),%ecx + andl %edi,%ebp + xorl 40(%esp),%ecx + roll $1,%ecx + addl %ebx,%ebp + rorl $2,%edi + movl %edx,%ebx + roll $5,%ebx + movl %ecx,52(%esp) + leal 2400959708(%ecx,%ebp,1),%ecx + movl %esi,%ebp + addl %ebx,%ecx + andl %eax,%ebp + movl 56(%esp),%ebx + addl %ebp,%ecx + + movl %edi,%ebp + xorl (%esp),%ebx + xorl %esi,%ebp + xorl 24(%esp),%ebx + andl %edx,%ebp + xorl 44(%esp),%ebx + roll $1,%ebx + addl %eax,%ebp + rorl $2,%edx + movl %ecx,%eax + roll $5,%eax + movl %ebx,56(%esp) + leal 2400959708(%ebx,%ebp,1),%ebx + movl %edi,%ebp + addl %eax,%ebx + andl %esi,%ebp + movl 60(%esp),%eax + addl %ebp,%ebx + + movl %edx,%ebp + xorl 4(%esp),%eax + xorl %edi,%ebp + xorl 28(%esp),%eax + andl %ecx,%ebp + xorl 48(%esp),%eax + roll $1,%eax + addl %esi,%ebp + rorl $2,%ecx + movl %ebx,%esi + roll $5,%esi + movl %eax,60(%esp) + leal 2400959708(%eax,%ebp,1),%eax + movl %edx,%ebp + addl %esi,%eax + andl %edi,%ebp + movl (%esp),%esi + addl %ebp,%eax + + movl %ecx,%ebp + xorl 8(%esp),%esi + xorl %edx,%ebp + xorl 32(%esp),%esi + andl %ebx,%ebp + xorl 52(%esp),%esi + roll $1,%esi + addl %edi,%ebp + rorl $2,%ebx + movl %eax,%edi + roll $5,%edi + movl %esi,(%esp) + leal 2400959708(%esi,%ebp,1),%esi + movl %ecx,%ebp + addl %edi,%esi + andl %edx,%ebp + movl 4(%esp),%edi + addl %ebp,%esi + + movl %ebx,%ebp + xorl 12(%esp),%edi + xorl %ecx,%ebp + xorl 36(%esp),%edi + andl %eax,%ebp + xorl 56(%esp),%edi + roll $1,%edi + addl %edx,%ebp + rorl $2,%eax + movl %esi,%edx + roll $5,%edx + movl %edi,4(%esp) + leal 2400959708(%edi,%ebp,1),%edi + movl %ebx,%ebp + addl %edx,%edi + andl %ecx,%ebp + movl 8(%esp),%edx + addl %ebp,%edi + + movl %eax,%ebp + xorl 16(%esp),%edx + xorl %ebx,%ebp + xorl 40(%esp),%edx + andl %esi,%ebp + xorl 60(%esp),%edx + roll $1,%edx + addl %ecx,%ebp + rorl $2,%esi + movl %edi,%ecx + roll $5,%ecx + movl %edx,8(%esp) + leal 2400959708(%edx,%ebp,1),%edx + movl %eax,%ebp + addl %ecx,%edx + andl %ebx,%ebp + movl 12(%esp),%ecx + addl %ebp,%edx + + movl %esi,%ebp + xorl 20(%esp),%ecx + xorl %eax,%ebp + xorl 44(%esp),%ecx + andl %edi,%ebp + xorl (%esp),%ecx + roll $1,%ecx + addl %ebx,%ebp + rorl $2,%edi + movl %edx,%ebx + roll $5,%ebx + movl %ecx,12(%esp) + leal 2400959708(%ecx,%ebp,1),%ecx + movl %esi,%ebp + addl %ebx,%ecx + andl %eax,%ebp + movl 16(%esp),%ebx + addl %ebp,%ecx + + movl %edi,%ebp + xorl 24(%esp),%ebx + xorl %esi,%ebp + xorl 48(%esp),%ebx + andl %edx,%ebp + xorl 4(%esp),%ebx + roll $1,%ebx + addl %eax,%ebp + rorl $2,%edx + movl %ecx,%eax + roll $5,%eax + movl %ebx,16(%esp) + leal 2400959708(%ebx,%ebp,1),%ebx + movl %edi,%ebp + addl %eax,%ebx + andl %esi,%ebp + movl 20(%esp),%eax + addl %ebp,%ebx + + movl %edx,%ebp + xorl 28(%esp),%eax + xorl %edi,%ebp + xorl 52(%esp),%eax + andl %ecx,%ebp + xorl 8(%esp),%eax + roll $1,%eax + addl %esi,%ebp + rorl $2,%ecx + movl %ebx,%esi + roll $5,%esi + movl %eax,20(%esp) + leal 2400959708(%eax,%ebp,1),%eax + movl %edx,%ebp + addl %esi,%eax + andl %edi,%ebp + movl 24(%esp),%esi + addl %ebp,%eax + + movl %ecx,%ebp + xorl 32(%esp),%esi + xorl %edx,%ebp + xorl 56(%esp),%esi + andl %ebx,%ebp + xorl 12(%esp),%esi + roll $1,%esi + addl %edi,%ebp + rorl $2,%ebx + movl %eax,%edi + roll $5,%edi + movl %esi,24(%esp) + leal 2400959708(%esi,%ebp,1),%esi + movl %ecx,%ebp + addl %edi,%esi + andl %edx,%ebp + movl 28(%esp),%edi + addl %ebp,%esi + + movl %ebx,%ebp + xorl 36(%esp),%edi + xorl %ecx,%ebp + xorl 60(%esp),%edi + andl %eax,%ebp + xorl 16(%esp),%edi + roll $1,%edi + addl %edx,%ebp + rorl $2,%eax + movl %esi,%edx + roll $5,%edx + movl %edi,28(%esp) + leal 2400959708(%edi,%ebp,1),%edi + movl %ebx,%ebp + addl %edx,%edi + andl %ecx,%ebp + movl 32(%esp),%edx + addl %ebp,%edi + + movl %eax,%ebp + xorl 40(%esp),%edx + xorl %ebx,%ebp + xorl (%esp),%edx + andl %esi,%ebp + xorl 20(%esp),%edx + roll $1,%edx + addl %ecx,%ebp + rorl $2,%esi + movl %edi,%ecx + roll $5,%ecx + movl %edx,32(%esp) + leal 2400959708(%edx,%ebp,1),%edx + movl %eax,%ebp + addl %ecx,%edx + andl %ebx,%ebp + movl 36(%esp),%ecx + addl %ebp,%edx + + movl %esi,%ebp + xorl 44(%esp),%ecx + xorl %eax,%ebp + xorl 4(%esp),%ecx + andl %edi,%ebp + xorl 24(%esp),%ecx + roll $1,%ecx + addl %ebx,%ebp + rorl $2,%edi + movl %edx,%ebx + roll $5,%ebx + movl %ecx,36(%esp) + leal 2400959708(%ecx,%ebp,1),%ecx + movl %esi,%ebp + addl %ebx,%ecx + andl %eax,%ebp + movl 40(%esp),%ebx + addl %ebp,%ecx + + movl %edi,%ebp + xorl 48(%esp),%ebx + xorl %esi,%ebp + xorl 8(%esp),%ebx + andl %edx,%ebp + xorl 28(%esp),%ebx + roll $1,%ebx + addl %eax,%ebp + rorl $2,%edx + movl %ecx,%eax + roll $5,%eax + movl %ebx,40(%esp) + leal 2400959708(%ebx,%ebp,1),%ebx + movl %edi,%ebp + addl %eax,%ebx + andl %esi,%ebp + movl 44(%esp),%eax + addl %ebp,%ebx + + movl %edx,%ebp + xorl 52(%esp),%eax + xorl %edi,%ebp + xorl 12(%esp),%eax + andl %ecx,%ebp + xorl 32(%esp),%eax + roll $1,%eax + addl %esi,%ebp + rorl $2,%ecx + movl %ebx,%esi + roll $5,%esi + movl %eax,44(%esp) + leal 2400959708(%eax,%ebp,1),%eax + movl %edx,%ebp + addl %esi,%eax + andl %edi,%ebp + movl 48(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl 56(%esp),%esi + xorl %ecx,%ebp + xorl 16(%esp),%esi + xorl %edx,%ebp + xorl 36(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,48(%esp) + leal 3395469782(%esi,%edi,1),%esi + movl 52(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 60(%esp),%edi + xorl %ebx,%ebp + xorl 20(%esp),%edi + xorl %ecx,%ebp + xorl 40(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,52(%esp) + leal 3395469782(%edi,%edx,1),%edi + movl 56(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl (%esp),%edx + xorl %eax,%ebp + xorl 24(%esp),%edx + xorl %ebx,%ebp + xorl 44(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,56(%esp) + leal 3395469782(%edx,%ecx,1),%edx + movl 60(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 4(%esp),%ecx + xorl %esi,%ebp + xorl 28(%esp),%ecx + xorl %eax,%ebp + xorl 48(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,60(%esp) + leal 3395469782(%ecx,%ebx,1),%ecx + movl (%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 8(%esp),%ebx + xorl %edi,%ebp + xorl 32(%esp),%ebx + xorl %esi,%ebp + xorl 52(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,(%esp) + leal 3395469782(%ebx,%eax,1),%ebx + movl 4(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 12(%esp),%eax + xorl %edx,%ebp + xorl 36(%esp),%eax + xorl %edi,%ebp + xorl 56(%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + movl %eax,4(%esp) + leal 3395469782(%eax,%esi,1),%eax + movl 8(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl 16(%esp),%esi + xorl %ecx,%ebp + xorl 40(%esp),%esi + xorl %edx,%ebp + xorl 60(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,8(%esp) + leal 3395469782(%esi,%edi,1),%esi + movl 12(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 20(%esp),%edi + xorl %ebx,%ebp + xorl 44(%esp),%edi + xorl %ecx,%ebp + xorl (%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,12(%esp) + leal 3395469782(%edi,%edx,1),%edi + movl 16(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 24(%esp),%edx + xorl %eax,%ebp + xorl 48(%esp),%edx + xorl %ebx,%ebp + xorl 4(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,16(%esp) + leal 3395469782(%edx,%ecx,1),%edx + movl 20(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 28(%esp),%ecx + xorl %esi,%ebp + xorl 52(%esp),%ecx + xorl %eax,%ebp + xorl 8(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,20(%esp) + leal 3395469782(%ecx,%ebx,1),%ecx + movl 24(%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 32(%esp),%ebx + xorl %edi,%ebp + xorl 56(%esp),%ebx + xorl %esi,%ebp + xorl 12(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,24(%esp) + leal 3395469782(%ebx,%eax,1),%ebx + movl 28(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 36(%esp),%eax + xorl %edx,%ebp + xorl 60(%esp),%eax + xorl %edi,%ebp + xorl 16(%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + movl %eax,28(%esp) + leal 3395469782(%eax,%esi,1),%eax + movl 32(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl 40(%esp),%esi + xorl %ecx,%ebp + xorl (%esp),%esi + xorl %edx,%ebp + xorl 20(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + movl %esi,32(%esp) + leal 3395469782(%esi,%edi,1),%esi + movl 36(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 44(%esp),%edi + xorl %ebx,%ebp + xorl 4(%esp),%edi + xorl %ecx,%ebp + xorl 24(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + movl %edi,36(%esp) + leal 3395469782(%edi,%edx,1),%edi + movl 40(%esp),%edx + addl %ebp,%edi + + movl %esi,%ebp + xorl 48(%esp),%edx + xorl %eax,%ebp + xorl 8(%esp),%edx + xorl %ebx,%ebp + xorl 28(%esp),%edx + roll $1,%edx + addl %ebp,%ecx + rorl $2,%esi + movl %edi,%ebp + roll $5,%ebp + movl %edx,40(%esp) + leal 3395469782(%edx,%ecx,1),%edx + movl 44(%esp),%ecx + addl %ebp,%edx + + movl %edi,%ebp + xorl 52(%esp),%ecx + xorl %esi,%ebp + xorl 12(%esp),%ecx + xorl %eax,%ebp + xorl 32(%esp),%ecx + roll $1,%ecx + addl %ebp,%ebx + rorl $2,%edi + movl %edx,%ebp + roll $5,%ebp + movl %ecx,44(%esp) + leal 3395469782(%ecx,%ebx,1),%ecx + movl 48(%esp),%ebx + addl %ebp,%ecx + + movl %edx,%ebp + xorl 56(%esp),%ebx + xorl %edi,%ebp + xorl 16(%esp),%ebx + xorl %esi,%ebp + xorl 36(%esp),%ebx + roll $1,%ebx + addl %ebp,%eax + rorl $2,%edx + movl %ecx,%ebp + roll $5,%ebp + movl %ebx,48(%esp) + leal 3395469782(%ebx,%eax,1),%ebx + movl 52(%esp),%eax + addl %ebp,%ebx + + movl %ecx,%ebp + xorl 60(%esp),%eax + xorl %edx,%ebp + xorl 20(%esp),%eax + xorl %edi,%ebp + xorl 40(%esp),%eax + roll $1,%eax + addl %ebp,%esi + rorl $2,%ecx + movl %ebx,%ebp + roll $5,%ebp + leal 3395469782(%eax,%esi,1),%eax + movl 56(%esp),%esi + addl %ebp,%eax + + movl %ebx,%ebp + xorl (%esp),%esi + xorl %ecx,%ebp + xorl 24(%esp),%esi + xorl %edx,%ebp + xorl 44(%esp),%esi + roll $1,%esi + addl %ebp,%edi + rorl $2,%ebx + movl %eax,%ebp + roll $5,%ebp + leal 3395469782(%esi,%edi,1),%esi + movl 60(%esp),%edi + addl %ebp,%esi + + movl %eax,%ebp + xorl 4(%esp),%edi + xorl %ebx,%ebp + xorl 28(%esp),%edi + xorl %ecx,%ebp + xorl 48(%esp),%edi + roll $1,%edi + addl %ebp,%edx + rorl $2,%eax + movl %esi,%ebp + roll $5,%ebp + leal 3395469782(%edi,%edx,1),%edi + addl %ebp,%edi + movl 96(%esp),%ebp + movl 100(%esp),%edx + addl (%ebp),%edi + addl 4(%ebp),%esi + addl 8(%ebp),%eax + addl 12(%ebp),%ebx + addl 16(%ebp),%ecx + movl %edi,(%ebp) + addl $64,%edx + movl %esi,4(%ebp) + cmpl 104(%esp),%edx + movl %eax,8(%ebp) + movl %ecx,%edi + movl %ebx,12(%ebp) + movl %edx,%esi + movl %ecx,16(%ebp) + jb .L000loop + addl $76,%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size sha1_block_data_order,.-.L_sha1_block_data_order_begin +.byte 83,72,65,49,32,98,108,111,99,107,32,116,114,97,110,115 +.byte 102,111,114,109,32,102,111,114,32,120,56,54,44,32,67,82 +.byte 89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112 +.byte 114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0 diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha256-586.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha256-586.S new file mode 100644 index 0000000000..260dde7ad7 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha256-586.S @@ -0,0 +1,3356 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/sha/asm/sha256-586.pl +# +# Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl sha256_block_data_order +.type sha256_block_data_order,@function +.align 16 +sha256_block_data_order: +.L_sha256_block_data_order_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl %esp,%ebx + call .L000pic_point +.L000pic_point: + popl %ebp + leal .L001K256-.L000pic_point(%ebp),%ebp + subl $16,%esp + andl $-64,%esp + shll $6,%eax + addl %edi,%eax + movl %esi,(%esp) + movl %edi,4(%esp) + movl %eax,8(%esp) + movl %ebx,12(%esp) + jmp .L002loop +.align 16 +.L002loop: + movl (%edi),%eax + movl 4(%edi),%ebx + movl 8(%edi),%ecx + bswap %eax + movl 12(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 16(%edi),%eax + movl 20(%edi),%ebx + movl 24(%edi),%ecx + bswap %eax + movl 28(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 32(%edi),%eax + movl 36(%edi),%ebx + movl 40(%edi),%ecx + bswap %eax + movl 44(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 48(%edi),%eax + movl 52(%edi),%ebx + movl 56(%edi),%ecx + bswap %eax + movl 60(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + addl $64,%edi + leal -36(%esp),%esp + movl %edi,104(%esp) + movl (%esi),%eax + movl 4(%esi),%ebx + movl 8(%esi),%ecx + movl 12(%esi),%edi + movl %ebx,8(%esp) + xorl %ecx,%ebx + movl %ecx,12(%esp) + movl %edi,16(%esp) + movl %ebx,(%esp) + movl 16(%esi),%edx + movl 20(%esi),%ebx + movl 24(%esi),%ecx + movl 28(%esi),%edi + movl %ebx,24(%esp) + movl %ecx,28(%esp) + movl %edi,32(%esp) +.align 16 +.L00300_15: + movl %edx,%ecx + movl 24(%esp),%esi + rorl $14,%ecx + movl 28(%esp),%edi + xorl %edx,%ecx + xorl %edi,%esi + movl 96(%esp),%ebx + rorl $5,%ecx + andl %edx,%esi + movl %edx,20(%esp) + xorl %ecx,%edx + addl 32(%esp),%ebx + xorl %edi,%esi + rorl $6,%edx + movl %eax,%ecx + addl %esi,%ebx + rorl $9,%ecx + addl %edx,%ebx + movl 8(%esp),%edi + xorl %eax,%ecx + movl %eax,4(%esp) + leal -4(%esp),%esp + rorl $11,%ecx + movl (%ebp),%esi + xorl %eax,%ecx + movl 20(%esp),%edx + xorl %edi,%eax + rorl $2,%ecx + addl %esi,%ebx + movl %eax,(%esp) + addl %ebx,%edx + andl 4(%esp),%eax + addl %ecx,%ebx + xorl %edi,%eax + addl $4,%ebp + addl %ebx,%eax + cmpl $3248222580,%esi + jne .L00300_15 + movl 156(%esp),%ecx + jmp .L00416_63 +.align 16 +.L00416_63: + movl %ecx,%ebx + movl 104(%esp),%esi + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 160(%esp),%ebx + shrl $10,%edi + addl 124(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 24(%esp),%esi + rorl $14,%ecx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %edx,%ecx + xorl %edi,%esi + movl %ebx,96(%esp) + rorl $5,%ecx + andl %edx,%esi + movl %edx,20(%esp) + xorl %ecx,%edx + addl 32(%esp),%ebx + xorl %edi,%esi + rorl $6,%edx + movl %eax,%ecx + addl %esi,%ebx + rorl $9,%ecx + addl %edx,%ebx + movl 8(%esp),%edi + xorl %eax,%ecx + movl %eax,4(%esp) + leal -4(%esp),%esp + rorl $11,%ecx + movl (%ebp),%esi + xorl %eax,%ecx + movl 20(%esp),%edx + xorl %edi,%eax + rorl $2,%ecx + addl %esi,%ebx + movl %eax,(%esp) + addl %ebx,%edx + andl 4(%esp),%eax + addl %ecx,%ebx + xorl %edi,%eax + movl 156(%esp),%ecx + addl $4,%ebp + addl %ebx,%eax + cmpl $3329325298,%esi + jne .L00416_63 + movl 356(%esp),%esi + movl 8(%esp),%ebx + movl 16(%esp),%ecx + addl (%esi),%eax + addl 4(%esi),%ebx + addl 8(%esi),%edi + addl 12(%esi),%ecx + movl %eax,(%esi) + movl %ebx,4(%esi) + movl %edi,8(%esi) + movl %ecx,12(%esi) + movl 24(%esp),%eax + movl 28(%esp),%ebx + movl 32(%esp),%ecx + movl 360(%esp),%edi + addl 16(%esi),%edx + addl 20(%esi),%eax + addl 24(%esi),%ebx + addl 28(%esi),%ecx + movl %edx,16(%esi) + movl %eax,20(%esi) + movl %ebx,24(%esi) + movl %ecx,28(%esi) + leal 356(%esp),%esp + subl $256,%ebp + cmpl 8(%esp),%edi + jb .L002loop + movl 12(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.align 32 +.L005loop_shrd: + movl (%edi),%eax + movl 4(%edi),%ebx + movl 8(%edi),%ecx + bswap %eax + movl 12(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 16(%edi),%eax + movl 20(%edi),%ebx + movl 24(%edi),%ecx + bswap %eax + movl 28(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 32(%edi),%eax + movl 36(%edi),%ebx + movl 40(%edi),%ecx + bswap %eax + movl 44(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + movl 48(%edi),%eax + movl 52(%edi),%ebx + movl 56(%edi),%ecx + bswap %eax + movl 60(%edi),%edx + bswap %ebx + pushl %eax + bswap %ecx + pushl %ebx + bswap %edx + pushl %ecx + pushl %edx + addl $64,%edi + leal -36(%esp),%esp + movl %edi,104(%esp) + movl (%esi),%eax + movl 4(%esi),%ebx + movl 8(%esi),%ecx + movl 12(%esi),%edi + movl %ebx,8(%esp) + xorl %ecx,%ebx + movl %ecx,12(%esp) + movl %edi,16(%esp) + movl %ebx,(%esp) + movl 16(%esi),%edx + movl 20(%esi),%ebx + movl 24(%esi),%ecx + movl 28(%esi),%edi + movl %ebx,24(%esp) + movl %ecx,28(%esp) + movl %edi,32(%esp) +.align 16 +.L00600_15_shrd: + movl %edx,%ecx + movl 24(%esp),%esi + shrdl $14,%ecx,%ecx + movl 28(%esp),%edi + xorl %edx,%ecx + xorl %edi,%esi + movl 96(%esp),%ebx + shrdl $5,%ecx,%ecx + andl %edx,%esi + movl %edx,20(%esp) + xorl %ecx,%edx + addl 32(%esp),%ebx + xorl %edi,%esi + shrdl $6,%edx,%edx + movl %eax,%ecx + addl %esi,%ebx + shrdl $9,%ecx,%ecx + addl %edx,%ebx + movl 8(%esp),%edi + xorl %eax,%ecx + movl %eax,4(%esp) + leal -4(%esp),%esp + shrdl $11,%ecx,%ecx + movl (%ebp),%esi + xorl %eax,%ecx + movl 20(%esp),%edx + xorl %edi,%eax + shrdl $2,%ecx,%ecx + addl %esi,%ebx + movl %eax,(%esp) + addl %ebx,%edx + andl 4(%esp),%eax + addl %ecx,%ebx + xorl %edi,%eax + addl $4,%ebp + addl %ebx,%eax + cmpl $3248222580,%esi + jne .L00600_15_shrd + movl 156(%esp),%ecx + jmp .L00716_63_shrd +.align 16 +.L00716_63_shrd: + movl %ecx,%ebx + movl 104(%esp),%esi + shrdl $11,%ecx,%ecx + movl %esi,%edi + shrdl $2,%esi,%esi + xorl %ebx,%ecx + shrl $3,%ebx + shrdl $7,%ecx,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + shrdl $17,%esi,%esi + addl 160(%esp),%ebx + shrl $10,%edi + addl 124(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 24(%esp),%esi + shrdl $14,%ecx,%ecx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %edx,%ecx + xorl %edi,%esi + movl %ebx,96(%esp) + shrdl $5,%ecx,%ecx + andl %edx,%esi + movl %edx,20(%esp) + xorl %ecx,%edx + addl 32(%esp),%ebx + xorl %edi,%esi + shrdl $6,%edx,%edx + movl %eax,%ecx + addl %esi,%ebx + shrdl $9,%ecx,%ecx + addl %edx,%ebx + movl 8(%esp),%edi + xorl %eax,%ecx + movl %eax,4(%esp) + leal -4(%esp),%esp + shrdl $11,%ecx,%ecx + movl (%ebp),%esi + xorl %eax,%ecx + movl 20(%esp),%edx + xorl %edi,%eax + shrdl $2,%ecx,%ecx + addl %esi,%ebx + movl %eax,(%esp) + addl %ebx,%edx + andl 4(%esp),%eax + addl %ecx,%ebx + xorl %edi,%eax + movl 156(%esp),%ecx + addl $4,%ebp + addl %ebx,%eax + cmpl $3329325298,%esi + jne .L00716_63_shrd + movl 356(%esp),%esi + movl 8(%esp),%ebx + movl 16(%esp),%ecx + addl (%esi),%eax + addl 4(%esi),%ebx + addl 8(%esi),%edi + addl 12(%esi),%ecx + movl %eax,(%esi) + movl %ebx,4(%esi) + movl %edi,8(%esi) + movl %ecx,12(%esi) + movl 24(%esp),%eax + movl 28(%esp),%ebx + movl 32(%esp),%ecx + movl 360(%esp),%edi + addl 16(%esi),%edx + addl 20(%esi),%eax + addl 24(%esi),%ebx + addl 28(%esi),%ecx + movl %edx,16(%esi) + movl %eax,20(%esi) + movl %ebx,24(%esi) + movl %ecx,28(%esi) + leal 356(%esp),%esp + subl $256,%ebp + cmpl 8(%esp),%edi + jb .L005loop_shrd + movl 12(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.align 64 +.L001K256: +.long 1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298 +.long 66051,67438087,134810123,202182159 +.byte 83,72,65,50,53,54,32,98,108,111,99,107,32,116,114,97 +.byte 110,115,102,111,114,109,32,102,111,114,32,120,56,54,44,32 +.byte 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 +.byte 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 +.byte 62,0 +.align 16 +.L008unrolled: + leal -96(%esp),%esp + movl (%esi),%eax + movl 4(%esi),%ebp + movl 8(%esi),%ecx + movl 12(%esi),%ebx + movl %ebp,4(%esp) + xorl %ecx,%ebp + movl %ecx,8(%esp) + movl %ebx,12(%esp) + movl 16(%esi),%edx + movl 20(%esi),%ebx + movl 24(%esi),%ecx + movl 28(%esi),%esi + movl %ebx,20(%esp) + movl %ecx,24(%esp) + movl %esi,28(%esp) + jmp .L009grand_loop +.align 16 +.L009grand_loop: + movl (%edi),%ebx + movl 4(%edi),%ecx + bswap %ebx + movl 8(%edi),%esi + bswap %ecx + movl %ebx,32(%esp) + bswap %esi + movl %ecx,36(%esp) + movl %esi,40(%esp) + movl 12(%edi),%ebx + movl 16(%edi),%ecx + bswap %ebx + movl 20(%edi),%esi + bswap %ecx + movl %ebx,44(%esp) + bswap %esi + movl %ecx,48(%esp) + movl %esi,52(%esp) + movl 24(%edi),%ebx + movl 28(%edi),%ecx + bswap %ebx + movl 32(%edi),%esi + bswap %ecx + movl %ebx,56(%esp) + bswap %esi + movl %ecx,60(%esp) + movl %esi,64(%esp) + movl 36(%edi),%ebx + movl 40(%edi),%ecx + bswap %ebx + movl 44(%edi),%esi + bswap %ecx + movl %ebx,68(%esp) + bswap %esi + movl %ecx,72(%esp) + movl %esi,76(%esp) + movl 48(%edi),%ebx + movl 52(%edi),%ecx + bswap %ebx + movl 56(%edi),%esi + bswap %ecx + movl %ebx,80(%esp) + bswap %esi + movl %ecx,84(%esp) + movl %esi,88(%esp) + movl 60(%edi),%ebx + addl $64,%edi + bswap %ebx + movl %edi,100(%esp) + movl %ebx,92(%esp) + movl %edx,%ecx + movl 20(%esp),%esi + rorl $14,%edx + movl 24(%esp),%edi + xorl %ecx,%edx + movl 32(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1116352408(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 16(%esp),%ecx + rorl $14,%edx + movl 20(%esp),%edi + xorl %esi,%edx + movl 36(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1899447441(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 12(%esp),%esi + rorl $14,%edx + movl 16(%esp),%edi + xorl %ecx,%edx + movl 40(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3049323471(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 8(%esp),%ecx + rorl $14,%edx + movl 12(%esp),%edi + xorl %esi,%edx + movl 44(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3921009573(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 4(%esp),%esi + rorl $14,%edx + movl 8(%esp),%edi + xorl %ecx,%edx + movl 48(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 961987163(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl (%esp),%ecx + rorl $14,%edx + movl 4(%esp),%edi + xorl %esi,%edx + movl 52(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1508970993(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 28(%esp),%esi + rorl $14,%edx + movl (%esp),%edi + xorl %ecx,%edx + movl 56(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2453635748(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 24(%esp),%ecx + rorl $14,%edx + movl 28(%esp),%edi + xorl %esi,%edx + movl 60(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2870763221(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 20(%esp),%esi + rorl $14,%edx + movl 24(%esp),%edi + xorl %ecx,%edx + movl 64(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3624381080(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 16(%esp),%ecx + rorl $14,%edx + movl 20(%esp),%edi + xorl %esi,%edx + movl 68(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 310598401(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 12(%esp),%esi + rorl $14,%edx + movl 16(%esp),%edi + xorl %ecx,%edx + movl 72(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 607225278(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 8(%esp),%ecx + rorl $14,%edx + movl 12(%esp),%edi + xorl %esi,%edx + movl 76(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1426881987(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 4(%esp),%esi + rorl $14,%edx + movl 8(%esp),%edi + xorl %ecx,%edx + movl 80(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1925078388(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl (%esp),%ecx + rorl $14,%edx + movl 4(%esp),%edi + xorl %esi,%edx + movl 84(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2162078206(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl %edx,%ecx + movl 28(%esp),%esi + rorl $14,%edx + movl (%esp),%edi + xorl %ecx,%edx + movl 88(%esp),%ebx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2614888103(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl %edx,%esi + movl 24(%esp),%ecx + rorl $14,%edx + movl 28(%esp),%edi + xorl %esi,%edx + movl 92(%esp),%ebx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3248222580(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 36(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 88(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 32(%esp),%ebx + shrl $10,%edi + addl 68(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,32(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3835390401(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 40(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 92(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 36(%esp),%ebx + shrl $10,%edi + addl 72(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,36(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 4022224774(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 44(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 32(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 40(%esp),%ebx + shrl $10,%edi + addl 76(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,40(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 264347078(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 48(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 36(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 44(%esp),%ebx + shrl $10,%edi + addl 80(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,44(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 604807628(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 52(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 40(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 48(%esp),%ebx + shrl $10,%edi + addl 84(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,48(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 770255983(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 56(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 44(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 52(%esp),%ebx + shrl $10,%edi + addl 88(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,52(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1249150122(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 60(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 48(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 56(%esp),%ebx + shrl $10,%edi + addl 92(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + movl %ebx,56(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1555081692(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 64(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 52(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 60(%esp),%ebx + shrl $10,%edi + addl 32(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + movl %ebx,60(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1996064986(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 68(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 56(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 64(%esp),%ebx + shrl $10,%edi + addl 36(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,64(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2554220882(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 72(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 60(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 68(%esp),%ebx + shrl $10,%edi + addl 40(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,68(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2821834349(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 76(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 64(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 72(%esp),%ebx + shrl $10,%edi + addl 44(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,72(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2952996808(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 80(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 68(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 76(%esp),%ebx + shrl $10,%edi + addl 48(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,76(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3210313671(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 84(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 72(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 80(%esp),%ebx + shrl $10,%edi + addl 52(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,80(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3336571891(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 88(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 76(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 84(%esp),%ebx + shrl $10,%edi + addl 56(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,84(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3584528711(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 92(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 80(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 88(%esp),%ebx + shrl $10,%edi + addl 60(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + movl %ebx,88(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 113926993(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 32(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 84(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 92(%esp),%ebx + shrl $10,%edi + addl 64(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + movl %ebx,92(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 338241895(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 36(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 88(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 32(%esp),%ebx + shrl $10,%edi + addl 68(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,32(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 666307205(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 40(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 92(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 36(%esp),%ebx + shrl $10,%edi + addl 72(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,36(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 773529912(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 44(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 32(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 40(%esp),%ebx + shrl $10,%edi + addl 76(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,40(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1294757372(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 48(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 36(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 44(%esp),%ebx + shrl $10,%edi + addl 80(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,44(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1396182291(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 52(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 40(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 48(%esp),%ebx + shrl $10,%edi + addl 84(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,48(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1695183700(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 56(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 44(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 52(%esp),%ebx + shrl $10,%edi + addl 88(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,52(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1986661051(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 60(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 48(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 56(%esp),%ebx + shrl $10,%edi + addl 92(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + movl %ebx,56(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2177026350(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 64(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 52(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 60(%esp),%ebx + shrl $10,%edi + addl 32(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + movl %ebx,60(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2456956037(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 68(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 56(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 64(%esp),%ebx + shrl $10,%edi + addl 36(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,64(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2730485921(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 72(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 60(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 68(%esp),%ebx + shrl $10,%edi + addl 40(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,68(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2820302411(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 76(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 64(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 72(%esp),%ebx + shrl $10,%edi + addl 44(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,72(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3259730800(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 80(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 68(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 76(%esp),%ebx + shrl $10,%edi + addl 48(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,76(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3345764771(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 84(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 72(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 80(%esp),%ebx + shrl $10,%edi + addl 52(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,80(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3516065817(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 88(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 76(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 84(%esp),%ebx + shrl $10,%edi + addl 56(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,84(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3600352804(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 92(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 80(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 88(%esp),%ebx + shrl $10,%edi + addl 60(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + movl %ebx,88(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 4094571909(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 32(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 84(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 92(%esp),%ebx + shrl $10,%edi + addl 64(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + movl %ebx,92(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 275423344(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 36(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 88(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 32(%esp),%ebx + shrl $10,%edi + addl 68(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,32(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 430227734(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 40(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 92(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 36(%esp),%ebx + shrl $10,%edi + addl 72(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,36(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 506948616(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 44(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 32(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 40(%esp),%ebx + shrl $10,%edi + addl 76(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,40(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 659060556(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 48(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 36(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 44(%esp),%ebx + shrl $10,%edi + addl 80(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,44(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 883997877(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 52(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 40(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 48(%esp),%ebx + shrl $10,%edi + addl 84(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,48(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 958139571(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 56(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 44(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 52(%esp),%ebx + shrl $10,%edi + addl 88(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,52(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1322822218(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 60(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 48(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 56(%esp),%ebx + shrl $10,%edi + addl 92(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + movl %ebx,56(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1537002063(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 64(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 52(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 60(%esp),%ebx + shrl $10,%edi + addl 32(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + movl %ebx,60(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 1747873779(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 68(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 56(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 64(%esp),%ebx + shrl $10,%edi + addl 36(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 20(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 24(%esp),%edi + xorl %ecx,%edx + movl %ebx,64(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,16(%esp) + xorl %ecx,%edx + addl 28(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 4(%esp),%edi + xorl %eax,%ecx + movl %eax,(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 1955562222(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 72(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 12(%esp),%edx + addl %ecx,%ebp + movl 60(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 68(%esp),%ebx + shrl $10,%edi + addl 40(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 16(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 20(%esp),%edi + xorl %esi,%edx + movl %ebx,68(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,12(%esp) + xorl %esi,%edx + addl 24(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl (%esp),%edi + xorl %ebp,%esi + movl %ebp,28(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2024104815(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 76(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 8(%esp),%edx + addl %esi,%eax + movl 64(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 72(%esp),%ebx + shrl $10,%edi + addl 44(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 12(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 16(%esp),%edi + xorl %ecx,%edx + movl %ebx,72(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,8(%esp) + xorl %ecx,%edx + addl 20(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 28(%esp),%edi + xorl %eax,%ecx + movl %eax,24(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2227730452(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 80(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 4(%esp),%edx + addl %ecx,%ebp + movl 68(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 76(%esp),%ebx + shrl $10,%edi + addl 48(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 8(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 12(%esp),%edi + xorl %esi,%edx + movl %ebx,76(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,4(%esp) + xorl %esi,%edx + addl 16(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 24(%esp),%edi + xorl %ebp,%esi + movl %ebp,20(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2361852424(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 84(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl (%esp),%edx + addl %esi,%eax + movl 72(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 80(%esp),%ebx + shrl $10,%edi + addl 52(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 4(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl 8(%esp),%edi + xorl %ecx,%edx + movl %ebx,80(%esp) + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,(%esp) + xorl %ecx,%edx + addl 12(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 20(%esp),%edi + xorl %eax,%ecx + movl %eax,16(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 2428436474(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 88(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 28(%esp),%edx + addl %ecx,%ebp + movl 76(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 84(%esp),%ebx + shrl $10,%edi + addl 56(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl (%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 4(%esp),%edi + xorl %esi,%edx + movl %ebx,84(%esp) + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,28(%esp) + xorl %esi,%edx + addl 8(%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 16(%esp),%edi + xorl %ebp,%esi + movl %ebp,12(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 2756734187(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + movl 92(%esp),%ecx + rorl $2,%esi + addl %edx,%eax + addl 24(%esp),%edx + addl %esi,%eax + movl 80(%esp),%esi + movl %ecx,%ebx + rorl $11,%ecx + movl %esi,%edi + rorl $2,%esi + xorl %ebx,%ecx + shrl $3,%ebx + rorl $7,%ecx + xorl %edi,%esi + xorl %ecx,%ebx + rorl $17,%esi + addl 88(%esp),%ebx + shrl $10,%edi + addl 60(%esp),%ebx + movl %edx,%ecx + xorl %esi,%edi + movl 28(%esp),%esi + rorl $14,%edx + addl %edi,%ebx + movl (%esp),%edi + xorl %ecx,%edx + xorl %edi,%esi + rorl $5,%edx + andl %ecx,%esi + movl %ecx,24(%esp) + xorl %ecx,%edx + addl 4(%esp),%ebx + xorl %esi,%edi + rorl $6,%edx + movl %eax,%ecx + addl %edi,%ebx + rorl $9,%ecx + movl %eax,%esi + movl 12(%esp),%edi + xorl %eax,%ecx + movl %eax,8(%esp) + xorl %edi,%eax + rorl $11,%ecx + andl %eax,%ebp + leal 3204031479(%ebx,%edx,1),%edx + xorl %esi,%ecx + xorl %edi,%ebp + movl 32(%esp),%esi + rorl $2,%ecx + addl %edx,%ebp + addl 20(%esp),%edx + addl %ecx,%ebp + movl 84(%esp),%ecx + movl %esi,%ebx + rorl $11,%esi + movl %ecx,%edi + rorl $2,%ecx + xorl %ebx,%esi + shrl $3,%ebx + rorl $7,%esi + xorl %edi,%ecx + xorl %esi,%ebx + rorl $17,%ecx + addl 92(%esp),%ebx + shrl $10,%edi + addl 64(%esp),%ebx + movl %edx,%esi + xorl %ecx,%edi + movl 24(%esp),%ecx + rorl $14,%edx + addl %edi,%ebx + movl 28(%esp),%edi + xorl %esi,%edx + xorl %edi,%ecx + rorl $5,%edx + andl %esi,%ecx + movl %esi,20(%esp) + xorl %esi,%edx + addl (%esp),%ebx + xorl %ecx,%edi + rorl $6,%edx + movl %ebp,%esi + addl %edi,%ebx + rorl $9,%esi + movl %ebp,%ecx + movl 8(%esp),%edi + xorl %ebp,%esi + movl %ebp,4(%esp) + xorl %edi,%ebp + rorl $11,%esi + andl %ebp,%eax + leal 3329325298(%ebx,%edx,1),%edx + xorl %ecx,%esi + xorl %edi,%eax + rorl $2,%esi + addl %edx,%eax + addl 16(%esp),%edx + addl %esi,%eax + movl 96(%esp),%esi + xorl %edi,%ebp + movl 12(%esp),%ecx + addl (%esi),%eax + addl 4(%esi),%ebp + addl 8(%esi),%edi + addl 12(%esi),%ecx + movl %eax,(%esi) + movl %ebp,4(%esi) + movl %edi,8(%esi) + movl %ecx,12(%esi) + movl %ebp,4(%esp) + xorl %edi,%ebp + movl %edi,8(%esp) + movl %ecx,12(%esp) + movl 20(%esp),%edi + movl 24(%esp),%ebx + movl 28(%esp),%ecx + addl 16(%esi),%edx + addl 20(%esi),%edi + addl 24(%esi),%ebx + addl 28(%esi),%ecx + movl %edx,16(%esi) + movl %edi,20(%esi) + movl %ebx,24(%esi) + movl %ecx,28(%esi) + movl %edi,20(%esp) + movl 100(%esp),%edi + movl %ebx,24(%esp) + movl %ecx,28(%esp) + cmpl 104(%esp),%edi + jb .L009grand_loop + movl 108(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size sha256_block_data_order,.-.L_sha256_block_data_order_begin diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha512-586.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha512-586.S new file mode 100644 index 0000000000..c01cc2bed8 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/sha/sha512-586.S @@ -0,0 +1,574 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/sha/asm/sha512-586.pl +# +# Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl sha512_block_data_order +.type sha512_block_data_order,@function +.align 16 +sha512_block_data_order: +.L_sha512_block_data_order_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl 20(%esp),%esi + movl 24(%esp),%edi + movl 28(%esp),%eax + movl %esp,%ebx + call .L000pic_point +.L000pic_point: + popl %ebp + leal .L001K512-.L000pic_point(%ebp),%ebp + subl $16,%esp + andl $-64,%esp + shll $7,%eax + addl %edi,%eax + movl %esi,(%esp) + movl %edi,4(%esp) + movl %eax,8(%esp) + movl %ebx,12(%esp) +.align 16 +.L002loop_x86: + movl (%edi),%eax + movl 4(%edi),%ebx + movl 8(%edi),%ecx + movl 12(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 16(%edi),%eax + movl 20(%edi),%ebx + movl 24(%edi),%ecx + movl 28(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 32(%edi),%eax + movl 36(%edi),%ebx + movl 40(%edi),%ecx + movl 44(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 48(%edi),%eax + movl 52(%edi),%ebx + movl 56(%edi),%ecx + movl 60(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 64(%edi),%eax + movl 68(%edi),%ebx + movl 72(%edi),%ecx + movl 76(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 80(%edi),%eax + movl 84(%edi),%ebx + movl 88(%edi),%ecx + movl 92(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 96(%edi),%eax + movl 100(%edi),%ebx + movl 104(%edi),%ecx + movl 108(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + movl 112(%edi),%eax + movl 116(%edi),%ebx + movl 120(%edi),%ecx + movl 124(%edi),%edx + bswap %eax + bswap %ebx + bswap %ecx + bswap %edx + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + addl $128,%edi + subl $72,%esp + movl %edi,204(%esp) + leal 8(%esp),%edi + movl $16,%ecx +.long 2784229001 +.align 16 +.L00300_15_x86: + movl 40(%esp),%ecx + movl 44(%esp),%edx + movl %ecx,%esi + shrl $9,%ecx + movl %edx,%edi + shrl $9,%edx + movl %ecx,%ebx + shll $14,%esi + movl %edx,%eax + shll $14,%edi + xorl %esi,%ebx + shrl $5,%ecx + xorl %edi,%eax + shrl $5,%edx + xorl %ecx,%eax + shll $4,%esi + xorl %edx,%ebx + shll $4,%edi + xorl %esi,%ebx + shrl $4,%ecx + xorl %edi,%eax + shrl $4,%edx + xorl %ecx,%eax + shll $5,%esi + xorl %edx,%ebx + shll $5,%edi + xorl %esi,%eax + xorl %edi,%ebx + movl 48(%esp),%ecx + movl 52(%esp),%edx + movl 56(%esp),%esi + movl 60(%esp),%edi + addl 64(%esp),%eax + adcl 68(%esp),%ebx + xorl %esi,%ecx + xorl %edi,%edx + andl 40(%esp),%ecx + andl 44(%esp),%edx + addl 192(%esp),%eax + adcl 196(%esp),%ebx + xorl %esi,%ecx + xorl %edi,%edx + movl (%ebp),%esi + movl 4(%ebp),%edi + addl %ecx,%eax + adcl %edx,%ebx + movl 32(%esp),%ecx + movl 36(%esp),%edx + addl %esi,%eax + adcl %edi,%ebx + movl %eax,(%esp) + movl %ebx,4(%esp) + addl %ecx,%eax + adcl %edx,%ebx + movl 8(%esp),%ecx + movl 12(%esp),%edx + movl %eax,32(%esp) + movl %ebx,36(%esp) + movl %ecx,%esi + shrl $2,%ecx + movl %edx,%edi + shrl $2,%edx + movl %ecx,%ebx + shll $4,%esi + movl %edx,%eax + shll $4,%edi + xorl %esi,%ebx + shrl $5,%ecx + xorl %edi,%eax + shrl $5,%edx + xorl %ecx,%ebx + shll $21,%esi + xorl %edx,%eax + shll $21,%edi + xorl %esi,%eax + shrl $21,%ecx + xorl %edi,%ebx + shrl $21,%edx + xorl %ecx,%eax + shll $5,%esi + xorl %edx,%ebx + shll $5,%edi + xorl %esi,%eax + xorl %edi,%ebx + movl 8(%esp),%ecx + movl 12(%esp),%edx + movl 16(%esp),%esi + movl 20(%esp),%edi + addl (%esp),%eax + adcl 4(%esp),%ebx + orl %esi,%ecx + orl %edi,%edx + andl 24(%esp),%ecx + andl 28(%esp),%edx + andl 8(%esp),%esi + andl 12(%esp),%edi + orl %esi,%ecx + orl %edi,%edx + addl %ecx,%eax + adcl %edx,%ebx + movl %eax,(%esp) + movl %ebx,4(%esp) + movb (%ebp),%dl + subl $8,%esp + leal 8(%ebp),%ebp + cmpb $148,%dl + jne .L00300_15_x86 +.align 16 +.L00416_79_x86: + movl 312(%esp),%ecx + movl 316(%esp),%edx + movl %ecx,%esi + shrl $1,%ecx + movl %edx,%edi + shrl $1,%edx + movl %ecx,%eax + shll $24,%esi + movl %edx,%ebx + shll $24,%edi + xorl %esi,%ebx + shrl $6,%ecx + xorl %edi,%eax + shrl $6,%edx + xorl %ecx,%eax + shll $7,%esi + xorl %edx,%ebx + shll $1,%edi + xorl %esi,%ebx + shrl $1,%ecx + xorl %edi,%eax + shrl $1,%edx + xorl %ecx,%eax + shll $6,%edi + xorl %edx,%ebx + xorl %edi,%eax + movl %eax,(%esp) + movl %ebx,4(%esp) + movl 208(%esp),%ecx + movl 212(%esp),%edx + movl %ecx,%esi + shrl $6,%ecx + movl %edx,%edi + shrl $6,%edx + movl %ecx,%eax + shll $3,%esi + movl %edx,%ebx + shll $3,%edi + xorl %esi,%eax + shrl $13,%ecx + xorl %edi,%ebx + shrl $13,%edx + xorl %ecx,%eax + shll $10,%esi + xorl %edx,%ebx + shll $10,%edi + xorl %esi,%ebx + shrl $10,%ecx + xorl %edi,%eax + shrl $10,%edx + xorl %ecx,%ebx + shll $13,%edi + xorl %edx,%eax + xorl %edi,%eax + movl 320(%esp),%ecx + movl 324(%esp),%edx + addl (%esp),%eax + adcl 4(%esp),%ebx + movl 248(%esp),%esi + movl 252(%esp),%edi + addl %ecx,%eax + adcl %edx,%ebx + addl %esi,%eax + adcl %edi,%ebx + movl %eax,192(%esp) + movl %ebx,196(%esp) + movl 40(%esp),%ecx + movl 44(%esp),%edx + movl %ecx,%esi + shrl $9,%ecx + movl %edx,%edi + shrl $9,%edx + movl %ecx,%ebx + shll $14,%esi + movl %edx,%eax + shll $14,%edi + xorl %esi,%ebx + shrl $5,%ecx + xorl %edi,%eax + shrl $5,%edx + xorl %ecx,%eax + shll $4,%esi + xorl %edx,%ebx + shll $4,%edi + xorl %esi,%ebx + shrl $4,%ecx + xorl %edi,%eax + shrl $4,%edx + xorl %ecx,%eax + shll $5,%esi + xorl %edx,%ebx + shll $5,%edi + xorl %esi,%eax + xorl %edi,%ebx + movl 48(%esp),%ecx + movl 52(%esp),%edx + movl 56(%esp),%esi + movl 60(%esp),%edi + addl 64(%esp),%eax + adcl 68(%esp),%ebx + xorl %esi,%ecx + xorl %edi,%edx + andl 40(%esp),%ecx + andl 44(%esp),%edx + addl 192(%esp),%eax + adcl 196(%esp),%ebx + xorl %esi,%ecx + xorl %edi,%edx + movl (%ebp),%esi + movl 4(%ebp),%edi + addl %ecx,%eax + adcl %edx,%ebx + movl 32(%esp),%ecx + movl 36(%esp),%edx + addl %esi,%eax + adcl %edi,%ebx + movl %eax,(%esp) + movl %ebx,4(%esp) + addl %ecx,%eax + adcl %edx,%ebx + movl 8(%esp),%ecx + movl 12(%esp),%edx + movl %eax,32(%esp) + movl %ebx,36(%esp) + movl %ecx,%esi + shrl $2,%ecx + movl %edx,%edi + shrl $2,%edx + movl %ecx,%ebx + shll $4,%esi + movl %edx,%eax + shll $4,%edi + xorl %esi,%ebx + shrl $5,%ecx + xorl %edi,%eax + shrl $5,%edx + xorl %ecx,%ebx + shll $21,%esi + xorl %edx,%eax + shll $21,%edi + xorl %esi,%eax + shrl $21,%ecx + xorl %edi,%ebx + shrl $21,%edx + xorl %ecx,%eax + shll $5,%esi + xorl %edx,%ebx + shll $5,%edi + xorl %esi,%eax + xorl %edi,%ebx + movl 8(%esp),%ecx + movl 12(%esp),%edx + movl 16(%esp),%esi + movl 20(%esp),%edi + addl (%esp),%eax + adcl 4(%esp),%ebx + orl %esi,%ecx + orl %edi,%edx + andl 24(%esp),%ecx + andl 28(%esp),%edx + andl 8(%esp),%esi + andl 12(%esp),%edi + orl %esi,%ecx + orl %edi,%edx + addl %ecx,%eax + adcl %edx,%ebx + movl %eax,(%esp) + movl %ebx,4(%esp) + movb (%ebp),%dl + subl $8,%esp + leal 8(%ebp),%ebp + cmpb $23,%dl + jne .L00416_79_x86 + movl 840(%esp),%esi + movl 844(%esp),%edi + movl (%esi),%eax + movl 4(%esi),%ebx + movl 8(%esi),%ecx + movl 12(%esi),%edx + addl 8(%esp),%eax + adcl 12(%esp),%ebx + movl %eax,(%esi) + movl %ebx,4(%esi) + addl 16(%esp),%ecx + adcl 20(%esp),%edx + movl %ecx,8(%esi) + movl %edx,12(%esi) + movl 16(%esi),%eax + movl 20(%esi),%ebx + movl 24(%esi),%ecx + movl 28(%esi),%edx + addl 24(%esp),%eax + adcl 28(%esp),%ebx + movl %eax,16(%esi) + movl %ebx,20(%esi) + addl 32(%esp),%ecx + adcl 36(%esp),%edx + movl %ecx,24(%esi) + movl %edx,28(%esi) + movl 32(%esi),%eax + movl 36(%esi),%ebx + movl 40(%esi),%ecx + movl 44(%esi),%edx + addl 40(%esp),%eax + adcl 44(%esp),%ebx + movl %eax,32(%esi) + movl %ebx,36(%esi) + addl 48(%esp),%ecx + adcl 52(%esp),%edx + movl %ecx,40(%esi) + movl %edx,44(%esi) + movl 48(%esi),%eax + movl 52(%esi),%ebx + movl 56(%esi),%ecx + movl 60(%esi),%edx + addl 56(%esp),%eax + adcl 60(%esp),%ebx + movl %eax,48(%esi) + movl %ebx,52(%esi) + addl 64(%esp),%ecx + adcl 68(%esp),%edx + movl %ecx,56(%esi) + movl %edx,60(%esi) + addl $840,%esp + subl $640,%ebp + cmpl 8(%esp),%edi + jb .L002loop_x86 + movl 12(%esp),%esp + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.align 64 +.L001K512: +.long 3609767458,1116352408 +.long 602891725,1899447441 +.long 3964484399,3049323471 +.long 2173295548,3921009573 +.long 4081628472,961987163 +.long 3053834265,1508970993 +.long 2937671579,2453635748 +.long 3664609560,2870763221 +.long 2734883394,3624381080 +.long 1164996542,310598401 +.long 1323610764,607225278 +.long 3590304994,1426881987 +.long 4068182383,1925078388 +.long 991336113,2162078206 +.long 633803317,2614888103 +.long 3479774868,3248222580 +.long 2666613458,3835390401 +.long 944711139,4022224774 +.long 2341262773,264347078 +.long 2007800933,604807628 +.long 1495990901,770255983 +.long 1856431235,1249150122 +.long 3175218132,1555081692 +.long 2198950837,1996064986 +.long 3999719339,2554220882 +.long 766784016,2821834349 +.long 2566594879,2952996808 +.long 3203337956,3210313671 +.long 1034457026,3336571891 +.long 2466948901,3584528711 +.long 3758326383,113926993 +.long 168717936,338241895 +.long 1188179964,666307205 +.long 1546045734,773529912 +.long 1522805485,1294757372 +.long 2643833823,1396182291 +.long 2343527390,1695183700 +.long 1014477480,1986661051 +.long 1206759142,2177026350 +.long 344077627,2456956037 +.long 1290863460,2730485921 +.long 3158454273,2820302411 +.long 3505952657,3259730800 +.long 106217008,3345764771 +.long 3606008344,3516065817 +.long 1432725776,3600352804 +.long 1467031594,4094571909 +.long 851169720,275423344 +.long 3100823752,430227734 +.long 1363258195,506948616 +.long 3750685593,659060556 +.long 3785050280,883997877 +.long 3318307427,958139571 +.long 3812723403,1322822218 +.long 2003034995,1537002063 +.long 3602036899,1747873779 +.long 1575990012,1955562222 +.long 1125592928,2024104815 +.long 2716904306,2227730452 +.long 442776044,2361852424 +.long 593698344,2428436474 +.long 3733110249,2756734187 +.long 2999351573,3204031479 +.long 3815920427,3329325298 +.long 3928383900,3391569614 +.long 566280711,3515267271 +.long 3454069534,3940187606 +.long 4000239992,4118630271 +.long 1914138554,116418474 +.long 2731055270,174292421 +.long 3203993006,289380356 +.long 320620315,460393269 +.long 587496836,685471733 +.long 1086792851,852142971 +.long 365543100,1017036298 +.long 2618297676,1126000580 +.long 3409855158,1288033470 +.long 4234509866,1501505948 +.long 987167468,1607167915 +.long 1246189591,1816402316 +.long 67438087,66051 +.long 202182159,134810123 +.size sha512_block_data_order,.-.L_sha512_block_data_order_begin +.byte 83,72,65,53,49,50,32,98,108,111,99,107,32,116,114,97 +.byte 110,115,102,111,114,109,32,102,111,114,32,120,56,54,44,32 +.byte 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 +.byte 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 +.byte 62,0 diff --git a/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/x86cpuid.S b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/x86cpuid.S new file mode 100644 index 0000000000..a1934cbc58 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/IA32Gcc/crypto/x86cpuid.S @@ -0,0 +1,449 @@ +# WARNING: do not edit! +# Generated from openssl/crypto/x86cpuid.pl +# +# Copyright 2004-2020 The OpenSSL Project Authors. All Rights Reserved. +# +# Licensed under the OpenSSL license (the "License"). You may not use +# this file except in compliance with the License. You can obtain a copy +# in the file LICENSE in the source distribution or at +# https://www.openssl.org/source/license.html + +.text +.globl OPENSSL_ia32_cpuid +.type OPENSSL_ia32_cpuid,@function +.align 16 +OPENSSL_ia32_cpuid: +.L_OPENSSL_ia32_cpuid_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + xorl %edx,%edx + pushfl + popl %eax + movl %eax,%ecx + xorl $2097152,%eax + pushl %eax + popfl + pushfl + popl %eax + xorl %eax,%ecx + xorl %eax,%eax + movl 20(%esp),%esi + movl %eax,8(%esi) + btl $21,%ecx + jnc .L000nocpuid + .byte 0x0f,0xa2 + movl %eax,%edi + xorl %eax,%eax + cmpl $1970169159,%ebx + setne %al + movl %eax,%ebp + cmpl $1231384169,%edx + setne %al + orl %eax,%ebp + cmpl $1818588270,%ecx + setne %al + orl %eax,%ebp + jz .L001intel + cmpl $1752462657,%ebx + setne %al + movl %eax,%esi + cmpl $1769238117,%edx + setne %al + orl %eax,%esi + cmpl $1145913699,%ecx + setne %al + orl %eax,%esi + jnz .L001intel + movl $2147483648,%eax + .byte 0x0f,0xa2 + cmpl $2147483649,%eax + jb .L001intel + movl %eax,%esi + movl $2147483649,%eax + .byte 0x0f,0xa2 + orl %ecx,%ebp + andl $2049,%ebp + cmpl $2147483656,%esi + jb .L001intel + movl $2147483656,%eax + .byte 0x0f,0xa2 + movzbl %cl,%esi + incl %esi + movl $1,%eax + xorl %ecx,%ecx + .byte 0x0f,0xa2 + btl $28,%edx + jnc .L002generic + shrl $16,%ebx + andl $255,%ebx + cmpl %esi,%ebx + ja .L002generic + andl $4026531839,%edx + jmp .L002generic +.L001intel: + cmpl $4,%edi + movl $-1,%esi + jb .L003nocacheinfo + movl $4,%eax + movl $0,%ecx + .byte 0x0f,0xa2 + movl %eax,%esi + shrl $14,%esi + andl $4095,%esi +.L003nocacheinfo: + movl $1,%eax + xorl %ecx,%ecx + .byte 0x0f,0xa2 + andl $3220176895,%edx + cmpl $0,%ebp + jne .L004notintel + orl $1073741824,%edx + andb $15,%ah + cmpb $15,%ah + jne .L004notintel + orl $1048576,%edx +.L004notintel: + btl $28,%edx + jnc .L002generic + andl $4026531839,%edx + cmpl $0,%esi + je .L002generic + orl $268435456,%edx + shrl $16,%ebx + cmpb $1,%bl + ja .L002generic + andl $4026531839,%edx +.L002generic: + andl $2048,%ebp + andl $4294965247,%ecx + movl %edx,%esi + orl %ecx,%ebp + cmpl $7,%edi + movl 20(%esp),%edi + jb .L005no_extended_info + movl $7,%eax + xorl %ecx,%ecx + .byte 0x0f,0xa2 + movl %ebx,8(%edi) +.L005no_extended_info: + btl $27,%ebp + jnc .L006clear_avx + xorl %ecx,%ecx +.byte 15,1,208 + andl $6,%eax + cmpl $6,%eax + je .L007done + cmpl $2,%eax + je .L006clear_avx +.L008clear_xmm: + andl $4261412861,%ebp + andl $4278190079,%esi +.L006clear_avx: + andl $4026525695,%ebp + andl $4294967263,8(%edi) +.L007done: + movl %esi,%eax + movl %ebp,%edx +.L000nocpuid: + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size OPENSSL_ia32_cpuid,.-.L_OPENSSL_ia32_cpuid_begin +.globl OPENSSL_rdtsc +.type OPENSSL_rdtsc,@function +.align 16 +OPENSSL_rdtsc: +.L_OPENSSL_rdtsc_begin: + xorl %eax,%eax + xorl %edx,%edx + leal OPENSSL_ia32cap_P,%ecx + btl $4,(%ecx) + jnc .L009notsc + .byte 0x0f,0x31 +.L009notsc: + ret +.size OPENSSL_rdtsc,.-.L_OPENSSL_rdtsc_begin +.globl OPENSSL_instrument_halt +.type OPENSSL_instrument_halt,@function +.align 16 +OPENSSL_instrument_halt: +.L_OPENSSL_instrument_halt_begin: + leal OPENSSL_ia32cap_P,%ecx + btl $4,(%ecx) + jnc .L010nohalt +.long 2421723150 + andl $3,%eax + jnz .L010nohalt + pushfl + popl %eax + btl $9,%eax + jnc .L010nohalt + .byte 0x0f,0x31 + pushl %edx + pushl %eax + hlt + .byte 0x0f,0x31 + subl (%esp),%eax + sbbl 4(%esp),%edx + addl $8,%esp + ret +.L010nohalt: + xorl %eax,%eax + xorl %edx,%edx + ret +.size OPENSSL_instrument_halt,.-.L_OPENSSL_instrument_halt_begin +.globl OPENSSL_far_spin +.type OPENSSL_far_spin,@function +.align 16 +OPENSSL_far_spin: +.L_OPENSSL_far_spin_begin: + pushfl + popl %eax + btl $9,%eax + jnc .L011nospin + movl 4(%esp),%eax + movl 8(%esp),%ecx +.long 2430111262 + xorl %eax,%eax + movl (%ecx),%edx + jmp .L012spin +.align 16 +.L012spin: + incl %eax + cmpl (%ecx),%edx + je .L012spin +.long 529567888 + ret +.L011nospin: + xorl %eax,%eax + xorl %edx,%edx + ret +.size OPENSSL_far_spin,.-.L_OPENSSL_far_spin_begin +.globl OPENSSL_wipe_cpu +.type OPENSSL_wipe_cpu,@function +.align 16 +OPENSSL_wipe_cpu: +.L_OPENSSL_wipe_cpu_begin: + xorl %eax,%eax + xorl %edx,%edx + leal OPENSSL_ia32cap_P,%ecx + movl (%ecx),%ecx + btl $1,(%ecx) + jnc .L013no_x87 +.long 4007259865,4007259865,4007259865,4007259865,2430851995 +.L013no_x87: + leal 4(%esp),%eax + ret +.size OPENSSL_wipe_cpu,.-.L_OPENSSL_wipe_cpu_begin +.globl OPENSSL_atomic_add +.type OPENSSL_atomic_add,@function +.align 16 +OPENSSL_atomic_add: +.L_OPENSSL_atomic_add_begin: + movl 4(%esp),%edx + movl 8(%esp),%ecx + pushl %ebx + nop + movl (%edx),%eax +.L014spin: + leal (%eax,%ecx,1),%ebx + nop +.long 447811568 + jne .L014spin + movl %ebx,%eax + popl %ebx + ret +.size OPENSSL_atomic_add,.-.L_OPENSSL_atomic_add_begin +.globl OPENSSL_cleanse +.type OPENSSL_cleanse,@function +.align 16 +OPENSSL_cleanse: +.L_OPENSSL_cleanse_begin: + movl 4(%esp),%edx + movl 8(%esp),%ecx + xorl %eax,%eax + cmpl $7,%ecx + jae .L015lot + cmpl $0,%ecx + je .L016ret +.L017little: + movb %al,(%edx) + subl $1,%ecx + leal 1(%edx),%edx + jnz .L017little +.L016ret: + ret +.align 16 +.L015lot: + testl $3,%edx + jz .L018aligned + movb %al,(%edx) + leal -1(%ecx),%ecx + leal 1(%edx),%edx + jmp .L015lot +.L018aligned: + movl %eax,(%edx) + leal -4(%ecx),%ecx + testl $-4,%ecx + leal 4(%edx),%edx + jnz .L018aligned + cmpl $0,%ecx + jne .L017little + ret +.size OPENSSL_cleanse,.-.L_OPENSSL_cleanse_begin +.globl CRYPTO_memcmp +.type CRYPTO_memcmp,@function +.align 16 +CRYPTO_memcmp: +.L_CRYPTO_memcmp_begin: + pushl %esi + pushl %edi + movl 12(%esp),%esi + movl 16(%esp),%edi + movl 20(%esp),%ecx + xorl %eax,%eax + xorl %edx,%edx + cmpl $0,%ecx + je .L019no_data +.L020loop: + movb (%esi),%dl + leal 1(%esi),%esi + xorb (%edi),%dl + leal 1(%edi),%edi + orb %dl,%al + decl %ecx + jnz .L020loop + negl %eax + shrl $31,%eax +.L019no_data: + popl %edi + popl %esi + ret +.size CRYPTO_memcmp,.-.L_CRYPTO_memcmp_begin +.globl OPENSSL_instrument_bus +.type OPENSSL_instrument_bus,@function +.align 16 +OPENSSL_instrument_bus: +.L_OPENSSL_instrument_bus_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl $0,%eax + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size OPENSSL_instrument_bus,.-.L_OPENSSL_instrument_bus_begin +.globl OPENSSL_instrument_bus2 +.type OPENSSL_instrument_bus2,@function +.align 16 +OPENSSL_instrument_bus2: +.L_OPENSSL_instrument_bus2_begin: + pushl %ebp + pushl %ebx + pushl %esi + pushl %edi + movl $0,%eax + popl %edi + popl %esi + popl %ebx + popl %ebp + ret +.size OPENSSL_instrument_bus2,.-.L_OPENSSL_instrument_bus2_begin +.globl OPENSSL_ia32_rdrand_bytes +.type OPENSSL_ia32_rdrand_bytes,@function +.align 16 +OPENSSL_ia32_rdrand_bytes: +.L_OPENSSL_ia32_rdrand_bytes_begin: + pushl %edi + pushl %ebx + xorl %eax,%eax + movl 12(%esp),%edi + movl 16(%esp),%ebx + cmpl $0,%ebx + je .L021done + movl $8,%ecx +.L022loop: +.byte 15,199,242 + jc .L023break + loop .L022loop + jmp .L021done +.align 16 +.L023break: + cmpl $4,%ebx + jb .L024tail + movl %edx,(%edi) + leal 4(%edi),%edi + addl $4,%eax + subl $4,%ebx + jz .L021done + movl $8,%ecx + jmp .L022loop +.align 16 +.L024tail: + movb %dl,(%edi) + leal 1(%edi),%edi + incl %eax + shrl $8,%edx + decl %ebx + jnz .L024tail +.L021done: + xorl %edx,%edx + popl %ebx + popl %edi + ret +.size OPENSSL_ia32_rdrand_bytes,.-.L_OPENSSL_ia32_rdrand_bytes_begin +.globl OPENSSL_ia32_rdseed_bytes +.type OPENSSL_ia32_rdseed_bytes,@function +.align 16 +OPENSSL_ia32_rdseed_bytes: +.L_OPENSSL_ia32_rdseed_bytes_begin: + pushl %edi + pushl %ebx + xorl %eax,%eax + movl 12(%esp),%edi + movl 16(%esp),%ebx + cmpl $0,%ebx + je .L025done + movl $8,%ecx +.L026loop: +.byte 15,199,250 + jc .L027break + loop .L026loop + jmp .L025done +.align 16 +.L027break: + cmpl $4,%ebx + jb .L028tail + movl %edx,(%edi) + leal 4(%edi),%edi + addl $4,%eax + subl $4,%ebx + jz .L025done + movl $8,%ecx + jmp .L026loop +.align 16 +.L028tail: + movb %dl,(%edi) + leal 1(%edi),%edi + incl %eax + shrl $8,%edx + decl %ebx + jnz .L028tail +.L025done: + xorl %edx,%edx + popl %ebx + popl %edi + ret +.size OPENSSL_ia32_rdseed_bytes,.-.L_OPENSSL_ia32_rdseed_bytes_begin +.hidden OPENSSL_cpuid_setup +.hidden OPENSSL_ia32cap_P +.comm OPENSSL_ia32cap_P,16,4 +.section .init + call OPENSSL_cpuid_setup From 46e7dc86a7e4d33026f791aba58667d9e30fc10e Mon Sep 17 00:00:00 2001 From: Christopher Zurcher Date: Thu, 22 Sep 2022 04:25:41 +0800 Subject: [PATCH 0056/1529] CryptoPkg/OpensslLib: Update generated files for native X64 Cc: Yi Li Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Christopher Zurcher Reviewed-by: Jiewen Yao --- .../Library/OpensslLib/OpensslLibX64.inf | 53 +++++++++++++++++++ .../Library/OpensslLib/OpensslLibX64Gcc.inf | 53 +++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf b/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf index b92feaf1bf..5e92ba0844 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf @@ -215,6 +215,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c + $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -399,6 +436,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -511,6 +552,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h + $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -600,6 +650,9 @@ RngLib PrintLib +[FixedPcd] + gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES + [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf b/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf index 4ffdd8cd06..0f1b4b16f8 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf @@ -215,6 +215,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c + $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -399,6 +436,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -511,6 +552,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h + $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -600,6 +650,9 @@ RngLib PrintLib +[FixedPcd] + gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES + [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, From bf43a4a9f8e5ea718f8c9caf88a1688317306ac9 Mon Sep 17 00:00:00 2001 From: Minh Nguyen Date: Mon, 19 Sep 2022 09:19:45 +0700 Subject: [PATCH 0057/1529] ArmPkg/ProcessorSubClassDxe: Get processor version from OemMiscLib In some scenarios, the processor version may be updated dynamically from pre-UEFI firmware during booting. But the processor version is fixed with PCD (PcdProcessorVersion), so it can not be updated it dynamically. This patch will support setting that value both statically and dynamically. Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel Acked-by: Leif Lindholm --- ArmPkg/Include/Library/OemMiscLib.h | 2 ++ .../Smbios/ProcessorSubClassDxe/ProcessorSubClass.c | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ArmPkg/Include/Library/OemMiscLib.h b/ArmPkg/Include/Library/OemMiscLib.h index 47cb30d84a..330bb4b014 100644 --- a/ArmPkg/Include/Library/OemMiscLib.h +++ b/ArmPkg/Include/Library/OemMiscLib.h @@ -1,5 +1,6 @@ /** @file * +* Copyright (c) 2022, Ampere Computing LLC. All rights reserved. * Copyright (c) 2021, NUVIA Inc. All rights reserved. * Copyright (c) 2015, Hisilicon Limited. All rights reserved. * Copyright (c) 2015, Linaro Limited. All rights reserved. @@ -58,6 +59,7 @@ typedef enum { SkuNumberType03, ProcessorPartNumType04, ProcessorSerialNumType04, + ProcessorVersionType04, SmbiosHiiStringFieldMax } OEM_MISC_SMBIOS_HII_STRING_FIELD; diff --git a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c index 0b9af9bd7e..3b12e26abf 100644 --- a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c +++ b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c @@ -1,6 +1,7 @@ /** @file ProcessorSubClass.c + Copyright (c) 2022, Ampere Computing LLC. All rights reserved. Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2015, Hisilicon Limited. All rights reserved. Copyright (c) 2015, Linaro Limited. All rights reserved. @@ -512,7 +513,6 @@ AllocateType4AndSetProcessorInformationStrings ( PartNumber = STRING_TOKEN (STR_PROCESSOR_PART_NUMBER); SET_HII_STRING_IF_PCD_NOT_EMPTY (PcdProcessorManufacturer, ProcessorManu); - SET_HII_STRING_IF_PCD_NOT_EMPTY (PcdProcessorVersion, ProcessorVersion); SET_HII_STRING_IF_PCD_NOT_EMPTY (PcdProcessorAssetTag, AssetTag); if (StrLen ((CHAR16 *)FixedPcdGetPtr (PcdProcessorSerialNumber)) > 0) { @@ -527,6 +527,12 @@ AllocateType4AndSetProcessorInformationStrings ( OemUpdateSmbiosInfo (mHiiHandle, PartNumber, ProcessorPartNumType04); } + if (StrLen ((CHAR16 *)FixedPcdGetPtr (PcdProcessorVersion)) > 0) { + HiiSetString (mHiiHandle, ProcessorVersion, (CHAR16 *)FixedPcdGetPtr (PcdProcessorVersion), NULL); + } else { + OemUpdateSmbiosInfo (mHiiHandle, ProcessorVersion, ProcessorVersionType04); + } + // Processor Designation StringBufferSize = sizeof (CHAR16) * SMBIOS_STRING_MAX_LENGTH; ProcessorStr = AllocateZeroPool (StringBufferSize); From 4459aa2e3c738a9378dfa1d060366f513da0dfa1 Mon Sep 17 00:00:00 2001 From: Minh Nguyen Date: Mon, 19 Sep 2022 09:19:46 +0700 Subject: [PATCH 0058/1529] ArmPkg: Correct return value of "SMCCC_ARCH_SOC_ID" Function ID call According to "SMC Calling Convention" specification, section 7.4, return value of Arm Architecture Calls is stored at first argument of SMC aguments (ARM_SMC_ARGS). This value can be negative values indicating error or positive values (including zero) indicating success. Positive value would contain information of respective Function ID (Section 7.3.4 and 7.4.4). For that reason, "SMCCC_VERSION" and "SMCCC_ARCH_FEATURES" Function ID calls read return value from "SmcCallStatus" variable (Args.Arg0 - first argument of SMC call). But "SMCCC_ARCH_SOC_ID" Function ID call is reading return value from "SmcParam" variable (Args.Arg1 - second argument of SMC call) so it leads to unexpected results of "Jep106Code" and "SocRevision". This patch is to correct it. Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel Acked-by: Leif Lindholm --- .../Smbios/ProcessorSubClassDxe/SmbiosProcessorArmCommon.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/SmbiosProcessorArmCommon.c b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/SmbiosProcessorArmCommon.c index e0010a40e4..b961be2133 100644 --- a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/SmbiosProcessorArmCommon.c +++ b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/SmbiosProcessorArmCommon.c @@ -2,7 +2,7 @@ Functions for processor information common to ARM and AARCH64. Copyright (c) 2021, NUVIA Inc. All rights reserved.
- Copyright (c) 2021, Ampere Computing LLC. All rights reserved.
+ Copyright (c) 2021 - 2022, Ampere Computing LLC. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -131,7 +131,7 @@ SmbiosGetSmcArm64SocId ( SmcCallStatus = ArmCallSmc1 (SMCCC_ARCH_SOC_ID, &SmcParam, NULL, NULL); if (SmcCallStatus >= 0) { - *Jep106Code = (INT32)SmcParam; + *Jep106Code = SmcCallStatus; } else { Status = EFI_UNSUPPORTED; } @@ -140,7 +140,7 @@ SmbiosGetSmcArm64SocId ( SmcCallStatus = ArmCallSmc1 (SMCCC_ARCH_SOC_ID, &SmcParam, NULL, NULL); if (SmcCallStatus >= 0) { - *SocRevision = (INT32)SmcParam; + *SocRevision = SmcCallStatus; } else { Status = EFI_UNSUPPORTED; } From 15e858d5a318925656769470bda9c888af6c768f Mon Sep 17 00:00:00 2001 From: Nhi Pham Date: Mon, 19 Sep 2022 09:19:47 +0700 Subject: [PATCH 0059/1529] ArmPkg/SmbiosMiscDxe: Support fetching System UUID This adds an API to OemMiscLib for fetching the system UUID according to the platform. Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel Acked-by: Leif Lindholm --- ArmPkg/Include/Library/OemMiscLib.h | 12 ++++++++++++ .../Smbios/OemMiscLibNull/OemMiscLib.c | 18 ++++++++++++++++++ .../Smbios/OemMiscLibNull/OemMiscLibNull.inf | 4 ++++ .../Type01/MiscSystemManufacturerFunction.c | 3 ++- 4 files changed, 36 insertions(+), 1 deletion(-) diff --git a/ArmPkg/Include/Library/OemMiscLib.h b/ArmPkg/Include/Library/OemMiscLib.h index 330bb4b014..d87737db9c 100644 --- a/ArmPkg/Include/Library/OemMiscLib.h +++ b/ArmPkg/Include/Library/OemMiscLib.h @@ -235,4 +235,16 @@ OemGetChassisNumPowerCords ( VOID ); +/** + Fetches the system UUID. + + @param[out] SystemUuid The pointer to the buffer to store the System UUID. + +**/ +VOID +EFIAPI +OemGetSystemUuid ( + OUT GUID *SystemUuid + ); + #endif // OEM_MISC_LIB_H_ diff --git a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c index 98970407a6..32f6d55c1a 100644 --- a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c +++ b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c @@ -1,6 +1,7 @@ /** @file * OemMiscLib.c * +* Copyright (c) 2022, Ampere Computing LLC. All rights reserved. * Copyright (c) 2021, NUVIA Inc. All rights reserved. * Copyright (c) 2018, Hisilicon Limited. All rights reserved. * Copyright (c) 2018, Linaro Limited. All rights reserved. @@ -10,6 +11,7 @@ **/ #include +#include #include #include #include @@ -236,3 +238,19 @@ OemGetChassisNumPowerCords ( ASSERT (FALSE); return 1; } + +/** + Fetches the system UUID. + + @param[out] SystemUuid The pointer to the buffer to store the System UUID. + +**/ +VOID +EFIAPI +OemGetSystemUuid ( + OUT GUID *SystemUuid + ) +{ + ASSERT (FALSE); + CopyGuid (SystemUuid, &gZeroGuid); +} diff --git a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf index 5c4268f68b..8653f57720 100644 --- a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf +++ b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf @@ -1,6 +1,7 @@ #/** @file # OemMiscLib.inf # +# Copyright (c) 2022, Ampere Computing LLC. All rights reserved. # Copyright (c) 2021, NUVIA Inc. All rights reserved. # Copyright (c) 2018, Hisilicon Limited. All rights reserved. # Copyright (c) 2018, Linaro Limited. All rights reserved. @@ -29,3 +30,6 @@ [LibraryClasses] BaseMemoryLib DebugLib + +[Guids] + gZeroGuid diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c index 5cf72644d0..22fb5eccaa 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c @@ -4,6 +4,7 @@ Based on files under Nt32Pkg/MiscSubClassPlatformDxe/ + Copyright (c) 2022, Ampere Computing LLC. All rights reserved.
Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.
Copyright (c) 2015, Hisilicon Limited. All rights reserved.
@@ -160,7 +161,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscSystemManufacturer) { SmbiosRecord->Hdr.Length = sizeof (SMBIOS_TABLE_TYPE1); - CopyGuid (&SmbiosRecord->Uuid, &InputData->Uuid); + OemGetSystemUuid (&SmbiosRecord->Uuid); OptionalStrStart = (CHAR8 *)(SmbiosRecord + 1); UnicodeStrToAsciiStrS (Manufacturer, OptionalStrStart, ManuStrLen + 1); From bcdb6636ae8f08b2285ea2977f3ab9028d7265ab Mon Sep 17 00:00:00 2001 From: Minh Nguyen Date: Mon, 19 Sep 2022 09:19:48 +0700 Subject: [PATCH 0060/1529] ArmPkg/SmbiosMiscDxe: Fix typo of "AssetTagType02" This patch fixes typo from "AssertTagType02" to "AssetTagType02". Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel Acked-by: Leif Lindholm --- ArmPkg/Include/Library/OemMiscLib.h | 2 +- .../SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ArmPkg/Include/Library/OemMiscLib.h b/ArmPkg/Include/Library/OemMiscLib.h index d87737db9c..1936619d9b 100644 --- a/ArmPkg/Include/Library/OemMiscLib.h +++ b/ArmPkg/Include/Library/OemMiscLib.h @@ -44,7 +44,7 @@ typedef enum { VersionType01, SkuNumberType01, FamilyType01, - AssertTagType02, + AssetTagType02, SerialNumberType02, BoardManufacturerType02, ProductNameType02, diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c index 870610b172..f61546955f 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c @@ -4,6 +4,7 @@ Based on files under Nt32Pkg/MiscSubClassPlatformDxe/ + Copyright (c) 2022, Ampere Computing LLC. All rights reserved.
Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.
Copyright (c) 2015, Hisilicon Limited. All rights reserved.
@@ -112,7 +113,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBaseBoardManufacturer) { OemUpdateSmbiosInfo ( mSmbiosMiscHiiHandle, STRING_TOKEN (STR_MISC_BASE_BOARD_ASSET_TAG), - AssertTagType02 + AssetTagType02 ); OemUpdateSmbiosInfo ( mSmbiosMiscHiiHandle, From c9adcb9621af36c0b1ed56d95e631c629eb9b5d8 Mon Sep 17 00:00:00 2001 From: Minh Nguyen Date: Mon, 19 Sep 2022 09:19:49 +0700 Subject: [PATCH 0061/1529] ArmPkg/SmbiosMiscDxe: Remove redundant updates in SMBIOS Type 2 This patch removes redundant updates of "BoardManufacturerType02" and "SerialNumberType02". Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel Acked-by: Leif Lindholm --- .../Type02/MiscBaseBoardManufacturerFunction.c | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c index f61546955f..3441e77988 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c @@ -120,16 +120,6 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBaseBoardManufacturer) { STRING_TOKEN (STR_MISC_BASE_BOARD_SERIAL_NUMBER), SerialNumberType02 ); - OemUpdateSmbiosInfo ( - mSmbiosMiscHiiHandle, - STRING_TOKEN (STR_MISC_BASE_BOARD_MANUFACTURER), - BoardManufacturerType02 - ); - OemUpdateSmbiosInfo ( - mSmbiosMiscHiiHandle, - STRING_TOKEN (STR_MISC_BASE_BOARD_SERIAL_NUMBER), - SerialNumberType02 - ); OemUpdateSmbiosInfo ( mSmbiosMiscHiiHandle, STRING_TOKEN (STR_MISC_BASE_BOARD_SKU_NUMBER), From ec7bdc08437c26cd550a9b6a2dc673513e62a9c0 Mon Sep 17 00:00:00 2001 From: Minh Nguyen Date: Mon, 19 Sep 2022 09:19:50 +0700 Subject: [PATCH 0062/1529] ArmPkg/SmbiosMiscDxe: Get SMBIOS information from OemMiscLib In some scenarios, the information of Bios Version, Bios Release and Embedded Controller Firmware Release are fetched during UEFI booting. This patch supports updating those fields dynamically when the PCDs are empty. Signed-off-by: Nhi Pham Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar Acked-by: Ard Biesheuvel --- ArmPkg/Include/Library/OemMiscLib.h | 21 ++++++++++++++ .../Smbios/OemMiscLibNull/OemMiscLib.c | 29 +++++++++++++++++++ .../Smbios/OemMiscLibNull/OemMiscLibNull.inf | 5 ++++ .../Type00/MiscBiosVendorFunction.c | 22 +++++++------- 4 files changed, 66 insertions(+), 11 deletions(-) diff --git a/ArmPkg/Include/Library/OemMiscLib.h b/ArmPkg/Include/Library/OemMiscLib.h index 1936619d9b..541274999e 100644 --- a/ArmPkg/Include/Library/OemMiscLib.h +++ b/ArmPkg/Include/Library/OemMiscLib.h @@ -37,6 +37,7 @@ typedef struct { } OEM_MISC_PROCESSOR_DATA; typedef enum { + BiosVersionType00, ProductNameType01, SerialNumType01, UuidType01, @@ -247,4 +248,24 @@ OemGetSystemUuid ( OUT GUID *SystemUuid ); +/** Fetches the BIOS release. + + @return The BIOS release. +**/ +UINT16 +EFIAPI +OemGetBiosRelease ( + VOID + ); + +/** Fetches the embedded controller firmware release. + + @return The embedded controller firmware release. +**/ +UINT16 +EFIAPI +OemGetEmbeddedControllerFirmwareRelease ( + VOID + ); + #endif // OEM_MISC_LIB_H_ diff --git a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c index 32f6d55c1a..a5d635da9e 100644 --- a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c +++ b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLib.c @@ -16,6 +16,7 @@ #include #include #include +#include /** Gets the CPU frequency of the specified processor. @@ -254,3 +255,31 @@ OemGetSystemUuid ( ASSERT (FALSE); CopyGuid (SystemUuid, &gZeroGuid); } + +/** Fetches the BIOS release. + + @return The BIOS release. +**/ +UINT16 +EFIAPI +OemGetBiosRelease ( + VOID + ) +{ + ASSERT (FALSE); + return PcdGet16 (PcdSystemBiosRelease); +} + +/** Fetches the embedded controller firmware release. + + @return The embedded controller firmware release. +**/ +UINT16 +EFIAPI +OemGetEmbeddedControllerFirmwareRelease ( + VOID + ) +{ + ASSERT (FALSE); + return PcdGet16 (PcdEmbeddedControllerFirmwareRelease); +} diff --git a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf index 8653f57720..7286ed6114 100644 --- a/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf +++ b/ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf @@ -30,6 +30,11 @@ [LibraryClasses] BaseMemoryLib DebugLib + PcdLib [Guids] gZeroGuid + +[Pcd] + gArmTokenSpaceGuid.PcdEmbeddedControllerFirmwareRelease + gArmTokenSpaceGuid.PcdSystemBiosRelease diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c index b49c4b754c..66ead22a6e 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c @@ -1,5 +1,6 @@ /** @file + Copyright (c) 2022, Ampere Computing LLC. All rights reserved.
Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2009, Intel Corporation. All rights reserved.
Copyright (c) 2015, Hisilicon Limited. All rights reserved.
@@ -13,6 +14,7 @@ #include #include #include +#include #include #include @@ -191,11 +193,11 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBiosVendor) { TokenToUpdate = STRING_TOKEN (STR_MISC_BIOS_VERSION); HiiSetString (mSmbiosMiscHiiHandle, TokenToUpdate, Version, NULL); } else { - Version = (CHAR16 *)PcdGetPtr (PcdFirmwareVersionString); - if (StrLen (Version) > 0) { - TokenToUpdate = STRING_TOKEN (STR_MISC_BIOS_VERSION); - HiiSetString (mSmbiosMiscHiiHandle, TokenToUpdate, Version, NULL); - } + OemUpdateSmbiosInfo ( + mSmbiosMiscHiiHandle, + STRING_TOKEN (STR_MISC_BIOS_VERSION), + BiosVersionType00 + ); } Char16String = GetBiosReleaseDate (); @@ -251,13 +253,11 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBiosVendor) { } } - SmbiosRecord->SystemBiosMajorRelease = (UINT8)(PcdGet16 (PcdSystemBiosRelease) >> 8); - SmbiosRecord->SystemBiosMinorRelease = (UINT8)(PcdGet16 (PcdSystemBiosRelease) & 0xFF); + SmbiosRecord->SystemBiosMajorRelease = (UINT8)(OemGetBiosRelease () >> 8); + SmbiosRecord->SystemBiosMinorRelease = (UINT8)(OemGetBiosRelease () & 0xFF); - SmbiosRecord->EmbeddedControllerFirmwareMajorRelease = (UINT16) - (PcdGet16 (PcdEmbeddedControllerFirmwareRelease) >> 8); - SmbiosRecord->EmbeddedControllerFirmwareMinorRelease = (UINT16) - (PcdGet16 (PcdEmbeddedControllerFirmwareRelease) & 0xFF); + SmbiosRecord->EmbeddedControllerFirmwareMajorRelease = (UINT16)(OemGetEmbeddedControllerFirmwareRelease () >> 8); + SmbiosRecord->EmbeddedControllerFirmwareMinorRelease = (UINT16)(OemGetEmbeddedControllerFirmwareRelease () & 0xFF); OptionalStrStart = (CHAR8 *)(SmbiosRecord + 1); UnicodeStrToAsciiStrS (Vendor, OptionalStrStart, VendorStrLen + 1); From 8014b5b5822244f134d74256249b24cd037f11f3 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Thu, 22 Sep 2022 14:36:44 -0600 Subject: [PATCH 0063/1529] DynamicTablesPkg: Add CM_ARM_CPC_INFO object Introduce the CM_ARM_CPC_INFO CmObj in the ArmNameSpaceObjects. This allows to describe CPC information, as described in ACPI 6.4, s8.4.7.1 "_CPC (Continuous Performance Control)". Signed-off-by: Jeff Brasen Reviewed-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/Include/AmlCpcInfo.h | 124 ++++++++++++++++++ .../Include/ArmNameSpaceObjects.h | 59 ++++++--- .../ConfigurationManagerObjectParser.c | 115 +++++++++++++--- 3 files changed, 264 insertions(+), 34 deletions(-) create mode 100644 DynamicTablesPkg/Include/AmlCpcInfo.h diff --git a/DynamicTablesPkg/Include/AmlCpcInfo.h b/DynamicTablesPkg/Include/AmlCpcInfo.h new file mode 100644 index 0000000000..8981c22954 --- /dev/null +++ b/DynamicTablesPkg/Include/AmlCpcInfo.h @@ -0,0 +1,124 @@ +/** @file + + Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef AML_CPC_INFO_H_ +#define AML_CPC_INFO_H_ + +#include + +#pragma pack(1) + +/** A structure that describes the Cpc information. + + Continuous Performance Control is described in DSDT/SSDT and associated + to cpus/clusters in the cpu topology. + + Unsupported Optional registers should be encoded with NULL resource + Register {(SystemMemory, 0, 0, 0, 0)} + + For values that support Integer or Buffer, integer will be used + if buffer is NULL resource. + If resource is not NULL then Integer must be 0 + + Cf. ACPI 6.4, s8.4.7.1 _CPC (Continuous Performance Control) + +**/ + +typedef struct AmlCpcInfo { + /// The revision number of the _CPC package format. + UINT32 Revision; + + /// Indicates the highest level of performance the processor + /// is theoretically capable of achieving. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE HighestPerformanceBuffer; + UINT32 HighestPerformanceInteger; + + /// Indicates the highest sustained performance level of the processor. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE NominalPerformanceBuffer; + UINT32 NominalPerformanceInteger; + + /// Indicates the lowest performance level of the processor with non-linear power savings. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE LowestNonlinearPerformanceBuffer; + UINT32 LowestNonlinearPerformanceInteger; + + /// Indicates the lowest performance level of the processor.. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE LowestPerformanceBuffer; + UINT32 LowestPerformanceInteger; + + /// Guaranteed Performance Register Buffer. + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE GuaranteedPerformanceRegister; + + /// Desired Performance Register Buffer. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE DesiredPerformanceRegister; + + /// Minimum Performance Register Buffer. + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE MinimumPerformanceRegister; + + /// Maximum Performance Register Buffer. + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE MaximumPerformanceRegister; + + /// Performance Reduction Tolerance Register. + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE PerformanceReductionToleranceRegister; + + /// Time Window Register. + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE TimeWindowRegister; + + /// Counter Wraparound Time + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE CounterWraparoundTimeBuffer; + UINT32 CounterWraparoundTimeInteger; + + /// Reference Performance Counter Register + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE ReferencePerformanceCounterRegister; + + /// Delivered Performance Counter Register + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE DeliveredPerformanceCounterRegister; + + /// Performance Limited Register + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE PerformanceLimitedRegister; + + /// CPPC EnableRegister + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE CPPCEnableRegister; + + /// Autonomous Selection Enable + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE AutonomousSelectionEnableBuffer; + UINT32 AutonomousSelectionEnableInteger; + + /// AutonomousActivity-WindowRegister + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE AutonomousActivityWindowRegister; + + /// EnergyPerformance-PreferenceRegister + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE EnergyPerformancePreferenceRegister; + + /// Reference Performance + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE ReferencePerformanceBuffer; + UINT32 ReferencePerformanceInteger; + + /// Lowest Frequency + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE LowestFrequencyBuffer; + UINT32 LowestFrequencyInteger; + + /// Nominal Frequency + /// Optional + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE NominalFrequencyBuffer; + UINT32 NominalFrequencyInteger; +} AML_CPC_INFO; + +#pragma pack() + +#endif //AML_CPC_INFO_H_ diff --git a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h index 102e0f96be..c66b441d53 100644 --- a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h @@ -13,6 +13,7 @@ #ifndef ARM_NAMESPACE_OBJECTS_H_ #define ARM_NAMESPACE_OBJECTS_H_ +#include #include #pragma pack(1) @@ -63,6 +64,7 @@ typedef enum ArmObjectID { EArmObjPciInterruptMapInfo, ///< 39 - Pci Interrupt Map Info EArmObjRmr, ///< 40 - Reserved Memory Range Node EArmObjMemoryRangeDescriptor, ///< 41 - Memory Range Descriptor + EArmObjCpcInfo, ///< 42 - Continuous Performance Control Info EArmObjMax } EARM_OBJECT_ID; @@ -97,99 +99,104 @@ typedef struct CmArmPowerManagementProfileInfo { */ typedef struct CmArmGicCInfo { /// The GIC CPU Interface number. - UINT32 CPUInterfaceNumber; + UINT32 CPUInterfaceNumber; /** The ACPI Processor UID. This must match the _UID of the CPU Device object information described in the DSDT/SSDT for the CPU. */ - UINT32 AcpiProcessorUid; + UINT32 AcpiProcessorUid; /** The flags field as described by the GICC structure in the ACPI Specification. */ - UINT32 Flags; + UINT32 Flags; /** The parking protocol version field as described by the GICC structure in the ACPI Specification. */ - UINT32 ParkingProtocolVersion; + UINT32 ParkingProtocolVersion; /** The Performance Interrupt field as described by the GICC structure in the ACPI Specification. */ - UINT32 PerformanceInterruptGsiv; + UINT32 PerformanceInterruptGsiv; /** The CPU Parked address field as described by the GICC structure in the ACPI Specification. */ - UINT64 ParkedAddress; + UINT64 ParkedAddress; /** The base address for the GIC CPU Interface as described by the GICC structure in the ACPI Specification. */ - UINT64 PhysicalBaseAddress; + UINT64 PhysicalBaseAddress; /** The base address for GICV interface as described by the GICC structure in the ACPI Specification. */ - UINT64 GICV; + UINT64 GICV; /** The base address for GICH interface as described by the GICC structure in the ACPI Specification. */ - UINT64 GICH; + UINT64 GICH; /** The GICV maintenance interrupt as described by the GICC structure in the ACPI Specification. */ - UINT32 VGICMaintenanceInterrupt; + UINT32 VGICMaintenanceInterrupt; /** The base address for GICR interface as described by the GICC structure in the ACPI Specification. */ - UINT64 GICRBaseAddress; + UINT64 GICRBaseAddress; /** The MPIDR for the CPU as described by the GICC structure in the ACPI Specification. */ - UINT64 MPIDR; + UINT64 MPIDR; /** The Processor Power Efficiency class as described by the GICC structure in the ACPI Specification. */ - UINT8 ProcessorPowerEfficiencyClass; + UINT8 ProcessorPowerEfficiencyClass; /** Statistical Profiling Extension buffer overflow GSIV. Zero if unsupported by this processor. This field was introduced in ACPI 6.3 (MADT revision 5) and is therefore ignored when generating MADT revision 4 or lower. */ - UINT16 SpeOverflowInterrupt; + UINT16 SpeOverflowInterrupt; /** The proximity domain to which the logical processor belongs. This field is used to populate the GICC affinity structure in the SRAT table. */ - UINT32 ProximityDomain; + UINT32 ProximityDomain; /** The clock domain to which the logical processor belongs. This field is used to populate the GICC affinity structure in the SRAT table. */ - UINT32 ClockDomain; + UINT32 ClockDomain; /** The GICC Affinity flags field as described by the GICC Affinity structure in the SRAT table. */ - UINT32 AffinityFlags; + UINT32 AffinityFlags; + + /** Optional field: Reference Token for the Cpc info of this processor. + i.e. a token referencing a CM_ARM_CPC_INFO object. + */ + CM_OBJECT_TOKEN CpcToken; } CM_ARM_GICC_INFO; /** A structure that describes the @@ -1070,6 +1077,24 @@ typedef struct CmArmRmrDescriptor { UINT64 Length; } CM_ARM_MEMORY_RANGE_DESCRIPTOR; +/** A structure that describes the Cpc information. + + Continuous Performance Control is described in DSDT/SSDT and associated + to cpus/clusters in the cpu topology. + + Unsupported Optional registers should be encoded with NULL resource + Register {(SystemMemory, 0, 0, 0, 0)} + + For values that support Integer or Buffer, integer will be used + if buffer is NULL resource. + If resource is not NULL then Integer must be 0 + + Cf. ACPI 6.4, s8.4.7.1 _CPC (Continuous Performance Control) + + ID: EArmObjCpcInfo +*/ +typedef AML_CPC_INFO CM_ARM_CPC_INFO; + #pragma pack() #endif // ARM_NAMESPACE_OBJECTS_H_ diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index c1b21d24a4..08b4f60dfb 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -34,23 +34,24 @@ STATIC CONST CM_OBJ_PARSER CmArmPowerManagementProfileInfoParser[] = { /** A parser for EArmObjGicCInfo. */ STATIC CONST CM_OBJ_PARSER CmArmGicCInfoParser[] = { - { "CPUInterfaceNumber", 4, "0x%x", NULL }, - { "AcpiProcessorUid", 4, "0x%x", NULL }, - { "Flags", 4, "0x%x", NULL }, - { "ParkingProtocolVersion", 4, "0x%x", NULL }, - { "PerformanceInterruptGsiv", 4, "0x%x", NULL }, - { "ParkedAddress", 8, "0x%llx", NULL }, - { "PhysicalBaseAddress", 8, "0x%llx", NULL }, - { "GICV", 8, "0x%llx", NULL }, - { "GICH", 8, "0x%llx", NULL }, - { "VGICMaintenanceInterrupt", 4, "0x%x", NULL }, - { "GICRBaseAddress", 8, "0x%llx", NULL }, - { "MPIDR", 8, "0x%llx", NULL }, - { "ProcessorPowerEfficiencyClass", 1, "0x%x", NULL }, - { "SpeOverflowInterrupt", 2, "0x%x", NULL }, - { "ProximityDomain", 4, "0x%x", NULL }, - { "ClockDomain", 4, "0x%x", NULL }, - { "AffinityFlags", 4, "0x%x", NULL } + { "CPUInterfaceNumber", 4, "0x%x", NULL }, + { "AcpiProcessorUid", 4, "0x%x", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "ParkingProtocolVersion", 4, "0x%x", NULL }, + { "PerformanceInterruptGsiv", 4, "0x%x", NULL }, + { "ParkedAddress", 8, "0x%llx", NULL }, + { "PhysicalBaseAddress", 8, "0x%llx", NULL }, + { "GICV", 8, "0x%llx", NULL }, + { "GICH", 8, "0x%llx", NULL }, + { "VGICMaintenanceInterrupt", 4, "0x%x", NULL }, + { "GICRBaseAddress", 8, "0x%llx", NULL }, + { "MPIDR", 8, "0x%llx", NULL }, + { "ProcessorPowerEfficiencyClass", 1, "0x%x", NULL }, + { "SpeOverflowInterrupt", 2, "0x%x", NULL }, + { "ProximityDomain", 4, "0x%x", NULL }, + { "ClockDomain", 4, "0x%x", NULL }, + { "AffinityFlags", 4, "0x%x", NULL }, + { "CpcToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } }; /** A parser for EArmObjGicDInfo. @@ -423,6 +424,84 @@ STATIC CONST CM_OBJ_PARSER CmPciInterruptMapInfoParser[] = { ARRAY_SIZE (CmArmGenericInterruptParser) }, }; +/** A parser for EArmObjCpcInfo. +*/ +STATIC CONST CM_OBJ_PARSER CmArmCpcInfoParser[] = { + { "Revision", 4, "0x%lx", NULL }, + { "HighestPerformanceBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "HighestPerformanceInteger", 4, "0x%lx", NULL }, + { "NominalPerformanceBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "NominalPerformanceInteger", 4, "0x%lx", NULL }, + { "LowestNonlinearPerformanceBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "LowestNonlinearPerformanceInteger", 4, "0x%lx", NULL }, + { "LowestPerformanceBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "LowestPerformanceInteger", 4, "0x%lx", NULL }, + { "GuaranteedPerformanceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "DesiredPerformanceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "MinimumPerformanceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "MaximumPerformanceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "PerformanceReductionToleranceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "TimeWindowRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "CounterWraparoundTimeBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "CounterWraparoundTimeInteger", 4, "0x%lx", NULL }, + { "ReferencePerformanceCounterRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "DeliveredPerformanceCounterRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "PerformanceLimitedRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "CPPCEnableRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "AutonomousSelectionEnableBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "AutonomousSelectionEnableInteger", 4, "0x%lx", NULL }, + { "AutonomousActivityWindowRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "EnergyPerformancePreferenceRegister", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "ReferencePerformanceBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "ReferencePerformanceInteger", 4, "0x%lx", NULL }, + { "LowestFrequencyBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "LowestFrequencyInteger", 4, "0x%lx", NULL }, + { "NominalFrequencyBuffer", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), + NULL, NULL, AcpiGenericAddressParser, + ARRAY_SIZE (AcpiGenericAddressParser) }, + { "NominalFrequencyInteger", 4, "0x%lx", NULL }, +}; + /** A parser for Arm namespace objects. */ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { @@ -501,6 +580,8 @@ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { ARRAY_SIZE (CmArmPciAddressMapInfoParser) }, { "EArmObjPciInterruptMapInfo", CmPciInterruptMapInfoParser, ARRAY_SIZE (CmPciInterruptMapInfoParser) }, + { "EArmObjCpcInfo", CmArmCpcInfoParser, + ARRAY_SIZE (CmArmCpcInfoParser) }, { "EArmObjMax", NULL, 0 }, }; From ec6f9484cc80da0c38c5a4f451267cec6fd3ebf6 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Thu, 22 Sep 2022 14:36:45 -0600 Subject: [PATCH 0064/1529] DynamicTablesPkg: AML Code generation to add _CPC entries _CPC entries can describe CPU performance information. The object is described in ACPI 6.4 s8.4.7.1. "_CPC (Continuous Performance Control)". Add AmlCreateCpcNode() helper function to add _CPC entries to an existing CPU object. Signed-off-by: Jeff Brasen Reviewed-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Include/Library/AmlLib/AmlLib.h | 54 ++ .../Common/AmlLib/CodeGen/AmlCodeGen.c | 475 ++++++++++++++++++ 2 files changed, 529 insertions(+) diff --git a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h index 39968660f2..0d8446d782 100644 --- a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h +++ b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h @@ -36,6 +36,7 @@ @} */ +#include #include #ifndef AML_HANDLE @@ -1336,6 +1337,59 @@ AmlAddNameIntegerPackage ( IN AML_OBJECT_NODE_HANDLE PackageNode ); +/** Create a _CPC node. + + Creates and optionally adds the following node + Name(_CPC, Package() + { + NumEntries, // Integer + Revision, // Integer + HighestPerformance, // Integer or Buffer (Resource Descriptor) + NominalPerformance, // Integer or Buffer (Resource Descriptor) + LowestNonlinearPerformance, // Integer or Buffer (Resource Descriptor) + LowestPerformance, // Integer or Buffer (Resource Descriptor) + GuaranteedPerformanceRegister, // Buffer (Resource Descriptor) + DesiredPerformanceRegister , // Buffer (Resource Descriptor) + MinimumPerformanceRegister , // Buffer (Resource Descriptor) + MaximumPerformanceRegister , // Buffer (Resource Descriptor) + PerformanceReductionToleranceRegister, // Buffer (Resource Descriptor) + TimeWindowRegister, // Buffer (Resource Descriptor) + CounterWraparoundTime, // Integer or Buffer (Resource Descriptor) + ReferencePerformanceCounterRegister, // Buffer (Resource Descriptor) + DeliveredPerformanceCounterRegister, // Buffer (Resource Descriptor) + PerformanceLimitedRegister, // Buffer (Resource Descriptor) + CPPCEnableRegister // Buffer (Resource Descriptor) + AutonomousSelectionEnable, // Integer or Buffer (Resource Descriptor) + AutonomousActivityWindowRegister, // Buffer (Resource Descriptor) + EnergyPerformancePreferenceRegister, // Buffer (Resource Descriptor) + ReferencePerformance // Integer or Buffer (Resource Descriptor) + LowestFrequency, // Integer or Buffer (Resource Descriptor) + NominalFrequency // Integer or Buffer (Resource Descriptor) + }) + + If resource buffer is NULL then integer will be used. + + Cf. ACPI 6.4, s8.4.7.1 _CPC (Continuous Performance Control) + + @ingroup CodeGenApis + + @param [in] CpcInfo CpcInfo object + @param [in] ParentNode If provided, set ParentNode as the parent + of the node created. + @param [out] NewCpcNode If success and provided, contains the created node. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +EFI_STATUS +EFIAPI +AmlCreateCpcNode ( + IN AML_CPC_INFO *CpcInfo, + IN AML_NODE_HANDLE ParentNode OPTIONAL, + OUT AML_OBJECT_NODE_HANDLE *NewCpcNode OPTIONAL + ); + // DEPRECATED APIS #ifndef DISABLE_NEW_DEPRECATED_INTERFACES diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c index 5fb39d077b..7e67482f99 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -2850,3 +2851,477 @@ AmlAddNameIntegerPackage ( return Status; } + +/** Adds a register to the package + + @ingroup CodeGenApis + + @param [in] Register If provided, register that will be added to package. + otherwise NULL register will be added + @param [in] PackageNode Package to add value to + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +STATIC +EFI_STATUS +EFIAPI +AmlAddRegisterToPackage ( + IN EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE *Register OPTIONAL, + IN AML_OBJECT_NODE_HANDLE PackageNode + ) +{ + EFI_STATUS Status; + AML_DATA_NODE_HANDLE RdNode; + AML_OBJECT_NODE_HANDLE ResourceTemplateNode; + + RdNode = NULL; + + Status = AmlCodeGenResourceTemplate (&ResourceTemplateNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + if (Register != NULL) { + Status = AmlCodeGenRdRegister ( + Register->AddressSpaceId, + Register->RegisterBitWidth, + Register->RegisterBitOffset, + Register->Address, + Register->AccessSize, + NULL, + &RdNode + ); + } else { + Status = AmlCodeGenRdRegister ( + EFI_ACPI_6_4_SYSTEM_MEMORY, + 0, + 0, + 0, + 0, + NULL, + &RdNode + ); + } + + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAppendRdNode (ResourceTemplateNode, RdNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + RdNode = NULL; + + Status = AmlVarListAddTail ( + (AML_NODE_HANDLE)PackageNode, + (AML_NODE_HANDLE)ResourceTemplateNode + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + return Status; + +error_handler: + if (RdNode != NULL) { + AmlDeleteTree ((AML_NODE_HANDLE)RdNode); + } + + if (ResourceTemplateNode != NULL) { + AmlDeleteTree ((AML_NODE_HANDLE)ResourceTemplateNode); + } + + return Status; +} + +/** Utility function to check if generic address points to NULL + + @param [in] Address Pointer to the Generic address + + @retval TRUE Address is system memory with an Address of 0. + @retval FALSE Address does not point to NULL. +**/ +STATIC +BOOLEAN +EFIAPI +IsNullGenericAddress ( + IN EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE *Address + ) +{ + if ((Address == NULL) || + ((Address->AddressSpaceId == EFI_ACPI_6_4_SYSTEM_MEMORY) && + (Address->Address == 0x0))) + { + return TRUE; + } + + return FALSE; +} + +/** Adds an integer or register to the package + + @ingroup CodeGenApis + + @param [in] Register If provided, register that will be added to package + @param [in] Integer If Register is NULL, integer that will be added to the package + @param [in] PackageNode Package to add value to + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +STATIC +EFI_STATUS +EFIAPI +AmlAddRegisterOrIntegerToPackage ( + IN EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE *Register OPTIONAL, + IN UINT32 Integer, + IN AML_OBJECT_NODE_HANDLE PackageNode + ) +{ + EFI_STATUS Status; + AML_OBJECT_NODE_HANDLE IntegerNode; + + IntegerNode = NULL; + + if (!IsNullGenericAddress (Register)) { + Status = AmlAddRegisterToPackage (Register, PackageNode); + } else { + Status = AmlCodeGenInteger (Integer, &IntegerNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + Status = AmlVarListAddTail ( + (AML_NODE_HANDLE)PackageNode, + (AML_NODE_HANDLE)IntegerNode + ); + } + + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + if (IntegerNode != NULL) { + AmlDeleteTree ((AML_NODE_HANDLE)IntegerNode); + } + } + + return Status; +} + +/** Create a _CPC node. + + Creates and optionally adds the following node + Name(_CPC, Package() + { + NumEntries, // Integer + Revision, // Integer + HighestPerformance, // Integer or Buffer (Resource Descriptor) + NominalPerformance, // Integer or Buffer (Resource Descriptor) + LowestNonlinearPerformance, // Integer or Buffer (Resource Descriptor) + LowestPerformance, // Integer or Buffer (Resource Descriptor) + GuaranteedPerformanceRegister, // Buffer (Resource Descriptor) + DesiredPerformanceRegister , // Buffer (Resource Descriptor) + MinimumPerformanceRegister , // Buffer (Resource Descriptor) + MaximumPerformanceRegister , // Buffer (Resource Descriptor) + PerformanceReductionToleranceRegister, // Buffer (Resource Descriptor) + TimeWindowRegister, // Buffer (Resource Descriptor) + CounterWraparoundTime, // Integer or Buffer (Resource Descriptor) + ReferencePerformanceCounterRegister, // Buffer (Resource Descriptor) + DeliveredPerformanceCounterRegister, // Buffer (Resource Descriptor) + PerformanceLimitedRegister, // Buffer (Resource Descriptor) + CPPCEnableRegister // Buffer (Resource Descriptor) + AutonomousSelectionEnable, // Integer or Buffer (Resource Descriptor) + AutonomousActivityWindowRegister, // Buffer (Resource Descriptor) + EnergyPerformancePreferenceRegister, // Buffer (Resource Descriptor) + ReferencePerformance // Integer or Buffer (Resource Descriptor) + LowestFrequency, // Integer or Buffer (Resource Descriptor) + NominalFrequency // Integer or Buffer (Resource Descriptor) + }) + + If resource buffer is NULL then integer will be used. + + Cf. ACPI 6.4, s8.4.7.1 _CPC (Continuous Performance Control) + + @ingroup CodeGenApis + + @param [in] CpcInfo CpcInfo object + @param [in] ParentNode If provided, set ParentNode as the parent + of the node created. + @param [out] NewCpcNode If success and provided, contains the created node. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +EFI_STATUS +EFIAPI +AmlCreateCpcNode ( + IN AML_CPC_INFO *CpcInfo, + IN AML_NODE_HANDLE ParentNode OPTIONAL, + OUT AML_OBJECT_NODE_HANDLE *NewCpcNode OPTIONAL + ) +{ + EFI_STATUS Status; + AML_OBJECT_NODE_HANDLE CpcNode; + AML_OBJECT_NODE_HANDLE CpcPackage; + UINT32 NumberOfEntries; + + if ((CpcInfo == NULL) || + ((ParentNode == NULL) && (NewCpcNode == NULL))) + { + ASSERT (0); + return EFI_INVALID_PARAMETER; + } + + // Revision 3 per ACPI 6.4 specification + if (CpcInfo->Revision == 3) { + // NumEntries 23 per ACPI 6.4 specification + NumberOfEntries = 23; + } else { + ASSERT (0); + return EFI_INVALID_PARAMETER; + } + + if ((IsNullGenericAddress (&CpcInfo->HighestPerformanceBuffer) && + (CpcInfo->HighestPerformanceInteger == 0)) || + (IsNullGenericAddress (&CpcInfo->NominalPerformanceBuffer) && + (CpcInfo->NominalPerformanceInteger == 0)) || + (IsNullGenericAddress (&CpcInfo->LowestNonlinearPerformanceBuffer) && + (CpcInfo->LowestNonlinearPerformanceInteger == 0)) || + (IsNullGenericAddress (&CpcInfo->LowestPerformanceBuffer) && + (CpcInfo->LowestPerformanceInteger == 0)) || + IsNullGenericAddress (&CpcInfo->DesiredPerformanceRegister) || + IsNullGenericAddress (&CpcInfo->ReferencePerformanceCounterRegister) || + IsNullGenericAddress (&CpcInfo->DeliveredPerformanceCounterRegister) || + IsNullGenericAddress (&CpcInfo->PerformanceLimitedRegister)) + { + ASSERT (0); + return EFI_INVALID_PARAMETER; + } + + CpcPackage = NULL; + + Status = AmlCodeGenNamePackage ("_CPC", NULL, &CpcNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + // Get the Package object node of the _CPC node, + // which is the 2nd fixed argument (i.e. index 1). + CpcPackage = (AML_OBJECT_NODE_HANDLE)AmlGetFixedArgument ( + CpcNode, + EAmlParseIndexTerm1 + ); + if ((CpcPackage == NULL) || + (AmlGetNodeType ((AML_NODE_HANDLE)CpcPackage) != EAmlNodeObject) || + (!AmlNodeHasOpCode (CpcPackage, AML_PACKAGE_OP, 0))) + { + ASSERT (0); + Status = EFI_INVALID_PARAMETER; + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + NULL, + NumberOfEntries, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + NULL, + CpcInfo->Revision, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->HighestPerformanceBuffer, + CpcInfo->HighestPerformanceInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->NominalPerformanceBuffer, + CpcInfo->NominalPerformanceInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->LowestNonlinearPerformanceBuffer, + CpcInfo->LowestNonlinearPerformanceInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->LowestPerformanceBuffer, + CpcInfo->LowestPerformanceInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->GuaranteedPerformanceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->DesiredPerformanceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->MinimumPerformanceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->MaximumPerformanceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->PerformanceReductionToleranceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->TimeWindowRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->CounterWraparoundTimeBuffer, + CpcInfo->CounterWraparoundTimeInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->ReferencePerformanceCounterRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->DeliveredPerformanceCounterRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->PerformanceLimitedRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->CPPCEnableRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->AutonomousSelectionEnableBuffer, + CpcInfo->AutonomousSelectionEnableInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->AutonomousActivityWindowRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterToPackage (&CpcInfo->EnergyPerformancePreferenceRegister, CpcPackage); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->ReferencePerformanceBuffer, + CpcInfo->ReferencePerformanceInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->LowestFrequencyBuffer, + CpcInfo->LowestFrequencyInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = AmlAddRegisterOrIntegerToPackage ( + &CpcInfo->NominalFrequencyBuffer, + CpcInfo->NominalFrequencyInteger, + CpcPackage + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = LinkNode (CpcNode, ParentNode, NewCpcNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + return Status; + +error_handler: + AmlDeleteTree ((AML_NODE_HANDLE)CpcNode); + return Status; +} From a80e298bfe9aed2c01b5c9ce56f0e244e341f33e Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Thu, 22 Sep 2022 14:36:46 -0600 Subject: [PATCH 0065/1529] DynamicTablesPkg: SSDT CPU _CPC generator Add code to use a token attached to GICC to generate _CPC object on cpus. Signed-off-by: Jeff Brasen Reviewed-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../SsdtCpuTopologyGenerator.c | 133 +++++++++++++++++- 1 file changed, 127 insertions(+), 6 deletions(-) diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c index 8561f48e1f..d06c7615fb 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c @@ -76,6 +76,16 @@ GET_OBJECT_LIST ( CM_ARM_LPI_INFO ); +/** + This macro expands to a function that retrieves the CPC + information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjCpcInfo, + CM_ARM_CPC_INFO + ); + /** Initialize the TokenTable. One entry should be allocated for each CM_ARM_PROC_HIERARCHY_INFO @@ -229,6 +239,93 @@ WriteAslName ( return EFI_SUCCESS; } +/** Create and add an _CPC Node to Cpu Node. + + For instance, transform an AML node from: + Device (C002) + { + Name (_UID, 2) + Name (_HID, "ACPI0007") + } + + To: + Device (C002) + { + Name (_UID, 2) + Name (_HID, "ACPI0007") + Name(_CPC, Package() + { + NumEntries, // Integer + Revision, // Integer + HighestPerformance, // Integer or Buffer (Resource Descriptor) + NominalPerformance, // Integer or Buffer (Resource Descriptor) + LowestNonlinearPerformance, // Integer or Buffer (Resource Descriptor) + LowestPerformance, // Integer or Buffer (Resource Descriptor) + GuaranteedPerformanceRegister, // Buffer (Resource Descriptor) + DesiredPerformanceRegister , // Buffer (Resource Descriptor) + MinimumPerformanceRegister , // Buffer (Resource Descriptor) + MaximumPerformanceRegister , // Buffer (Resource Descriptor) + PerformanceReductionToleranceRegister, // Buffer (Resource Descriptor) + TimeWindowRegister, // Buffer (Resource Descriptor) + CounterWraparoundTime, // Integer or Buffer (Resource Descriptor) + ReferencePerformanceCounterRegister, // Buffer (Resource Descriptor) + DeliveredPerformanceCounterRegister, // Buffer (Resource Descriptor) + PerformanceLimitedRegister, // Buffer (Resource Descriptor) + CPPCEnableRegister // Buffer (Resource Descriptor) + AutonomousSelectionEnable, // Integer or Buffer (Resource Descriptor) + AutonomousActivityWindowRegister, // Buffer (Resource Descriptor) + EnergyPerformancePreferenceRegister, // Buffer (Resource Descriptor) + ReferencePerformance // Integer or Buffer (Resource Descriptor) + LowestFrequency, // Integer or Buffer (Resource Descriptor) + NominalFrequency // Integer or Buffer (Resource Descriptor) + }) + } + + @param [in] Generator The SSDT Cpu Topology generator. + @param [in] CfgMgrProtocol Pointer to the Configuration Manager + Protocol Interface. + @param [in] GicCInfo Pointer to the CM_ARM_GICC_INFO object + describing the Cpu. + @param [in] Node CPU Node to which the _CPC node is + attached. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +STATIC +EFI_STATUS +EFIAPI +CreateAmlCpcNode ( + IN ACPI_CPU_TOPOLOGY_GENERATOR *Generator, + IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, + IN CM_ARM_GICC_INFO *GicCInfo, + IN AML_OBJECT_NODE_HANDLE *Node + ) +{ + EFI_STATUS Status; + CM_ARM_CPC_INFO *CpcInfo; + + Status = GetEArmObjCpcInfo ( + CfgMgrProtocol, + GicCInfo->CpcToken, + &CpcInfo, + NULL + ); + if (EFI_ERROR (Status)) { + ASSERT (0); + return Status; + } + + Status = AmlCreateCpcNode ( + CpcInfo, + Node, + NULL + ); + ASSERT_EFI_ERROR (Status); + return Status; +} + /** Create and add an _LPI method to Cpu/Cluster Node. For instance, transform an AML node from: @@ -581,7 +678,20 @@ CreateAmlCpuFromProcHierarchy ( // CM_ARM_PROC_HIERARCHY_INFO, create an _LPI method returning them. if (ProcHierarchyNodeInfo->LpiToken != CM_NULL_TOKEN) { Status = CreateAmlLpiMethod (Generator, ProcHierarchyNodeInfo, CpuNode); - ASSERT_EFI_ERROR (Status); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + } + + // If a CPC info is associated with the + // GicCinfo, create an _CPC method returning them. + if (GicCInfo->CpcToken != CM_NULL_TOKEN) { + Status = CreateAmlCpcNode (Generator, CfgMgrProtocol, GicCInfo, CpuNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } } return Status; @@ -934,10 +1044,11 @@ CreateTopologyFromGicC ( IN AML_OBJECT_NODE_HANDLE ScopeNode ) { - EFI_STATUS Status; - CM_ARM_GICC_INFO *GicCInfo; - UINT32 GicCInfoCount; - UINT32 Index; + EFI_STATUS Status; + CM_ARM_GICC_INFO *GicCInfo; + UINT32 GicCInfoCount; + UINT32 Index; + AML_OBJECT_NODE_HANDLE CpuNode; ASSERT (Generator != NULL); ASSERT (CfgMgrProtocol != NULL); @@ -961,12 +1072,22 @@ CreateTopologyFromGicC ( ScopeNode, &GicCInfo[Index], Index, - NULL + &CpuNode ); if (EFI_ERROR (Status)) { ASSERT (0); break; } + + // If a CPC info is associated with the + // GicCinfo, create an _CPC method returning them. + if (GicCInfo->CpcToken != CM_NULL_TOKEN) { + Status = CreateAmlCpcNode (Generator, CfgMgrProtocol, &GicCInfo[Index], CpuNode); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + break; + } + } } // for return Status; From b77683d00a8638c691bed2853638f2fdfd3bc34b Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Fri, 23 Sep 2022 09:56:16 -0600 Subject: [PATCH 0066/1529] EmbeddedPkg/PrePi: Check for enough space before aligning heap pointer Update check for enough space to occur prior to alignment offset. This prevents cases where EfiFreeMemoryTop < EfiFreeMemoryBottom. Signed-off-by: Jeff Brasen Reviewed-by: Ard Biesheuvel --- .../MemoryAllocationLib.c | 48 ++++++++----------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c index 2cc2a71121..08a0add340 100644 --- a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c +++ b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c @@ -23,41 +23,35 @@ InternalAllocatePages ( ) { EFI_PEI_HOB_POINTERS Hob; - EFI_PHYSICAL_ADDRESS Offset; + EFI_PHYSICAL_ADDRESS NewTop; Hob.Raw = GetHobList (); - // Check to see if on 4k boundary - Offset = Hob.HandoffInformationTable->EfiFreeMemoryTop & 0xFFF; - if (Offset != 0) { - // If not aligned, make the allocation aligned. - Hob.HandoffInformationTable->EfiFreeMemoryTop -= Offset; - } + NewTop = Hob.HandoffInformationTable->EfiFreeMemoryTop & ~(EFI_PHYSICAL_ADDRESS)EFI_PAGE_MASK; + NewTop -= Pages * EFI_PAGE_SIZE; // // Verify that there is sufficient memory to satisfy the allocation // - if (Hob.HandoffInformationTable->EfiFreeMemoryTop - ((Pages * EFI_PAGE_SIZE) + sizeof (EFI_HOB_MEMORY_ALLOCATION)) < Hob.HandoffInformationTable->EfiFreeMemoryBottom) { - return 0; - } else { - // - // Update the PHIT to reflect the memory usage - // - Hob.HandoffInformationTable->EfiFreeMemoryTop -= Pages * EFI_PAGE_SIZE; - - // This routine used to create a memory allocation HOB a la PEI, but that's not - // necessary for us. - - // - // Create a memory allocation HOB. - // - BuildMemoryAllocationHob ( - Hob.HandoffInformationTable->EfiFreeMemoryTop, - Pages * EFI_PAGE_SIZE, - MemoryType - ); - return (VOID *)(UINTN)Hob.HandoffInformationTable->EfiFreeMemoryTop; + if (NewTop < (Hob.HandoffInformationTable->EfiFreeMemoryBottom + sizeof (EFI_HOB_MEMORY_ALLOCATION))) { + return NULL; } + + // + // Update the PHIT to reflect the memory usage + // + Hob.HandoffInformationTable->EfiFreeMemoryTop = NewTop; + + // + // Create a memory allocation HOB. + // + BuildMemoryAllocationHob ( + Hob.HandoffInformationTable->EfiFreeMemoryTop, + Pages * EFI_PAGE_SIZE, + MemoryType + ); + + return (VOID *)(UINTN)Hob.HandoffInformationTable->EfiFreeMemoryTop; } /** From b05883cad117dfb73b78ca0c55df4ba61c26f81f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 23 Sep 2022 12:45:51 -0700 Subject: [PATCH 0067/1529] CryptoPkg: Add missing library mappings to DSC file REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4080 Add SynchronizationLib and MmServicesTableLib mappings that are required for the CRYPTO_SERVICES set to ALL or MIN_DXE_MIN_SMM builds. Also update the family PCD settings for the PACKAGE and ALL profiles to enable all families. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 9bee423e21..7034e8a412 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -66,6 +66,7 @@ TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf [LibraryClasses.ARM, LibraryClasses.AARCH64] # @@ -89,6 +90,7 @@ [LibraryClasses.common.DXE_SMM_DRIVER] SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf + MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf !if $(CRYPTO_SERVICES) IN "ALL NONE MIN_PEI MIN_DXE_MIN_SMM" [LibraryClasses] @@ -159,16 +161,16 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tdes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Arc4.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tls.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsSet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsGet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.RsaPss.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.ParallelHash.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Bn.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif From c6614a4ff338ee06a3bb1906c679777c0f0422b8 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Mon, 26 Sep 2022 08:24:33 +0800 Subject: [PATCH 0068/1529] CryptoPkg: Fix pem heap-buffer-overflow due to BIO_snprintf() REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4075 Fake BIO_snprintf() does not actually print anything to buf, it should return -1 as error. 0 will be considered a correct return value, the consumer may think that the buf is valid and parse the buffer. please refer to bugzilla link for details. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c index c1fc33538f..b65d29485b 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c @@ -494,7 +494,9 @@ BIO_snprintf ( ... ) { - return 0; + // Because the function does not actually print anything to buf, it returns -1 as error. + // Otherwise, the consumer may think that the buf is valid and parse the buffer. + return -1; } #ifdef __GNUC__ From 221010363390177feb4572ecab7449d6aec3a65c Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sun, 25 Sep 2022 17:26:18 +0800 Subject: [PATCH 0069/1529] CryptoPkg: Add EC support REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3828 This patch is used to add CryptEc library, which is wrapped over OpenSSL. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 424 ++++++++++ .../Library/BaseCryptLib/BaseCryptLib.inf | 2 + .../Library/BaseCryptLib/PeiCryptLib.inf | 1 + CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c | 765 ++++++++++++++++++ .../Library/BaseCryptLib/Pk/CryptEcNull.c | 496 ++++++++++++ .../Library/BaseCryptLib/SmmCryptLib.inf | 1 + .../BaseCryptLibNull/BaseCryptLibNull.inf | 1 + .../Library/BaseCryptLibNull/Pk/CryptEcNull.c | 496 ++++++++++++ 8 files changed, 2186 insertions(+) create mode 100644 CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c create mode 100644 CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 3026299e29..63c6228368 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -14,6 +14,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include +#define CRYPTO_NID_NULL 0x0000 + +// Key Exchange +#define CRYPTO_NID_SECP256R1 0x0204 +#define CRYPTO_NID_SECP384R1 0x0205 +#define CRYPTO_NID_SECP521R1 0x0206 + /// /// MD5 digest size in bytes /// @@ -3254,4 +3261,421 @@ BigNumAddMod ( OUT VOID *BnRes ); +// ===================================================================================== +// Basic Elliptic Curve Primitives +// ===================================================================================== + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcGroupInit ( + IN UINTN CryptoNid + ); + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ); + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ); + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +EcGroupFree ( + IN VOID *EcGroup + ); + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcPointInit ( + IN CONST VOID *EcGroup + ); + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +EcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ); + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ); + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ); + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ); + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ); + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ); + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ); + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ); + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ); + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ); + +// ===================================================================================== +// Elliptic Curve Diffie Hellman Primitives +// ===================================================================================== + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +EcNewByNid ( + IN UINTN Nid + ); + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +EcFree ( + IN VOID *EcContext + ); + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ); + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +EcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ); + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ); + #endif // __BASE_CRYPT_LIB_H__ diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 0208d706b8..9634bd5fea 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -53,6 +53,8 @@ Pk/CryptTs.c Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c + Pk/CryptEcNull.c |*|*|*|!gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + Pk/CryptEc.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled Pem/CryptPem.c Bn/CryptBn.c diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 82b97bc6d3..3799780c9f 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -59,6 +59,7 @@ Pk/CryptTsNull.c Pk/CryptRsaPss.c Pk/CryptRsaPssSignNull.c + Pk/CryptEcNull.c Pem/CryptPemNull.c Rand/CryptRandNull.c Bn/CryptBnNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c new file mode 100644 index 0000000000..396c819834 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c @@ -0,0 +1,765 @@ +/** @file + Elliptic Curve and ECDH API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "InternalCryptLib.h" +#include +#include +#include + +// ===================================================================================== +// Basic Elliptic Curve Primitives +// ===================================================================================== + +/** + Return the Nid of certain ECC curve. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval !=-1 On success. + @retval -1 ECC curve not supported. +**/ +STATIC +INT32 +CryptoNidToOpensslNid ( + IN UINTN CryptoNid + ) +{ + INT32 Nid; + + switch (CryptoNid) { + case CRYPTO_NID_SECP256R1: + Nid = NID_X9_62_prime256v1; + break; + case CRYPTO_NID_SECP384R1: + Nid = NID_secp384r1; + break; + case CRYPTO_NID_SECP521R1: + Nid = NID_secp521r1; + break; + default: + return -1; + } + + return Nid; +} + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcGroupInit ( + IN UINTN CryptoNid + ) +{ + INT32 Nid; + + Nid = CryptoNidToOpensslNid (CryptoNid); + + if (Nid < 0) { + return NULL; + } + + return EC_GROUP_new_by_curve_name (Nid); +} + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient.. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_GROUP_get_curve (EcGroup, BnPrime, BnA, BnB, BnCtx); +} + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ) +{ + return (BOOLEAN)EC_GROUP_get_order (EcGroup, BnOrder, NULL); +} + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +EcGroupFree ( + IN VOID *EcGroup + ) +{ + EC_GROUP_free (EcGroup); +} + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcPointInit ( + IN CONST VOID *EcGroup + ) +{ + return EC_POINT_new (EcGroup); +} + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +EcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ) +{ + if (Clear) { + EC_POINT_clear_free (EcPoint); + } else { + EC_POINT_free (EcPoint); + } +} + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_get_affine_coordinates (EcGroup, EcPoint, BnX, BnY, BnCtx); +} + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_set_affine_coordinates (EcGroup, EcPoint, BnX, BnY, BnCtx); +} + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_add (EcGroup, EcPointResult, EcPointA, EcPointB, BnCtx); +} + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_mul (EcGroup, EcPointResult, NULL, EcPoint, BnPScalar, BnCtx); +} + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_invert (EcGroup, EcPoint, BnCtx); +} + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ) +{ + return EC_POINT_is_on_curve (EcGroup, EcPoint, BnCtx) == 1; +} + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ) +{ + return EC_POINT_is_at_infinity (EcGroup, EcPoint) == 1; +} + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + return EC_POINT_cmp (EcGroup, EcPointA, EcPointB, BnCtx) == 0; +} + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ) +{ + return (BOOLEAN)EC_POINT_set_compressed_coordinates (EcGroup, EcPoint, BnX, YBit, BnCtx); +} + +// ===================================================================================== +// Elliptic Curve Diffie Hellman Primitives +// ===================================================================================== + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +EcNewByNid ( + IN UINTN Nid + ) +{ + INT32 OpenSslNid; + + OpenSslNid = CryptoNidToOpensslNid (Nid); + if (OpenSslNid < 0) { + return NULL; + } + + return (VOID *)EC_KEY_new_by_curve_name (OpenSslNid); +} + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +EcFree ( + IN VOID *EcContext + ) +{ + EC_KEY_free ((EC_KEY *)EcContext); +} + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + EC_KEY *EcKey; + CONST EC_GROUP *Group; + CONST EC_POINT *EcPoint; + BOOLEAN RetVal; + BIGNUM *BnX; + BIGNUM *BnY; + UINTN HalfSize; + INTN XSize; + INTN YSize; + + if ((EcContext == NULL) || (PublicKeySize == NULL)) { + return FALSE; + } + + if ((PublicKey == NULL) && (*PublicKeySize != 0)) { + return FALSE; + } + + EcKey = (EC_KEY *)EcContext; + Group = EC_KEY_get0_group (EcKey); + HalfSize = (EC_GROUP_get_degree (Group) + 7) / 8; + + // Assume RAND_seed was called + if (EC_KEY_generate_key (EcKey) != 1) { + return FALSE; + } + + if (*PublicKeySize < HalfSize * 2) { + *PublicKeySize = HalfSize * 2; + return FALSE; + } + + *PublicKeySize = HalfSize * 2; + + EcPoint = EC_KEY_get0_public_key (EcKey); + if (EcPoint == NULL) { + return FALSE; + } + + RetVal = FALSE; + BnX = BN_new (); + BnY = BN_new (); + if ((BnX == NULL) || (BnY == NULL)) { + goto fail; + } + + if (EC_POINT_get_affine_coordinates (Group, EcPoint, BnX, BnY, NULL) != 1) { + goto fail; + } + + XSize = BN_num_bytes (BnX); + YSize = BN_num_bytes (BnY); + if ((XSize <= 0) || (YSize <= 0)) { + goto fail; + } + + ASSERT ((UINTN)XSize <= HalfSize && (UINTN)YSize <= HalfSize); + + ZeroMem (PublicKey, *PublicKeySize); + BN_bn2bin (BnX, &PublicKey[0 + HalfSize - XSize]); + BN_bn2bin (BnY, &PublicKey[HalfSize + HalfSize - YSize]); + + RetVal = TRUE; + +fail: + BN_free (BnX); + BN_free (BnY); + return RetVal; +} + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +EcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + EC_KEY *EcKey; + CONST EC_GROUP *Group; + CONST EC_POINT *EcPoint; + BIGNUM *BnX; + BIGNUM *BnY; + UINTN HalfSize; + INTN XSize; + INTN YSize; + BOOLEAN RetVal; + + if ((EcContext == NULL) || (PublicKeySize == NULL)) { + return FALSE; + } + + if ((PublicKey == NULL) && (*PublicKeySize != 0)) { + return FALSE; + } + + EcKey = (EC_KEY *)EcContext; + Group = EC_KEY_get0_group (EcKey); + HalfSize = (EC_GROUP_get_degree (Group) + 7) / 8; + if (*PublicKeySize < HalfSize * 2) { + *PublicKeySize = HalfSize * 2; + return FALSE; + } + + *PublicKeySize = HalfSize * 2; + + EcPoint = EC_KEY_get0_public_key (EcKey); + if (EcPoint == NULL) { + return FALSE; + } + + RetVal = FALSE; + BnX = BN_new (); + BnY = BN_new (); + if ((BnX == NULL) || (BnY == NULL)) { + goto fail; + } + + if (EC_POINT_get_affine_coordinates (Group, EcPoint, BnX, BnY, NULL) != 1) { + goto fail; + } + + XSize = BN_num_bytes (BnX); + YSize = BN_num_bytes (BnY); + if ((XSize <= 0) || (YSize <= 0)) { + goto fail; + } + + ASSERT ((UINTN)XSize <= HalfSize && (UINTN)YSize <= HalfSize); + + if (PublicKey != NULL) { + ZeroMem (PublicKey, *PublicKeySize); + BN_bn2bin (BnX, &PublicKey[0 + HalfSize - XSize]); + BN_bn2bin (BnY, &PublicKey[HalfSize + HalfSize - YSize]); + } + + RetVal = TRUE; + +fail: + BN_free (BnX); + BN_free (BnY); + return RetVal; +} + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If public key is compressed, the PeerPublic will only contain half key (X). + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ) +{ + EC_KEY *EcKey; + EC_KEY *PeerEcKey; + CONST EC_GROUP *Group; + BOOLEAN RetVal; + BIGNUM *BnX; + BIGNUM *BnY; + EC_POINT *Point; + INT32 OpenSslNid; + UINTN HalfSize; + + if ((EcContext == NULL) || (PeerPublic == NULL) || (KeySize == NULL)) { + return FALSE; + } + + if ((Key == NULL) && (*KeySize != 0)) { + return FALSE; + } + + if (PeerPublicSize > INT_MAX) { + return FALSE; + } + + EcKey = (EC_KEY *)EcContext; + Group = EC_KEY_get0_group (EcKey); + HalfSize = (EC_GROUP_get_degree (Group) + 7) / 8; + if ((CompressFlag == NULL) && (PeerPublicSize != HalfSize * 2)) { + return FALSE; + } + + if ((CompressFlag != NULL) && (PeerPublicSize != HalfSize)) { + return FALSE; + } + + if (*KeySize < HalfSize) { + *KeySize = HalfSize; + return FALSE; + } + + *KeySize = HalfSize; + + RetVal = FALSE; + Point = NULL; + BnX = BN_bin2bn (PeerPublic, (INT32)HalfSize, NULL); + BnY = NULL; + Point = EC_POINT_new (Group); + PeerEcKey = NULL; + if ((BnX == NULL) || (Point == NULL)) { + goto fail; + } + + if (CompressFlag == NULL) { + BnY = BN_bin2bn (PeerPublic + HalfSize, (INT32)HalfSize, NULL); + if (BnY == NULL) { + goto fail; + } + + if (EC_POINT_set_affine_coordinates (Group, Point, BnX, BnY, NULL) != 1) { + goto fail; + } + } else { + if (EC_POINT_set_compressed_coordinates (Group, Point, BnX, *CompressFlag, NULL) != 1) { + goto fail; + } + } + + // Validate NIST ECDH public key + OpenSslNid = EC_GROUP_get_curve_name (Group); + PeerEcKey = EC_KEY_new_by_curve_name (OpenSslNid); + if (PeerEcKey == NULL) { + goto fail; + } + + if (EC_KEY_set_public_key (PeerEcKey, Point) != 1) { + goto fail; + } + + if (EC_KEY_check_key (PeerEcKey) != 1) { + goto fail; + } + + if (ECDH_compute_key (Key, *KeySize, Point, EcKey, NULL) <= 0) { + goto fail; + } + + RetVal = TRUE; + +fail: + BN_free (BnX); + BN_free (BnY); + EC_POINT_free (Point); + EC_KEY_free (PeerEcKey); + return RetVal; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c new file mode 100644 index 0000000000..d9f1004f6c --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c @@ -0,0 +1,496 @@ +/** @file + Elliptic Curve and ECDH API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcGroupInit ( + IN UINTN CryptoNid + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient.. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +EcGroupFree ( + IN VOID *EcGroup + ) +{ + ASSERT (FALSE); +} + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcPointInit ( + IN CONST VOID *EcGroup + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +EcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ) +{ + ASSERT (FALSE); +} + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +EcNewByNid ( + IN UINTN Nid + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +EcFree ( + IN VOID *EcContext + ) +{ + ASSERT (FALSE); +} + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +EcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 986581319c..9318052a51 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -60,6 +60,7 @@ Pk/CryptTsNull.c Pk/CryptRsaPss.c Pk/CryptRsaPssSignNull.c + Pk/CryptEcNull.c Pem/CryptPem.c Bn/CryptBnNull.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf index 88ada0430d..9cb8d42ff4 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +++ b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf @@ -50,6 +50,7 @@ Pk/CryptX509Null.c Pk/CryptAuthenticodeNull.c Pk/CryptTsNull.c + Pk/CryptEcNull.c Pem/CryptPemNull.c Rand/CryptRandNull.c Pk/CryptRsaPssNull.c diff --git a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c new file mode 100644 index 0000000000..d9f1004f6c --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c @@ -0,0 +1,496 @@ +/** @file + Elliptic Curve and ECDH API implementation based on OpenSSL + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcGroupInit ( + IN UINTN CryptoNid + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient.. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +EcGroupFree ( + IN VOID *EcGroup + ) +{ + ASSERT (FALSE); +} + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcPointInit ( + IN CONST VOID *EcGroup + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +EcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ) +{ + ASSERT (FALSE); +} + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +EcNewByNid ( + IN UINTN Nid + ) +{ + ASSERT (FALSE); + return NULL; +} + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +EcFree ( + IN VOID *EcContext + ) +{ + ASSERT (FALSE); +} + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +EcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ) +{ + ASSERT (FALSE); + return FALSE; +} From 6ee9c95df12766d776b7459bc29ea94b704e94ff Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sun, 25 Sep 2022 17:26:19 +0800 Subject: [PATCH 0070/1529] CryptoPkg: Add EC APIs to DXE and protocol REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3828 The implementation provides CryptEc library functions for EFI Driveer and EFI BaseCrypt Protocol. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 1 + CryptoPkg/Driver/Crypto.c | 496 +++++++++++ .../Pcd/PcdCryptoServiceFamilyEnable.h | 25 + .../BaseCryptLibOnProtocolPpi/CryptLib.c | 469 ++++++++++ CryptoPkg/Private/Protocol/Crypto.h | 831 +++++++++++++----- 5 files changed, 1622 insertions(+), 200 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 7034e8a412..e4e7bc0dbf 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -172,6 +172,7 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.ParallelHash.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Bn.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Ec.Family | 0 !endif !if $(CRYPTO_SERVICES) == MIN_PEI diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index 9872b5bf70..7a8266aaba 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -5519,6 +5519,481 @@ CryptoServiceBigNumAddMod ( return CALL_BASECRYPTLIB (Bn.Services.AddMod, BigNumAddMod, (BnA, BnB, BnM, BnRes), FALSE); } +// ===================================================================================== +// Basic Elliptic Curve Primitives +// ===================================================================================== + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +CryptoServiceEcGroupInit ( + IN UINTN CryptoNid + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GroupInit, EcGroupInit, (CryptoNid), NULL); +} + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GroupGetCurve, EcGroupGetCurve, (EcGroup, BnPrime, BnA, BnB, BnCtx), FALSE); +} + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GroupGetOrder, EcGroupGetOrder, (EcGroup, BnOrder), FALSE); +} + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +CryptoServiceEcGroupFree ( + IN VOID *EcGroup + ) +{ + CALL_VOID_BASECRYPTLIB (Ec.Services.GroupFree, EcGroupFree, (EcGroup)); +} + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +CryptoServiceEcPointInit ( + IN CONST VOID *EcGroup + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointInit, EcPointInit, (EcGroup), NULL); +} + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +CryptoServiceEcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ) +{ + CALL_VOID_BASECRYPTLIB (Ec.Services.PointDeInit, EcPointDeInit, (EcPoint, Clear)); +} + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointGetAffineCoordinates, EcPointGetAffineCoordinates, (EcGroup, EcPoint, BnX, BnY, BnCtx), FALSE); +} + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointSetAffineCoordinates, EcPointSetAffineCoordinates, (EcGroup, EcPoint, BnX, BnY, BnCtx), FALSE); +} + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointAdd, EcPointAdd, (EcGroup, EcPointResult, EcPointA, EcPointB, BnCtx), FALSE); +} + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointMul, EcPointMul, (EcGroup, EcPointResult, EcPoint, BnPScalar, BnCtx), FALSE); +} + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointInvert, EcPointInvert, (EcGroup, EcPoint, BnCtx), FALSE); +} + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointIsOnCurve, EcPointIsOnCurve, (EcGroup, EcPoint, BnCtx), FALSE); +} + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointIsAtInfinity, EcPointIsAtInfinity, (EcGroup, EcPoint), FALSE); +} + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointEqual, EcPointEqual, (EcGroup, EcPointA, EcPointB, BnCtx), FALSE); +} + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.PointSetCompressedCoordinates, EcPointSetCompressedCoordinates, (EcGroup, EcPoint, BnX, YBit, BnCtx), FALSE); +} + +// ===================================================================================== +// Elliptic Curve Diffie Hellman Primitives +// ===================================================================================== + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +CryptoServiceEcNewByNid ( + IN UINTN Nid + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.NewByNid, EcNewByNid, (Nid), NULL); +} + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +CryptoServiceEcFree ( + IN VOID *EcContext + ) +{ + CALL_VOID_BASECRYPTLIB (Ec.Services.Free, EcFree, (EcContext)); +} + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GenerateKey, EcGenerateKey, (EcContext, PublicKey, PublicKeySize), FALSE); +} + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GetPubKey, EcGetPubKey, (EcContext, PublicKey, PublicKeySize), FALSE); +} + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +CryptoServiceEcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.DhComputeKey, EcDhComputeKey, (EcContext, PeerPublic, PeerPublicSize, CompressFlag, Key, KeySize), FALSE); +} + const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { /// Version CryptoServiceGetCryptoVersion, @@ -5770,4 +6245,25 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceBigNumContextFree, CryptoServiceBigNumSetUint, CryptoServiceBigNumAddMod, + /// EC + CryptoServiceEcGroupInit, + CryptoServiceEcGroupGetCurve, + CryptoServiceEcGroupGetOrder, + CryptoServiceEcGroupFree, + CryptoServiceEcPointInit, + CryptoServiceEcPointDeInit, + CryptoServiceEcPointGetAffineCoordinates, + CryptoServiceEcPointSetAffineCoordinates, + CryptoServiceEcPointAdd, + CryptoServiceEcPointMul, + CryptoServiceEcPointInvert, + CryptoServiceEcPointIsOnCurve, + CryptoServiceEcPointIsAtInfinity, + CryptoServiceEcPointEqual, + CryptoServiceEcPointSetCompressedCoordinates, + CryptoServiceEcNewByNid, + CryptoServiceEcFree, + CryptoServiceEcGenerateKey, + CryptoServiceEcGetPubKey, + CryptoServiceEcDhComputeKey, }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 52b44ca4f8..45bafc2161 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -356,6 +356,31 @@ typedef struct { } Services; UINT32 Family; } Bn; + union { + struct { + UINT8 GroupInit : 1; + UINT8 GroupGetCurve : 1; + UINT8 GroupGetOrder : 1; + UINT8 GroupFree : 1; + UINT8 PointInit : 1; + UINT8 PointDeInit : 1; + UINT8 PointGetAffineCoordinates : 1; + UINT8 PointSetAffineCoordinates : 1; + UINT8 PointAdd : 1; + UINT8 PointMul : 1; + UINT8 PointInvert : 1; + UINT8 PointIsOnCurve : 1; + UINT8 PointIsAtInfinity : 1; + UINT8 PointEqual : 1; + UINT8 PointSetCompressedCoordinates : 1; + UINT8 NewByNid : 1; + UINT8 Free : 1; + UINT8 GenerateKey : 1; + UINT8 GetPubKey : 1; + UINT8 DhComputeKey : 1; + } Services; + UINT32 Family; + } Ec; } PCD_CRYPTO_SERVICE_FAMILY_ENABLE; #endif diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index ce6981f091..791e2ef599 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -4553,3 +4553,472 @@ BigNumAddMod ( { CALL_CRYPTO_SERVICE (BigNumAddMod, (BnA, BnB, BnM, BnRes), FALSE); } + +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcGroupInit ( + IN UINTN CryptoNid + ) +{ + CALL_CRYPTO_SERVICE (EcGroupInit, (CryptoNid), NULL); +} + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetCurve ( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcGroupGetCurve, (EcGroup, BnPrime, BnA, BnB, BnCtx), FALSE); +} + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnOrder Group prime number. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcGroupGetOrder ( + IN VOID *EcGroup, + OUT VOID *BnOrder + ) +{ + CALL_CRYPTO_SERVICE (EcGroupGetOrder, (EcGroup, BnOrder), FALSE); +} + +/** + Free previously allocated EC group object using EcGroupInit(). + + @param[in] EcGroup EC group object to free. +**/ +VOID +EFIAPI +EcGroupFree ( + IN VOID *EcGroup + ) +{ + CALL_VOID_CRYPTO_SERVICE (EcGroupFree, (EcGroup)); +} + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit(). + + @retval EC Point object On success. + @retval NULL On failure. +**/ +VOID * +EFIAPI +EcPointInit ( + IN CONST VOID *EcGroup + ) +{ + CALL_CRYPTO_SERVICE (EcPointInit, (EcGroup), NULL); +} + +/** + Free previously allocated EC Point object using EcPointInit(). + + @param[in] EcPoint EC Point to free. + @param[in] Clear TRUE iff the memory should be cleared. +**/ +VOID +EFIAPI +EcPointDeInit ( + IN VOID *EcPoint, + IN BOOLEAN Clear + ) +{ + CALL_VOID_CRYPTO_SERVICE (EcPointDeInit, (EcPoint, Clear)); +} + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[out] BnX X coordinate. + @param[out] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointGetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointGetAffineCoordinates, (EcGroup, EcPoint, BnX, BnY, BnCtx), FALSE); +} + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point object. + @param[in] BnX X coordinate. + @param[in] BnY Y coordinate. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetAffineCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointSetAffineCoordinates, (EcGroup, EcPoint, BnX, BnY, BnCtx), FALSE); +} + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point. + @param[in] EcPointB EC Point. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointAdd ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointAdd, (EcGroup, EcPointResult, EcPointA, EcPointB, BnCtx), FALSE); +} + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar. + + @param[in] EcGroup EC group object. + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point. + @param[in] BnPScalar P Scalar. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointMul ( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointMul, (EcGroup, EcPointResult, EcPoint, BnPScalar, BnCtx), FALSE); +} + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object. + @param[in,out] EcPoint EC point to invert. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointInvert ( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointInvert, (EcGroup, EcPoint, BnCtx), FALSE); +} + +/** + Check if the supplied point is on EC curve. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On curve. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsOnCurve ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointIsOnCurve, (EcGroup, EcPoint, BnCtx), FALSE); +} + +/** + Check if the supplied point is at infinity. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC point to check. + + @retval TRUE At infinity. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointIsAtInfinity ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ) +{ + CALL_CRYPTO_SERVICE (EcPointIsAtInfinity, (EcGroup, EcPoint), FALSE); +} + +/** + Check if EC points are equal. + + @param[in] EcGroup EC group object. + @param[in] EcPointA EC point A. + @param[in] EcPointB EC point B. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE A == B. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointEqual ( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointEqual, (EcGroup, EcPointA, EcPointB, BnCtx), FALSE); +} + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object. + @param[in] EcPoint EC Point. + @param[in] BnX X coordinate. + @param[in] YBit 0 or 1 to identify which Y value is used. + @param[in] BnCtx BN context, created with BigNumNewContext(). + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +BOOLEAN +EFIAPI +EcPointSetCompressedCoordinates ( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ) +{ + CALL_CRYPTO_SERVICE (EcPointSetCompressedCoordinates, (EcGroup, EcPoint, BnX, YBit, BnCtx), FALSE); +} + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +VOID * +EFIAPI +EcNewByNid ( + IN UINTN Nid + ) +{ + CALL_CRYPTO_SERVICE (EcNewByNid, (Nid), NULL); +} + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +VOID +EFIAPI +EcFree ( + IN VOID *EcContext + ) +{ + CALL_VOID_CRYPTO_SERVICE (EcFree, (EcContext)); +} + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to the buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcGenerateKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + CALL_CRYPTO_SERVICE (EcGenerateKey, (EcContext, PublicKey, PublicKeySize), FALSE); +} + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +BOOLEAN +EFIAPI +EcGetPubKey ( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ) +{ + CALL_CRYPTO_SERVICE (EcGetPubKey, (EcContext, PublicKey, PublicKeySize), FALSE); +} + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +BOOLEAN +EFIAPI +EcDhComputeKey ( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ) +{ + CALL_CRYPTO_SERVICE (EcDhComputeKey, (EcContext, PeerPublic, PeerPublicSize, CompressFlag, Key, KeySize), FALSE); +} diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index 3bf37575e9..2f267c7f55 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 12 +#define EDKII_CRYPTO_VERSION 13 /// /// EDK II Crypto Protocol forward declaration @@ -4289,240 +4289,671 @@ BOOLEAN OUT VOID *BnRes ); +/** + Initialize new opaque EcGroup object. This object represents an EC curve and + and is used for calculation within this group. This object should be freed + using EcGroupFree() function. + + @param[in] CryptoNid Identifying number for the ECC curve (Defined in + BaseCryptLib.h). + + @retval EcGroup object On success + @retval NULL On failure +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_EC_GROUP_INIT)( + IN UINTN CryptoNid + ); + +/** + Get EC curve parameters. While elliptic curve equation is Y^2 mod P = (X^3 + AX + B) Mod P. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object. + @param[out] BnPrime Group prime number. + @param[out] BnA A coefficient. + @param[out] BnB B coefficient. + @param[in] BnCtx BN context. + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GROUP_GET_CURVE)( + IN CONST VOID *EcGroup, + OUT VOID *BnPrime, + OUT VOID *BnA, + OUT VOID *BnB, + IN VOID *BnCtx + ); + +/** + Get EC group order. + This function will set the provided Big Number object to the corresponding + value. The caller needs to make sure that the "out" BigNumber parameter + is properly initialized. + + @param[in] EcGroup EC group object + @param[out] BnOrder Group prime number + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GROUP_GET_ORDER)( + IN VOID *EcGroup, + OUT VOID *BnOrder + ); + +/** + Free previously allocated EC group object using EcGroupInit() + + @param[in] EcGroup EC group object to free +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_EC_GROUP_FREE)( + IN VOID *EcGroup + ); + +/** + Initialize new opaque EC Point object. This object represents an EC point + within the given EC group (curve). + + @param[in] EC Group, properly initialized using EcGroupInit() + + @retval EC Point object On success + @retval NULL On failure +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_EC_POINT_INIT)( + IN CONST VOID *EcGroup + ); + +/** + Free previously allocated EC Point object using EcPointInit() + + @param[in] EcPoint EC Point to free + @param[in] Clear TRUE iff the memory should be cleared +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_EC_POINT_DE_INIT)( + IN VOID *EcPoint, + IN BOOLEAN Clear + ); + +/** + Get EC point affine (x,y) coordinates. + This function will set the provided Big Number objects to the corresponding + values. The caller needs to make sure all the "out" BigNumber parameters + are properly initialized. + + @param[in] EcGroup EC group object + @param[in] EcPoint EC point object + @param[out] BnX X coordinate + @param[out] BnY Y coordinate + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_GET_AFFINE_COORDINATES)( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + OUT VOID *BnX, + OUT VOID *BnY, + IN VOID *BnCtx + ); + +/** + Set EC point affine (x,y) coordinates. + + @param[in] EcGroup EC group object + @param[in] EcPoint EC point object + @param[in] BnX X coordinate + @param[in] BnY Y coordinate + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_SET_AFFINE_COORDINATES)( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN CONST VOID *BnY, + IN VOID *BnCtx + ); + +/** + EC Point addition. EcPointResult = EcPointA + EcPointB + + @param[in] EcGroup EC group object + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPointA EC Point + @param[in] EcPointB EC Point + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_ADD)( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ); + +/** + Variable EC point multiplication. EcPointResult = EcPoint * BnPScalar + + @param[in] EcGroup EC group object + @param[out] EcPointResult EC point to hold the result. The point should + be properly initialized. + @param[in] EcPoint EC Point + @param[in] BnPScalar P Scalar + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_MUL)( + IN CONST VOID *EcGroup, + OUT VOID *EcPointResult, + IN CONST VOID *EcPoint, + IN CONST VOID *BnPScalar, + IN VOID *BnCtx + ); + +/** + Calculate the inverse of the supplied EC point. + + @param[in] EcGroup EC group object + @param[in,out] EcPoint EC point to invert + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_INVERT)( + IN CONST VOID *EcGroup, + IN OUT VOID *EcPoint, + IN VOID *BnCtx + ); + +/** + Check if the supplied point is on EC curve + + @param[in] EcGroup EC group object + @param[in] EcPoint EC point to check + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On curve + @retval FALSE Otherwise +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_IS_ON_CURVE)( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint, + IN VOID *BnCtx + ); + +/** + Check if the supplied point is at infinity + + @param[in] EcGroup EC group object + @param[in] EcPoint EC point to check + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE At infinity + @retval FALSE Otherwise +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_IS_AT_INFINITY)( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPoint + ); + +/** + Check if EC points are equal + + @param[in] EcGroup EC group object + @param[in] EcPointA EC point A + @param[in] EcPointB EC point B + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE A == B + @retval FALSE Otherwise +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_EQUAL)( + IN CONST VOID *EcGroup, + IN CONST VOID *EcPointA, + IN CONST VOID *EcPointB, + IN VOID *BnCtx + ); + +/** + Set EC point compressed coordinates. Points can be described in terms of + their compressed coordinates. For a point (x, y), for any given value for x + such that the point is on the curve there will only ever be two possible + values for y. Therefore, a point can be set using this function where BnX is + the x coordinate and YBit is a value 0 or 1 to identify which of the two + possible values for y should be used. + + @param[in] EcGroup EC group object + @param[in] EcPoint EC Point + @param[in] BnX X coordinate + @param[in] YBit 0 or 1 to identify which Y value is used + @param[in] BnCtx BN context, created with BigNumNewContext() + + @retval TRUE On success. + @retval FALSE Otherwise. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_POINT_SET_COMPRESSED_COORDINATES)( + IN CONST VOID *EcGroup, + IN VOID *EcPoint, + IN CONST VOID *BnX, + IN UINT8 YBit, + IN VOID *BnCtx + ); + +/** + Allocates and Initializes one Elliptic Curve Context for subsequent use + with the NID. + + @param[in] Nid cipher NID + @return Pointer to the Elliptic Curve Context that has been initialized. + If the allocations fails, EcNewByNid() returns NULL. +**/ +typedef +VOID * +(EFIAPI *EDKII_CRYPTO_EC_NEW_BY_NID)( + IN UINTN Nid + ); + +/** + Release the specified EC context. + + @param[in] EcContext Pointer to the EC context to be released. +**/ +typedef +VOID +(EFIAPI *EDKII_CRYPTO_EC_FREE)( + IN VOID *EcContext + ); + +/** + Generates EC key and returns EC public key (X, Y), Please note, this function uses + pseudo random number generator. The caller must make sure RandomSeed() + function was properly called before. + The Ec context should be correctly initialized by EcNewByNid. + This function generates random secret, and computes the public key (X, Y), which is + returned via parameter Public, PublicSize. + X is the first half of Public with size being PublicSize / 2, + Y is the second half of Public with size being PublicSize / 2. + EC context is updated accordingly. + If the Public buffer is too small to hold the public X, Y, FALSE is returned and + PublicSize is set to the required buffer size to obtain the public X, Y. + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + If EcContext is NULL, then return FALSE. + If PublicSize is NULL, then return FALSE. + If PublicSize is large enough but Public is NULL, then return FALSE. + @param[in, out] EcContext Pointer to the EC context. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC public X,Y generation succeeded. + @retval FALSE EC public X,Y generation failed. + @retval FALSE PublicKeySize is not large enough. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GENERATE_KEY)( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ); + +/** + Gets the public key component from the established EC context. + The Ec context should be correctly initialized by EcNewByNid, and successfully + generate key pair from EcGenerateKey(). + For P-256, the PublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to EC context being set. + @param[out] PublicKey Pointer to t buffer to receive generated public X,Y. + @param[in, out] PublicKeySize On input, the size of Public buffer in bytes. + On output, the size of data returned in Public buffer in bytes. + @retval TRUE EC key component was retrieved successfully. + @retval FALSE Invalid EC key component. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GET_PUB_KEY)( + IN OUT VOID *EcContext, + OUT UINT8 *PublicKey, + IN OUT UINTN *PublicKeySize + ); + +/** + Computes exchanged common key. + Given peer's public key (X, Y), this function computes the exchanged common key, + based on its own context including value of curve parameter and random secret. + X is the first half of PeerPublic with size being PeerPublicSize / 2, + Y is the second half of PeerPublic with size being PeerPublicSize / 2. + If EcContext is NULL, then return FALSE. + If PeerPublic is NULL, then return FALSE. + If PeerPublicSize is 0, then return FALSE. + If Key is NULL, then return FALSE. + If KeySize is not large enough, then return FALSE. + For P-256, the PeerPublicSize is 64. First 32-byte is X, Second 32-byte is Y. + For P-384, the PeerPublicSize is 96. First 48-byte is X, Second 48-byte is Y. + For P-521, the PeerPublicSize is 132. First 66-byte is X, Second 66-byte is Y. + @param[in, out] EcContext Pointer to the EC context. + @param[in] PeerPublic Pointer to the peer's public X,Y. + @param[in] PeerPublicSize Size of peer's public X,Y in bytes. + @param[in] CompressFlag Flag of PeerPublic is compressed or not. + @param[out] Key Pointer to the buffer to receive generated key. + @param[in, out] KeySize On input, the size of Key buffer in bytes. + On output, the size of data returned in Key buffer in bytes. + @retval TRUE EC exchanged key generation succeeded. + @retval FALSE EC exchanged key generation failed. + @retval FALSE KeySize is not large enough. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_DH_COMPUTE_KEY)( + IN OUT VOID *EcContext, + IN CONST UINT8 *PeerPublic, + IN UINTN PeerPublicSize, + IN CONST INT32 *CompressFlag, + OUT UINT8 *Key, + IN OUT UINTN *KeySize + ); + /// /// EDK II Crypto Protocol /// struct _EDKII_CRYPTO_PROTOCOL { /// Version - EDKII_CRYPTO_GET_VERSION GetVersion; + EDKII_CRYPTO_GET_VERSION GetVersion; /// HMAC MD5 - deprecated and unsupported - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_NEW DeprecatedHmacMd5New; - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_FREE DeprecatedHmacMd5Free; - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_SET_KEY DeprecatedHmacMd5SetKey; - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_DUPLICATE DeprecatedHmacMd5Duplicate; - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_UPDATE DeprecatedHmacMd5Update; - DEPRECATED_EDKII_CRYPTO_HMAC_MD5_FINAL DeprecatedHmacMd5Final; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_NEW DeprecatedHmacMd5New; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_FREE DeprecatedHmacMd5Free; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_SET_KEY DeprecatedHmacMd5SetKey; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_DUPLICATE DeprecatedHmacMd5Duplicate; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_UPDATE DeprecatedHmacMd5Update; + DEPRECATED_EDKII_CRYPTO_HMAC_MD5_FINAL DeprecatedHmacMd5Final; /// HMAC SHA1 - deprecated and unsupported - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_NEW DeprecatedHmacSha1New; - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_FREE DeprecatedHmacSha1Free; - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_SET_KEY DeprecatedHmacSha1SetKey; - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_DUPLICATE DeprecatedHmacSha1Duplicate; - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_UPDATE DeprecatedHmacSha1Update; - DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_FINAL DeprecatedHmacSha1Final; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_NEW DeprecatedHmacSha1New; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_FREE DeprecatedHmacSha1Free; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_SET_KEY DeprecatedHmacSha1SetKey; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_DUPLICATE DeprecatedHmacSha1Duplicate; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_UPDATE DeprecatedHmacSha1Update; + DEPRECATED_EDKII_CRYPTO_HMAC_SHA1_FINAL DeprecatedHmacSha1Final; /// HMAC SHA256 - EDKII_CRYPTO_HMAC_SHA256_NEW HmacSha256New; - EDKII_CRYPTO_HMAC_SHA256_FREE HmacSha256Free; - EDKII_CRYPTO_HMAC_SHA256_SET_KEY HmacSha256SetKey; - EDKII_CRYPTO_HMAC_SHA256_DUPLICATE HmacSha256Duplicate; - EDKII_CRYPTO_HMAC_SHA256_UPDATE HmacSha256Update; - EDKII_CRYPTO_HMAC_SHA256_FINAL HmacSha256Final; + EDKII_CRYPTO_HMAC_SHA256_NEW HmacSha256New; + EDKII_CRYPTO_HMAC_SHA256_FREE HmacSha256Free; + EDKII_CRYPTO_HMAC_SHA256_SET_KEY HmacSha256SetKey; + EDKII_CRYPTO_HMAC_SHA256_DUPLICATE HmacSha256Duplicate; + EDKII_CRYPTO_HMAC_SHA256_UPDATE HmacSha256Update; + EDKII_CRYPTO_HMAC_SHA256_FINAL HmacSha256Final; /// Md4 - deprecated and unsupported - DEPRECATED_EDKII_CRYPTO_MD4_GET_CONTEXT_SIZE DeprecatedMd4GetContextSize; - DEPRECATED_EDKII_CRYPTO_MD4_INIT DeprecatedMd4Init; - DEPRECATED_EDKII_CRYPTO_MD4_DUPLICATE DeprecatedMd4Duplicate; - DEPRECATED_EDKII_CRYPTO_MD4_UPDATE DeprecatedMd4Update; - DEPRECATED_EDKII_CRYPTO_MD4_FINAL DeprecatedMd4Final; - DEPRECATED_EDKII_CRYPTO_MD4_HASH_ALL DeprecatedMd4HashAll; + DEPRECATED_EDKII_CRYPTO_MD4_GET_CONTEXT_SIZE DeprecatedMd4GetContextSize; + DEPRECATED_EDKII_CRYPTO_MD4_INIT DeprecatedMd4Init; + DEPRECATED_EDKII_CRYPTO_MD4_DUPLICATE DeprecatedMd4Duplicate; + DEPRECATED_EDKII_CRYPTO_MD4_UPDATE DeprecatedMd4Update; + DEPRECATED_EDKII_CRYPTO_MD4_FINAL DeprecatedMd4Final; + DEPRECATED_EDKII_CRYPTO_MD4_HASH_ALL DeprecatedMd4HashAll; /// Md5 - EDKII_CRYPTO_MD5_GET_CONTEXT_SIZE Md5GetContextSize; - EDKII_CRYPTO_MD5_INIT Md5Init; - EDKII_CRYPTO_MD5_DUPLICATE Md5Duplicate; - EDKII_CRYPTO_MD5_UPDATE Md5Update; - EDKII_CRYPTO_MD5_FINAL Md5Final; - EDKII_CRYPTO_MD5_HASH_ALL Md5HashAll; + EDKII_CRYPTO_MD5_GET_CONTEXT_SIZE Md5GetContextSize; + EDKII_CRYPTO_MD5_INIT Md5Init; + EDKII_CRYPTO_MD5_DUPLICATE Md5Duplicate; + EDKII_CRYPTO_MD5_UPDATE Md5Update; + EDKII_CRYPTO_MD5_FINAL Md5Final; + EDKII_CRYPTO_MD5_HASH_ALL Md5HashAll; /// Pkcs - EDKII_CRYPTO_PKCS1_ENCRYPT_V2 Pkcs1v2Encrypt; - EDKII_CRYPTO_PKCS5_PW_HASH Pkcs5HashPassword; - EDKII_CRYPTO_PKCS7_VERIFY Pkcs7Verify; - EDKII_CRYPTO_PKCS7_VERIFY_EKU VerifyEKUsInPkcs7Signature; - EDKII_CRYPTO_PKCS7_GET_SIGNERS Pkcs7GetSigners; - EDKII_CRYPTO_PKCS7_FREE_SIGNERS Pkcs7FreeSigners; - EDKII_CRYPTO_PKCS7_SIGN Pkcs7Sign; - EDKII_CRYPTO_PKCS7_GET_ATTACHED_CONTENT Pkcs7GetAttachedContent; - EDKII_CRYPTO_PKCS7_GET_CERTIFICATES_LIST Pkcs7GetCertificatesList; - EDKII_CRYPTO_AUTHENTICODE_VERIFY AuthenticodeVerify; - EDKII_CRYPTO_IMAGE_TIMESTAMP_VERIFY ImageTimestampVerify; + EDKII_CRYPTO_PKCS1_ENCRYPT_V2 Pkcs1v2Encrypt; + EDKII_CRYPTO_PKCS5_PW_HASH Pkcs5HashPassword; + EDKII_CRYPTO_PKCS7_VERIFY Pkcs7Verify; + EDKII_CRYPTO_PKCS7_VERIFY_EKU VerifyEKUsInPkcs7Signature; + EDKII_CRYPTO_PKCS7_GET_SIGNERS Pkcs7GetSigners; + EDKII_CRYPTO_PKCS7_FREE_SIGNERS Pkcs7FreeSigners; + EDKII_CRYPTO_PKCS7_SIGN Pkcs7Sign; + EDKII_CRYPTO_PKCS7_GET_ATTACHED_CONTENT Pkcs7GetAttachedContent; + EDKII_CRYPTO_PKCS7_GET_CERTIFICATES_LIST Pkcs7GetCertificatesList; + EDKII_CRYPTO_AUTHENTICODE_VERIFY AuthenticodeVerify; + EDKII_CRYPTO_IMAGE_TIMESTAMP_VERIFY ImageTimestampVerify; /// DH - EDKII_CRYPTO_DH_NEW DhNew; - EDKII_CRYPTO_DH_FREE DhFree; - EDKII_CRYPTO_DH_GENERATE_PARAMETER DhGenerateParameter; - EDKII_CRYPTO_DH_SET_PARAMETER DhSetParameter; - EDKII_CRYPTO_DH_GENERATE_KEY DhGenerateKey; - EDKII_CRYPTO_DH_COMPUTE_KEY DhComputeKey; + EDKII_CRYPTO_DH_NEW DhNew; + EDKII_CRYPTO_DH_FREE DhFree; + EDKII_CRYPTO_DH_GENERATE_PARAMETER DhGenerateParameter; + EDKII_CRYPTO_DH_SET_PARAMETER DhSetParameter; + EDKII_CRYPTO_DH_GENERATE_KEY DhGenerateKey; + EDKII_CRYPTO_DH_COMPUTE_KEY DhComputeKey; /// Random - EDKII_CRYPTO_RANDOM_SEED RandomSeed; - EDKII_CRYPTO_RANDOM_BYTES RandomBytes; + EDKII_CRYPTO_RANDOM_SEED RandomSeed; + EDKII_CRYPTO_RANDOM_BYTES RandomBytes; /// RSA - EDKII_CRYPTO_RSA_VERIFY_PKCS1 RsaVerifyPkcs1; - EDKII_CRYPTO_RSA_NEW RsaNew; - EDKII_CRYPTO_RSA_FREE RsaFree; - EDKII_CRYPTO_RSA_SET_KEY RsaSetKey; - EDKII_CRYPTO_RSA_GET_KEY RsaGetKey; - EDKII_CRYPTO_RSA_GENERATE_KEY RsaGenerateKey; - EDKII_CRYPTO_RSA_CHECK_KEY RsaCheckKey; - EDKII_CRYPTO_RSA_PKCS1_SIGN RsaPkcs1Sign; - EDKII_CRYPTO_RSA_PKCS1_VERIFY RsaPkcs1Verify; - EDKII_CRYPTO_RSA_GET_PRIVATE_KEY_FROM_PEM RsaGetPrivateKeyFromPem; - EDKII_CRYPTO_RSA_GET_PUBLIC_KEY_FROM_X509 RsaGetPublicKeyFromX509; + EDKII_CRYPTO_RSA_VERIFY_PKCS1 RsaVerifyPkcs1; + EDKII_CRYPTO_RSA_NEW RsaNew; + EDKII_CRYPTO_RSA_FREE RsaFree; + EDKII_CRYPTO_RSA_SET_KEY RsaSetKey; + EDKII_CRYPTO_RSA_GET_KEY RsaGetKey; + EDKII_CRYPTO_RSA_GENERATE_KEY RsaGenerateKey; + EDKII_CRYPTO_RSA_CHECK_KEY RsaCheckKey; + EDKII_CRYPTO_RSA_PKCS1_SIGN RsaPkcs1Sign; + EDKII_CRYPTO_RSA_PKCS1_VERIFY RsaPkcs1Verify; + EDKII_CRYPTO_RSA_GET_PRIVATE_KEY_FROM_PEM RsaGetPrivateKeyFromPem; + EDKII_CRYPTO_RSA_GET_PUBLIC_KEY_FROM_X509 RsaGetPublicKeyFromX509; /// Sha1 - EDKII_CRYPTO_SHA1_GET_CONTEXT_SIZE Sha1GetContextSize; - EDKII_CRYPTO_SHA1_INIT Sha1Init; - EDKII_CRYPTO_SHA1_DUPLICATE Sha1Duplicate; - EDKII_CRYPTO_SHA1_UPDATE Sha1Update; - EDKII_CRYPTO_SHA1_FINAL Sha1Final; - EDKII_CRYPTO_SHA1_HASH_ALL Sha1HashAll; + EDKII_CRYPTO_SHA1_GET_CONTEXT_SIZE Sha1GetContextSize; + EDKII_CRYPTO_SHA1_INIT Sha1Init; + EDKII_CRYPTO_SHA1_DUPLICATE Sha1Duplicate; + EDKII_CRYPTO_SHA1_UPDATE Sha1Update; + EDKII_CRYPTO_SHA1_FINAL Sha1Final; + EDKII_CRYPTO_SHA1_HASH_ALL Sha1HashAll; /// Sha256 - EDKII_CRYPTO_SHA256_GET_CONTEXT_SIZE Sha256GetContextSize; - EDKII_CRYPTO_SHA256_INIT Sha256Init; - EDKII_CRYPTO_SHA256_DUPLICATE Sha256Duplicate; - EDKII_CRYPTO_SHA256_UPDATE Sha256Update; - EDKII_CRYPTO_SHA256_FINAL Sha256Final; - EDKII_CRYPTO_SHA256_HASH_ALL Sha256HashAll; + EDKII_CRYPTO_SHA256_GET_CONTEXT_SIZE Sha256GetContextSize; + EDKII_CRYPTO_SHA256_INIT Sha256Init; + EDKII_CRYPTO_SHA256_DUPLICATE Sha256Duplicate; + EDKII_CRYPTO_SHA256_UPDATE Sha256Update; + EDKII_CRYPTO_SHA256_FINAL Sha256Final; + EDKII_CRYPTO_SHA256_HASH_ALL Sha256HashAll; /// Sha384 - EDKII_CRYPTO_SHA384_GET_CONTEXT_SIZE Sha384GetContextSize; - EDKII_CRYPTO_SHA384_INIT Sha384Init; - EDKII_CRYPTO_SHA384_DUPLICATE Sha384Duplicate; - EDKII_CRYPTO_SHA384_UPDATE Sha384Update; - EDKII_CRYPTO_SHA384_FINAL Sha384Final; - EDKII_CRYPTO_SHA384_HASH_ALL Sha384HashAll; + EDKII_CRYPTO_SHA384_GET_CONTEXT_SIZE Sha384GetContextSize; + EDKII_CRYPTO_SHA384_INIT Sha384Init; + EDKII_CRYPTO_SHA384_DUPLICATE Sha384Duplicate; + EDKII_CRYPTO_SHA384_UPDATE Sha384Update; + EDKII_CRYPTO_SHA384_FINAL Sha384Final; + EDKII_CRYPTO_SHA384_HASH_ALL Sha384HashAll; /// Sha512 - EDKII_CRYPTO_SHA512_GET_CONTEXT_SIZE Sha512GetContextSize; - EDKII_CRYPTO_SHA512_INIT Sha512Init; - EDKII_CRYPTO_SHA512_DUPLICATE Sha512Duplicate; - EDKII_CRYPTO_SHA512_UPDATE Sha512Update; - EDKII_CRYPTO_SHA512_FINAL Sha512Final; - EDKII_CRYPTO_SHA512_HASH_ALL Sha512HashAll; + EDKII_CRYPTO_SHA512_GET_CONTEXT_SIZE Sha512GetContextSize; + EDKII_CRYPTO_SHA512_INIT Sha512Init; + EDKII_CRYPTO_SHA512_DUPLICATE Sha512Duplicate; + EDKII_CRYPTO_SHA512_UPDATE Sha512Update; + EDKII_CRYPTO_SHA512_FINAL Sha512Final; + EDKII_CRYPTO_SHA512_HASH_ALL Sha512HashAll; /// X509 - EDKII_CRYPTO_X509_GET_SUBJECT_NAME X509GetSubjectName; - EDKII_CRYPTO_X509_GET_COMMON_NAME X509GetCommonName; - EDKII_CRYPTO_X509_GET_ORGANIZATION_NAME X509GetOrganizationName; - EDKII_CRYPTO_X509_VERIFY_CERT X509VerifyCert; - EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE X509ConstructCertificate; - EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE_STACK X509ConstructCertificateStack; - EDKII_CRYPTO_X509_FREE X509Free; - EDKII_CRYPTO_X509_STACK_FREE X509StackFree; - EDKII_CRYPTO_X509_GET_TBS_CERT X509GetTBSCert; + EDKII_CRYPTO_X509_GET_SUBJECT_NAME X509GetSubjectName; + EDKII_CRYPTO_X509_GET_COMMON_NAME X509GetCommonName; + EDKII_CRYPTO_X509_GET_ORGANIZATION_NAME X509GetOrganizationName; + EDKII_CRYPTO_X509_VERIFY_CERT X509VerifyCert; + EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE X509ConstructCertificate; + EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE_STACK X509ConstructCertificateStack; + EDKII_CRYPTO_X509_FREE X509Free; + EDKII_CRYPTO_X509_STACK_FREE X509StackFree; + EDKII_CRYPTO_X509_GET_TBS_CERT X509GetTBSCert; /// TDES - deprecated and unsupported - DEPRECATED_EDKII_CRYPTO_TDES_GET_CONTEXT_SIZE DeprecatedTdesGetContextSize; - DEPRECATED_EDKII_CRYPTO_TDES_INIT DeprecatedTdesInit; - DEPRECATED_EDKII_CRYPTO_TDES_ECB_ENCRYPT DeprecatedTdesEcbEncrypt; - DEPRECATED_EDKII_CRYPTO_TDES_ECB_DECRYPT DeprecatedTdesEcbDecrypt; - DEPRECATED_EDKII_CRYPTO_TDES_CBC_ENCRYPT DeprecatedTdesCbcEncrypt; - DEPRECATED_EDKII_CRYPTO_TDES_CBC_DECRYPT DeprecatedTdesCbcDecrypt; + DEPRECATED_EDKII_CRYPTO_TDES_GET_CONTEXT_SIZE DeprecatedTdesGetContextSize; + DEPRECATED_EDKII_CRYPTO_TDES_INIT DeprecatedTdesInit; + DEPRECATED_EDKII_CRYPTO_TDES_ECB_ENCRYPT DeprecatedTdesEcbEncrypt; + DEPRECATED_EDKII_CRYPTO_TDES_ECB_DECRYPT DeprecatedTdesEcbDecrypt; + DEPRECATED_EDKII_CRYPTO_TDES_CBC_ENCRYPT DeprecatedTdesCbcEncrypt; + DEPRECATED_EDKII_CRYPTO_TDES_CBC_DECRYPT DeprecatedTdesCbcDecrypt; /// AES - ECB Mode is deprecated and unsupported - EDKII_CRYPTO_AES_GET_CONTEXT_SIZE AesGetContextSize; - EDKII_CRYPTO_AES_INIT AesInit; - DEPRECATED_EDKII_CRYPTO_AES_ECB_ENCRYPT DeprecatedAesEcbEncrypt; - DEPRECATED_EDKII_CRYPTO_AES_ECB_DECRYPT DeprecatedAesEcbDecrypt; - EDKII_CRYPTO_AES_CBC_ENCRYPT AesCbcEncrypt; - EDKII_CRYPTO_AES_CBC_DECRYPT AesCbcDecrypt; + EDKII_CRYPTO_AES_GET_CONTEXT_SIZE AesGetContextSize; + EDKII_CRYPTO_AES_INIT AesInit; + DEPRECATED_EDKII_CRYPTO_AES_ECB_ENCRYPT DeprecatedAesEcbEncrypt; + DEPRECATED_EDKII_CRYPTO_AES_ECB_DECRYPT DeprecatedAesEcbDecrypt; + EDKII_CRYPTO_AES_CBC_ENCRYPT AesCbcEncrypt; + EDKII_CRYPTO_AES_CBC_DECRYPT AesCbcDecrypt; /// Arc4 - deprecated and unsupported - DEPRECATED_EDKII_CRYPTO_ARC4_GET_CONTEXT_SIZE DeprecatedArc4GetContextSize; - DEPRECATED_EDKII_CRYPTO_ARC4_INIT DeprecatedArc4Init; - DEPRECATED_EDKII_CRYPTO_ARC4_ENCRYPT DeprecatedArc4Encrypt; - DEPRECATED_EDKII_CRYPTO_ARC4_DECRYPT DeprecatedArc4Decrypt; - DEPRECATED_EDKII_CRYPTO_ARC4_RESET DeprecatedArc4Reset; + DEPRECATED_EDKII_CRYPTO_ARC4_GET_CONTEXT_SIZE DeprecatedArc4GetContextSize; + DEPRECATED_EDKII_CRYPTO_ARC4_INIT DeprecatedArc4Init; + DEPRECATED_EDKII_CRYPTO_ARC4_ENCRYPT DeprecatedArc4Encrypt; + DEPRECATED_EDKII_CRYPTO_ARC4_DECRYPT DeprecatedArc4Decrypt; + DEPRECATED_EDKII_CRYPTO_ARC4_RESET DeprecatedArc4Reset; /// SM3 - EDKII_CRYPTO_SM3_GET_CONTEXT_SIZE Sm3GetContextSize; - EDKII_CRYPTO_SM3_INIT Sm3Init; - EDKII_CRYPTO_SM3_DUPLICATE Sm3Duplicate; - EDKII_CRYPTO_SM3_UPDATE Sm3Update; - EDKII_CRYPTO_SM3_FINAL Sm3Final; - EDKII_CRYPTO_SM3_HASH_ALL Sm3HashAll; + EDKII_CRYPTO_SM3_GET_CONTEXT_SIZE Sm3GetContextSize; + EDKII_CRYPTO_SM3_INIT Sm3Init; + EDKII_CRYPTO_SM3_DUPLICATE Sm3Duplicate; + EDKII_CRYPTO_SM3_UPDATE Sm3Update; + EDKII_CRYPTO_SM3_FINAL Sm3Final; + EDKII_CRYPTO_SM3_HASH_ALL Sm3HashAll; /// HKDF - EDKII_CRYPTO_HKDF_SHA_256_EXTRACT_AND_EXPAND HkdfSha256ExtractAndExpand; + EDKII_CRYPTO_HKDF_SHA_256_EXTRACT_AND_EXPAND HkdfSha256ExtractAndExpand; /// X509 (Continued) - EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE_STACK_V X509ConstructCertificateStackV; + EDKII_CRYPTO_X509_CONSTRUCT_CERTIFICATE_STACK_V X509ConstructCertificateStackV; /// TLS - EDKII_CRYPTO_TLS_INITIALIZE TlsInitialize; - EDKII_CRYPTO_TLS_CTX_FREE TlsCtxFree; - EDKII_CRYPTO_TLS_CTX_NEW TlsCtxNew; - EDKII_CRYPTO_TLS_FREE TlsFree; - EDKII_CRYPTO_TLS_NEW TlsNew; - EDKII_CRYPTO_TLS_IN_HANDSHAKE TlsInHandshake; - EDKII_CRYPTO_TLS_DO_HANDSHAKE TlsDoHandshake; - EDKII_CRYPTO_TLS_HANDLE_ALERT TlsHandleAlert; - EDKII_CRYPTO_TLS_CLOSE_NOTIFY TlsCloseNotify; - EDKII_CRYPTO_TLS_CTRL_TRAFFIC_OUT TlsCtrlTrafficOut; - EDKII_CRYPTO_TLS_CTRL_TRAFFIC_IN TlsCtrlTrafficIn; - EDKII_CRYPTO_TLS_READ TlsRead; - EDKII_CRYPTO_TLS_WRITE TlsWrite; + EDKII_CRYPTO_TLS_INITIALIZE TlsInitialize; + EDKII_CRYPTO_TLS_CTX_FREE TlsCtxFree; + EDKII_CRYPTO_TLS_CTX_NEW TlsCtxNew; + EDKII_CRYPTO_TLS_FREE TlsFree; + EDKII_CRYPTO_TLS_NEW TlsNew; + EDKII_CRYPTO_TLS_IN_HANDSHAKE TlsInHandshake; + EDKII_CRYPTO_TLS_DO_HANDSHAKE TlsDoHandshake; + EDKII_CRYPTO_TLS_HANDLE_ALERT TlsHandleAlert; + EDKII_CRYPTO_TLS_CLOSE_NOTIFY TlsCloseNotify; + EDKII_CRYPTO_TLS_CTRL_TRAFFIC_OUT TlsCtrlTrafficOut; + EDKII_CRYPTO_TLS_CTRL_TRAFFIC_IN TlsCtrlTrafficIn; + EDKII_CRYPTO_TLS_READ TlsRead; + EDKII_CRYPTO_TLS_WRITE TlsWrite; /// TLS Set - EDKII_CRYPTO_TLS_SET_VERSION TlsSetVersion; - EDKII_CRYPTO_TLS_SET_CONNECTION_END TlsSetConnectionEnd; - EDKII_CRYPTO_TLS_SET_CIPHER_LIST TlsSetCipherList; - EDKII_CRYPTO_TLS_SET_COMPRESSION_METHOD TlsSetCompressionMethod; - EDKII_CRYPTO_TLS_SET_VERIFY TlsSetVerify; - EDKII_CRYPTO_TLS_SET_VERIFY_HOST TlsSetVerifyHost; - EDKII_CRYPTO_TLS_SET_SESSIONID TlsSetSessionId; - EDKII_CRYPTO_TLS_SET_CA_CERTIFICATE TlsSetCaCertificate; - EDKII_CRYPTO_TLS_SET_HOST_PUBLIC_CERT TlsSetHostPublicCert; - EDKII_CRYPTO_TLS_SET_HOST_PRIVATE_KEY TlsSetHostPrivateKey; - EDKII_CRYPTO_TLS_SET_CERT_REVOCATION_LIST TlsSetCertRevocationList; + EDKII_CRYPTO_TLS_SET_VERSION TlsSetVersion; + EDKII_CRYPTO_TLS_SET_CONNECTION_END TlsSetConnectionEnd; + EDKII_CRYPTO_TLS_SET_CIPHER_LIST TlsSetCipherList; + EDKII_CRYPTO_TLS_SET_COMPRESSION_METHOD TlsSetCompressionMethod; + EDKII_CRYPTO_TLS_SET_VERIFY TlsSetVerify; + EDKII_CRYPTO_TLS_SET_VERIFY_HOST TlsSetVerifyHost; + EDKII_CRYPTO_TLS_SET_SESSIONID TlsSetSessionId; + EDKII_CRYPTO_TLS_SET_CA_CERTIFICATE TlsSetCaCertificate; + EDKII_CRYPTO_TLS_SET_HOST_PUBLIC_CERT TlsSetHostPublicCert; + EDKII_CRYPTO_TLS_SET_HOST_PRIVATE_KEY TlsSetHostPrivateKey; + EDKII_CRYPTO_TLS_SET_CERT_REVOCATION_LIST TlsSetCertRevocationList; /// TLS Get - EDKII_CRYPTO_TLS_GET_VERSION TlsGetVersion; - EDKII_CRYPTO_TLS_GET_CONNECTION_END TlsGetConnectionEnd; - EDKII_CRYPTO_TLS_GET_CURRENT_CIPHER TlsGetCurrentCipher; - EDKII_CRYPTO_TLS_GET_CURRENT_COMPRESSION_ID TlsGetCurrentCompressionId; - EDKII_CRYPTO_TLS_GET_VERIFY TlsGetVerify; - EDKII_CRYPTO_TLS_GET_SESSION_ID TlsGetSessionId; - EDKII_CRYPTO_TLS_GET_CLIENT_RANDOM TlsGetClientRandom; - EDKII_CRYPTO_TLS_GET_SERVER_RANDOM TlsGetServerRandom; - EDKII_CRYPTO_TLS_GET_KEY_MATERIAL TlsGetKeyMaterial; - EDKII_CRYPTO_TLS_GET_CA_CERTIFICATE TlsGetCaCertificate; - EDKII_CRYPTO_TLS_GET_HOST_PUBLIC_CERT TlsGetHostPublicCert; - EDKII_CRYPTO_TLS_GET_HOST_PRIVATE_KEY TlsGetHostPrivateKey; - EDKII_CRYPTO_TLS_GET_CERT_REVOCATION_LIST TlsGetCertRevocationList; + EDKII_CRYPTO_TLS_GET_VERSION TlsGetVersion; + EDKII_CRYPTO_TLS_GET_CONNECTION_END TlsGetConnectionEnd; + EDKII_CRYPTO_TLS_GET_CURRENT_CIPHER TlsGetCurrentCipher; + EDKII_CRYPTO_TLS_GET_CURRENT_COMPRESSION_ID TlsGetCurrentCompressionId; + EDKII_CRYPTO_TLS_GET_VERIFY TlsGetVerify; + EDKII_CRYPTO_TLS_GET_SESSION_ID TlsGetSessionId; + EDKII_CRYPTO_TLS_GET_CLIENT_RANDOM TlsGetClientRandom; + EDKII_CRYPTO_TLS_GET_SERVER_RANDOM TlsGetServerRandom; + EDKII_CRYPTO_TLS_GET_KEY_MATERIAL TlsGetKeyMaterial; + EDKII_CRYPTO_TLS_GET_CA_CERTIFICATE TlsGetCaCertificate; + EDKII_CRYPTO_TLS_GET_HOST_PUBLIC_CERT TlsGetHostPublicCert; + EDKII_CRYPTO_TLS_GET_HOST_PRIVATE_KEY TlsGetHostPrivateKey; + EDKII_CRYPTO_TLS_GET_CERT_REVOCATION_LIST TlsGetCertRevocationList; /// RSA PSS - EDKII_CRYPTO_RSA_PSS_SIGN RsaPssSign; - EDKII_CRYPTO_RSA_PSS_VERIFY RsaPssVerify; + EDKII_CRYPTO_RSA_PSS_SIGN RsaPssSign; + EDKII_CRYPTO_RSA_PSS_VERIFY RsaPssVerify; /// Parallel hash - EDKII_CRYPTO_PARALLEL_HASH_ALL ParallelHash256HashAll; + EDKII_CRYPTO_PARALLEL_HASH_ALL ParallelHash256HashAll; /// HMAC SHA256 (continued) - EDKII_CRYPTO_HMAC_SHA256_ALL HmacSha256All; + EDKII_CRYPTO_HMAC_SHA256_ALL HmacSha256All; /// HMAC SHA384 - EDKII_CRYPTO_HMAC_SHA384_NEW HmacSha384New; - EDKII_CRYPTO_HMAC_SHA384_FREE HmacSha384Free; - EDKII_CRYPTO_HMAC_SHA384_SET_KEY HmacSha384SetKey; - EDKII_CRYPTO_HMAC_SHA384_DUPLICATE HmacSha384Duplicate; - EDKII_CRYPTO_HMAC_SHA384_UPDATE HmacSha384Update; - EDKII_CRYPTO_HMAC_SHA384_FINAL HmacSha384Final; - EDKII_CRYPTO_HMAC_SHA384_ALL HmacSha384All; + EDKII_CRYPTO_HMAC_SHA384_NEW HmacSha384New; + EDKII_CRYPTO_HMAC_SHA384_FREE HmacSha384Free; + EDKII_CRYPTO_HMAC_SHA384_SET_KEY HmacSha384SetKey; + EDKII_CRYPTO_HMAC_SHA384_DUPLICATE HmacSha384Duplicate; + EDKII_CRYPTO_HMAC_SHA384_UPDATE HmacSha384Update; + EDKII_CRYPTO_HMAC_SHA384_FINAL HmacSha384Final; + EDKII_CRYPTO_HMAC_SHA384_ALL HmacSha384All; /// HKDF (continued) - EDKII_CRYPTO_HKDF_SHA_256_EXTRACT HkdfSha256Extract; - EDKII_CRYPTO_HKDF_SHA_256_EXPAND HkdfSha256Expand; - EDKII_CRYPTO_HKDF_SHA_384_EXTRACT_AND_EXPAND HkdfSha384ExtractAndExpand; - EDKII_CRYPTO_HKDF_SHA_384_EXTRACT HkdfSha384Extract; - EDKII_CRYPTO_HKDF_SHA_384_EXPAND HkdfSha384Expand; + EDKII_CRYPTO_HKDF_SHA_256_EXTRACT HkdfSha256Extract; + EDKII_CRYPTO_HKDF_SHA_256_EXPAND HkdfSha256Expand; + EDKII_CRYPTO_HKDF_SHA_384_EXTRACT_AND_EXPAND HkdfSha384ExtractAndExpand; + EDKII_CRYPTO_HKDF_SHA_384_EXTRACT HkdfSha384Extract; + EDKII_CRYPTO_HKDF_SHA_384_EXPAND HkdfSha384Expand; /// AEAD AES-GCM - EDKII_AEAD_AES_GCM_ENCRYPT AeadAesGcmEncrypt; - EDKII_AEAD_AES_GCM_DECRYPT AeadAesGcmDecrypt; + EDKII_AEAD_AES_GCM_ENCRYPT AeadAesGcmEncrypt; + EDKII_AEAD_AES_GCM_DECRYPT AeadAesGcmDecrypt; /// BIGNUM - EDKII_CRYPTO_BIGNUM_INIT BigNumInit; - EDKII_CRYPTO_BIGNUM_FROM_BIN BigNumFromBin; - EDKII_CRYPTO_BIGNUM_TO_BIN BigNumToBin; - EDKII_CRYPTO_BIGNUM_FREE BigNumFree; - EDKII_CRYPTO_BIGNUM_ADD BigNumAdd; - EDKII_CRYPTO_BIGNUM_SUB BigNumSub; - EDKII_CRYPTO_BIGNUM_MOD BigNumMod; - EDKII_CRYPTO_BIGNUM_EXP_MOD BigNumExpMod; - EDKII_CRYPTO_BIGNUM_INVERSE_MOD BigNumInverseMod; - EDKII_CRYPTO_BIGNUM_DIV BigNumDiv; - EDKII_CRYPTO_BIGNUM_MUL_MOD BigNumMulMod; - EDKII_CRYPTO_BIGNUM_CMP BigNumCmp; - EDKII_CRYPTO_BIGNUM_BITS BigNumBits; - EDKII_CRYPTO_BIGNUM_BYTES BigNumBytes; - EDKII_CRYPTO_BIGNUM_IS_WORD BigNumIsWord; - EDKII_CRYPTO_BIGNUM_IS_ODD BigNumIsOdd; - EDKII_CRYPTO_BIGNUM_COPY BigNumCopy; - EDKII_CRYPTO_BIGNUM_VALUE_ONE BigNumValueOne; - EDKII_CRYPTO_BIGNUM_R_SHIFT BigNumRShift; - EDKII_CRYPTO_BIGNUM_CONST_TIME BigNumConstTime; - EDKII_CRYPTO_BIGNUM_SQR_MOD BigNumSqrMod; - EDKII_CRYPTO_BIGNUM_NEW_CONTEXT BigNumNewContext; - EDKII_CRYPTO_BIGNUM_CONTEXT_FREE BigNumContextFree; - EDKII_CRYPTO_BIGNUM_SET_UINT BigNumSetUint; - EDKII_CRYPTO_BIGNUM_ADD_MOD BigNumAddMod; + EDKII_CRYPTO_BIGNUM_INIT BigNumInit; + EDKII_CRYPTO_BIGNUM_FROM_BIN BigNumFromBin; + EDKII_CRYPTO_BIGNUM_TO_BIN BigNumToBin; + EDKII_CRYPTO_BIGNUM_FREE BigNumFree; + EDKII_CRYPTO_BIGNUM_ADD BigNumAdd; + EDKII_CRYPTO_BIGNUM_SUB BigNumSub; + EDKII_CRYPTO_BIGNUM_MOD BigNumMod; + EDKII_CRYPTO_BIGNUM_EXP_MOD BigNumExpMod; + EDKII_CRYPTO_BIGNUM_INVERSE_MOD BigNumInverseMod; + EDKII_CRYPTO_BIGNUM_DIV BigNumDiv; + EDKII_CRYPTO_BIGNUM_MUL_MOD BigNumMulMod; + EDKII_CRYPTO_BIGNUM_CMP BigNumCmp; + EDKII_CRYPTO_BIGNUM_BITS BigNumBits; + EDKII_CRYPTO_BIGNUM_BYTES BigNumBytes; + EDKII_CRYPTO_BIGNUM_IS_WORD BigNumIsWord; + EDKII_CRYPTO_BIGNUM_IS_ODD BigNumIsOdd; + EDKII_CRYPTO_BIGNUM_COPY BigNumCopy; + EDKII_CRYPTO_BIGNUM_VALUE_ONE BigNumValueOne; + EDKII_CRYPTO_BIGNUM_R_SHIFT BigNumRShift; + EDKII_CRYPTO_BIGNUM_CONST_TIME BigNumConstTime; + EDKII_CRYPTO_BIGNUM_SQR_MOD BigNumSqrMod; + EDKII_CRYPTO_BIGNUM_NEW_CONTEXT BigNumNewContext; + EDKII_CRYPTO_BIGNUM_CONTEXT_FREE BigNumContextFree; + EDKII_CRYPTO_BIGNUM_SET_UINT BigNumSetUint; + EDKII_CRYPTO_BIGNUM_ADD_MOD BigNumAddMod; + /// EC + EDKII_CRYPTO_EC_GROUP_INIT EcGroupInit; + EDKII_CRYPTO_EC_GROUP_GET_CURVE EcGroupGetCurve; + EDKII_CRYPTO_EC_GROUP_GET_ORDER EcGroupGetOrder; + EDKII_CRYPTO_EC_GROUP_FREE EcGroupFree; + EDKII_CRYPTO_EC_POINT_INIT EcPointInit; + EDKII_CRYPTO_EC_POINT_DE_INIT EcPointDeInit; + EDKII_CRYPTO_EC_POINT_GET_AFFINE_COORDINATES EcPointGetAffineCoordinates; + EDKII_CRYPTO_EC_POINT_SET_AFFINE_COORDINATES EcPointSetAffineCoordinates; + EDKII_CRYPTO_EC_POINT_ADD EcPointAdd; + EDKII_CRYPTO_EC_POINT_MUL EcPointMul; + EDKII_CRYPTO_EC_POINT_INVERT EcPointInvert; + EDKII_CRYPTO_EC_POINT_IS_ON_CURVE EcPointIsOnCurve; + EDKII_CRYPTO_EC_POINT_IS_AT_INFINITY EcPointIsAtInfinity; + EDKII_CRYPTO_EC_POINT_EQUAL EcPointEqual; + EDKII_CRYPTO_EC_POINT_SET_COMPRESSED_COORDINATES EcPointSetCompressedCoordinates; + EDKII_CRYPTO_EC_NEW_BY_NID EcNewByNid; + EDKII_CRYPTO_EC_FREE EcFree; + EDKII_CRYPTO_EC_GENERATE_KEY EcGenerateKey; + EDKII_CRYPTO_EC_GET_PUB_KEY EcGetPubKey; + EDKII_CRYPTO_EC_DH_COMPUTE_KEY EcDhComputeKey; }; extern GUID gEdkiiCryptoProtocolGuid; From 81cb190f389d00b1ccc662db3820ee0df6c7ec2f Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sun, 25 Sep 2022 17:26:20 +0800 Subject: [PATCH 0071/1529] CryptoPkg: Add ECC related usage reference Describes the use cases under which ECC needs to be enabled, and provides the impact on memory size for developers' reference. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Michael D Kinney Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dec | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/CryptoPkg/CryptoPkg.dec b/CryptoPkg/CryptoPkg.dec index d9b64e5763..217e73c3bc 100644 --- a/CryptoPkg/CryptoPkg.dec +++ b/CryptoPkg/CryptoPkg.dec @@ -83,7 +83,36 @@ ## Enable/Disable the ECC feature in openssl library. The default is disabled. # If ECC feature is disabled, all related source files will not be compiled. + # @Prompt Enable/Disable ECC feature in openssl library gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled|FALSE|BOOLEAN|0x0000003 + # Set it to TRUE if: + # 1) Platform needs ECC in TLS, or asymmetric cryptography services such as + # X509 certificate or PEM format data processing. + # 2) Platform needs to enable PcdCryptoServiceFamilyEnable.Ec service. + # Please note: + # ECC feature will cause a significant memory increase, approximate memory impact + # in below table for reference by platform developers with FW size limitations. + # Uncompressed LZMA Compressed + # CPU CRYPTO_SERVICES Module EC=FALSE EC=TRUE EC=FALSE EC=TRUE Increase + # ==== =============== ======== ======== ======= ======== ======= ======== + # IA32 NONE CryptoPei 21536 21568 0 KB + # IA32 NONE CryptoDxe 21632 21696 0 KB + # IA32 NONE CryptoSmm 22976 23072 0 KB + # IA32 MIN_PEI CryptoPei 248992 249120 0 KB + # IA32 MIN_DXE_MIN_SMM CryptoDxe 636672 829568 288520 401034 113 KB + # IA32 MIN_DXE_MIN_SMM CryptoSmm 426048 601472 191517 296022 105 KB + # IA32 ALL CryptoPei 423840 598976 189047 293759 104 KB + # IA32 ALL CryptoDxe 645280 838144 292955 405277 113 KB + # IA32 ALL CryptoSmm 441888 617184 198779 303628 105 KB + # X64 NONE CryptoPei 29632 29664 0 KB + # X64 NONE CryptoDxe 29792 29792 0 KB + # X64 NONE CryptoSmm 31296 31296 0 KB + # X64 MIN_PEI CryptoPei 310784 310848 0 KB + # X64 MIN_DXE_MIN_SMM CryptoDxe 804288 1016256 311436 426596 115 KB + # X64 MIN_DXE_MIN_SMM CryptoSmm 543776 733920 204483 310775 106 KB + # X64 ALL CryptoPei 540384 730240 202494 308467 106 KB + # X64 ALL CryptoDxe 815392 1027296 316228 431321 115 KB + # X64 ALL CryptoSmm 563648 753696 213488 319644 106 KB [UserExtensions.TianoCore."ExtraFiles"] CryptoPkgExtra.uni From bcd8dcd10c29d7abc64fa361cecbcc61c9724653 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sun, 25 Sep 2022 17:26:21 +0800 Subject: [PATCH 0072/1529] CryptoPkg/Test: Add unit test for CryptoEc Add unit test for CryptoEc. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- .../BaseCryptLib/UnitTestHostBaseCryptLib.inf | 2 + CryptoPkg/Test/CryptoPkgHostUnitTest.dsc | 3 + .../BaseCryptLib/BaseCryptLibUnitTests.c | 1 + .../UnitTest/Library/BaseCryptLib/EcTests.c | 290 ++++++++++++++++++ .../Library/BaseCryptLib/TestBaseCryptLib.h | 2 + .../BaseCryptLib/TestBaseCryptLibHost.inf | 1 + .../BaseCryptLib/TestBaseCryptLibShell.inf | 1 + 7 files changed, 300 insertions(+) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c diff --git a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf index 6891db97fb..168e24e4c0 100644 --- a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf @@ -48,6 +48,8 @@ Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c Bn/CryptBn.c + Pk/CryptEcNull.c |*|*|*|!gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + Pk/CryptEc.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled SysCall/UnitTestHostCrtWrapper.c diff --git a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc index 16478f4a57..b6e1a66198 100644 --- a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc +++ b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc @@ -19,6 +19,9 @@ !include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +[PcdsFixedAtBuild] + gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled|TRUE + [LibraryClasses] OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c index 8450e95172..63bae35b80 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c @@ -28,6 +28,7 @@ SUITE_DESC mSuiteDesc[] = { { "Hkdf extract and expand tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mHkdfTestNum, mHkdfTest }, { "Aead AES Gcm tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAeadAesGcmTestNum, mAeadAesGcmTest }, { "Bn verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mBnTestNum, mBnTest }, + { "EC verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mEcTestNum, mEcTest }, }; EFI_STATUS diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c new file mode 100644 index 0000000000..54ce0b22df --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c @@ -0,0 +1,290 @@ +/** @file + Application for Diffie-Hellman Primitives Validation. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "TestBaseCryptLib.h" + +#define EC_CURVE_NUM_SUPPORTED 3 +UINTN EcCurveList[EC_CURVE_NUM_SUPPORTED] = { CRYPTO_NID_SECP256R1, CRYPTO_NID_SECP384R1, CRYPTO_NID_SECP521R1 }; +UINTN EcKeyHalfSize[EC_CURVE_NUM_SUPPORTED] = { 32, 48, 66 }; + +struct Generator { + UINT8 X[66]; + UINT8 Y[66]; +}; + +// Generator points of all ec curve +struct Generator EcCurveGenerator[EC_CURVE_NUM_SUPPORTED] = +{ + // CRYPTO_NID_SECP256R1 + { + { 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, + 0x63, 0xA4, 0x40, 0xF2, 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, + 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96 }, + + { 0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, + 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, + 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5 } + }, + // CRYPTO_NID_SECP384R1 + { + { 0xAA, 0x87, 0xCA, 0x22, 0xBE, 0x8B, 0x05, 0x37, 0x8E, 0xB1, 0xC7, 0x1E, + 0xF3, 0x20, 0xAD, 0x74, 0x6E, 0x1D, 0x3B, 0x62, 0x8B, 0xA7, 0x9B, 0x98, + 0x59, 0xF7, 0x41, 0xE0, 0x82, 0x54, 0x2A, 0x38, 0x55, 0x02, 0xF2, 0x5D, + 0xBF, 0x55, 0x29, 0x6C, 0x3A, 0x54, 0x5E, 0x38, 0x72, 0x76, 0x0A, 0xB7 }, + + { 0x36, 0x17, 0xde, 0x4a, 0x96, 0x26, 0x2c, 0x6f, 0x5d, 0x9e, 0x98, 0xbf, + 0x92, 0x92, 0xdc, 0x29, 0xf8, 0xf4, 0x1d, 0xbd, 0x28, 0x9a, 0x14, 0x7c, + 0xe9, 0xda, 0x31, 0x13, 0xb5, 0xf0, 0xb8, 0xc0, 0x0a, 0x60, 0xb1, 0xce, + 0x1d, 0x7e, 0x81, 0x9d, 0x7a, 0x43, 0x1d, 0x7c, 0x90, 0xea, 0x0e, 0x5f } + }, + // CRYPTO_NID_SECP521R1 + { + { 0x00, 0xC6, 0x85, 0x8E, 0x06, 0xB7, 0x04, 0x04, 0xE9, 0xCD, 0x9E, 0x3E, + 0xCB, 0x66, 0x23, 0x95, 0xB4, 0x42, 0x9C, 0x64, 0x81, 0x39, 0x05, 0x3F, + 0xB5, 0x21, 0xF8, 0x28, 0xAF, 0x60, 0x6B, 0x4D, 0x3D, 0xBA, 0xA1, 0x4B, + 0x5E, 0x77, 0xEF, 0xE7, 0x59, 0x28, 0xFE, 0x1D, 0xC1, 0x27, 0xA2, 0xFF, + 0xA8, 0xDE, 0x33, 0x48, 0xB3, 0xC1, 0x85, 0x6A, 0x42, 0x9B, 0xF9, 0x7E, + 0x7E, 0x31, 0xC2, 0xE5, 0xBD, 0x66 }, + + { 0x01, 0x18, 0x39, 0x29, 0x6a, 0x78, 0x9a, 0x3b, 0xc0, 0x04, 0x5c, 0x8a, + 0x5f, 0xb4, 0x2c, 0x7d, 0x1b, 0xd9, 0x98, 0xf5, 0x44, 0x49, 0x57, 0x9b, + 0x44, 0x68, 0x17, 0xaf, 0xbd, 0x17, 0x27, 0x3e, 0x66, 0x2c, 0x97, 0xee, + 0x72, 0x99, 0x5e, 0xf4, 0x26, 0x40, 0xc5, 0x50, 0xb9, 0x01, 0x3f, 0xad, + 0x07, 0x61, 0x35, 0x3c, 0x70, 0x86, 0xa2, 0x72, 0xc2, 0x40, 0x88, 0xbe, + 0x94, 0x76, 0x9f, 0xd1, 0x66, 0x50 } + } +}; + +VOID *Ec1; +VOID *Ec2; +VOID *Group; +VOID *Point1; +VOID *Point2; +VOID *PointRes; +VOID *BnX; +VOID *BnY; +VOID *BnP; +VOID *BnOrder; + +UNIT_TEST_STATUS +EFIAPI +TestVerifyEcPreReq ( + UNIT_TEST_CONTEXT Context + ) +{ + Ec1 = NULL; + Ec2 = NULL; + Group = NULL; + Point1 = NULL; + Point2 = NULL; + PointRes = NULL; + BnX = NULL; + BnY = NULL; + BnP = BigNumInit (); + BnOrder = BigNumInit (); + if ((BnP == NULL) || (BnOrder == NULL)) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + return UNIT_TEST_PASSED; +} + +VOID +EFIAPI +TestVerifyEcCleanUp ( + UNIT_TEST_CONTEXT Context + ) +{ + BigNumFree (BnX, TRUE); + BigNumFree (BnY, TRUE); + BigNumFree (BnP, TRUE); + BigNumFree (BnOrder, TRUE); + EcGroupFree (Group); + EcPointDeInit (Point1, TRUE); + EcPointDeInit (Point2, TRUE); + EcPointDeInit (PointRes, TRUE); + EcFree (Ec1); + EcFree (Ec2); +} + +UNIT_TEST_STATUS +EFIAPI +TestVerifyEcBasic ( + UNIT_TEST_CONTEXT Context + ) +{ + UINTN CurveCount; + BOOLEAN Status; + + // + // Initialize BigNumbers + // + for (CurveCount = 0; CurveCount < EC_CURVE_NUM_SUPPORTED; CurveCount++) { + // + // Basic EC functions unit test + // + Group = EcGroupInit (EcCurveList[CurveCount]); + if (Group == NULL) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + Point1 = EcPointInit (Group); + Point2 = EcPointInit (Group); + PointRes = EcPointInit (Group); + BnX = BigNumFromBin (EcCurveGenerator[CurveCount].X, EcKeyHalfSize[CurveCount]); + BnY = BigNumFromBin (EcCurveGenerator[CurveCount].Y, EcKeyHalfSize[CurveCount]); + if ((Point1 == NULL) || (Point2 == NULL) || (PointRes == NULL) || (BnX == NULL) || (BnY == NULL)) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + Status = EcGroupGetCurve (Group, BnP, NULL, NULL, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcGroupGetOrder (Group, BnOrder); + UT_ASSERT_TRUE (Status); + + // Point G should on curve + Status = EcPointSetAffineCoordinates (Group, Point1, BnX, BnY, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointSetAffineCoordinates (Group, Point2, BnX, BnY, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointEqual (Group, Point1, Point2, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointIsOnCurve (Group, Point1, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointIsAtInfinity (Group, Point1); + UT_ASSERT_FALSE (Status); + + // Point 2G should on curve + Status = EcPointAdd (Group, PointRes, Point1, Point1, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointIsOnCurve (Group, PointRes, NULL); + UT_ASSERT_TRUE (Status); + + // Point Order * G should at infinity + Status = EcPointMul (Group, PointRes, Point1, BnOrder, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointIsAtInfinity (Group, PointRes); + UT_ASSERT_TRUE (Status); + + // -(-G) == G + Status = EcPointInvert (Group, Point2, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointEqual (Group, Point2, Point1, NULL); + UT_ASSERT_FALSE (Status); + + Status = EcPointInvert (Group, Point2, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointEqual (Group, Point2, Point1, NULL); + UT_ASSERT_TRUE (Status); + + // Compress point test + Status = EcPointSetCompressedCoordinates (Group, Point1, BnX, 0, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointSetCompressedCoordinates (Group, Point2, BnX, 1, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointEqual (Group, Point2, Point1, NULL); + UT_ASSERT_FALSE (Status); + + Status = EcPointInvert (Group, Point2, NULL); + UT_ASSERT_TRUE (Status); + + Status = EcPointEqual (Group, Point2, Point1, NULL); + UT_ASSERT_TRUE (Status); + } + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestVerifyEcDh ( + UNIT_TEST_CONTEXT Context + ) +{ + UINT8 Public1[66 * 2]; + UINTN Public1Length; + UINT8 Public2[66 * 2]; + UINTN Public2Length; + UINT8 Key1[66]; + UINTN Key1Length; + UINT8 Key2[66]; + UINTN Key2Length; + UINTN CurveCount; + BOOLEAN Status; + + for (CurveCount = 0; CurveCount < EC_CURVE_NUM_SUPPORTED; CurveCount++) { + // + // Initial key length + // + Public1Length = sizeof (Public1); + Public2Length = sizeof (Public2); + Key1Length = sizeof (Key1); + Key2Length = sizeof (Key2); + // + // ECDH functions unit test + // + Ec1 = EcNewByNid (EcCurveList[CurveCount]); + if (Ec1 == NULL) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + Ec2 = EcNewByNid (EcCurveList[CurveCount]); + if (Ec2 == NULL) { + return UNIT_TEST_ERROR_TEST_FAILED; + } + + Status = EcGenerateKey (Ec1, Public1, &Public1Length); + UT_ASSERT_TRUE (Status); + UT_ASSERT_EQUAL (Public1Length, EcKeyHalfSize[CurveCount] * 2); + + Status = EcGenerateKey (Ec2, Public2, &Public2Length); + UT_ASSERT_TRUE (Status); + UT_ASSERT_EQUAL (Public2Length, EcKeyHalfSize[CurveCount] * 2); + + Status = EcDhComputeKey (Ec1, Public2, Public2Length, NULL, Key1, &Key1Length); + UT_ASSERT_TRUE (Status); + UT_ASSERT_EQUAL (Key1Length, EcKeyHalfSize[CurveCount]); + + Status = EcDhComputeKey (Ec2, Public1, Public1Length, NULL, Key2, &Key2Length); + UT_ASSERT_TRUE (Status); + UT_ASSERT_EQUAL (Key2Length, EcKeyHalfSize[CurveCount]); + + UT_ASSERT_EQUAL (Key1Length, Key2Length); + UT_ASSERT_MEM_EQUAL (Key1, Key2, Key1Length); + + Status = EcGetPubKey (Ec1, Public2, &Public2Length); + UT_ASSERT_TRUE (Status); + UT_ASSERT_EQUAL (Public2Length, EcKeyHalfSize[CurveCount] * 2); + + UT_ASSERT_EQUAL (Public1Length, Public2Length); + UT_ASSERT_MEM_EQUAL (Public1, Public2, Public1Length); + } + + return UNIT_TEST_PASSED; +} + +TEST_DESC mEcTest[] = { + // + // -----Description-----------------Class------------------Function----Pre----Post----Context + // + { "TestVerifyEcBasic()", "CryptoPkg.BaseCryptLib.Ec", TestVerifyEcBasic, TestVerifyEcPreReq, TestVerifyEcCleanUp, NULL }, + { "TestVerifyEcDh()", "CryptoPkg.BaseCryptLib.Ec", TestVerifyEcDh, TestVerifyEcPreReq, TestVerifyEcCleanUp, NULL }, +}; + +UINTN mEcTestNum = ARRAY_SIZE (mEcTest); diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h index fc44030ff6..3a84e63a87 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h @@ -95,6 +95,8 @@ extern TEST_DESC mAeadAesGcmTest[]; extern UINTN mBnTestNum; extern TEST_DESC mBnTest[]; +extern UINTN mEcTestNum; +extern TEST_DESC mEcTest[]; /** Creates a framework you can use */ EFI_STATUS EFIAPI diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf index 40dfade717..023b796946 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf @@ -40,6 +40,7 @@ HkdfTests.c AeadAesGcmTests.c BnTests.c + EcTests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf index 00e6b088b8..5bfd190236 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf @@ -39,6 +39,7 @@ HkdfTests.c AeadAesGcmTests.c BnTests.c + EcTests.c [Packages] MdePkg/MdePkg.dec From 270a479b4722104fbb1a2114508e5e0b9e762083 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Tue, 9 Aug 2022 17:35:50 -0700 Subject: [PATCH 0073/1529] IntelFsp2WrapperPkg: Implement FSP 2.4 MultiPhase wrapper handlers. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3916 Implement MultiPhase wrapper handlers and only call to MultiPhase handlers when FSP supports. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- .../FspmWrapperPeim/FspmWrapperPeim.c | 33 ++++++++++++++----- .../FspmWrapperPeim/FspmWrapperPeim.inf | 1 + .../FspsWrapperPeim/FspsWrapperPeim.c | 27 +++++++++++---- .../FspsWrapperPeim/FspsWrapperPeim.inf | 3 +- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.c b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.c index ac27524d08..ea206a7960 100644 --- a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.c +++ b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -35,6 +36,8 @@ #include #include #include +#include +#include extern EFI_GUID gFspHobGuid; @@ -119,25 +122,39 @@ PeiFspMemoryInit ( TimeStampCounterStart = AsmReadTsc (); Status = CallFspMemoryInit (FspmUpdDataPtr, &FspHobListPtr); - // Create hobs after memory initialization and not in temp RAM. Hence passing the recorded timestamp here - PERF_START_EX (&gFspApiPerformanceGuid, "EventRec", NULL, TimeStampCounterStart, FSP_STATUS_CODE_MEMORY_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_ENTRY); - PERF_END_EX (&gFspApiPerformanceGuid, "EventRec", NULL, 0, FSP_STATUS_CODE_MEMORY_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_EXIT); - DEBUG ((DEBUG_INFO, "Total time spent executing FspMemoryInitApi: %d millisecond\n", DivU64x32 (GetTimeInNanoSecond (AsmReadTsc () - TimeStampCounterStart), 1000000))); // // Reset the system if FSP API returned FSP_STATUS_RESET_REQUIRED status // if ((Status >= FSP_STATUS_RESET_REQUIRED_COLD) && (Status <= FSP_STATUS_RESET_REQUIRED_8)) { - DEBUG ((DEBUG_INFO, "FspMemoryInitApi requested reset 0x%x\n", Status)); + DEBUG ((DEBUG_INFO, "FspMemoryInitApi requested reset %r\n", Status)); CallFspWrapperResetSystem (Status); } - if (EFI_ERROR (Status)) { + if ((Status != FSP_STATUS_VARIABLE_REQUEST) && EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "ERROR - Failed to execute FspMemoryInitApi(), Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); } - DEBUG ((DEBUG_INFO, "FspMemoryInit status: 0x%x\n", Status)); - ASSERT_EFI_ERROR (Status); + DEBUG ((DEBUG_INFO, "FspMemoryInit status: %r\n", Status)); + if (Status == FSP_STATUS_VARIABLE_REQUEST) { + // + // call to Variable request handler + // + FspWrapperVariableRequestHandler (&FspHobListPtr, FspMultiPhaseMemInitApiIndex); + } + + // + // See if MultiPhase process is required or not + // + FspWrapperMultiPhaseHandler (&FspHobListPtr, FspMultiPhaseMemInitApiIndex); // FspM MultiPhase + + // + // Create hobs after memory initialization and not in temp RAM. Hence passing the recorded timestamp here + // + PERF_START_EX (&gFspApiPerformanceGuid, "EventRec", NULL, TimeStampCounterStart, FSP_STATUS_CODE_MEMORY_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_ENTRY); + PERF_END_EX (&gFspApiPerformanceGuid, "EventRec", NULL, 0, FSP_STATUS_CODE_MEMORY_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_EXIT); + DEBUG ((DEBUG_INFO, "Total time spent executing FspMemoryInitApi: %d millisecond\n", DivU64x32 (GetTimeInNanoSecond (AsmReadTsc () - TimeStampCounterStart), 1000000))); Status = TestFspMemoryInitApiOutput (FspmUpdDataPtr, &FspHobListPtr); if (EFI_ERROR (Status)) { diff --git a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf index e2262d693c..332509e0bc 100644 --- a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf +++ b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf @@ -46,6 +46,7 @@ FspWrapperApiLib FspWrapperApiTestLib FspMeasurementLib + FspWrapperMultiPhaseProcessLib [Packages] MdePkg/MdePkg.dec diff --git a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c index ee48dd69d3..091ddb697a 100644 --- a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c +++ b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -36,6 +37,7 @@ #include #include #include +#include extern EFI_PEI_NOTIFY_DESCRIPTOR mS3EndOfPeiNotifyDesc; extern EFI_GUID gFspHobGuid; @@ -318,23 +320,36 @@ PeiMemoryDiscoveredNotify ( TimeStampCounterStart = AsmReadTsc (); PERF_START_EX (&gFspApiPerformanceGuid, "EventRec", NULL, 0, FSP_STATUS_CODE_SILICON_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_ENTRY); Status = CallFspSiliconInit ((VOID *)FspsUpdDataPtr); - PERF_END_EX (&gFspApiPerformanceGuid, "EventRec", NULL, 0, FSP_STATUS_CODE_SILICON_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_EXIT); - DEBUG ((DEBUG_INFO, "Total time spent executing FspSiliconInitApi: %d millisecond\n", DivU64x32 (GetTimeInNanoSecond (AsmReadTsc () - TimeStampCounterStart), 1000000))); // // Reset the system if FSP API returned FSP_STATUS_RESET_REQUIRED status // if ((Status >= FSP_STATUS_RESET_REQUIRED_COLD) && (Status <= FSP_STATUS_RESET_REQUIRED_8)) { - DEBUG ((DEBUG_INFO, "FspSiliconInitApi requested reset 0x%x\n", Status)); + DEBUG ((DEBUG_INFO, "FspSiliconInitApi requested reset %r\n", Status)); CallFspWrapperResetSystem (Status); } - if (EFI_ERROR (Status)) { + if ((Status != FSP_STATUS_VARIABLE_REQUEST) && EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "ERROR - Failed to execute FspSiliconInitApi(), Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); } - DEBUG ((DEBUG_INFO, "FspSiliconInit status: 0x%x\n", Status)); - ASSERT_EFI_ERROR (Status); + DEBUG ((DEBUG_INFO, "FspSiliconInit status: %r\n", Status)); + + if (Status == FSP_STATUS_VARIABLE_REQUEST) { + // + // call to Variable request handler + // + FspWrapperVariableRequestHandler (&FspHobListPtr, FspMultiPhaseSiInitApiIndex); + } + + // + // See if MultiPhase process is required or not + // + FspWrapperMultiPhaseHandler (&FspHobListPtr, FspMultiPhaseSiInitApiIndex); // FspS MultiPhase + + PERF_END_EX (&gFspApiPerformanceGuid, "EventRec", NULL, 0, FSP_STATUS_CODE_SILICON_INIT | FSP_STATUS_CODE_COMMON_CODE | FSP_STATUS_CODE_API_EXIT); + DEBUG ((DEBUG_INFO, "Total time spent executing FspSiliconInitApi: %d millisecond\n", DivU64x32 (GetTimeInNanoSecond (AsmReadTsc () - TimeStampCounterStart), 1000000))); Status = TestFspSiliconInitApiOutput ((VOID *)NULL); if (RETURN_ERROR (Status)) { diff --git a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf index 0598f85ab3..f9c2ffca1c 100644 --- a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf +++ b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf @@ -6,7 +6,7 @@ # register TemporaryRamDonePpi to call TempRamExit API, and register MemoryDiscoveredPpi # notify to call FspSiliconInit API. # -# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2014 - 2022, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -46,6 +46,7 @@ FspWrapperApiLib FspWrapperApiTestLib FspMeasurementLib + FspWrapperMultiPhaseProcessLib [Packages] MdePkg/MdePkg.dec From 32b3317146638044386de8f0d6da6fc68dd2bba4 Mon Sep 17 00:00:00 2001 From: jdzhang Date: Wed, 21 Sep 2022 11:05:40 +0800 Subject: [PATCH 0074/1529] MdeModulePkg/XhciDxe: Input context update for Evaluate Context command REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4074 Update XhcEvaluateContext/XhcEvaluateContext64 to properly initialize the input context for Evaluate Context command. Signed-off-by: jdzhang Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index c2906e06fd..4ae0297607 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -3957,6 +3957,7 @@ XhcEvaluateContext ( CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; EVT_TRB_COMMAND_COMPLETION *EvtTrb; INPUT_CONTEXT *InputContext; + DEVICE_CONTEXT *OutputContext; EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); @@ -3964,11 +3965,15 @@ XhcEvaluateContext ( // // 4.6.7 Evaluate Context // - InputContext = Xhc->UsbDevContext[SlotId].InputContext; + InputContext = Xhc->UsbDevContext[SlotId].InputContext; + OutputContext = Xhc->UsbDevContext[SlotId].OutputContext; ZeroMem (InputContext, sizeof (INPUT_CONTEXT)); + CopyMem (&InputContext->EP[0], &OutputContext->EP[0], sizeof (ENDPOINT_CONTEXT)); + InputContext->InputControlContext.Dword2 |= BIT1; InputContext->EP[0].MaxPacketSize = MaxPacketSize; + InputContext->EP[0].EPState = 0; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); @@ -4013,6 +4018,7 @@ XhcEvaluateContext64 ( CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; EVT_TRB_COMMAND_COMPLETION *EvtTrb; INPUT_CONTEXT_64 *InputContext; + DEVICE_CONTEXT_64 *OutputContext; EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); @@ -4020,11 +4026,15 @@ XhcEvaluateContext64 ( // // 4.6.7 Evaluate Context // - InputContext = Xhc->UsbDevContext[SlotId].InputContext; + InputContext = Xhc->UsbDevContext[SlotId].InputContext; + OutputContext = Xhc->UsbDevContext[SlotId].OutputContext; ZeroMem (InputContext, sizeof (INPUT_CONTEXT_64)); + CopyMem (&InputContext->EP[0], &OutputContext->EP[0], sizeof (ENDPOINT_CONTEXT_64)); + InputContext->InputControlContext.Dword2 |= BIT1; InputContext->EP[0].MaxPacketSize = MaxPacketSize; + InputContext->EP[0].EPState = 0; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); From 1fbeac8c306c86dc3be00f4b0d4b16ec2e42a2db Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 27 Sep 2022 15:07:53 +0800 Subject: [PATCH 0075/1529] OvmfPkg/PeilessStartupLib: move mPageTablePool to stack PeilessStartupLib is running in SEC phase. In this phase global variable is not allowed to be modified. This patch moves mPageTablePool to stack and pass it as input parameter between functions. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- .../PeilessStartupLib/X64/VirtualMemory.c | 117 ++++++++++-------- 1 file changed, 68 insertions(+), 49 deletions(-) diff --git a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c index 6877e521e4..b444c052d1 100644 --- a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c +++ b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c @@ -21,11 +21,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "PageTables.h" -// -// Global variable to keep track current available memory used as page table. -// -PAGE_TABLE_POOL *mPageTablePool = NULL; - UINTN mLevelShift[5] = { 0, PAGING_L1_ADDRESS_SHIFT, @@ -273,14 +268,17 @@ ToSplitPageTable ( reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. But usually this won't happen in practice. - @param PoolPages The least page number of the pool to be created. + @param[in] PoolPages The least page number of the pool to be created. + @param[in, out] PageTablePool Pointer of Pointer to the current available memory + used as page table. @retval TRUE The pool is initialized successfully. @retval FALSE The memory is out of resource. **/ BOOLEAN InitializePageTablePool ( - IN UINTN PoolPages + IN UINTN PoolPages, + IN OUT PAGE_TABLE_POOL **PageTablePool ) { VOID *Buffer; @@ -303,20 +301,20 @@ InitializePageTablePool ( // // Link all pools into a list for easier track later. // - if (mPageTablePool == NULL) { - mPageTablePool = Buffer; - mPageTablePool->NextPool = mPageTablePool; + if (*PageTablePool == NULL) { + *(UINT64 *)(UINTN)PageTablePool = (UINT64)(UINTN)Buffer; + (*PageTablePool)->NextPool = *PageTablePool; } else { - ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool; - mPageTablePool->NextPool = Buffer; - mPageTablePool = Buffer; + ((PAGE_TABLE_POOL *)Buffer)->NextPool = (*PageTablePool)->NextPool; + (*PageTablePool)->NextPool = Buffer; + *PageTablePool = Buffer; } // // Reserve one page for pool header. // - mPageTablePool->FreePages = PoolPages - 1; - mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1); + (*PageTablePool)->FreePages = PoolPages - 1; + (*PageTablePool)->Offset = EFI_PAGES_TO_SIZE (1); return TRUE; } @@ -333,14 +331,17 @@ InitializePageTablePool ( If there is not enough memory remaining to satisfy the request, then NULL is returned. - @param Pages The number of 4 KB pages to allocate. + @param[in] Pages The number of 4 KB pages to allocate. + @param[in, out] PageTablePool Pointer of pointer to the current available + memory used as page table. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * AllocatePageTableMemory ( - IN UINTN Pages + IN UINTN Pages, + IN OUT PAGE_TABLE_POOL **PageTablePool ) { VOID *Buffer; @@ -349,30 +350,31 @@ AllocatePageTableMemory ( return NULL; } - DEBUG ((DEBUG_INFO, "AllocatePageTableMemory. mPageTablePool=%p, Pages=%d\n", mPageTablePool, Pages)); + DEBUG ((DEBUG_INFO, "AllocatePageTableMemory. PageTablePool=%p, Pages=%d\n", *PageTablePool, Pages)); // // Renew the pool if necessary. // - if ((mPageTablePool == NULL) || - (Pages > mPageTablePool->FreePages)) + if ((*PageTablePool == NULL) || + (Pages > (*PageTablePool)->FreePages)) { - if (!InitializePageTablePool (Pages)) { + if (!InitializePageTablePool (Pages, PageTablePool)) { return NULL; } } - Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset; + Buffer = (UINT8 *)(*PageTablePool) + (*PageTablePool)->Offset; - mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages); - mPageTablePool->FreePages -= Pages; + (*PageTablePool)->Offset += EFI_PAGES_TO_SIZE (Pages); + (*PageTablePool)->FreePages -= Pages; DEBUG (( DEBUG_INFO, - "%a:%a: Buffer=0x%Lx Pages=%ld\n", + "%a:%a: Buffer=0x%Lx Pages=%ld, PageTablePool=%p\n", gEfiCallerBaseName, __FUNCTION__, Buffer, - Pages + Pages, + *PageTablePool )); return Buffer; @@ -385,6 +387,8 @@ AllocatePageTableMemory ( @param[in, out] PageEntry2M Pointer to 2M page entry. @param[in] StackBase Stack base address. @param[in] StackSize Stack size. + @param[in, out] PageTablePool Pointer to the current available memory used as + page table. **/ VOID @@ -392,7 +396,8 @@ Split2MPageTo4K ( IN EFI_PHYSICAL_ADDRESS PhysicalAddress, IN OUT UINT64 *PageEntry2M, IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize + IN UINTN StackSize, + IN OUT PAGE_TABLE_POOL *PageTablePool ) { EFI_PHYSICAL_ADDRESS PhysicalAddress4K; @@ -401,7 +406,7 @@ Split2MPageTo4K ( DEBUG ((DEBUG_INFO, "Split2MPageTo4K\n")); - PageTableEntry = AllocatePageTableMemory (1); + PageTableEntry = AllocatePageTableMemory (1, &PageTablePool); if (PageTableEntry == NULL) { ASSERT (FALSE); @@ -448,6 +453,8 @@ Split2MPageTo4K ( @param[in, out] PageEntry1G Pointer to 1G page entry. @param[in] StackBase Stack base address. @param[in] StackSize Stack size. + @param[in, out] PageTablePool Pointer to the current available memory used as + page table. **/ VOID @@ -455,14 +462,16 @@ Split1GPageTo2M ( IN EFI_PHYSICAL_ADDRESS PhysicalAddress, IN OUT UINT64 *PageEntry1G, IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize + IN UINTN StackSize, + IN OUT PAGE_TABLE_POOL *PageTablePool ) { EFI_PHYSICAL_ADDRESS PhysicalAddress2M; UINTN IndexOfPageDirectoryEntries; PAGE_TABLE_ENTRY *PageDirectoryEntry; - PageDirectoryEntry = AllocatePageTableMemory (1); + DEBUG ((DEBUG_INFO, "Split1GPageTo2M\n")); + PageDirectoryEntry = AllocatePageTableMemory (1, &PageTablePool); if (PageDirectoryEntry == NULL) { ASSERT (FALSE); @@ -480,7 +489,7 @@ Split1GPageTo2M ( // // Need to split this 2M page that covers NULL or stack range. // - Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)PageDirectoryEntry, StackBase, StackSize); + Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)PageDirectoryEntry, StackBase, StackSize, PageTablePool); } else { // // Fill in the Page Directory entries @@ -496,16 +505,19 @@ Split1GPageTo2M ( /** Set one page of page table pool memory to be read-only. - @param[in] PageTableBase Base address of page table (CR3). - @param[in] Address Start address of a page to be set as read-only. - @param[in] Level4Paging Level 4 paging flag. + @param[in] PageTableBase Base address of page table (CR3). + @param[in] Address Start address of a page to be set as read-only. + @param[in] Level4Paging Level 4 paging flag. + @param[in, out] PageTablePool Pointer to the current available memory used as + page table. **/ VOID SetPageTablePoolReadOnly ( IN UINTN PageTableBase, IN EFI_PHYSICAL_ADDRESS Address, - IN BOOLEAN Level4Paging + IN BOOLEAN Level4Paging, + IN OUT PAGE_TABLE_POOL *PageTablePool ) { UINTN Index; @@ -573,7 +585,8 @@ SetPageTablePoolReadOnly ( // ASSERT (Level > 1); - NewPageTable = AllocatePageTableMemory (1); + DEBUG ((DEBUG_INFO, "SetPageTablePoolReadOnly\n")); + NewPageTable = AllocatePageTableMemory (1, &PageTablePool); if (NewPageTable == NULL) { ASSERT (FALSE); @@ -604,14 +617,17 @@ SetPageTablePoolReadOnly ( /** Prevent the memory pages used for page table from been overwritten. - @param[in] PageTableBase Base address of page table (CR3). - @param[in] Level4Paging Level 4 paging flag. + @param[in] PageTableBase Base address of page table (CR3). + @param[in] Level4Paging Level 4 paging flag. + @param[in, out] PageTablePool Pointer to the current available memory used as + page table. **/ VOID EnablePageTableProtection ( - IN UINTN PageTableBase, - IN BOOLEAN Level4Paging + IN UINTN PageTableBase, + IN BOOLEAN Level4Paging, + IN OUT PAGE_TABLE_POOL *PageTablePool ) { PAGE_TABLE_POOL *HeadPool; @@ -621,7 +637,7 @@ EnablePageTableProtection ( DEBUG ((DEBUG_INFO, "EnablePageTableProtection\n")); - if (mPageTablePool == NULL) { + if (PageTablePool == NULL) { return; } @@ -632,10 +648,10 @@ EnablePageTableProtection ( AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); // - // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to + // SetPageTablePoolReadOnly might update PageTablePool. It's safer to // remember original one in advance. // - HeadPool = mPageTablePool; + HeadPool = PageTablePool; Pool = HeadPool; do { Address = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool; @@ -647,7 +663,7 @@ EnablePageTableProtection ( // protection to them one by one. // while (PoolSize > 0) { - SetPageTablePoolReadOnly (PageTableBase, Address, Level4Paging); + SetPageTablePoolReadOnly (PageTableBase, Address, Level4Paging, PageTablePool); Address += PAGE_TABLE_POOL_UNIT_SIZE; PoolSize -= PAGE_TABLE_POOL_UNIT_SIZE; } @@ -700,6 +716,7 @@ CreateIdentityMappingPageTables ( BOOLEAN Page1GSupport; PAGE_TABLE_1G_ENTRY *PageDirectory1GEntry; IA32_CR4 Cr4; + PAGE_TABLE_POOL *PageTablePool; // // Set PageMapLevel5Entry to suppress incorrect compiler/analyzer warnings @@ -785,13 +802,14 @@ CreateIdentityMappingPageTables ( (UINT64)TotalPagesNum )); - BigPageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum); + PageTablePool = NULL; + BigPageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum, &PageTablePool); if (BigPageAddress == 0) { ASSERT (FALSE); return 0; } - DEBUG ((DEBUG_INFO, "BigPageAddress = 0x%llx\n", BigPageAddress)); + DEBUG ((DEBUG_INFO, "BigPageAddress = 0x%llx, PageTablePool=%p\n", BigPageAddress, PageTablePool)); // // By architecture only one PageMapLevel4 exists - so lets allocate storage for it. @@ -856,7 +874,8 @@ CreateIdentityMappingPageTables ( PageAddress, (UINT64 *)PageDirectory1GEntry, StackBase, - StackSize + StackSize, + PageTablePool ); } else { // @@ -892,7 +911,7 @@ CreateIdentityMappingPageTables ( // // Need to split this 2M page that covers NULL or stack range. // - Split2MPageTo4K (PageAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize); + Split2MPageTo4K (PageAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize, PageTablePool); } else { // // Fill in the Page Directory entries @@ -929,7 +948,7 @@ CreateIdentityMappingPageTables ( // Protect the page table by marking the memory used for page table to be // read-only. // - EnablePageTableProtection ((UINTN)PageMap, TRUE); + EnablePageTableProtection ((UINTN)PageMap, TRUE, PageTablePool); return (UINTN)PageMap; } From 74ad75898df297f85c1a71be75383495167e40de Mon Sep 17 00:00:00 2001 From: VictorX Hsu Date: Mon, 26 Sep 2022 18:48:24 +0800 Subject: [PATCH 0076/1529] UefiPayloadPkg: Provide a wrapper for UniversalPayloadBuild.py REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4071 Provide a wrapper to wrap UniversalPayloadBuild.py Reviewed-by: Guo Dong Reviewed-by: James Lu Signed-off-by: VictorX Hsu --- UefiPayloadPkg/UniversalPayloadBuild.sh | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 UefiPayloadPkg/UniversalPayloadBuild.sh diff --git a/UefiPayloadPkg/UniversalPayloadBuild.sh b/UefiPayloadPkg/UniversalPayloadBuild.sh new file mode 100644 index 0000000000..9a72eedd35 --- /dev/null +++ b/UefiPayloadPkg/UniversalPayloadBuild.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then + echo python_exe=${PYTHON_COMMAND} +fi + +# Get file path of UniversalPayloadBuild.sh +uplbld_filepath=${BASH_SOURCE:-$0} +# Remove ".sh" extension +uplbld_filepath_noext=${uplbld_filepath%.*} +# execute UniversalPayloadBuild.py to build UefiPayloadPkg +exec "${python_exe:-python}" "$uplbld_filepath_noext.py" "$@" From a87fa6f77b31ad1f778a3d5c6fe1c265ddd6b482 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 22 Sep 2022 07:55:30 +0200 Subject: [PATCH 0077/1529] OvmfPkg/PlatformInitLib: q35 mtrr setup fix Traditional q35 memory layout is 2.75 GB of low memory, leaving room for the pcie mmconfig at 0xb0000000 and the 32-bit pci mmio window at 0xc0000000. Because of that OVMF tags the memory range above 0xb0000000 as uncachable via mtrr. A while ago qemu started to gigabyte-align memory by default (to make huge pages more effective) and q35 uses only 2G of low memory in that case. Which effectively makes the 32-bit pci mmio window start at 0x80000000. This patch updates the mtrr setup code accordingly. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 26 ++++++++++++++------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 942eaf89cf..d1a4f4b207 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -55,15 +55,25 @@ PlatformQemuUc32BaseInitialization ( } if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { - // - // On q35, the 32-bit area that we'll mark as UC, through variable MTRRs, - // starts at PcdPciExpressBaseAddress. The platform DSC is responsible for - // setting PcdPciExpressBaseAddress such that describing the - // [PcdPciExpressBaseAddress, 4GB) range require a very small number of - // variable MTRRs (preferably 1 or 2). - // + LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); ASSERT (PcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32); - PlatformInfoHob->Uc32Base = (UINT32)PcdGet64 (PcdPciExpressBaseAddress); + ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= LowerMemorySize); + + if (LowerMemorySize <= BASE_2GB) { + // Newer qemu with gigabyte aligned memory, + // 32-bit pci mmio window is 2G -> 4G then. + PlatformInfoHob->Uc32Base = BASE_2GB; + } else { + // + // On q35, the 32-bit area that we'll mark as UC, through variable MTRRs, + // starts at PcdPciExpressBaseAddress. The platform DSC is responsible for + // setting PcdPciExpressBaseAddress such that describing the + // [PcdPciExpressBaseAddress, 4GB) range require a very small number of + // variable MTRRs (preferably 1 or 2). + // + PlatformInfoHob->Uc32Base = (UINT32)PcdGet64 (PcdPciExpressBaseAddress); + } + return; } From 9c24c756acedf6d2b4d3dc04ecce30f8bea6501a Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 21 Sep 2022 07:30:44 +0200 Subject: [PATCH 0078/1529] OvmfPkg/QemuBootOrderLib: allow slash in rom filenames See comment for details. Needed to avoid the parser abort, so we can continue parsing the bootorder fw_cfg file. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- .../QemuBootOrderLib/QemuBootOrderLib.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c index 398de7fab4..374c6d8f5e 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c +++ b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c @@ -432,6 +432,8 @@ ParseOfwNode ( OUT BOOLEAN *IsFinal ) { + BOOLEAN AcceptSlash = FALSE; + // // A leading slash is expected. End of string is tolerated. // @@ -464,6 +466,21 @@ ParseOfwNode ( return RETURN_INVALID_PARAMETER; } + if (SubstringEq (OfwNode->DriverName, "rom")) { + // + // bug compatibility hack + // + // qemu passes fw_cfg filenames as rom unit address. + // The filenames have slashes: + // /rom@genroms/linuxboot_dma.bin + // + // Alow slashes in the unit address to avoid the parser trip up, + // so we can successfully parse the following lines (the rom + // entries themself are ignored). + // + AcceptSlash = TRUE; + } + // // unit-address // @@ -475,7 +492,7 @@ ParseOfwNode ( OfwNode->UnitAddress.Ptr = *Ptr; OfwNode->UnitAddress.Len = 0; - while (IsPrintNotDelim (**Ptr)) { + while (IsPrintNotDelim (**Ptr) || (AcceptSlash && **Ptr == '/')) { ++*Ptr; ++OfwNode->UnitAddress.Len; } From ce4f95816cb6b48510cee261569b57be93920cbe Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 21 Sep 2022 07:30:45 +0200 Subject: [PATCH 0079/1529] OvmfPkg/QemuBootOrderLib: skip unsupported entries in StoreQemuBootOrder When finding an unsupported entry just skip over and continue with the next entry instead of stop processing altogether. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- .../QemuBootOrderLib/QemuBootOrderLib.c | 56 ++++++++++--------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c index 374c6d8f5e..18646daa67 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c +++ b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c @@ -1775,34 +1775,38 @@ StoreQemuBootOrder ( Translated, &TranslatedSize ); - while (!RETURN_ERROR (Status)) { - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + while (Status == EFI_SUCCESS || + Status == EFI_UNSUPPORTED) + { + if (Status == EFI_SUCCESS) { + EFI_DEVICE_PATH_PROTOCOL *DevicePath; - // - // Convert the UEFI devpath prefix to binary representation. - // - ASSERT (Translated[TranslatedSize] == L'\0'); - DevicePath = ConvertTextToDevicePath (Translated); - if (DevicePath == NULL) { - Status = RETURN_OUT_OF_RESOURCES; - goto FreeExtraPciRoots; - } + // + // Convert the UEFI devpath prefix to binary representation. + // + ASSERT (Translated[TranslatedSize] == L'\0'); + DevicePath = ConvertTextToDevicePath (Translated); + if (DevicePath == NULL) { + Status = RETURN_OUT_OF_RESOURCES; + goto FreeExtraPciRoots; + } - UnicodeSPrint ( - VariableName, - sizeof (VariableName), - L"QemuBootOrder%04d", - VariableIndex++ - ); - DEBUG ((DEBUG_INFO, "%a: %s = %s\n", __FUNCTION__, VariableName, Translated)); - gRT->SetVariable ( - VariableName, - &gQemuBootOrderGuid, - EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, - GetDevicePathSize (DevicePath), - DevicePath - ); - FreePool (DevicePath); + UnicodeSPrint ( + VariableName, + sizeof (VariableName), + L"QemuBootOrder%04d", + VariableIndex++ + ); + DEBUG ((DEBUG_INFO, "%a: %s = %s\n", __FUNCTION__, VariableName, Translated)); + gRT->SetVariable ( + VariableName, + &gQemuBootOrderGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + GetDevicePathSize (DevicePath), + DevicePath + ); + FreePool (DevicePath); + } // // Move to the next OFW devpath. From c0f6bbafd70ce2ee5c26818e20329e1291a6af13 Mon Sep 17 00:00:00 2001 From: Rodrigo Gonzalez Del Cueto Date: Thu, 22 Sep 2022 15:35:36 +0800 Subject: [PATCH 0080/1529] SecurityPkg: Remove enforcement of final GoIdle transition for CRB commands REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4077 Following the design described in the TCG specification, the driver implementation of the CRB protocol does not require enforcing completing the transition to goIdle at the end of a command sequence. Signed-off-by: Rodrigo Gonzalez Del Cueto Cc: Jiewen Yao Cc: Jian J Wang Reviewed-by: Jian J Wang --- SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2Ptp.c | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2Ptp.c b/SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2Ptp.c index 840265292a..1f9ac5ab5a 100644 --- a/SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2Ptp.c +++ b/SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2Ptp.c @@ -381,19 +381,6 @@ PtpCrbTpmCommand ( // MmioWrite32 ((UINTN)&CrbReg->CrbControlRequest, PTP_CRB_CONTROL_AREA_REQUEST_GO_IDLE); - // - // Only enforce Idle state transition if execution fails when CRBIdleBypass==1 - // Leave regular Idle delay at the beginning of next command execution - // - if (GetCachedIdleByPass () == 1) { - Status = PtpCrbWaitRegisterBits ( - &CrbReg->CrbControlStatus, - PTP_CRB_CONTROL_AREA_STATUS_TPM_IDLE, - 0, - PTP_TIMEOUT_C - ); - } - return Status; } From 6904ff816b05bb0333bd7dee5be73ed994476782 Mon Sep 17 00:00:00 2001 From: "Jeff Brasen via groups.io" Date: Mon, 14 Feb 2022 18:45:31 +0000 Subject: [PATCH 0081/1529] MdeModulePkg/NonDiscoverablePciDeviceDxe: Allow partial FreeBuffer Add support for partial free of non cached buffers. If a request for less than the full size is requested new allocations for the remaining head and tail of the buffer are added to the list. Added verification that Buffer is EFI_PAGE_SIZE aligned. The XHCI driver does this if the page size for the controller is >4KB. Signed-off-by: Jeff Brasen Acked-by: Liming Gao --- .../NonDiscoverablePciDeviceIo.c | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c index c1c5c6267c..2fb78d8f96 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c @@ -960,13 +960,25 @@ NonCoherentPciIoFreeBuffer ( LIST_ENTRY *Entry; EFI_STATUS Status; NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *Alloc; + NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *AllocHead; + NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *AllocTail; BOOLEAN Found; + UINTN StartPages; + UINTN EndPages; + + if (HostAddress != ALIGN_POINTER (HostAddress, EFI_PAGE_SIZE)) { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Found = FALSE; Alloc = NULL; + AllocHead = NULL; + AllocTail = NULL; + // // Find the uncached allocation list entry associated // with this allocation @@ -976,9 +988,19 @@ NonCoherentPciIoFreeBuffer ( Entry = Entry->ForwardLink) { Alloc = BASE_CR (Entry, NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION, List); - if ((Alloc->HostAddress == HostAddress) && (Alloc->NumPages == Pages)) { + + StartPages = 0; + if (Alloc->HostAddress < HostAddress) { + StartPages = EFI_SIZE_TO_PAGES ( + (UINTN)HostAddress - (UINTN)Alloc->HostAddress + ); + } + + if ((Alloc->HostAddress <= HostAddress) && + (Alloc->NumPages >= (Pages + StartPages))) + { // - // We are freeing the exact allocation we were given + // We are freeing at least part of what we were given // before by AllocateBuffer() // Found = TRUE; @@ -991,7 +1013,45 @@ NonCoherentPciIoFreeBuffer ( return EFI_NOT_FOUND; } + EndPages = Alloc->NumPages - (Pages + StartPages); + + if (StartPages != 0) { + AllocHead = AllocatePool (sizeof *AllocHead); + if (AllocHead == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + AllocHead->HostAddress = Alloc->HostAddress; + + AllocHead->NumPages = StartPages; + AllocHead->Attributes = Alloc->Attributes; + } + + if (EndPages != 0) { + AllocTail = AllocatePool (sizeof *AllocTail); + if (AllocTail == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + AllocTail->HostAddress = (UINT8 *)Alloc->HostAddress + + EFI_PAGES_TO_SIZE (Pages + StartPages); + + AllocTail->NumPages = EndPages; + AllocTail->Attributes = Alloc->Attributes; + } + RemoveEntryList (&Alloc->List); + // + // Record this new sub allocations in the linked list, so we + // can restore the memory space attributes later + // + if (AllocHead != NULL) { + InsertHeadList (&Dev->UncachedAllocationList, &AllocHead->List); + } + + if (AllocTail != NULL) { + InsertHeadList (&Dev->UncachedAllocationList, &AllocTail->List); + } Status = gDS->SetMemorySpaceAttributes ( (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, From 625af3cfce9346ee70bd654da83b243b38a34443 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 19 Jul 2022 21:44:35 +0800 Subject: [PATCH 0082/1529] BaseTools/VolInfo: Correct buffer for GenCrc32 tool If the guided section was encoded with GenCrc32 tool the resulting 'EFI_GUID_DEFINED_SECTION.DataOffset' field points to the start of the meaningfull data that follows the CRC32 value. But if we want to decode the section with GenCrc32 tool we need to provide a buffer that includes the CRC32 value itself. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/VolInfo/VolInfo.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index 135924e028..184d753ba4 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -2009,6 +2009,13 @@ Routine Description: ); free (ExtractionTool); + if (!CompareGuid ( + EfiGuid, + &gEfiCrc32GuidedSectionExtractionProtocolGuid + ) + ) { + DataOffset -= 4; + } Status = PutFileImage ( ToolInputFile, From 0ef2fc6207194c568aeaf2d3c4ecbf801fc33430 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 30 Aug 2022 18:14:40 +0800 Subject: [PATCH 0083/1529] BaseTools/VolInfo: Fix EFI_SECTION_GUID_DEFINED parsing Currently 'PutFileImage' function is called with arguments that are not advanced on each section parsing. This would lead to an error if EFI_SECTION_GUID_DEFINED is not the first in a file. The same mistake is present in the parsing of CRC32 guided section case. Use correct arguments to fix the issue. Signed-off-by: Konstantin Aladyshev Reviewed-by: Bob Feng Reviewed-by: Liming Gao --- BaseTools/Source/C/VolInfo/VolInfo.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index 184d753ba4..4628e756d7 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -2019,8 +2019,8 @@ Routine Description: Status = PutFileImage ( ToolInputFile, - (CHAR8*) SectionBuffer + DataOffset, - BufferLength - DataOffset + (CHAR8*)Ptr + DataOffset, + SectionLength - DataOffset ); system (SystemCommand); @@ -2065,8 +2065,8 @@ Routine Description: // printf ("/------------ Encapsulation section start -----------------\\\n"); Status = ParseSection ( - SectionBuffer + DataOffset, - BufferLength - DataOffset + Ptr + DataOffset, + SectionLength - DataOffset ); if (EFI_ERROR (Status)) { Error (NULL, 0, 0003, "parse of CRC32 GUIDED section failed", NULL); From 664a7e4169d9cf6c762a5bbed9f69f9b05b98442 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Thu, 21 Jul 2022 21:11:48 +0800 Subject: [PATCH 0084/1529] BaseTools/VolInfo: Increase GUID base name string The current string lenght (=60) is not enough for cases where basename is a path to Build folder. Drop custom define and use MAX_LINE_LEN from the BaseTools codebase instead. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/VolInfo/VolInfo.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index 4628e756d7..d9be3d8c18 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -51,15 +51,13 @@ EFI_GUID gEfiCrc32GuidedSectionExtractionProtocolGuid = EFI_CRC32_GUIDED_SECTIO #define EFI_SECTION_ERROR EFIERR (100) -#define MAX_BASENAME_LEN 60 // not good to hardcode, but let's be reasonable - // // Structure to keep a list of guid-to-basenames // typedef struct _GUID_TO_BASENAME { struct _GUID_TO_BASENAME *Next; INT8 Guid[PRINTED_GUID_BUFFER_SIZE]; - INT8 BaseName[MAX_BASENAME_LEN]; + INT8 BaseName[MAX_LINE_LEN]; } GUID_TO_BASENAME; static GUID_TO_BASENAME *mGuidBaseNameList = NULL; From 54abbba7c5738f14630c6dbc55f21013420c1acd Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Fri, 22 Jul 2022 23:37:30 +0800 Subject: [PATCH 0085/1529] BaseTools/VolInfo: Parse apriori files Output file GUIDs from the DXE and PEI apriori files. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/VolInfo/VolInfo.c | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index d9be3d8c18..8da4d5e713 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -43,6 +43,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // EFI_GUID gEfiCrc32GuidedSectionExtractionProtocolGuid = EFI_CRC32_GUIDED_SECTION_EXTRACTION_PROTOCOL_GUID; +EFI_GUID gPeiAprioriFileNameGuid = { 0x1b45cc0a, 0x156a, 0x428a, { 0XAF, 0x62, 0x49, 0x86, 0x4d, 0xa0, 0xe6, 0xe6 }}; +EFI_GUID gAprioriGuid = { 0xFC510EE7, 0xFFDC, 0x11D4, { 0xBD, 0x41, 0x00, 0x80, 0xC7, 0x3C, 0x88, 0x81 }}; #define UTILITY_MAJOR_VERSION 1 #define UTILITY_MINOR_VERSION 0 @@ -107,6 +109,12 @@ ReadHeader ( OUT BOOLEAN *ErasePolarity ); +STATIC +EFI_STATUS +PrintAprioriFile ( + EFI_FFS_FILE_HEADER *FileHeader + ); + STATIC EFI_STATUS PrintFileInfo ( @@ -1083,6 +1091,53 @@ Routine Description: return EFI_SUCCESS; } +STATIC +EFI_STATUS +PrintAprioriFile ( + EFI_FFS_FILE_HEADER *FileHeader + ) +/*++ + +Routine Description: + + Print GUIDs from the APRIORI file + +Arguments: + + FileHeader - The file header + +Returns: + + EFI_SUCCESS - The APRIORI file was parsed correctly + EFI_SECTION_ERROR - Problem with file parsing + +--*/ +{ + UINT8 GuidBuffer[PRINTED_GUID_BUFFER_SIZE]; + UINT32 HeaderSize; + + HeaderSize = FvBufGetFfsHeaderSize (FileHeader); + + if (FileHeader->Type != EFI_FV_FILETYPE_FREEFORM) + return EFI_SECTION_ERROR; + + EFI_COMMON_SECTION_HEADER* SectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINTN) FileHeader + HeaderSize); + if (SectionHeader->Type != EFI_SECTION_RAW) + return EFI_SECTION_ERROR; + + UINT32 SectionLength = GetSectionFileLength (SectionHeader); + EFI_GUID* FileName = (EFI_GUID *) ((UINT8 *) SectionHeader + sizeof (EFI_COMMON_SECTION_HEADER)); + while (((UINT8 *) FileName) < ((UINT8 *) SectionHeader + SectionLength)) { + PrintGuidToBuffer (FileName, GuidBuffer, sizeof (GuidBuffer), TRUE); + printf ("%s ", GuidBuffer); + PrintGuidName (GuidBuffer); + printf ("\n"); + FileName++; + } + + return EFI_SUCCESS; +} + STATIC EFI_STATUS PrintFileInfo ( @@ -1339,6 +1394,25 @@ Routine Description: break; } + if (!CompareGuid ( + &FileHeader->Name, + &gPeiAprioriFileNameGuid + )) + { + printf("\n"); + printf("PEI APRIORI FILE:\n"); + return PrintAprioriFile (FileHeader); + } + if (!CompareGuid ( + &FileHeader->Name, + &gAprioriGuid + )) + { + printf("\n"); + printf("DXE APRIORI FILE:\n"); + return PrintAprioriFile (FileHeader); + } + return EFI_SUCCESS; } From d1b07aa3000e549ab15f9aed649fb329d72e4d2c Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Sun, 24 Jul 2022 17:47:39 +0800 Subject: [PATCH 0086/1529] BaseTools/VolInfo: Update copyright information Add Konstantin Aladyshev to the copyright header. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/VolInfo/VolInfo.c | 1 + 1 file changed, 1 insertion(+) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index 8da4d5e713..ffc396e295 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -2,6 +2,7 @@ The tool dumps the contents of a firmware volume Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2022, Konstantin Aladyshev
SPDX-License-Identifier: BSD-2-Clause-Patent **/ From 138e0446eddbd575f1a86f4bc54976e36a0d54f6 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Fri, 22 Jul 2022 21:30:11 +0800 Subject: [PATCH 0087/1529] BaseTools/VolInfo: Update file and section type strings Change SMM to MM in naming according to the recent PI specifications. Remove trailing whitespaces in some strings. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/VolInfo/VolInfo.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/BaseTools/Source/C/VolInfo/VolInfo.c b/BaseTools/Source/C/VolInfo/VolInfo.c index ffc396e295..428011ca04 100644 --- a/BaseTools/Source/C/VolInfo/VolInfo.c +++ b/BaseTools/Source/C/VolInfo/VolInfo.c @@ -685,11 +685,11 @@ Routine Description: // // 0x17 // - "EFI_SECTION_FIRMWARE_VOLUME_IMAGE ", + "EFI_SECTION_FIRMWARE_VOLUME_IMAGE", // // 0x18 // - "EFI_SECTION_FREEFORM_SUBTYPE_GUID ", + "EFI_SECTION_FREEFORM_SUBTYPE_GUID", // // 0x19 // @@ -705,7 +705,7 @@ Routine Description: // // 0x1C // - "EFI_SECTION_SMM_DEPEX", + "EFI_SECTION_MM_DEPEX", // // 0x1C+ // @@ -1338,7 +1338,7 @@ Routine Description: break; case EFI_FV_FILETYPE_SMM: - printf ("EFI_FV_FILETYPE_SMM\n"); + printf ("EFI_FV_FILETYPE_MM\n"); break; case EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE: @@ -1346,11 +1346,11 @@ Routine Description: break; case EFI_FV_FILETYPE_COMBINED_SMM_DXE: - printf ("EFI_FV_FILETYPE_COMBINED_SMM_DXE\n"); + printf ("EFI_FV_FILETYPE_COMBINED_MM_DXE\n"); break; case EFI_FV_FILETYPE_SMM_CORE: - printf ("EFI_FV_FILETYPE_SMM_CORE\n"); + printf ("EFI_FV_FILETYPE_MM_CORE\n"); break; case EFI_FV_FILETYPE_MM_STANDALONE: From 382f0398d66a4f70008edb2b077631a4fbab2e59 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Sep 2022 20:52:36 -0400 Subject: [PATCH 0088/1529] EmbeddedPkg/AcpiLib: Fix code formatting errors REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4046 This package did not have CI enabled so code changes were merged that fail uncrustify formatting. This change updates those files to include uncustify formatting. Cc: Leif Lindholm Cc: Ard Biesheuvel Cc: Abner Chang Cc: Daniel Schaefer Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Acked-by: Ard Biesheuvel --- EmbeddedPkg/Include/Library/AcpiLib.h | 22 +++--- EmbeddedPkg/Library/AcpiLib/AcpiLib.c | 98 ++++++++++++++------------- 2 files changed, 61 insertions(+), 59 deletions(-) diff --git a/EmbeddedPkg/Include/Library/AcpiLib.h b/EmbeddedPkg/Include/Library/AcpiLib.h index 9dbacd85b0..29137a4a53 100644 --- a/EmbeddedPkg/Include/Library/AcpiLib.h +++ b/EmbeddedPkg/Include/Library/AcpiLib.h @@ -144,8 +144,8 @@ LocateAndInstallAcpiFromFv ( EFI_STATUS EFIAPI AcpiUpdateChecksum ( - IN OUT UINT8 *Buffer, - IN UINTN Size + IN OUT UINT8 *Buffer, + IN UINTN Size ); /** @@ -168,11 +168,11 @@ AcpiUpdateChecksum ( EFI_STATUS EFIAPI AcpiLocateTableBySignature ( - IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, - IN UINT32 TableSignature, - IN OUT UINTN *Index, - OUT EFI_ACPI_DESCRIPTION_HEADER **Table, - OUT UINTN *TableKey + IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, + IN UINT32 TableSignature, + IN OUT UINTN *Index, + OUT EFI_ACPI_DESCRIPTION_HEADER **Table, + OUT UINTN *TableKey ); /** @@ -193,10 +193,10 @@ AcpiLocateTableBySignature ( EFI_STATUS EFIAPI AcpiAmlObjectUpdateInteger ( - IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, - IN EFI_ACPI_HANDLE TableHandle, - IN CHAR8 *AsciiObjectPath, - IN UINTN Value + IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, + IN EFI_ACPI_HANDLE TableHandle, + IN CHAR8 *AsciiObjectPath, + IN UINTN Value ); #endif // __ACPI_LIB_H__ diff --git a/EmbeddedPkg/Library/AcpiLib/AcpiLib.c b/EmbeddedPkg/Library/AcpiLib/AcpiLib.c index ea2ad63b20..cb593a7b2a 100644 --- a/EmbeddedPkg/Library/AcpiLib/AcpiLib.c +++ b/EmbeddedPkg/Library/AcpiLib/AcpiLib.c @@ -192,13 +192,13 @@ LocateAndInstallAcpiFromFv ( EFI_STATUS EFIAPI AcpiUpdateChecksum ( - IN OUT UINT8 *Buffer, - IN UINTN Size + IN OUT UINT8 *Buffer, + IN UINTN Size ) { - UINTN ChecksumOffset; + UINTN ChecksumOffset; - if (Buffer == NULL || Size == 0) { + if ((Buffer == NULL) || (Size == 0)) { return EFI_INVALID_PARAMETER; } @@ -237,11 +237,11 @@ AcpiUpdateChecksum ( EFI_STATUS EFIAPI AcpiLocateTableBySignature ( - IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, - IN UINT32 TableSignature, - IN OUT UINTN *Index, - OUT EFI_ACPI_DESCRIPTION_HEADER **Table, - OUT UINTN *TableKey + IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, + IN UINT32 TableSignature, + IN OUT UINTN *Index, + OUT EFI_ACPI_DESCRIPTION_HEADER **Table, + OUT UINTN *TableKey ) { EFI_STATUS Status; @@ -249,9 +249,10 @@ AcpiLocateTableBySignature ( EFI_ACPI_TABLE_VERSION TableVersion; UINTN TableIndex; - if (AcpiSdtProtocol == NULL - || Table == NULL - || TableKey == NULL) { + if ( (AcpiSdtProtocol == NULL) + || (Table == NULL) + || (TableKey == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -261,7 +262,7 @@ AcpiLocateTableBySignature ( // Search for ACPI Table with matching signature // TableVersion = 0; - TableIndex = *Index; + TableIndex = *Index; while (!EFI_ERROR (Status)) { Status = AcpiSdtProtocol->GetAcpiTable ( TableIndex, @@ -301,26 +302,26 @@ AcpiLocateTableBySignature ( EFI_STATUS EFIAPI AcpiAmlObjectUpdateInteger ( - IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, - IN EFI_ACPI_HANDLE TableHandle, - IN CHAR8 *AsciiObjectPath, - IN UINTN Value + IN EFI_ACPI_SDT_PROTOCOL *AcpiSdtProtocol, + IN EFI_ACPI_HANDLE TableHandle, + IN CHAR8 *AsciiObjectPath, + IN UINTN Value ) { - EFI_STATUS Status; - EFI_ACPI_HANDLE ObjectHandle; - EFI_ACPI_HANDLE DataHandle; - EFI_ACPI_DATA_TYPE DataType; - UINT8 *Buffer; - UINTN BufferSize; - UINTN DataSize; - - if (AcpiSdtProtocol == NULL || AsciiObjectPath == NULL) { + EFI_STATUS Status; + EFI_ACPI_HANDLE ObjectHandle; + EFI_ACPI_HANDLE DataHandle; + EFI_ACPI_DATA_TYPE DataType; + UINT8 *Buffer; + UINTN BufferSize; + UINTN DataSize; + + if ((AcpiSdtProtocol == NULL) || (AsciiObjectPath == NULL)) { return EFI_INVALID_PARAMETER; } ObjectHandle = NULL; - DataHandle = NULL; + DataHandle = NULL; Status = AcpiSdtProtocol->FindPath (TableHandle, AsciiObjectPath, &ObjectHandle); if (EFI_ERROR (Status)) { @@ -332,6 +333,7 @@ AcpiAmlObjectUpdateInteger ( Status = EFI_NOT_FOUND; goto Exit; } + ASSERT (DataType == EFI_ACPI_DATA_TYPE_OPCODE); ASSERT (Buffer != NULL); @@ -350,7 +352,7 @@ AcpiAmlObjectUpdateInteger ( ASSERT (DataType == EFI_ACPI_DATA_TYPE_OPCODE); ASSERT (Buffer != NULL); - if (Buffer[0] == AML_ZERO_OP || Buffer[0] == AML_ONE_OP) { + if ((Buffer[0] == AML_ZERO_OP) || (Buffer[0] == AML_ONE_OP)) { Status = AcpiSdtProtocol->SetOption (DataHandle, 0, (VOID *)&Value, sizeof (UINT8)); ASSERT_EFI_ERROR (Status); } else { @@ -358,26 +360,26 @@ AcpiAmlObjectUpdateInteger ( // Check the size of data object // switch (Buffer[0]) { - case AML_BYTE_PREFIX: - DataSize = sizeof (UINT8); - break; - - case AML_WORD_PREFIX: - DataSize = sizeof (UINT16); - break; - - case AML_DWORD_PREFIX: - DataSize = sizeof (UINT32); - break; - - case AML_QWORD_PREFIX: - DataSize = sizeof (UINT64); - break; - - default: - // The data type of the ACPI object is not an integer - Status = EFI_INVALID_PARAMETER; - goto Exit; + case AML_BYTE_PREFIX: + DataSize = sizeof (UINT8); + break; + + case AML_WORD_PREFIX: + DataSize = sizeof (UINT16); + break; + + case AML_DWORD_PREFIX: + DataSize = sizeof (UINT32); + break; + + case AML_QWORD_PREFIX: + DataSize = sizeof (UINT64); + break; + + default: + // The data type of the ACPI object is not an integer + Status = EFI_INVALID_PARAMETER; + goto Exit; } Status = AcpiSdtProtocol->SetOption (DataHandle, 1, (VOID *)&Value, DataSize); From 6ee56e0e4d7fdfbde258d6b06332d0789882defc Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Sep 2022 20:56:28 -0400 Subject: [PATCH 0089/1529] EmbeddedPkg: Add CI YAML file REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4046 Adds EmbeddedPkg to the list of supported build packages for edk2 CI and fixes Library Class Check errors reported. These changes allow EmbeddedPkg to pass NO-TARGET CI testing. Cc: Leif Lindholm Cc: Ard Biesheuvel Cc: Abner Chang Cc: Daniel Schaefer Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Acked-by: Ard Biesheuvel --- .pytool/CISettings.py | 1 + EmbeddedPkg/EmbeddedPkg.ci.yaml | 89 +++++++++++++++++++++++++++++++++ EmbeddedPkg/EmbeddedPkg.dec | 8 +++ 3 files changed, 98 insertions(+) create mode 100644 EmbeddedPkg/EmbeddedPkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index cf9e0d77b1..aef850a545 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -53,6 +53,7 @@ def GetPackagesSupported(self): "ArmPlatformPkg", "ArmVirtPkg", "DynamicTablesPkg", + "EmbeddedPkg", "EmulatorPkg", "MdePkg", "MdeModulePkg", diff --git a/EmbeddedPkg/EmbeddedPkg.ci.yaml b/EmbeddedPkg/EmbeddedPkg.ci.yaml new file mode 100644 index 0000000000..21f30108a2 --- /dev/null +++ b/EmbeddedPkg/EmbeddedPkg.ci.yaml @@ -0,0 +1,89 @@ +## @file +# Core CI configuration for EmbeddedPkg +# +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined .pytool/Plugin/LicenseCheck + "LicenseCheck": { + "IgnoreFiles": [] + }, + + "EccCheck": { + ## Exception sample looks like below: + ## "ExceptionList": [ + ## "", "" + ## ] + "ExceptionList": [ + ], + ## Both file path and directory path are accepted. + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "EmbeddedPkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "ArmPkg/ArmPkg.dec", + "ArmPlatformPkg/ArmPlatformPkg.dec", + "EmbeddedPkg/EmbeddedPkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "MdePkg/MdePkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined .pytool/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [], + }, + + ## options defined .pytool/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined .pytool/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails right now with over 270 errors + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} diff --git a/EmbeddedPkg/EmbeddedPkg.dec b/EmbeddedPkg/EmbeddedPkg.dec index 637888e0fd..341ef5e6a6 100644 --- a/EmbeddedPkg/EmbeddedPkg.dec +++ b/EmbeddedPkg/EmbeddedPkg.dec @@ -36,6 +36,14 @@ GdbSerialLib|Include/Library/GdbSerialLib.h DebugAgentTimerLib|Include/Library/DebugAgentTimerLib.h NorFlashInfoLib|Include/Library/NorFlashInfoLib.h + HalRuntimeServicesLib|Include/Library/HalRuntimeServicesLib.h + PrePiHobListPointerLib|Include/Library/PrePiHobListPointerLib.h + TimeBaseLib|Include/Library/TimeBaseLib.h + AcpiLib|Include/Library/AcpiLib.h + AndroidBootImgLib|Include/Library/AndroidBootImgLib.h + DmaLib|Include/Library/DmaLib.h + EfiFileLib|Include/Library/EfiFileLib.h + FdtLoadLib|Include/Library/FdtLoadLib.h DtPlatformDtbLoaderLib|Include/Library/DtPlatformDtbLoaderLib.h From 4b0f0abae19f56cf3635957b46858c47cee05c75 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 18:48:10 -0400 Subject: [PATCH 0090/1529] EmbeddedPkg: Only run in CI for GCC5 REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4046 This package currently does not build on non-GCC toolchains. This change adds the package to edk2 CI so it can benefit from ongoing CI and only tests the package against GCC. Cc: Leif Lindholm Cc: Ard Biesheuvel Cc: Abner Chang Cc: Daniel Schaefer Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Acked-by: Ard Biesheuvel --- .azurepipelines/templates/pr-gate-build-job.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 0e4ad019bf..54a74a1a98 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -21,6 +21,10 @@ jobs: #Use matrix to speed up the build process strategy: matrix: + ${{ if eq(parameters.tool_chain_tag, 'GCC5') }}: + TARGET_GCC_ONLY: + Build.Pkgs: 'EmbeddedPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_ARM_ARMPLATFORM: Build.Pkgs: 'ArmPkg,ArmPlatformPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' From e40aaf5b102b4f3d7f75a12fc7fd1e3072a93421 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 13:45:01 -0400 Subject: [PATCH 0091/1529] IntelFsp2Pkg: Fix code formatting errors REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 This package did not have CI enabled so code changes were merged that fail uncrustify formatting. This change updates those files to include uncustify formatting. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Chasel Chiu Reviewed-by: Michael D Kinney --- IntelFsp2Pkg/Include/Ppi/Variable.h | 8 ++++---- .../Library/BaseFspDebugLibSerialPort/DebugLib.c | 9 +++++---- .../Library/BaseFspSwitchStackLib/FspSwitchStackLib.c | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/IntelFsp2Pkg/Include/Ppi/Variable.h b/IntelFsp2Pkg/Include/Ppi/Variable.h index 3e1f4b98a9..581f148808 100644 --- a/IntelFsp2Pkg/Include/Ppi/Variable.h +++ b/IntelFsp2Pkg/Include/Ppi/Variable.h @@ -184,10 +184,10 @@ EFI_STATUS /// to store data in the PEI environment. /// struct _EDKII_PEI_VARIABLE_PPI { - EDKII_PEI_GET_VARIABLE GetVariable; - EDKII_PEI_GET_NEXT_VARIABLE_NAME GetNextVariableName; - EDKII_PEI_SET_VARIABLE SetVariable; - EDKII_PEI_QUERY_VARIABLE_INFO QueryVariableInfo; + EDKII_PEI_GET_VARIABLE GetVariable; + EDKII_PEI_GET_NEXT_VARIABLE_NAME GetNextVariableName; + EDKII_PEI_SET_VARIABLE SetVariable; + EDKII_PEI_QUERY_VARIABLE_INFO QueryVariableInfo; }; extern EFI_GUID gEdkiiPeiVariablePpiGuid; diff --git a/IntelFsp2Pkg/Library/BaseFspDebugLibSerialPort/DebugLib.c b/IntelFsp2Pkg/Library/BaseFspDebugLibSerialPort/DebugLib.c index cb2317bfb2..8e24b946cd 100644 --- a/IntelFsp2Pkg/Library/BaseFspDebugLibSerialPort/DebugLib.c +++ b/IntelFsp2Pkg/Library/BaseFspDebugLibSerialPort/DebugLib.c @@ -193,8 +193,8 @@ DebugBPrint ( **/ VOID FillHex ( - UINTN Value, - CHAR8 *Buffer + UINTN Value, + CHAR8 *Buffer ) { INTN Idx; @@ -227,8 +227,8 @@ DebugAssertInternal ( VOID ) { - CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; - UINTN *Frame; + CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; + UINTN *Frame; Frame = (UINTN *)GetStackFramePointer (); @@ -250,6 +250,7 @@ DebugAssertInternal ( sizeof (Buffer) / sizeof (CHAR8) - 1 ); } + SerialPortWrite ((UINT8 *)"ASSERT DUMP:\n", 13); while (Frame != NULL) { FillHex ((UINTN)Frame, Buffer + 9); diff --git a/IntelFsp2Pkg/Library/BaseFspSwitchStackLib/FspSwitchStackLib.c b/IntelFsp2Pkg/Library/BaseFspSwitchStackLib/FspSwitchStackLib.c index 69a021f42b..a0b2193bde 100644 --- a/IntelFsp2Pkg/Library/BaseFspSwitchStackLib/FspSwitchStackLib.c +++ b/IntelFsp2Pkg/Library/BaseFspSwitchStackLib/FspSwitchStackLib.c @@ -31,6 +31,6 @@ SwapStack ( FspData = GetFspGlobalDataPointer (); OldStack = FspData->CoreStack; - FspData->CoreStack = (UINTN) NewStack; + FspData->CoreStack = (UINTN)NewStack; return OldStack; } From 051dc07996d792f6e9c916bb5a2ea05161438e9b Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 13:47:21 -0400 Subject: [PATCH 0092/1529] IntelFsp2Pkg/BaseFspMultiPhaseLib: Replace duplicate GUID REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 The FILE_GUID for this library instance file is a duplicate of Library/SecFspSecPlatformLibNull/SecFspSecPlatformLibNull.inf. This change replaces the duplicated GUID value with a unique GUID. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Chasel Chiu Reviewed-by: Michael D Kinney --- .../Library/BaseFspMultiPhaseLib/BaseFspMultiPhaseLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/IntelFsp2Pkg/Library/BaseFspMultiPhaseLib/BaseFspMultiPhaseLib.inf b/IntelFsp2Pkg/Library/BaseFspMultiPhaseLib/BaseFspMultiPhaseLib.inf index a79f6aecda..b9dd132ea8 100644 --- a/IntelFsp2Pkg/Library/BaseFspMultiPhaseLib/BaseFspMultiPhaseLib.inf +++ b/IntelFsp2Pkg/Library/BaseFspMultiPhaseLib/BaseFspMultiPhaseLib.inf @@ -15,7 +15,7 @@ [Defines] INF_VERSION = 0x00010005 BASE_NAME = BaseFspMultiPhaseLib - FILE_GUID = C128CADC-623E-4E41-97CB-A7138E627460 + FILE_GUID = 74C14477-E742-4A0A-9787-27B1CF34F698 MODULE_TYPE = SEC VERSION_STRING = 1.0 LIBRARY_CLASS = FspMultiPhaseLib From 28e9e8eb24a29ee96ed628e70b33d26cffb31b75 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 15:46:08 -0400 Subject: [PATCH 0093/1529] IntelFsp2Pkg: Add CI YAML file REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 Adds IntelFsp2Pkg to the list of supported build packages for edk2 CI and defines an initial set of CI configuration options. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 1 + IntelFsp2Pkg/IntelFsp2Pkg.ci.yaml | 90 +++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 IntelFsp2Pkg/IntelFsp2Pkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index aef850a545..dc3506769f 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -55,6 +55,7 @@ def GetPackagesSupported(self): "DynamicTablesPkg", "EmbeddedPkg", "EmulatorPkg", + "IntelFsp2Pkg", "MdePkg", "MdeModulePkg", "NetworkPkg", diff --git a/IntelFsp2Pkg/IntelFsp2Pkg.ci.yaml b/IntelFsp2Pkg/IntelFsp2Pkg.ci.yaml new file mode 100644 index 0000000000..95d18cfcde --- /dev/null +++ b/IntelFsp2Pkg/IntelFsp2Pkg.ci.yaml @@ -0,0 +1,90 @@ +## @file +# Core CI configuration for IntelFsp2Pkg +# +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined .pytool/Plugin/LicenseCheck + "LicenseCheck": { + "IgnoreFiles": [] + }, + + "EccCheck": { + ## Exception sample looks like below: + ## "ExceptionList": [ + ## "", "" + ## ] + "ExceptionList": [ + ], + ## Both file path and directory path are accepted. + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "IntelFsp2Pkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "IntelFsp2Pkg/IntelFsp2Pkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "MdePkg/MdePkg.dec", + "UefiCpuPkg/UefiCpuPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined .pytool/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "IntelFsp2Pkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [], + }, + + ## options defined .pytool/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined .pytool/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails right now + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From a989318619e1aed4e6c129ed74521f7ed8c5d137 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 15:52:39 -0400 Subject: [PATCH 0094/1529] IntelFsp2WrapperPkg: Fix code formatting errors REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 This package did not have CI enabled so code changes were merged that fail uncrustify formatting. This change updates those files to include uncustify formatting. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Chasel Chiu Reviewed-by: Michael D Kinney --- .../Library/BaseFspWrapperApiLib/FspWrapperApiLib.c | 4 ++++ .../Library/BaseFspWrapperApiLib/IA32/DispatchExecute.c | 1 - .../SecFspWrapperPlatformSecLibSample/SecRamInitData.c | 8 ++++---- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/FspWrapperApiLib.c b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/FspWrapperApiLib.c index 5b5beb5c65..2e82a0c1b5 100644 --- a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/FspWrapperApiLib.c +++ b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/FspWrapperApiLib.c @@ -115,6 +115,7 @@ CallFspNotifyPhase ( } else { Status = Execute64BitCode ((UINTN)NotifyPhaseApi, (UINTN)NotifyPhaseParams, (UINTN)NULL); } + SetInterruptState (InterruptState); return Status; @@ -152,6 +153,7 @@ CallFspMemoryInit ( } else { Status = Execute64BitCode ((UINTN)FspMemoryInitApi, (UINTN)FspmUpdDataPtr, (UINTN)HobListPtr); } + SetInterruptState (InterruptState); return Status; @@ -187,6 +189,7 @@ CallTempRamExit ( } else { Status = Execute64BitCode ((UINTN)TempRamExitApi, (UINTN)TempRamExitParam, (UINTN)NULL); } + SetInterruptState (InterruptState); return Status; @@ -222,6 +225,7 @@ CallFspSiliconInit ( } else { Status = Execute64BitCode ((UINTN)FspSiliconInitApi, (UINTN)FspsUpdDataPtr, (UINTN)NULL); } + SetInterruptState (InterruptState); return Status; diff --git a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/IA32/DispatchExecute.c b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/IA32/DispatchExecute.c index a17ca7dcab..c8248eb888 100644 --- a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/IA32/DispatchExecute.c +++ b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/IA32/DispatchExecute.c @@ -69,4 +69,3 @@ Execute64BitCode ( { return EFI_UNSUPPORTED; } - diff --git a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/SecRamInitData.c b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/SecRamInitData.c index d2acb2fd46..fb0d9a8683 100644 --- a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/SecRamInitData.c +++ b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/SecRamInitData.c @@ -10,10 +10,10 @@ #include typedef struct { - EFI_PHYSICAL_ADDRESS MicrocodeRegionBase; - UINT64 MicrocodeRegionSize; - EFI_PHYSICAL_ADDRESS CodeRegionBase; - UINT64 CodeRegionSize; + EFI_PHYSICAL_ADDRESS MicrocodeRegionBase; + UINT64 MicrocodeRegionSize; + EFI_PHYSICAL_ADDRESS CodeRegionBase; + UINT64 CodeRegionSize; } FSPT_CORE_UPD; typedef struct { From 24d5871dc34181537c6d3fa62840503fe33fdc86 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 17:18:28 -0400 Subject: [PATCH 0095/1529] IntelFsp2WrapperPkg: Add CI YAML file REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 Adds IntelFsp2WrapperPkg to the list of supported build packages for edk2 CI and defines an initial set of CI configuration options. Adds a special case for the Library Class check CI plugin to ignore FspWrapperPlatformMultiPhaseLib with an explanatory comment. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 1 + .../IntelFsp2WrapperPkg.ci.yaml | 96 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index dc3506769f..76769b5329 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -56,6 +56,7 @@ def GetPackagesSupported(self): "EmbeddedPkg", "EmulatorPkg", "IntelFsp2Pkg", + "IntelFsp2WrapperPkg", "MdePkg", "MdeModulePkg", "NetworkPkg", diff --git a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml new file mode 100644 index 0000000000..6788a723a1 --- /dev/null +++ b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml @@ -0,0 +1,96 @@ +## @file +# Core CI configuration for IntelFsp2WrapperPkg +# +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined .pytool/Plugin/LicenseCheck + "LicenseCheck": { + "IgnoreFiles": [] + }, + + "EccCheck": { + ## Exception sample looks like below: + ## "ExceptionList": [ + ## "", "" + ## ] + "ExceptionList": [ + ], + ## Both file path and directory path are accepted. + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "IntelFsp2WrapperPkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "IntelFsp2Pkg/IntelFsp2Pkg.dec", + "IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "MdePkg/MdePkg.dec", + "SecurityPkg/SecurityPkg.dec", + "UefiCpuPkg/UefiCpuPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined .pytool/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "IntelFsp2WrapperPkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [], + }, + + ## options defined .pytool/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreLibraryClass": [ + # This header file contains a small function in a separate library so platforms + # do not have to override the whole main library instance. + "FspWrapperPlatformMultiPhaseLib" + ] + }, + + ## options defined .pytool/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails right now + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 370f182c32fdf63bcdac6fab3b3106014ac7c0d7 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 6 Sep 2022 17:19:17 -0400 Subject: [PATCH 0096/1529] .azurepipelines: Add IntelFsp2Pkg and IntelFsp2WrapperPkg to CI REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4048 Adds these packages to a new edk2 matrix job so they can be validated in edk2 CI. Cc: Bret Barkelew Cc: Chasel Chiu Cc: Liming Gao Cc: Michael D Kinney Cc: Nate DeSimone Cc: Sean Brogan Cc: Star Zeng Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .azurepipelines/templates/pr-gate-build-job.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 54a74a1a98..fe344e0b3c 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -49,6 +49,9 @@ jobs: TARGET_CRYPTO: Build.Pkgs: 'CryptoPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' + TARGET_FSP: + Build.Pkgs: 'IntelFsp2Pkg,IntelFsp2WrapperPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_SECURITY: Build.Pkgs: 'SecurityPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' From 0342fa1abf13320e47e8ec1ea134fa4ae7c5dbf4 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 1 Sep 2022 14:51:45 -0400 Subject: [PATCH 0097/1529] SignedCapsulePkg: Add package CI YAML file REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4050 Adds the package as a supported package to .pytool/CISettings.py and adds a CI YAML for the package so it can be run in CI. Cc: Jian J Wang Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 1 + SignedCapsulePkg/SignedCapsulePkg.ci.yaml | 90 +++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 SignedCapsulePkg/SignedCapsulePkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 76769b5329..f72e327787 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -65,6 +65,7 @@ def GetPackagesSupported(self): "UefiCpuPkg", "FmpDevicePkg", "ShellPkg", + "SignedCapsulePkg", "StandaloneMmPkg", "FatPkg", "CryptoPkg", diff --git a/SignedCapsulePkg/SignedCapsulePkg.ci.yaml b/SignedCapsulePkg/SignedCapsulePkg.ci.yaml new file mode 100644 index 0000000000..5f48613bd7 --- /dev/null +++ b/SignedCapsulePkg/SignedCapsulePkg.ci.yaml @@ -0,0 +1,90 @@ +## @file +# Core CI configuration for SignedCapsulePkg +# +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined .pytool/Plugin/LicenseCheck + "LicenseCheck": { + "IgnoreFiles": [] + }, + + "EccCheck": { + ## Exception sample looks like below: + ## "ExceptionList": [ + ## "", "" + ## ] + "ExceptionList": [ + ], + ## Both file path and directory path are accepted. + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "SignedCapsulePkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "MdeModulePkg/MdeModulePkg.dec", + "MdePkg/MdePkg.dec", + "SecurityPkg/SecurityPkg.dec", + "SignedCapsulePkg/SignedCapsulePkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined .pytool/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "SignedCapsulePkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [], + }, + + ## options defined .pytool/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined .pytool/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Failures need to be reviewed and resolved in the future + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From bf5d56953c2c26886096a42994290bdba15d9ba0 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 1 Sep 2022 14:54:12 -0400 Subject: [PATCH 0098/1529] .azurepipelines: Add SignedCapsulePkg to CI REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4050 Adds SignedCapsulePkg to the "OTHER" CI matrix job so it is built in edk2 CI. Cc: Sean Brogan Cc: Bret Barkelew Cc: Michael D Kinney Cc: Liming Gao Cc: Jian J Wang Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .azurepipelines/templates/pr-gate-build-job.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index fe344e0b3c..c3c849c3dc 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -41,7 +41,7 @@ jobs: Build.Pkgs: 'NetworkPkg,RedfishPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_OTHER: - Build.Pkgs: 'PcAtChipsetPkg,PrmPkg,ShellPkg,StandaloneMmPkg' + Build.Pkgs: 'PcAtChipsetPkg,PrmPkg,ShellPkg,StandaloneMmPkg,SignedCapsulePkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_FMP_FAT_TEST: Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestFrameworkPkg,DynamicTablesPkg' From 5be076b3a9c5bace8569f3bd2081405a3bb85ad8 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Tue, 4 Oct 2022 13:10:14 -0700 Subject: [PATCH 0099/1529] IntelFsp2WrapperPkg: Add header for PlatformMultiPhaseLib. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4092 To comply with coding style rule each library class should have its own header even if it is just a private child library instance consumed by parent public library in the same package. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- .../Library/FspWrapperMultiPhaseProcessLib.h | 18 ----------- .../Library/FspWrapperPlatformMultiPhaseLib.h | 30 +++++++++++++++++++ IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec | 2 +- .../PeiFspWrapperMultiPhaseProcessLib.c | 2 +- 4 files changed, 32 insertions(+), 20 deletions(-) create mode 100644 IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformMultiPhaseLib.h diff --git a/IntelFsp2WrapperPkg/Include/Library/FspWrapperMultiPhaseProcessLib.h b/IntelFsp2WrapperPkg/Include/Library/FspWrapperMultiPhaseProcessLib.h index 65a5db233f..aadacc9b50 100644 --- a/IntelFsp2WrapperPkg/Include/Library/FspWrapperMultiPhaseProcessLib.h +++ b/IntelFsp2WrapperPkg/Include/Library/FspWrapperMultiPhaseProcessLib.h @@ -9,24 +9,6 @@ #ifndef __FSP_WRAPPER_MULTI_PHASE_PROCESS_LIB_H__ #define __FSP_WRAPPER_MULTI_PHASE_PROCESS_LIB_H__ -/** - FSP Wrapper Platform MultiPhase Handler - - @param[in] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) - @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. - @param[in] PhaseIndex - Indicates current execution phase of FSP MultiPhase initialization. - - @retval EFI_STATUS Always return EFI_SUCCESS - -**/ -VOID -EFIAPI -FspWrapperPlatformMultiPhaseHandler ( - IN OUT VOID **FspHobListPtr, - IN UINT8 ComponentIndex, - IN UINT32 PhaseIndex - ); - /** FSP Wrapper Variable Request Handler diff --git a/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformMultiPhaseLib.h b/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformMultiPhaseLib.h new file mode 100644 index 0000000000..272b0e3911 --- /dev/null +++ b/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformMultiPhaseLib.h @@ -0,0 +1,30 @@ +/** @file + Provide FSP wrapper Platform MultiPhase handling functions. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef FSP_WRAPPER_PLATFORM_MULTI_PHASE_LIB_H_ +#define FSP_WRAPPER_PLATFORM_MULTI_PHASE_LIB_H_ + +/** + FSP Wrapper Platform MultiPhase Handler + + @param[in] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) + @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. + @param[in] PhaseIndex - Indicates current execution phase of FSP MultiPhase initialization. + + @retval EFI_STATUS Always return EFI_SUCCESS + +**/ +VOID +EFIAPI +FspWrapperPlatformMultiPhaseHandler ( + IN OUT VOID **FspHobListPtr, + IN UINT8 ComponentIndex, + IN UINT32 PhaseIndex + ); + +#endif //FSP_WRAPPER_PLATFORM_MULTI_PHASE_LIB_H_ diff --git a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec index 95ada0f7a1..922ccc063f 100644 --- a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec +++ b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dec @@ -33,7 +33,7 @@ FspWrapperMultiPhaseProcessLib|Include/Library/FspWrapperMultiPhaseProcessLib.h ## @libraryclass Provide MultiPhase platform actions related functions. - FspWrapperPlatformMultiPhaseLib|Include/Library/FspWrapperMultiPhaseProcessLib.h + FspWrapperPlatformMultiPhaseLib|Include/Library/FspWrapperPlatformMultiPhaseLib.h [Guids] diff --git a/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c b/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c index 3ddc07690a..1248accf87 100644 --- a/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c +++ b/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c @@ -16,7 +16,7 @@ #include #include #include -#include +#include /** Execute 32-bit FSP API entry code. From 49434f223f0a2e6db3c8ce63eb65df5cc8bf57bc Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Tue, 4 Oct 2022 18:04:40 -0700 Subject: [PATCH 0100/1529] IntelFsp2WrapperPkg: Remove CI exception of PlatformMultiPhaseLib. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4092 Duplicate library class header issue will be resolved and CI exception for FspWrapperPlatformMultiPhaseLib should be removed too. Cc: Nate DeSimone Cc: Star Zeng Cc: Michael Kubacki Signed-off-by: Chasel Chiu Reviewed-by: Michael Kubacki --- IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml index 6788a723a1..45cb5a7d6f 100644 --- a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml +++ b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.ci.yaml @@ -78,11 +78,7 @@ ## options defined .pytool/Plugin/LibraryClassCheck "LibraryClassCheck": { - "IgnoreLibraryClass": [ - # This header file contains a small function in a separate library so platforms - # do not have to override the whole main library instance. - "FspWrapperPlatformMultiPhaseLib" - ] + "IgnoreLibraryClass": [] }, ## options defined .pytool/Plugin/SpellCheck From 7151334d83ead551a4a7ff0d4f167a547982dca4 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 4 Oct 2022 10:55:27 -0400 Subject: [PATCH 0101/1529] SourceLevelDebugPkg: Fix spelling errors REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4091 Fixes spelling errors in the package so the SpellCheck CI plugin can be enabled. Cc: Hao A Wu Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Hao A Wu Reviewed-by: Michael D Kinney --- .../Include/Library/DebugCommunicationLib.h | 2 +- .../DebugAgent/DebugAgentCommon/DebugAgent.c | 8 +++---- .../DebugAgent/DebugAgentCommon/DebugAgent.h | 2 +- .../DebugAgent/DxeDebugAgent/SerialIo.c | 22 +++++++++---------- .../DebugCommunicationLibSerialPort.c | 2 +- .../DebugCommunicationLibUsb.c | 2 +- .../DebugCommunicationLibUsb3Internal.h | 2 +- .../Ia32/IntHandlerFuncs.c | 2 +- .../PeCoffExtraActionLib.h | 2 +- .../X64/IntHandlerFuncs.c | 2 +- 10 files changed, 23 insertions(+), 23 deletions(-) diff --git a/SourceLevelDebugPkg/Include/Library/DebugCommunicationLib.h b/SourceLevelDebugPkg/Include/Library/DebugCommunicationLib.h index ad7bccda28..ebb2168632 100644 --- a/SourceLevelDebugPkg/Include/Library/DebugCommunicationLib.h +++ b/SourceLevelDebugPkg/Include/Library/DebugCommunicationLib.h @@ -71,7 +71,7 @@ DebugPortInitialize ( ); /** - Read data from debug device and save the datas in buffer. + Read data from debug device and save the data in a buffer. Reads NumberOfBytes data bytes from a debug device into the buffer specified by Buffer. The number of bytes actually read is returned. diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c index a1e61a6ef9..b553a2a9aa 100644 --- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c +++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c @@ -1,5 +1,5 @@ /** @file - Commond Debug Agent library implementation. It mainly includes + Common Debug Agent library implementation. It mainly includes the first C function called by exception/interrupt handlers, read/write debug packet to communication with HOST based on transfer protocol. @@ -608,7 +608,7 @@ DebugAgentDataMsgPrint ( } /** - Read remaing debug packet except for the start symbol + Read remaining debug packet except for the start symbol @param[in] Handle Pointer to Debug Port handle. @param[in, out] DebugHeader Debug header buffer including start symbol. @@ -616,7 +616,7 @@ DebugAgentDataMsgPrint ( @retval EFI_SUCCESS Read the symbol in BreakSymbol. @retval EFI_CRC_ERROR CRC check fail. @retval EFI_TIMEOUT Timeout occurs when reading debug packet. - @retval EFI_DEVICE_ERROR Receive the old or responsed packet. + @retval EFI_DEVICE_ERROR Receive the old or response packet. **/ EFI_STATUS @@ -651,7 +651,7 @@ ReadRemainingBreakPacket ( if (IS_REQUEST (DebugHeader)) { if (DebugHeader->SequenceNo == (UINT8)(Mailbox->HostSequenceNo + 1)) { // - // Only updagte HostSequenceNo for new command packet + // Only update HostSequenceNo for new command packet // UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, DebugHeader->SequenceNo); return EFI_SUCCESS; diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h index a0ede308ef..4c72f8f3a9 100644 --- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h +++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.h @@ -452,7 +452,7 @@ DebugAgentDataMsgPrint ( ); /** - Read remaing debug packet except for the start symbol + Read remaining debug packet except for the start symbol @param[in] Handle Pointer to Debug Port handle. @param[in, out] DebugHeader Debug header buffer including start symbol. diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c index 6661275cc3..97d30c802d 100644 --- a/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c +++ b/SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgent/SerialIo.c @@ -213,10 +213,10 @@ SERIAL_IO_DEVICE_PATH mSerialIoDevicePath = { } }; -#define DEBGU_SERIAL_IO_FIFO_DEPTH 10 +#define DEBUG_SERIAL_IO_FIFO_DEPTH 10 // // Data buffer for Terminal input character and Debug Symbols. -// The depth is DEBGU_SERIAL_IO_FIFO_DEPTH. +// The depth is DEBUG_SERIAL_IO_FIFO_DEPTH. // Fields: // First UINT8: The index of the first data in array Data[]. // Last UINT8: The index, which you can put a new data into array Data[]. @@ -227,7 +227,7 @@ typedef struct { UINT8 First; UINT8 Last; UINT8 Surplus; - UINT8 Data[DEBGU_SERIAL_IO_FIFO_DEPTH]; + UINT8 Data[DEBUG_SERIAL_IO_FIFO_DEPTH]; } DEBUG_SERIAL_FIFO; // @@ -236,10 +236,10 @@ typedef struct { EFI_HANDLE mSerialIoHandle = NULL; UINTN mLoopbackBuffer = 0; DEBUG_SERIAL_FIFO mSerialFifoForTerminal = { - 0, 0, DEBGU_SERIAL_IO_FIFO_DEPTH, { 0 } + 0, 0, DEBUG_SERIAL_IO_FIFO_DEPTH, { 0 } }; DEBUG_SERIAL_FIFO mSerialFifoForDebug = { - 0, 0, DEBGU_SERIAL_IO_FIFO_DEPTH, { 0 } + 0, 0, DEBUG_SERIAL_IO_FIFO_DEPTH, { 0 } }; /** @@ -251,11 +251,11 @@ DEBUG_SERIAL_FIFO mSerialFifoForDebug = { **/ BOOLEAN -IsDebugTermianlFifoEmpty ( +IsDebugTerminalFifoEmpty ( IN DEBUG_SERIAL_FIFO *Fifo ) { - if (Fifo->Surplus == DEBGU_SERIAL_IO_FIFO_DEPTH) { + if (Fifo->Surplus == DEBUG_SERIAL_IO_FIFO_DEPTH) { return TRUE; } @@ -313,7 +313,7 @@ DebugTerminalFifoAdd ( Fifo->Data[Fifo->Last] = Data; Fifo->Surplus--; Fifo->Last++; - if (Fifo->Last == DEBGU_SERIAL_IO_FIFO_DEPTH) { + if (Fifo->Last == DEBUG_SERIAL_IO_FIFO_DEPTH) { Fifo->Last = 0; } @@ -339,7 +339,7 @@ DebugTerminalFifoRemove ( // // if FIFO is empty, no data can remove // - if (IsDebugTermianlFifoEmpty (Fifo)) { + if (IsDebugTerminalFifoEmpty (Fifo)) { return EFI_OUT_OF_RESOURCES; } @@ -349,7 +349,7 @@ DebugTerminalFifoRemove ( *Data = Fifo->Data[Fifo->First]; Fifo->Surplus++; Fifo->First++; - if (Fifo->First == DEBGU_SERIAL_IO_FIFO_DEPTH) { + if (Fifo->First == DEBUG_SERIAL_IO_FIFO_DEPTH) { Fifo->First = 0; } @@ -532,7 +532,7 @@ SerialGetControl ( // Check to see if the Terminal FIFO is empty and // check to see if the input buffer in the Debug Communication Library is empty // - if (!IsDebugTermianlFifoEmpty (&mSerialFifoForTerminal) || DebugPortPollBuffer (Handle)) { + if (!IsDebugTerminalFifoEmpty (&mSerialFifoForTerminal) || DebugPortPollBuffer (Handle)) { *Control &= ~EFI_SERIAL_INPUT_BUFFER_EMPTY; } diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c index 34c269e6b5..9953904725 100644 --- a/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c +++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.c @@ -70,7 +70,7 @@ DebugPortInitialize ( } /** - Read data from debug device and save the datas in buffer. + Read data from debug device and save the data in a buffer. Reads NumberOfBytes data bytes from a debug device into the buffer specified by Buffer. The number of bytes actually read is returned. diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c index 479757f5ba..da55f3e69e 100644 --- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c +++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb/DebugCommunicationLibUsb.c @@ -768,7 +768,7 @@ InitializeUsbDebugHardware ( } /** - Read data from debug device and save the datas in buffer. + Read data from debug device and save the data in a buffer. Reads NumberOfBytes data bytes from a debug device into the buffer specified by Buffer. The number of bytes actually read is returned. diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Internal.h b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Internal.h index c73233ea49..cc5f294f33 100644 --- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Internal.h +++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Internal.h @@ -586,7 +586,7 @@ XhcWriteDebugReg ( /** Verifies if the bit positions specified by a mask are set in a register. - @param[in, out] Register UNITN register + @param[in, out] Register UINTN register @param[in] BitMask 32-bit mask @return BOOLEAN - TRUE if all bits specified by the mask are enabled. diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c index 600bde10d6..3e6db0db86 100644 --- a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c +++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/Ia32/IntHandlerFuncs.c @@ -15,7 +15,7 @@ @param[in] InterruptType Interrupt type. @retval TRUE IDT entries were setup by Debug Agent. - @retval FALSE IDT entries were not setuo by Debug Agent. + @retval FALSE IDT entries were not setup by Debug Agent. **/ BOOLEAN diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h index 149186b226..f428af9632 100644 --- a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h +++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLib.h @@ -34,7 +34,7 @@ extern UINTN AsmInterruptHandle; @param[in] InterruptType Interrupt type. @retval TRUE IDT entries were setup by Debug Agent. - @retval FALSE IDT entries were not setuo by Debug Agent. + @retval FALSE IDT entries were not setup by Debug Agent. **/ BOOLEAN diff --git a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c index 952285a8ea..1baa88206b 100644 --- a/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c +++ b/SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/X64/IntHandlerFuncs.c @@ -15,7 +15,7 @@ @param[in] InterruptType Interrupt type. @retval TRUE IDT entries were setup by Debug Agent. - @retval FALSE IDT entries were not setuo by Debug Agent. + @retval FALSE IDT entries were not setup by Debug Agent. **/ BOOLEAN From 52fb2ff62e284e76aae13a688c1b5339b511755c Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 4 Oct 2022 11:01:50 -0400 Subject: [PATCH 0102/1529] SourceLevelDebugPkg: Add package CI YAML file REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4091 Adds the package as a supported package to .pytool/CISettings.py and adds a CI YAML for the package so it can be run in CI. Cc: Hao A Wu Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Hao A Wu Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 1 + .../SourceLevelDebugPkg.ci.yaml | 117 ++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 SourceLevelDebugPkg/SourceLevelDebugPkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index f72e327787..0c8320b1a3 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -73,6 +73,7 @@ def GetPackagesSupported(self): "UnitTestFrameworkPkg", "OvmfPkg", "RedfishPkg", + "SourceLevelDebugPkg", "UefiPayloadPkg" ) diff --git a/SourceLevelDebugPkg/SourceLevelDebugPkg.ci.yaml b/SourceLevelDebugPkg/SourceLevelDebugPkg.ci.yaml new file mode 100644 index 0000000000..8887a6d10b --- /dev/null +++ b/SourceLevelDebugPkg/SourceLevelDebugPkg.ci.yaml @@ -0,0 +1,117 @@ +## @file +# Core CI configuration for SourceLevelDebugPkg +# +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined .pytool/Plugin/LicenseCheck + "LicenseCheck": { + "IgnoreFiles": [] + }, + + "EccCheck": { + ## Exception sample looks like below: + ## "ExceptionList": [ + ## "", "" + ## ] + "ExceptionList": [ + ], + ## Both file path and directory path are accepted. + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "SourceLevelDebugPkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined .pytool/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "MdeModulePkg/MdeModulePkg.dec", + "MdePkg/MdePkg.dec", + "SecurityPkg/SecurityPkg.dec", + "SourceLevelDebugPkg/SourceLevelDebugPkg.dec", + "UefiCpuPkg/UefiCpuPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined .pytool/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "SourceLevelDebugPkg.dsc" + }, + + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "" # Don't support this test + }, + + ## options defined .pytool/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [], + }, + + ## options defined .pytool/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined .pytool/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": False, # All failures were addressed when SpellCheck was enabled in this package + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [ # words to extend to the dictionary for this package + "bidir", + "bsp's", + "capbility", # comes from external package + "dcddi", + "dcerstba", + "dcportsc", + "dcerstsz", + "epring", + "evalu", + "fxrestor", + "hccparams", + "hcsparams", + "iretd", + "iretq", + "isoch", + "mfindex", + "ompressed", + "portsc", + "sequenceno", + "smmentrybreak", + "stosd", + "stosq", + "ttach", + "urb's", + "xhc's" + ], + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 252d6154f9c13c96ce7e7be84ef54c38fdf5ef02 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 4 Oct 2022 11:05:37 -0400 Subject: [PATCH 0103/1529] .azurepipelines: Add SourceLevelDebugPkg to CI REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4091 Adds SourceLevelDebugPkg to the "OTHER" CI matrix job so it is built in edk2 CI. Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Hao A Wu Reviewed-by: Michael D Kinney --- .azurepipelines/templates/pr-gate-build-job.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index c3c849c3dc..7f88b41dc8 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -41,7 +41,7 @@ jobs: Build.Pkgs: 'NetworkPkg,RedfishPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_OTHER: - Build.Pkgs: 'PcAtChipsetPkg,PrmPkg,ShellPkg,StandaloneMmPkg,SignedCapsulePkg' + Build.Pkgs: 'PcAtChipsetPkg,PrmPkg,ShellPkg,SourceLevelDebugPkg,StandaloneMmPkg,SignedCapsulePkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_FMP_FAT_TEST: Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestFrameworkPkg,DynamicTablesPkg' From f774f3aa5a0f6ec03446e2eec1d9fe80e6f1da37 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Thu, 6 Oct 2022 08:44:38 -0600 Subject: [PATCH 0104/1529] MdeModulePkg/UefiBootManagerLib: Add Disk Info support for Ufs Add support for getting disk info from UFS devices. Signed-off-by: Jeff Brasen Reviewed-by: Zhichao Gao --- MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c | 4 +++- .../Library/UefiBootManagerLib/UefiBootManagerLib.inf | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c index fac33b9ee9..030b2ee3ec 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c @@ -195,7 +195,9 @@ BmGetDescriptionFromDiskInfo ( BmEliminateExtraSpaces (Description); } - } else if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoScsiInterfaceGuid)) { + } else if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoScsiInterfaceGuid) || + CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoUfsInterfaceGuid)) + { BufferSize = sizeof (EFI_SCSI_INQUIRY_DATA); Status = DiskInfo->Inquiry ( DiskInfo, diff --git a/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf b/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf index fe05d5f1cc..2fc0a80a4e 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf +++ b/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf @@ -85,6 +85,7 @@ gEfiDiskInfoIdeInterfaceGuid ## SOMETIMES_CONSUMES ## GUID gEfiDiskInfoScsiInterfaceGuid ## SOMETIMES_CONSUMES ## GUID gEfiDiskInfoSdMmcInterfaceGuid ## SOMETIMES_CONSUMES ## GUID + gEfiDiskInfoUfsInterfaceGuid ## SOMETIMES_CONSUMES ## GUID [Protocols] gEfiPciRootBridgeIoProtocolGuid ## CONSUMES From 36cf06b828efd3c6a10123e98231ef8f46e1c180 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 4 Oct 2022 15:47:25 +0200 Subject: [PATCH 0105/1529] OvmfPkg/PlatformInitLib: qemu cpuid physbits detection Add some qemu specific quirks to PlatformAddressWidthFromCpuid() to figure whenever the PhysBits value returned by CPUID is something real we can work with or not. See the source code comment for details on the logic. Also apply some limits to the address space we are going to use: * Place a hard cap at 47 PhysBits (128 TB) to avoid using addresses which require 5-level paging support. * Cap at 40 PhysBits (1 TB) in case the CPU has no support for gigabyte pages, to avoid excessive amounts of pages being used for page tables. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 100 ++++++++++++++++---- 1 file changed, 83 insertions(+), 17 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index d1a4f4b207..143a01ceb0 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -503,39 +503,105 @@ PlatformGetFirstNonAddress ( } /* - * Use CPUID to figure physical address width. Does *not* work - * reliable on qemu. For historical reasons qemu returns phys-bits=40 - * even in case the host machine supports less than that. + * Use CPUID to figure physical address width. * - * qemu has a cpu property (host-phys-bits={on,off}) to change that - * and make sure guest phys-bits are not larger than host phys-bits., - * but it is off by default. Exception: microvm machine type - * hard-wires that property to on. + * Does *not* work reliable on qemu. For historical reasons qemu + * returns phys-bits=40 by default even in case the host machine + * supports less than that. + * + * So we apply the following rules (which can be enabled/disabled + * using the QemuQuirk parameter) to figure whenever we can work with + * the returned physical address width or not: + * + * (1) If it is 41 or higher consider it valid. + * (2) If it is 40 or lower consider it valid in case it matches a + * known-good value for the CPU vendor, which is: + * -> 36 or 39 for Intel + * -> 40 for AMD + * (3) Otherwise consider it invalid. + * + * Recommendation: Run qemu with host-phys-bits=on. That will make + * sure guest phys-bits is not larger than host phys-bits. Some + * distro builds do that by default. */ VOID EFIAPI PlatformAddressWidthFromCpuid ( - IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob, + IN BOOLEAN QemuQuirk ) { - UINT32 RegEax; + UINT32 RegEax, RegEbx, RegEcx, RegEdx, Max; + UINT8 PhysBits; + CHAR8 Signature[13] = { 0 }; + BOOLEAN Valid = FALSE; + BOOLEAN Page1GSupport = FALSE; + + AsmCpuid (0x80000000, &RegEax, &RegEbx, &RegEcx, &RegEdx); + *(UINT32 *)(Signature + 0) = RegEbx; + *(UINT32 *)(Signature + 4) = RegEdx; + *(UINT32 *)(Signature + 8) = RegEcx; + Max = RegEax; + + if (Max >= 0x80000001) { + AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx); + if ((RegEdx & BIT26) != 0) { + Page1GSupport = TRUE; + } + } - AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); - if (RegEax >= 0x80000008) { + if (Max >= 0x80000008) { AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL); - PlatformInfoHob->PhysMemAddressWidth = (UINT8)RegEax; + PhysBits = (UINT8)RegEax; } else { - PlatformInfoHob->PhysMemAddressWidth = 36; + PhysBits = 36; } - PlatformInfoHob->FirstNonAddress = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth); + if (!QemuQuirk) { + Valid = TRUE; + } else if (PhysBits >= 41) { + Valid = TRUE; + } else if (AsciiStrCmp (Signature, "GenuineIntel") == 0) { + if ((PhysBits == 36) || (PhysBits == 39)) { + Valid = TRUE; + } + } else if (AsciiStrCmp (Signature, "AuthenticAMD") == 0) { + if (PhysBits == 40) { + Valid = TRUE; + } + } DEBUG (( DEBUG_INFO, - "%a: cpuid: phys-bits is %d\n", + "%a: Signature: '%a', PhysBits: %d, QemuQuirk: %a, Valid: %a\n", __FUNCTION__, - PlatformInfoHob->PhysMemAddressWidth + Signature, + PhysBits, + QemuQuirk ? "On" : "Off", + Valid ? "Yes" : "No" )); + + if (Valid) { + if (PhysBits > 47) { + /* + * Avoid 5-level paging altogether for now, which limits + * PhysBits to 48. Also avoid using address bit 48, due to sign + * extension we can't identity-map these addresses (and lots of + * places in edk2 assume we have everything identity-mapped). + * So the actual limit is 47. + */ + DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 47 (avoid 5-level paging)\n", __func__)); + PhysBits = 47; + } + + if (!Page1GSupport && (PhysBits > 40)) { + DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 40 (no 1G pages available)\n", __func__)); + PhysBits = 40; + } + + PlatformInfoHob->PhysMemAddressWidth = PhysBits; + PlatformInfoHob->FirstNonAddress = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth); + } } /** @@ -672,7 +738,7 @@ PlatformAddressWidthInitialization ( EFI_STATUS Status; if (PlatformInfoHob->HostBridgeDevId == 0xffff /* microvm */) { - PlatformAddressWidthFromCpuid (PlatformInfoHob); + PlatformAddressWidthFromCpuid (PlatformInfoHob, FALSE); return; } From 27d432fc8e8e94ea65f035e3c9f85a61ca91670b Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 4 Oct 2022 15:47:26 +0200 Subject: [PATCH 0106/1529] OvmfPkg/PlatformInitLib: detect physical address space Try detect physical address space, when successful use it. Otherwise go continue using the current guesswork code path. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 143a01ceb0..16ecbfadc3 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -761,6 +761,19 @@ PlatformAddressWidthInitialization ( FirstNonAddress = PlatformGetFirstNonAddress (PlatformInfoHob); } + PlatformAddressWidthFromCpuid (PlatformInfoHob, TRUE); + if (PlatformInfoHob->PhysMemAddressWidth != 0) { + // physical address width is known + PlatformInfoHob->FirstNonAddress = FirstNonAddress; + return; + } + + // + // physical address width is NOT known + // -> do some guess work, mostly based on installed memory + // -> try be conservstibe to stay below the guaranteed minimum of + // 36 phys bits (aka 64 GB). + // PhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress); // From 593d03873c008c2e6dd9fd59d4d5370c4169db9d Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 4 Oct 2022 15:47:27 +0200 Subject: [PATCH 0107/1529] OvmfPkg/PlatformInitLib: dynamic mmio window size In case we have a reliable PhysMemAddressWidth use that to dynamically size the 64bit address window. Allocate 1/8 of the physical address space and place the window at the upper end of the address space. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 16ecbfadc3..ae217d0242 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -604,6 +604,33 @@ PlatformAddressWidthFromCpuid ( } } +VOID +EFIAPI +PlatformDynamicMmioWindow ( + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + UINT64 AddrSpace, MmioSpace; + + AddrSpace = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth); + MmioSpace = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth - 3); + + if ((PlatformInfoHob->PcdPciMmio64Size < MmioSpace) && + (PlatformInfoHob->PcdPciMmio64Base + MmioSpace < AddrSpace)) + { + DEBUG ((DEBUG_INFO, "%a: using dynamic mmio window\n", __func__)); + DEBUG ((DEBUG_INFO, "%a: Addr Space 0x%Lx (%Ld GB)\n", __func__, AddrSpace, RShiftU64 (AddrSpace, 30))); + DEBUG ((DEBUG_INFO, "%a: MMIO Space 0x%Lx (%Ld GB)\n", __func__, MmioSpace, RShiftU64 (MmioSpace, 30))); + PlatformInfoHob->PcdPciMmio64Size = MmioSpace; + PlatformInfoHob->PcdPciMmio64Base = AddrSpace - MmioSpace; + } else { + DEBUG ((DEBUG_INFO, "%a: using classic mmio window\n", __func__)); + } + + DEBUG ((DEBUG_INFO, "%a: Pci64 Base 0x%Lx\n", __func__, PlatformInfoHob->PcdPciMmio64Base)); + DEBUG ((DEBUG_INFO, "%a: Pci64 Size 0x%Lx\n", __func__, PlatformInfoHob->PcdPciMmio64Size)); +} + /** Iterate over the PCI host bridges resources information optionally provided in fw-cfg and find the highest address contained in the PCI MMIO windows. If @@ -765,6 +792,7 @@ PlatformAddressWidthInitialization ( if (PlatformInfoHob->PhysMemAddressWidth != 0) { // physical address width is known PlatformInfoHob->FirstNonAddress = FirstNonAddress; + PlatformDynamicMmioWindow (PlatformInfoHob); return; } From 19efa8c5f3ec831bb5cf65f1c86dfe94e75f7366 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 4 Oct 2022 15:47:28 +0200 Subject: [PATCH 0108/1529] OvmfPkg/PciHotPlugInitDxe: reserve more mmio space In case the 64-bit pci mmio window is larger than the default size of 32G be generous and hand out larger chunks of address space for prefetchable mmio bridge windows. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek --- OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c | 21 ++++++++++++++++++-- OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c index c122855b73..3f9c84cf2b 100644 --- a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c +++ b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c @@ -556,6 +556,7 @@ GetResourcePadding ( EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS *Address; BOOLEAN DefaultIo; BOOLEAN DefaultMmio; + BOOLEAN DefaultPrefMmio; RESOURCE_PADDING ReservationRequest; EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *FirstResource; EFI_STATUS ReservationHintStatus; @@ -588,8 +589,9 @@ GetResourcePadding ( return EFI_INVALID_PARAMETER; } - DefaultIo = TRUE; - DefaultMmio = TRUE; + DefaultIo = TRUE; + DefaultMmio = TRUE; + DefaultPrefMmio = TRUE; // // Init ReservationRequest, and point FirstResource one past the last @@ -722,6 +724,7 @@ GetResourcePadding ( HighBit = HighBitSetRoundUp32 (ReservationHint.Prefetchable32BitMmio); if (HighBit != -1) { SetMmioPadding (--FirstResource, TRUE, TRUE, (UINTN)HighBit); + DefaultPrefMmio = FALSE; } } else if ((ReservationHint.Prefetchable64BitMmio > 0) && (ReservationHint.Prefetchable64BitMmio < MAX_UINT64)) @@ -729,6 +732,7 @@ GetResourcePadding ( HighBit = HighBitSetRoundUp64 (ReservationHint.Prefetchable64BitMmio); if (HighBit != -1) { SetMmioPadding (--FirstResource, TRUE, FALSE, (UINTN)HighBit); + DefaultPrefMmio = FALSE; } } } @@ -752,6 +756,19 @@ GetResourcePadding ( ); } + if (DefaultPrefMmio) { + UINT64 Pci64Size = PcdGet64 (PcdPciMmio64Size); + + if (Pci64Size > SIZE_32GB) { + SetMmioPadding ( + --FirstResource, + TRUE, + FALSE, + (UINTN)HighBitSetRoundUp64 (RShiftU64 (Pci64Size, 8)) + ); + } + } + // // Output a copy of ReservationRequest from the lowest-address populated // entry until the end of the structure (including diff --git a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf index 78b95faa7a..f56b1de6fd 100644 --- a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf +++ b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf @@ -40,6 +40,7 @@ [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId ## CONSUMES + gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size ## CONSUMES [Depex] TRUE From 51015bc7174fa88eeb9fd7dc5e0716e0c689df18 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 6 Oct 2022 13:05:25 +0200 Subject: [PATCH 0109/1529] OvmfPkg/Microvm: add SECURE_BOOT_FEATURE_ENABLED Compiler flag is needed to make (stateless) secure boot be actually secure, i.e. restore EFI variables from ROM on reset. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Microvm/MicrovmX64.dsc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 33d68a5493..e60d3a2071 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -91,6 +91,15 @@ INTEL:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES + # + # SECURE_BOOT_FEATURE_ENABLED + # +!if $(SECURE_BOOT_ENABLE) == TRUE + MSFT:*_*_*_CC_FLAGS = /D SECURE_BOOT_FEATURE_ENABLED + INTEL:*_*_*_CC_FLAGS = /D SECURE_BOOT_FEATURE_ENABLED + GCC:*_*_*_CC_FLAGS = -D SECURE_BOOT_FEATURE_ENABLED +!endif + !include NetworkPkg/NetworkBuildOptions.dsc.inc [BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] From dce90778bae89a69cf6ba86bc640cdc1e11521cf Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 6 Oct 2022 13:05:26 +0200 Subject: [PATCH 0110/1529] Revert "OvmfPkg/Microvm: no secure boot" This reverts commit 60d55c4156523e5dfb316b7c0c445b96c8f8be81. Now that we have stateless secure boot support (which doesn't need SMM) in OVMF we can enable the build option for MicroVM. Bring it back by reverting the commit removing it. Also add the new PlatformPKProtectionLib. Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Microvm/MicrovmX64.dsc | 22 +++++++++++++++++++++- OvmfPkg/Microvm/MicrovmX64.fdf | 4 ++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index e60d3a2071..7eff8e2a88 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -214,7 +214,15 @@ !endif RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf +!if $(SECURE_BOOT_ENABLE) == TRUE + PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf + AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + PlatformPKProtectionLib|SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.inf + SecureBootVariableProvisionLib|SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.inf +!else AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf +!endif VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf @@ -691,7 +699,14 @@ MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf - MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf + MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf { + +!if $(SECURE_BOOT_ENABLE) == TRUE + NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf +!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!endif + } + MdeModulePkg/Universal/EbcDxe/EbcDxe.inf OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf @@ -853,6 +868,11 @@ gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000 } +!if $(SECURE_BOOT_ENABLE) == TRUE + SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf + OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.inf +!endif + OvmfPkg/PlatformDxe/Platform.inf OvmfPkg/IoMmuDxe/IoMmuDxe.inf diff --git a/OvmfPkg/Microvm/MicrovmX64.fdf b/OvmfPkg/Microvm/MicrovmX64.fdf index ff0aab2bcb..380ba3a368 100644 --- a/OvmfPkg/Microvm/MicrovmX64.fdf +++ b/OvmfPkg/Microvm/MicrovmX64.fdf @@ -206,6 +206,10 @@ INF OvmfPkg/VirtioBlkDxe/VirtioBlk.inf INF OvmfPkg/VirtioScsiDxe/VirtioScsi.inf INF OvmfPkg/VirtioRngDxe/VirtioRng.inf +!if $(SECURE_BOOT_ENABLE) == TRUE + INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf +!endif + INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf From afe92a82d115eb8becff0426115827d15794eb16 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 4 Oct 2022 13:21:57 +0200 Subject: [PATCH 0111/1529] OvmfPkg: rename QemuBootOrderNNNN to VMMBootOrderNNNN While the actual implementation (using qemu fw_cfg) is qemu-specific, the idea to store the boot order as configured by the VMM in EFI variables is not. So lets give the variables a more neutral name while we still can (i.e. no stable tag yet with the new feature). While being at it also fix the NNNN format (use %x instead of %d for consistency with BootNNNN). Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c | 6 +++--- OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf | 2 +- OvmfPkg/OvmfPkg.dec | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c index 18646daa67..cea4b7a099 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c +++ b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c @@ -1709,7 +1709,7 @@ ConnectDevicesFromQemu ( Attempt to retrieve the "bootorder" fw_cfg file from QEMU. Translate the OpenFirmware device paths therein to UEFI device path fragments. - On Success store the device path in QemuBootOrderNNNN variables. + On Success store the device path in VMMBootOrderNNNN variables. **/ VOID EFIAPI @@ -1794,13 +1794,13 @@ StoreQemuBootOrder ( UnicodeSPrint ( VariableName, sizeof (VariableName), - L"QemuBootOrder%04d", + L"VMMBootOrder%04x", VariableIndex++ ); DEBUG ((DEBUG_INFO, "%a: %s = %s\n", __FUNCTION__, VariableName, Translated)); gRT->SetVariable ( VariableName, - &gQemuBootOrderGuid, + &gVMMBootOrderGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, GetDevicePathSize (DevicePath), DevicePath diff --git a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf index 211344fb0b..6e320e3e85 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf +++ b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf @@ -49,7 +49,7 @@ [Guids] gEfiGlobalVariableGuid gVirtioMmioTransportGuid - gQemuBootOrderGuid + gVMMBootOrderGuid [FeaturePcd] gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index 6d689ecc5d..f13dd4a61f 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -146,7 +146,7 @@ gConfidentialComputingSecretGuid = {0xadf956ad, 0xe98c, 0x484c, {0xae, 0x11, 0xb5, 0x1c, 0x7d, 0x33, 0x64, 0x47}} gConfidentialComputingSevSnpBlobGuid = {0x067b1f5f, 0xcf26, 0x44c5, {0x85, 0x54, 0x93, 0xd7, 0x77, 0x91, 0x2d, 0x42}} gUefiOvmfPkgPlatformInfoGuid = {0xdec9b486, 0x1f16, 0x47c7, {0x8f, 0x68, 0xdf, 0x1a, 0x41, 0x88, 0x8b, 0xa5}} - gQemuBootOrderGuid = {0x668f4529, 0x63d0, 0x4bb5, {0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a}} + gVMMBootOrderGuid = {0x668f4529, 0x63d0, 0x4bb5, {0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a}} [Ppis] # PPI whose presence in the PPI database signals that the TPM base address From b152ea67d8fb9855867e92f6838d01989aad6227 Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Thu, 29 Sep 2022 17:06:51 +0800 Subject: [PATCH 0112/1529] UefiCpuPkg/CpuExceptionHandlerLib: Code optimization to allow bigger stack This commit is a code optimization to allow bigger seperate stack size in ArchSetupExceptionStack. In previous code logic, CPU_STACK_ALIGNMENT bytes will be wasted if StackTop is already CPU_STACK_ALIGNMENT aligned. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Reviewed-by: Abner Chang --- .../CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c | 5 ++++- .../CpuExceptionHandlerLib/X64/ArchExceptionHandler.c | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c index 8c398ebc5b..c30ece1dc9 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c @@ -215,7 +215,10 @@ ArchSetupExceptionStack ( // Fixup exception task descriptor and task-state segment // AsmGetTssTemplateMap (&TemplateMap); - StackTop = StackTop - CPU_STACK_ALIGNMENT; + // + // Plus 1 byte is for compact stack layout in case StackTop is already aligned. + // + StackTop = StackTop - CPU_STACK_ALIGNMENT + 1; StackTop = (UINTN)ALIGN_POINTER (StackTop, CPU_STACK_ALIGNMENT); IdtTable = (IA32_IDT_GATE_DESCRIPTOR *)Idtr.Base; for (Index = 0; Index < CPU_STACK_SWITCH_EXCEPTION_NUMBER; ++Index) { diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c index 80e9f08e5b..4e85880ed4 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c @@ -223,7 +223,10 @@ ArchSetupExceptionStack ( // Fixup exception task descriptor and task-state segment // ZeroMem (Tss, sizeof (*Tss)); - StackTop = StackTop - CPU_STACK_ALIGNMENT; + // + // Plus 1 byte is for compact stack layout in case StackTop is already aligned. + // + StackTop = StackTop - CPU_STACK_ALIGNMENT + 1; StackTop = (UINTN)ALIGN_POINTER (StackTop, CPU_STACK_ALIGNMENT); IdtTable = (IA32_IDT_GATE_DESCRIPTOR *)Idtr.Base; for (Index = 0; Index < CPU_STACK_SWITCH_EXCEPTION_NUMBER; ++Index) { From ab18a9a32d7a726e84cd220e75eb5aa9b70dd80b Mon Sep 17 00:00:00 2001 From: Zhihao Li Date: Tue, 27 Sep 2022 20:57:38 +0800 Subject: [PATCH 0113/1529] UefiCpuPkg: Reset a parameter when BSP Exit in CPU relaxed mode. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4083 In CPU relaxed mode, it doesn't reset the value of mSmmMpSyncData->AllApArrivedWithException when BSP exit smm mode. So this patch will reset this variable. Cc: Eric Dong Reviewed-by: Ray Ni Signed-off-by: Zhihao Li Reviewed-by: Abner Chang --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 13c2cb8da4..c79da418e3 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -696,8 +696,9 @@ BSPHandler ( // // Allow APs to check in from this point on // - *mSmmMpSyncData->Counter = 0; - *mSmmMpSyncData->AllCpusInSync = FALSE; + *mSmmMpSyncData->Counter = 0; + *mSmmMpSyncData->AllCpusInSync = FALSE; + mSmmMpSyncData->AllApArrivedWithException = FALSE; } /** From cd26ce1d42a3e689ceb10ffedb6536d2a5b33b9a Mon Sep 17 00:00:00 2001 From: Foster Nong Date: Thu, 29 Sep 2022 17:20:01 +0800 Subject: [PATCH 0114/1529] MdeModulePkg: Handle InitialVFs=0 case for SR-IOV Per the section 3.3.5 SR-IOV spec v1.1, InitialVFs (0ch). InitialVFs indicates to SR-PCIM the number of VFs that are initially associated with the PF. The minimum value of InitialVFs is 0. Below code is used to calculate SR-IOV reserved bus number, if InitialVFs =0, it maybe calculate the wrong bus number in this case. LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride we can fix it with below code: if (PciIoDevice->InitialVFs == 0) { PciIoDevice->ReservedBusNum = 0; } else { PFRid = EFI_PCI_RID (Bus, Device, Func); LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride; // // Calculate ReservedBusNum for this PF // PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); // // Calculate ReservedBusNum for this PF // PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); } https://bugzilla.tianocore.org/show_bug.cgi?id=4069 Signed-off-by: Foster Nong Reviewed-by: Ray Ni --- .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index 509f828b62..eb250f6f7b 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -2416,13 +2416,17 @@ CreatePciIoDevice ( // // Calculate LastVF // - PFRid = EFI_PCI_RID (Bus, Device, Func); - LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride; + if (PciIoDevice->InitialVFs == 0) { + PciIoDevice->ReservedBusNum = 0; + } else { + PFRid = EFI_PCI_RID (Bus, Device, Func); + LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride; - // - // Calculate ReservedBusNum for this PF - // - PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); + // + // Calculate ReservedBusNum for this PF + // + PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); + } DEBUG (( DEBUG_INFO, From 9013dd40ce9f351787d63151af48dac9cd34a82d Mon Sep 17 00:00:00 2001 From: Yuan Yu Date: Wed, 28 Sep 2022 15:49:24 +0800 Subject: [PATCH 0115/1529] CryptoPkg: Fix integer overflow SECSPERDAY is 86400 which exceeds the limit of a UINT16 which is 65536. Therefore DayRemainder cannot use UINT16. This patch makes it UINT32. Cc: Ard Biesheuvel Cc: Jordan Justen Cc: Laszlo Ersek Cc: Anthony Perard Cc: Julien Grall Signed-off-by: Yuan Yu Reviewed-by: Ard Biesheuvel Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c index 7d28446d4b..bf8a532581 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c @@ -118,7 +118,7 @@ gmtime ( { struct tm *GmTime; UINT16 DayNo; - UINT16 DayRemainder; + UINT32 DayRemainder; time_t Year; time_t YearNo; UINT16 TotalDays; @@ -136,7 +136,7 @@ gmtime ( ZeroMem ((VOID *)GmTime, (UINTN)sizeof (struct tm)); DayNo = (UINT16)(*timer / SECSPERDAY); - DayRemainder = (UINT16)(*timer % SECSPERDAY); + DayRemainder = (UINT32)(*timer % SECSPERDAY); GmTime->tm_sec = (int)(DayRemainder % SECSPERMIN); GmTime->tm_min = (int)((DayRemainder % SECSPERHOUR) / SECSPERMIN); From 288f243ccf874afffccbef76365a60fe850676d6 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sat, 7 May 2022 15:37:32 +0800 Subject: [PATCH 0116/1529] MdePkg: Add Tls configuration related define REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3892 Consumed by TlsSetEcCurve and TlsSetSignatureAlgoList. Cc: Jiewen Yao Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Yi Li Acked-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Tls1.h | 112 +++++++++++++++++-------- 1 file changed, 75 insertions(+), 37 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/Tls1.h b/MdePkg/Include/IndustryStandard/Tls1.h index cf67428b11..f1ba0af7dc 100644 --- a/MdePkg/Include/IndustryStandard/Tls1.h +++ b/MdePkg/Include/IndustryStandard/Tls1.h @@ -13,44 +13,48 @@ #pragma pack(1) /// -/// TLS Cipher Suite, refers to A.5 of rfc-2246, rfc-4346 and rfc-5246. +/// TLS Cipher Suite, refers to A.5 of rfc-2246, rfc-4346, rfc-5246, rfc-5288 and rfc-5289. /// -#define TLS_RSA_WITH_NULL_MD5 {0x00, 0x01} -#define TLS_RSA_WITH_NULL_SHA {0x00, 0x02} -#define TLS_RSA_WITH_RC4_128_MD5 {0x00, 0x04} -#define TLS_RSA_WITH_RC4_128_SHA {0x00, 0x05} -#define TLS_RSA_WITH_IDEA_CBC_SHA {0x00, 0x07} -#define TLS_RSA_WITH_DES_CBC_SHA {0x00, 0x09} -#define TLS_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x0A} -#define TLS_DH_DSS_WITH_DES_CBC_SHA {0x00, 0x0C} -#define TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA {0x00, 0x0D} -#define TLS_DH_RSA_WITH_DES_CBC_SHA {0x00, 0x0F} -#define TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x10} -#define TLS_DHE_DSS_WITH_DES_CBC_SHA {0x00, 0x12} -#define TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA {0x00, 0x13} -#define TLS_DHE_RSA_WITH_DES_CBC_SHA {0x00, 0x15} -#define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x16} -#define TLS_RSA_WITH_AES_128_CBC_SHA {0x00, 0x2F} -#define TLS_DH_DSS_WITH_AES_128_CBC_SHA {0x00, 0x30} -#define TLS_DH_RSA_WITH_AES_128_CBC_SHA {0x00, 0x31} -#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA {0x00, 0x32} -#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA {0x00, 0x33} -#define TLS_RSA_WITH_AES_256_CBC_SHA {0x00, 0x35} -#define TLS_DH_DSS_WITH_AES_256_CBC_SHA {0x00, 0x36} -#define TLS_DH_RSA_WITH_AES_256_CBC_SHA {0x00, 0x37} -#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA {0x00, 0x38} -#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA {0x00, 0x39} -#define TLS_RSA_WITH_NULL_SHA256 {0x00, 0x3B} -#define TLS_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x3C} -#define TLS_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x3D} -#define TLS_DH_DSS_WITH_AES_128_CBC_SHA256 {0x00, 0x3E} -#define TLS_DH_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x3F} -#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 {0x00, 0x40} -#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x67} -#define TLS_DH_DSS_WITH_AES_256_CBC_SHA256 {0x00, 0x68} -#define TLS_DH_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x69} -#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 {0x00, 0x6A} -#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x6B} +#define TLS_RSA_WITH_NULL_MD5 {0x00, 0x01} +#define TLS_RSA_WITH_NULL_SHA {0x00, 0x02} +#define TLS_RSA_WITH_RC4_128_MD5 {0x00, 0x04} +#define TLS_RSA_WITH_RC4_128_SHA {0x00, 0x05} +#define TLS_RSA_WITH_IDEA_CBC_SHA {0x00, 0x07} +#define TLS_RSA_WITH_DES_CBC_SHA {0x00, 0x09} +#define TLS_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x0A} +#define TLS_DH_DSS_WITH_DES_CBC_SHA {0x00, 0x0C} +#define TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA {0x00, 0x0D} +#define TLS_DH_RSA_WITH_DES_CBC_SHA {0x00, 0x0F} +#define TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x10} +#define TLS_DHE_DSS_WITH_DES_CBC_SHA {0x00, 0x12} +#define TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA {0x00, 0x13} +#define TLS_DHE_RSA_WITH_DES_CBC_SHA {0x00, 0x15} +#define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA {0x00, 0x16} +#define TLS_RSA_WITH_AES_128_CBC_SHA {0x00, 0x2F} +#define TLS_DH_DSS_WITH_AES_128_CBC_SHA {0x00, 0x30} +#define TLS_DH_RSA_WITH_AES_128_CBC_SHA {0x00, 0x31} +#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA {0x00, 0x32} +#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA {0x00, 0x33} +#define TLS_RSA_WITH_AES_256_CBC_SHA {0x00, 0x35} +#define TLS_DH_DSS_WITH_AES_256_CBC_SHA {0x00, 0x36} +#define TLS_DH_RSA_WITH_AES_256_CBC_SHA {0x00, 0x37} +#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA {0x00, 0x38} +#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA {0x00, 0x39} +#define TLS_RSA_WITH_NULL_SHA256 {0x00, 0x3B} +#define TLS_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x3C} +#define TLS_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x3D} +#define TLS_DH_DSS_WITH_AES_128_CBC_SHA256 {0x00, 0x3E} +#define TLS_DH_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x3F} +#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 {0x00, 0x40} +#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 {0x00, 0x67} +#define TLS_DH_DSS_WITH_AES_256_CBC_SHA256 {0x00, 0x68} +#define TLS_DH_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x69} +#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 {0x00, 0x6A} +#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 {0x00, 0x6B} +#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 {0x00, 0x9F} +#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 {0xC0, 0x2B} +#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 {0xC0, 0x2C} +#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 {0xC0, 0x30} /// /// TLS Version, refers to A.1 of rfc-2246, rfc-4346 and rfc-5246. @@ -95,6 +99,40 @@ typedef struct { // #define TLS_CIPHERTEXT_RECORD_MAX_PAYLOAD_LENGTH 18432 +/// +/// TLS Hash algorithm, refers to section 7.4.1.4.1. of rfc-5246. +/// +typedef enum { + TlsHashAlgoNone = 0, + TlsHashAlgoMd5 = 1, + TlsHashAlgoSha1 = 2, + TlsHashAlgoSha224 = 3, + TlsHashAlgoSha256 = 4, + TlsHashAlgoSha384 = 5, + TlsHashAlgoSha512 = 6, +} TLS_HASH_ALGO; + +/// +/// TLS Signature algorithm, refers to section 7.4.1.4.1. of rfc-5246. +/// +typedef enum { + TlsSignatureAlgoAnonymous = 0, + TlsSignatureAlgoRsa = 1, + TlsSignatureAlgoDsa = 2, + TlsSignatureAlgoEcdsa = 3, +} TLS_SIGNATURE_ALGO; + +/// +/// TLS Supported Elliptic Curves Extensions, refers to section 5.1.1 of rfc-8422. +/// +typedef enum { + TlsEcNamedCurveSecp256r1 = 23, + TlsEcNamedCurveSecp384r1 = 24, + TlsEcNamedCurveSecp521r1 = 25, + TlsEcNamedCurveX25519 = 29, + TlsEcNamedCurveX448 = 30, +} TLS_EC_NAMED_CURVE; + #pragma pack() #endif From e4393b684551e4a7bb551deda742072431e17a22 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Sun, 25 Sep 2022 17:14:06 +0800 Subject: [PATCH 0117/1529] CryptoPkg: Extend Tls function library REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3892 1. TlsSetSignatureAlgoList(): Configure the list of TLS signature algorithms that should be used as part of the TLS session establishment. This is needed for some WLAN Supplicant connection establishment flows that allow only specific TLS signature algorithms to be used, e.g., Authenticate and Key Managmenet (AKM) suites that are SUITE-B compliant. 2. TlsSetEcCurve(): Configure the Elliptic Curve that should be used for TLS flows the use cipher suite with EC, e.g., TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384. This is needed for some WLAN Supplicant connection establishment flows that allow only specific TLS signature algorithms to be used, e.g., Authenticate and Key Managmenet (AKM) suites that are SUITE-B compliant. 3. TlsShutdown(): Shutdown the TLS connection without releasing the resources, meaning a new connection can be started without calling TlsNew() and without setting certificates etc. 4. TlsGetExportKey(): Derive keying material from a TLS connection using the mechanism described in RFC 5705 and export the key material (needed by EAP methods such as EAP-TTLS and EAP-PEAP). 5. TlsSetHostPrivateKeyEx(): This function adds the local private key (PEM-encoded or PKCS#8 or DER-encoded private key) into the specified TLS object for TLS negotiation. There is already a similar function TlsSetHostPrivateKey(), the new Ex function introduces a new parameter Password, set Password to NULL when useless. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/TlsLib.h | 126 +++++- CryptoPkg/Library/TlsLib/InternalTlsLib.h | 4 + CryptoPkg/Library/TlsLib/TlsConfig.c | 366 +++++++++++++++++- CryptoPkg/Library/TlsLib/TlsProcess.c | 32 ++ CryptoPkg/Library/TlsLibNull/TlsConfigNull.c | 123 +++++- CryptoPkg/Library/TlsLibNull/TlsProcessNull.c | 23 ++ 6 files changed, 667 insertions(+), 7 deletions(-) diff --git a/CryptoPkg/Include/Library/TlsLib.h b/CryptoPkg/Include/Library/TlsLib.h index 3b75fde0aa..d37c5fcc35 100644 --- a/CryptoPkg/Include/Library/TlsLib.h +++ b/CryptoPkg/Include/Library/TlsLib.h @@ -294,6 +294,25 @@ TlsWrite ( IN UINTN BufferSize ); +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +EFI_STATUS +EFIAPI +TlsShutdown ( + IN VOID *Tls + ); + /** Set a new TLS/SSL method for a particular TLS object. @@ -492,11 +511,38 @@ TlsSetHostPublicCert ( /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +EFI_STATUS +EFIAPI +TlsSetHostPrivateKeyEx ( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ); + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -534,6 +580,53 @@ TlsSetCertRevocationList ( IN UINTN DataSize ); +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +EFI_STATUS +EFIAPI +TlsSetSignatureAlgoList ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ); + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +EFI_STATUS +EFIAPI +TlsSetEcCurve ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ); + /** Gets the protocol version used by the specified TLS connection. @@ -810,4 +903,33 @@ TlsGetCertRevocationList ( IN OUT UINTN *DataSize ); +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +EFI_STATUS +EFIAPI +TlsGetExportKey ( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ); + #endif // __TLS_LIB_H__ diff --git a/CryptoPkg/Library/TlsLib/InternalTlsLib.h b/CryptoPkg/Library/TlsLib/InternalTlsLib.h index cf5ffe1b73..97a46af6c1 100644 --- a/CryptoPkg/Library/TlsLib/InternalTlsLib.h +++ b/CryptoPkg/Library/TlsLib/InternalTlsLib.h @@ -17,6 +17,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/CryptoPkg/Library/TlsLib/TlsConfig.c b/CryptoPkg/Library/TlsLib/TlsConfig.c index 0673c9d532..dbe1f06529 100644 --- a/CryptoPkg/Library/TlsLib/TlsConfig.c +++ b/CryptoPkg/Library/TlsLib/TlsConfig.c @@ -62,6 +62,38 @@ STATIC CONST TLS_CIPHER_MAPPING TlsCipherMappingTable[] = { MAP (0x0068, "DH-DSS-AES256-SHA256"), /// TLS_DH_DSS_WITH_AES_256_CBC_SHA256 MAP (0x0069, "DH-RSA-AES256-SHA256"), /// TLS_DH_RSA_WITH_AES_256_CBC_SHA256 MAP (0x006B, "DHE-RSA-AES256-SHA256"), /// TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + MAP (0x009F, "DHE-RSA-AES256-GCM-SHA384"), /// TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + MAP (0xC02B, "ECDHE-ECDSA-AES128-GCM-SHA256"), /// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + MAP (0xC02C, "ECDHE-ECDSA-AES256-GCM-SHA384"), /// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + MAP (0xC030, "ECDHE-RSA-AES256-GCM-SHA384"), /// TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 +}; + +typedef struct { + // + // TLS Algorithm + // + UINT8 Algo; + // + // TLS Algorithm name + // + CONST CHAR8 *Name; +} TLS_ALGO_TO_NAME; + +STATIC CONST TLS_ALGO_TO_NAME TlsHashAlgoToName[] = { + { TlsHashAlgoNone, NULL }, + { TlsHashAlgoMd5, "MD5" }, + { TlsHashAlgoSha1, "SHA1" }, + { TlsHashAlgoSha224, "SHA224" }, + { TlsHashAlgoSha256, "SHA256" }, + { TlsHashAlgoSha384, "SHA384" }, + { TlsHashAlgoSha512, "SHA512" }, +}; + +STATIC CONST TLS_ALGO_TO_NAME TlsSignatureAlgoToName[] = { + { TlsSignatureAlgoAnonymous, NULL }, + { TlsSignatureAlgoRsa, "RSA" }, + { TlsSignatureAlgoDsa, "DSA" }, + { TlsSignatureAlgoEcdsa, "ECDSA" }, }; /** @@ -831,11 +863,107 @@ TlsSetHostPublicCert ( /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +EFI_STATUS +EFIAPI +TlsSetHostPrivateKeyEx ( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ) +{ + TLS_CONNECTION *TlsConn; + BIO *Bio; + EVP_PKEY *Pkey; + BOOLEAN Verify; + + TlsConn = (TLS_CONNECTION *)Tls; + + if ((TlsConn == NULL) || (TlsConn->Ssl == NULL) || (Data == NULL) || (DataSize == 0)) { + return EFI_INVALID_PARAMETER; + } + + // Try to parse the private key in DER format or un-encrypted PKC#8 + if (SSL_use_PrivateKey_ASN1 ( + EVP_PKEY_RSA, + TlsConn->Ssl, + Data, + (long)DataSize + ) == 1) + { + goto verify; + } + + if (SSL_use_PrivateKey_ASN1 ( + EVP_PKEY_DSA, + TlsConn->Ssl, + Data, + (long)DataSize + ) == 1) + { + goto verify; + } + + if (SSL_use_PrivateKey_ASN1 ( + EVP_PKEY_EC, + TlsConn->Ssl, + Data, + (long)DataSize + ) == 1) + { + goto verify; + } + + // Try to parse the private key in PEM format or encrypted PKC#8 + Bio = BIO_new_mem_buf (Data, (int)DataSize); + if (Bio != NULL) { + Verify = FALSE; + Pkey = PEM_read_bio_PrivateKey (Bio, NULL, NULL, Password); + if ((Pkey != NULL) && (SSL_use_PrivateKey (TlsConn->Ssl, Pkey) == 1)) { + Verify = TRUE; + } + + EVP_PKEY_free (Pkey); + BIO_free (Bio); + + if (Verify) { + goto verify; + } + } + + return EFI_ABORTED; + +verify: + if (SSL_check_private_key (TlsConn->Ssl) == 1) { + return EFI_SUCCESS; + } + + return EFI_ABORTED; +} + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -852,7 +980,7 @@ TlsSetHostPrivateKey ( IN UINTN DataSize ) { - return EFI_UNSUPPORTED; + return TlsSetHostPrivateKeyEx (Tls, Data, DataSize, NULL); } /** @@ -879,6 +1007,188 @@ TlsSetCertRevocationList ( return EFI_UNSUPPORTED; } +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +EFI_STATUS +EFIAPI +TlsSetSignatureAlgoList ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + TLS_CONNECTION *TlsConn; + UINTN Index; + UINTN SignAlgoStrSize; + CHAR8 *SignAlgoStr; + CHAR8 *Pos; + UINT8 *SignatureAlgoList; + EFI_STATUS Status; + + TlsConn = (TLS_CONNECTION *)Tls; + + if ((TlsConn == NULL) || (TlsConn->Ssl == NULL) || (Data == NULL) || (DataSize < 3) || + ((DataSize % 2) == 0) || (Data[0] != DataSize - 1)) + { + return EFI_INVALID_PARAMETER; + } + + SignatureAlgoList = Data + 1; + SignAlgoStrSize = 0; + for (Index = 0; Index < Data[0]; Index += 2) { + CONST CHAR8 *Tmp; + + if (SignatureAlgoList[Index] >= ARRAY_SIZE (TlsHashAlgoToName)) { + return EFI_INVALID_PARAMETER; + } + + Tmp = TlsHashAlgoToName[SignatureAlgoList[Index]].Name; + if (!Tmp) { + return EFI_INVALID_PARAMETER; + } + + // Add 1 for the '+' + SignAlgoStrSize += AsciiStrLen (Tmp) + 1; + + if (SignatureAlgoList[Index + 1] >= ARRAY_SIZE (TlsSignatureAlgoToName)) { + return EFI_INVALID_PARAMETER; + } + + Tmp = TlsSignatureAlgoToName[SignatureAlgoList[Index + 1]].Name; + if (!Tmp) { + return EFI_INVALID_PARAMETER; + } + + // Add 1 for the ':' or for the NULL terminator + SignAlgoStrSize += AsciiStrLen (Tmp) + 1; + } + + if (!SignAlgoStrSize) { + return EFI_UNSUPPORTED; + } + + SignAlgoStr = AllocatePool (SignAlgoStrSize); + if (SignAlgoStr == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + Pos = SignAlgoStr; + for (Index = 0; Index < Data[0]; Index += 2) { + CONST CHAR8 *Tmp; + + Tmp = TlsHashAlgoToName[SignatureAlgoList[Index]].Name; + CopyMem (Pos, Tmp, AsciiStrLen (Tmp)); + Pos += AsciiStrLen (Tmp); + *Pos++ = '+'; + + Tmp = TlsSignatureAlgoToName[SignatureAlgoList[Index + 1]].Name; + CopyMem (Pos, Tmp, AsciiStrLen (Tmp)); + Pos += AsciiStrLen (Tmp); + *Pos++ = ':'; + } + + *(Pos - 1) = '\0'; + + if (SSL_set1_sigalgs_list (TlsConn->Ssl, SignAlgoStr) < 1) { + Status = EFI_INVALID_PARAMETER; + } else { + Status = EFI_SUCCESS; + } + + FreePool (SignAlgoStr); + return Status; +} + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +EFI_STATUS +EFIAPI +TlsSetEcCurve ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + #if !FixedPcdGetBool (PcdOpensslEcEnabled) + return EFI_UNSUPPORTED; + #else + TLS_CONNECTION *TlsConn; + EC_KEY *EcKey; + INT32 Nid; + INT32 Ret; + + TlsConn = (TLS_CONNECTION *)Tls; + + if ((TlsConn == NULL) || (TlsConn->Ssl == NULL) || (Data == NULL) || (DataSize != sizeof (UINT32))) { + return EFI_INVALID_PARAMETER; + } + + switch (*((UINT32 *)Data)) { + case TlsEcNamedCurveSecp256r1: + return EFI_UNSUPPORTED; + case TlsEcNamedCurveSecp384r1: + Nid = NID_secp384r1; + break; + case TlsEcNamedCurveSecp521r1: + Nid = NID_secp521r1; + break; + case TlsEcNamedCurveX25519: + Nid = NID_X25519; + break; + case TlsEcNamedCurveX448: + Nid = NID_X448; + break; + default: + return EFI_UNSUPPORTED; + } + + if (SSL_set1_curves (TlsConn->Ssl, &Nid, 1) != 1) { + return EFI_INVALID_PARAMETER; + } + + EcKey = EC_KEY_new_by_curve_name (Nid); + if (EcKey == NULL) { + return EFI_INVALID_PARAMETER; + } + + Ret = SSL_set_tmp_ecdh (TlsConn->Ssl, EcKey); + EC_KEY_free (EcKey); + + if (Ret != 1) { + return EFI_INVALID_PARAMETER; + } + + return EFI_SUCCESS; + #endif +} + /** Gets the protocol version used by the specified TLS connection. @@ -1306,3 +1616,53 @@ TlsGetCertRevocationList ( { return EFI_UNSUPPORTED; } + +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +EFI_STATUS +EFIAPI +TlsGetExportKey ( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ) +{ + TLS_CONNECTION *TlsConn; + + TlsConn = (TLS_CONNECTION *)Tls; + + if ((TlsConn == NULL) || (TlsConn->Ssl == NULL)) { + return EFI_INVALID_PARAMETER; + } + + return SSL_export_keying_material ( + TlsConn->Ssl, + KeyBuffer, + KeyBufferLen, + Label, + AsciiStrLen (Label), + Context, + ContextLen, + Context != NULL + ) == 1 ? + EFI_SUCCESS : EFI_PROTOCOL_ERROR; +} diff --git a/CryptoPkg/Library/TlsLib/TlsProcess.c b/CryptoPkg/Library/TlsLib/TlsProcess.c index 0f2ad7a9fb..a803d86c4f 100644 --- a/CryptoPkg/Library/TlsLib/TlsProcess.c +++ b/CryptoPkg/Library/TlsLib/TlsProcess.c @@ -461,3 +461,35 @@ TlsWrite ( // return SSL_write (TlsConn->Ssl, Buffer, (UINT32)BufferSize); } + +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +EFI_STATUS +EFIAPI +TlsShutdown ( + IN VOID *Tls + ) +{ + TLS_CONNECTION *TlsConn; + + TlsConn = (TLS_CONNECTION *)Tls; + + if ((TlsConn == NULL) || ((TlsConn->Ssl) == NULL)) { + return EFI_INVALID_PARAMETER; + } + + SSL_set_quiet_shutdown (TlsConn->Ssl, 1); + SSL_shutdown (TlsConn->Ssl); + return SSL_clear (TlsConn->Ssl) == 1 ? EFI_SUCCESS : EFI_PROTOCOL_ERROR; +} diff --git a/CryptoPkg/Library/TlsLibNull/TlsConfigNull.c b/CryptoPkg/Library/TlsLibNull/TlsConfigNull.c index 03726fd726..18dd604382 100644 --- a/CryptoPkg/Library/TlsLibNull/TlsConfigNull.c +++ b/CryptoPkg/Library/TlsLibNull/TlsConfigNull.c @@ -242,11 +242,42 @@ TlsSetHostPublicCert ( /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +EFI_STATUS +EFIAPI +TlsSetHostPrivateKeyEx ( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ) +{ + ASSERT (FALSE); + return EFI_UNSUPPORTED; +} + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -292,6 +323,61 @@ TlsSetCertRevocationList ( return EFI_UNSUPPORTED; } +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +EFI_STATUS +EFIAPI +TlsSetSignatureAlgoList ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return EFI_UNSUPPORTED; +} + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +EFI_STATUS +EFIAPI +TlsSetEcCurve ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + ASSERT (FALSE); + return EFI_UNSUPPORTED; +} + /** Gets the protocol version used by the specified TLS connection. @@ -617,3 +703,36 @@ TlsGetCertRevocationList ( ASSERT (FALSE); return EFI_UNSUPPORTED; } + +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +EFI_STATUS +EFIAPI +TlsGetExportKey ( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ) +{ + ASSERT (FALSE); + return EFI_UNSUPPORTED; +} diff --git a/CryptoPkg/Library/TlsLibNull/TlsProcessNull.c b/CryptoPkg/Library/TlsLibNull/TlsProcessNull.c index 0958ddd8d6..395dac548d 100644 --- a/CryptoPkg/Library/TlsLibNull/TlsProcessNull.c +++ b/CryptoPkg/Library/TlsLibNull/TlsProcessNull.c @@ -245,3 +245,26 @@ TlsWrite ( ASSERT (FALSE); return 0; } + +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +EFI_STATUS +EFIAPI +TlsShutdown ( + IN VOID *Tls + ) +{ + ASSERT (FALSE); + return EFI_UNSUPPORTED; +} From 09555326142f0203bec78d62433b1c9f0c4e1fe4 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Mon, 26 Sep 2022 00:13:05 +0800 Subject: [PATCH 0118/1529] CryptoPkg: Add new Tls APIs to DXE and protocol REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3892 The implementation provides new Tls library functions for Crypto EFI Driver and Protocol. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Driver/Crypto.c | 155 +++++++++++++++++- .../Pcd/PcdCryptoServiceFamilyEnable.h | 5 + .../BaseCryptLibOnProtocolPpi/CryptLib.c | 146 ++++++++++++++++- CryptoPkg/Private/Protocol/Crypto.h | 136 ++++++++++++++- 4 files changed, 435 insertions(+), 7 deletions(-) diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index 7a8266aaba..f1ff77855c 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -4238,6 +4238,28 @@ CryptoServiceTlsWrite ( return CALL_BASECRYPTLIB (Tls.Services.Write, TlsWrite, (Tls, Buffer, BufferSize), 0); } +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +EFI_STATUS +EFIAPI +CryptoServiceTlsShutdown ( + IN VOID *Tls + ) +{ + return CALL_BASECRYPTLIB (Tls.Services.Shutdown, TlsShutdown, (Tls), EFI_UNSUPPORTED); +} + /** Set a new TLS/SSL method for a particular TLS object. @@ -4463,11 +4485,41 @@ CryptoServiceTlsSetHostPublicCert ( /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +EFI_STATUS +EFIAPI +CryptoServiceTlsSetHostPrivateKeyEx ( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ) +{ + return CALL_BASECRYPTLIB (TlsSet.Services.HostPrivateKeyEx, TlsSetHostPrivateKeyEx, (Tls, Data, DataSize, Password), EFI_UNSUPPORTED); +} + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -4511,6 +4563,59 @@ CryptoServiceTlsSetCertRevocationList ( return CALL_BASECRYPTLIB (TlsSet.Services.CertRevocationList, TlsSetCertRevocationList, (Data, DataSize), EFI_UNSUPPORTED); } +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +EFI_STATUS +EFIAPI +CryptoServiceTlsSetSignatureAlgoList ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + return CALL_BASECRYPTLIB (TlsSet.Services.SignatureAlgoList, TlsSetSignatureAlgoList, (Tls, Data, DataSize), EFI_UNSUPPORTED); +} + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +EFI_STATUS +EFIAPI +CryptoServiceTlsSetEcCurve ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + return CALL_BASECRYPTLIB (TlsSet.Services.EcCurve, TlsSetEcCurve, (Tls, Data, DataSize), EFI_UNSUPPORTED); +} + /** Gets the protocol version used by the specified TLS connection. @@ -4826,6 +4931,44 @@ CryptoServiceTlsGetCertRevocationList ( return CALL_BASECRYPTLIB (TlsGet.Services.CertRevocationList, TlsGetCertRevocationList, (Data, DataSize), EFI_UNSUPPORTED); } +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +EFI_STATUS +EFIAPI +CryptoServiceTlsGetExportKey ( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ) +{ + return CALL_BASECRYPTLIB ( + TlsGet.Services.ExportKey, + TlsGetExportKey, + (Tls, Label, Context, ContextLen, + KeyBuffer, KeyBufferLen), + EFI_UNSUPPORTED + ); +} + /** Carries out the RSA-SSA signature generation with EMSA-PSS encoding scheme. @@ -6266,4 +6409,12 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceEcGenerateKey, CryptoServiceEcGetPubKey, CryptoServiceEcDhComputeKey, + /// TLS (continued) + CryptoServiceTlsShutdown, + /// TLS Set (continued) + CryptoServiceTlsSetHostPrivateKeyEx, + CryptoServiceTlsSetSignatureAlgoList, + CryptoServiceTlsSetEcCurve, + /// TLS Get (continued) + CryptoServiceTlsGetExportKey }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 45bafc2161..4740589417 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -269,6 +269,7 @@ typedef struct { UINT8 CtrlTrafficIn : 1; UINT8 Read : 1; UINT8 Write : 1; + UINT8 Shutdown : 1; } Services; UINT32 Family; } Tls; @@ -285,6 +286,9 @@ typedef struct { UINT8 HostPublicCert : 1; UINT8 HostPrivateKey : 1; UINT8 CertRevocationList : 1; + UINT8 HostPrivateKeyEx : 1; + UINT8 SignatureAlgoList : 1; + UINT8 EcCurve : 1; } Services; UINT32 Family; } TlsSet; @@ -303,6 +307,7 @@ typedef struct { UINT8 HostPublicCert : 1; UINT8 HostPrivateKey : 1; UINT8 CertRevocationList : 1; + UINT8 ExportKey : 1; } Services; UINT32 Family; } TlsGet; diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 791e2ef599..52b934a545 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -3474,6 +3474,28 @@ TlsWrite ( CALL_CRYPTO_SERVICE (TlsWrite, (Tls, Buffer, BufferSize), 0); } +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +EFI_STATUS +EFIAPI +TlsShutdown ( + IN VOID *Tls + ) +{ + CALL_CRYPTO_SERVICE (TlsShutdown, (Tls), EFI_UNSUPPORTED); +} + /** Set a new TLS/SSL method for a particular TLS object. @@ -3699,11 +3721,41 @@ TlsSetHostPublicCert ( /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +EFI_STATUS +EFIAPI +TlsSetHostPrivateKeyEx ( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ) +{ + CALL_CRYPTO_SERVICE (TlsSetHostPrivateKeyEx, (Tls, Data, DataSize, Password), EFI_UNSUPPORTED); +} + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -3747,6 +3799,59 @@ TlsSetCertRevocationList ( CALL_CRYPTO_SERVICE (TlsSetCertRevocationList, (Data, DataSize), EFI_UNSUPPORTED); } +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +EFI_STATUS +EFIAPI +TlsSetSignatureAlgoList ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + CALL_CRYPTO_SERVICE (TlsSetSignatureAlgoList, (Tls, Data, DataSize), EFI_UNSUPPORTED); +} + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +EFI_STATUS +EFIAPI +TlsSetEcCurve ( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ) +{ + CALL_CRYPTO_SERVICE (TlsSetSignatureAlgoList, (Tls, Data, DataSize), EFI_UNSUPPORTED); +} + /** Gets the protocol version used by the specified TLS connection. @@ -4062,6 +4167,43 @@ TlsGetCertRevocationList ( CALL_CRYPTO_SERVICE (TlsGetCertRevocationList, (Data, DataSize), EFI_UNSUPPORTED); } +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +EFI_STATUS +EFIAPI +TlsGetExportKey ( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ) +{ + CALL_CRYPTO_SERVICE ( + TlsGetExportKey, + (Tls, Label, Context, ContextLen, + KeyBuffer, KeyBufferLen), + EFI_UNSUPPORTED + ); +} + // ===================================================================================== // Big number primitive // ===================================================================================== diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index 2f267c7f55..6293efa36b 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 13 +#define EDKII_CRYPTO_VERSION 14 /// /// EDK II Crypto Protocol forward declaration @@ -3186,6 +3186,25 @@ INTN IN UINTN BufferSize ); +/** + Shutdown a TLS connection. + + Shutdown the TLS connection without releasing the resources, meaning a new + connection can be started without calling TlsNew() and without setting + certificates etc. + + @param[in] Tls Pointer to the TLS object to shutdown. + + @retval EFI_SUCCESS The TLS is shutdown successfully. + @retval EFI_INVALID_PARAMETER Tls is NULL. + @retval EFI_PROTOCOL_ERROR Some other error occurred. +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_CRYPTO_TLS_SHUTDOWN)( + IN VOID *Tls + ); + /** Set a new TLS/SSL method for a particular TLS object. @@ -3384,11 +3403,38 @@ EFI_STATUS /** Adds the local private key to the specified TLS object. - This function adds the local private key (PEM-encoded RSA or PKCS#8 private + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private + key) into the specified TLS object for TLS negotiation. + + @param[in] Tls Pointer to the TLS object. + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded + or PKCS#8 private key. + @param[in] DataSize The size of data buffer in bytes. + @param[in] Password Pointer to NULL-terminated private key password, set it to NULL + if private key not encrypted. + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_ABORTED Invalid private key data. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_CRYPTO_TLS_SET_HOST_PRIVATE_KEY_EX)( + IN VOID *Tls, + IN VOID *Data, + IN UINTN DataSize, + IN VOID *Password OPTIONAL + ); + +/** + Adds the local private key to the specified TLS object. + + This function adds the local private key (DER-encoded or PEM-encoded or PKCS#8 private key) into the specified TLS object for TLS negotiation. @param[in] Tls Pointer to the TLS object. - @param[in] Data Pointer to the data buffer of a PEM-encoded RSA + @param[in] Data Pointer to the data buffer of a DER-encoded or PEM-encoded or PKCS#8 private key. @param[in] DataSize The size of data buffer in bytes. @@ -3680,6 +3726,82 @@ EFI_STATUS IN OUT UINTN *DataSize ); +/** + Set the signature algorithm list to used by the TLS object. + + This function sets the signature algorithms for use by a specified TLS object. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data Array of UINT8 of signature algorithms. The array consists of + pairs of the hash algorithm and the signature algorithm as defined + in RFC 5246 + @param[in] DataSize The length the SignatureAlgoList. Must be divisible by 2. + + @retval EFI_SUCCESS The signature algorithm list was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED No supported TLS signature algorithm was found in SignatureAlgoList + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_CRYPTO_TLS_SET_SIGNATURE_ALGO_LIST)( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ); + +/** + Set the EC curve to be used for TLS flows + + This function sets the EC curve to be used for TLS flows. + + @param[in] Tls Pointer to a TLS object. + @param[in] Data An EC named curve as defined in section 5.1.1 of RFC 4492. + @param[in] DataSize Size of Data, it should be sizeof (UINT32) + + @retval EFI_SUCCESS The EC curve was set successfully. + @retval EFI_INVALID_PARAMETER The parameters are invalid. + @retval EFI_UNSUPPORTED The requested TLS EC curve is not supported + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_CRYPTO_TLS_SET_EC_CURVE)( + IN VOID *Tls, + IN UINT8 *Data, + IN UINTN DataSize + ); + +/** + Derive keying material from a TLS connection. + + This function exports keying material using the mechanism described in RFC + 5705. + + @param[in] Tls Pointer to the TLS object + @param[in] Label Description of the key for the PRF function + @param[in] Context Optional context + @param[in] ContextLen The length of the context value in bytes + @param[out] KeyBuffer Buffer to hold the output of the TLS-PRF + @param[in] KeyBufferLen The length of the KeyBuffer + + @retval EFI_SUCCESS The operation succeeded. + @retval EFI_INVALID_PARAMETER The TLS object is invalid. + @retval EFI_PROTOCOL_ERROR Some other error occurred. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_CRYPTO_TLS_GET_EXPORT_KEY)( + IN VOID *Tls, + IN CONST VOID *Label, + IN CONST VOID *Context, + IN UINTN ContextLen, + OUT VOID *KeyBuffer, + IN UINTN KeyBufferLen + ); + /** Gets the CA-supplied certificate revocation list data set in the specified TLS object. @@ -4954,6 +5076,14 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_EC_GENERATE_KEY EcGenerateKey; EDKII_CRYPTO_EC_GET_PUB_KEY EcGetPubKey; EDKII_CRYPTO_EC_DH_COMPUTE_KEY EcDhComputeKey; + /// TLS (continued) + EDKII_CRYPTO_TLS_SHUTDOWN TlsShutdown; + /// TLS Set (continued) + EDKII_CRYPTO_TLS_SET_HOST_PRIVATE_KEY_EX TlsSetHostPrivateKeyEx; + EDKII_CRYPTO_TLS_SET_SIGNATURE_ALGO_LIST TlsSetSignatureAlgoList; + EDKII_CRYPTO_TLS_SET_EC_CURVE TlsSetEcCurve; + /// TLS Get (continued) + EDKII_CRYPTO_TLS_GET_EXPORT_KEY TlsGetExportKey; }; extern GUID gEdkiiCryptoProtocolGuid; From 2845d381aa3414dd49142aa450d92bd3ba2a03a4 Mon Sep 17 00:00:00 2001 From: Dimitrije Pavlov Date: Wed, 17 Aug 2022 09:35:03 -0500 Subject: [PATCH 0119/1529] OvmfPkg/VirtioNetDxe: Check ChildHandle argument in GetControllerName Per the UEFI specification, a device driver implementation should return EFI_UNSUPPORTED if the ChildHandle argument in EFI_COMPONENT_NAME2_PROTOCOL.GetControllerName() is not NULL. Signed-off-by: Dimitrije Pavlov Reviewed-by: Samer El-Haj-Mahmoud Reviewed-by: Sunny Wang --- OvmfPkg/VirtioNetDxe/ComponentName.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/OvmfPkg/VirtioNetDxe/ComponentName.c b/OvmfPkg/VirtioNetDxe/ComponentName.c index e340ca2f8f..718096630f 100644 --- a/OvmfPkg/VirtioNetDxe/ComponentName.c +++ b/OvmfPkg/VirtioNetDxe/ComponentName.c @@ -129,6 +129,13 @@ VirtioNetGetControllerName ( return EFI_INVALID_PARAMETER; } + // + // This is a device driver, so ChildHandle must be NULL. + // + if (ChildHandle != NULL) { + return EFI_UNSUPPORTED; + } + // // confirm that the device is managed by this driver, using the VirtIo // Protocol From 6485a2ac5352e670508d5d4186d7ce73645c8de2 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 10:47:58 +0800 Subject: [PATCH 0120/1529] CryptoPkg: Add EC key retrieving and signature interface. This patch is used to retrieve EC key from PEM and X509 and carry out the EC-DSA signature and verify it. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4102 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 129 +++++++++ CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c | 87 ++++++ .../Library/BaseCryptLib/Pem/CryptPemNull.c | 30 ++ CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c | 258 ++++++++++++++++++ .../Library/BaseCryptLib/Pk/CryptEcNull.c | 82 ++++++ CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c | 83 ++++++ .../Library/BaseCryptLib/Pk/CryptX509Null.c | 28 ++ .../BaseCryptLibNull/Pem/CryptPemNull.c | 30 ++ .../Library/BaseCryptLibNull/Pk/CryptEcNull.c | 82 ++++++ .../BaseCryptLibNull/Pk/CryptX509Null.c | 28 ++ 10 files changed, 837 insertions(+) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index 63c6228368..dfeb8c7d55 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -16,6 +16,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define CRYPTO_NID_NULL 0x0000 +// Hash +#define CRYPTO_NID_SHA256 0x0001 +#define CRYPTO_NID_SHA384 0x0002 +#define CRYPTO_NID_SHA512 0x0003 + // Key Exchange #define CRYPTO_NID_SECP256R1 0x0204 #define CRYPTO_NID_SECP384R1 0x0205 @@ -3678,4 +3683,128 @@ EcDhComputeKey ( IN OUT UINTN *KeySize ); +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +EcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ); + +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +EcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ); + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +EcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ); + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +EcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ); + #endif // __BASE_CRYPT_LIB_H__ diff --git a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c index 7733d772f4..559a6b4df0 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c +++ b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c @@ -126,3 +126,90 @@ RsaGetPrivateKeyFromPem ( return Status; } + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +EcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ) +{ + #if FixedPcdGetBool (PcdOpensslEcEnabled) + BOOLEAN Status; + BIO *PemBio; + + // + // Check input parameters. + // + if ((PemData == NULL) || (EcContext == NULL) || (PemSize > INT_MAX)) { + return FALSE; + } + + // + // Add possible block-cipher descriptor for PEM data decryption. + // NOTE: Only support most popular ciphers AES for the encrypted PEM. + // + if (EVP_add_cipher (EVP_aes_128_cbc ()) == 0) { + return FALSE; + } + + if (EVP_add_cipher (EVP_aes_192_cbc ()) == 0) { + return FALSE; + } + + if (EVP_add_cipher (EVP_aes_256_cbc ()) == 0) { + return FALSE; + } + + Status = FALSE; + + // + // Read encrypted PEM Data. + // + PemBio = BIO_new (BIO_s_mem ()); + if (PemBio == NULL) { + goto _Exit; + } + + if (BIO_write (PemBio, PemData, (int)PemSize) <= 0) { + goto _Exit; + } + + // + // Retrieve EC Private Key from encrypted PEM data. + // + *EcContext = PEM_read_bio_ECPrivateKey (PemBio, NULL, (pem_password_cb *)&PasswordCallback, (void *)Password); + if (*EcContext != NULL) { + Status = TRUE; + } + +_Exit: + // + // Release Resources. + // + BIO_free (PemBio); + + return Status; + #else + return FALSE; + #endif +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPemNull.c b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPemNull.c index 4eeabd91ad..4ca9357c96 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPemNull.c +++ b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPemNull.c @@ -36,3 +36,33 @@ RsaGetPrivateKeyFromPem ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +EcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c index 396c819834..d8cc9ba0e8 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEc.c @@ -763,3 +763,261 @@ EcDhComputeKey ( EC_KEY_free (PeerEcKey); return RetVal; } + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +EcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ) +{ + EC_KEY *EcKey; + ECDSA_SIG *EcDsaSig; + INT32 OpenSslNid; + UINT8 HalfSize; + BIGNUM *R; + BIGNUM *S; + INTN RSize; + INTN SSize; + + if ((EcContext == NULL) || (MessageHash == NULL)) { + return FALSE; + } + + if (Signature == NULL) { + return FALSE; + } + + EcKey = (EC_KEY *)EcContext; + OpenSslNid = EC_GROUP_get_curve_name (EC_KEY_get0_group (EcKey)); + switch (OpenSslNid) { + case NID_X9_62_prime256v1: + HalfSize = 32; + break; + case NID_secp384r1: + HalfSize = 48; + break; + case NID_secp521r1: + HalfSize = 66; + break; + default: + return FALSE; + } + + if (*SigSize < (UINTN)(HalfSize * 2)) { + *SigSize = HalfSize * 2; + return FALSE; + } + + *SigSize = HalfSize * 2; + ZeroMem (Signature, *SigSize); + + switch (HashNid) { + case CRYPTO_NID_SHA256: + if (HashSize != SHA256_DIGEST_SIZE) { + return FALSE; + } + + break; + + case CRYPTO_NID_SHA384: + if (HashSize != SHA384_DIGEST_SIZE) { + return FALSE; + } + + break; + + case CRYPTO_NID_SHA512: + if (HashSize != SHA512_DIGEST_SIZE) { + return FALSE; + } + + break; + + default: + return FALSE; + } + + EcDsaSig = ECDSA_do_sign ( + MessageHash, + (UINT32)HashSize, + (EC_KEY *)EcContext + ); + if (EcDsaSig == NULL) { + return FALSE; + } + + ECDSA_SIG_get0 (EcDsaSig, (CONST BIGNUM **)&R, (CONST BIGNUM **)&S); + + RSize = BN_num_bytes (R); + SSize = BN_num_bytes (S); + if ((RSize <= 0) || (SSize <= 0)) { + ECDSA_SIG_free (EcDsaSig); + return FALSE; + } + + ASSERT ((UINTN)RSize <= HalfSize && (UINTN)SSize <= HalfSize); + + BN_bn2bin (R, &Signature[0 + HalfSize - RSize]); + BN_bn2bin (S, &Signature[HalfSize + HalfSize - SSize]); + + ECDSA_SIG_free (EcDsaSig); + + return TRUE; +} + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +EcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ) +{ + INT32 Result; + EC_KEY *EcKey; + ECDSA_SIG *EcDsaSig; + INT32 OpenSslNid; + UINT8 HalfSize; + BIGNUM *R; + BIGNUM *S; + + if ((EcContext == NULL) || (MessageHash == NULL) || (Signature == NULL)) { + return FALSE; + } + + if ((SigSize > INT_MAX) || (SigSize == 0)) { + return FALSE; + } + + EcKey = (EC_KEY *)EcContext; + OpenSslNid = EC_GROUP_get_curve_name (EC_KEY_get0_group (EcKey)); + switch (OpenSslNid) { + case NID_X9_62_prime256v1: + HalfSize = 32; + break; + case NID_secp384r1: + HalfSize = 48; + break; + case NID_secp521r1: + HalfSize = 66; + break; + default: + return FALSE; + } + + if (SigSize != (UINTN)(HalfSize * 2)) { + return FALSE; + } + + switch (HashNid) { + case CRYPTO_NID_SHA256: + if (HashSize != SHA256_DIGEST_SIZE) { + return FALSE; + } + + break; + + case CRYPTO_NID_SHA384: + if (HashSize != SHA384_DIGEST_SIZE) { + return FALSE; + } + + break; + + case CRYPTO_NID_SHA512: + if (HashSize != SHA512_DIGEST_SIZE) { + return FALSE; + } + + break; + + default: + return FALSE; + } + + EcDsaSig = ECDSA_SIG_new (); + if (EcDsaSig == NULL) { + ECDSA_SIG_free (EcDsaSig); + return FALSE; + } + + R = BN_bin2bn (Signature, (UINT32)HalfSize, NULL); + S = BN_bin2bn (Signature + HalfSize, (UINT32)HalfSize, NULL); + if ((R == NULL) || (S == NULL)) { + ECDSA_SIG_free (EcDsaSig); + return FALSE; + } + + ECDSA_SIG_set0 (EcDsaSig, R, S); + + Result = ECDSA_do_verify ( + MessageHash, + (UINT32)HashSize, + EcDsaSig, + (EC_KEY *)EcContext + ); + + ECDSA_SIG_free (EcDsaSig); + + return (Result == 1); +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c index d9f1004f6c..1129fa7696 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptEcNull.c @@ -494,3 +494,85 @@ EcDhComputeKey ( ASSERT (FALSE); return FALSE; } + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +EcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +EcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index e6bb45e641..58d3f27b11 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -842,3 +842,86 @@ X509GetTBSCert ( return TRUE; } + +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +EcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ) +{ + #if FixedPcdGetBool (PcdOpensslEcEnabled) + BOOLEAN Status; + EVP_PKEY *Pkey; + X509 *X509Cert; + + // + // Check input parameters. + // + if ((Cert == NULL) || (EcContext == NULL)) { + return FALSE; + } + + Pkey = NULL; + X509Cert = NULL; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + Status = FALSE; + goto _Exit; + } + + Status = FALSE; + + // + // Retrieve and check EVP_PKEY data from X509 Certificate. + // + Pkey = X509_get_pubkey (X509Cert); + if ((Pkey == NULL) || (EVP_PKEY_id (Pkey) != EVP_PKEY_EC)) { + goto _Exit; + } + + // + // Duplicate EC Context from the retrieved EVP_PKEY. + // + if ((*EcContext = EC_KEY_dup (EVP_PKEY_get0_EC_KEY (Pkey))) != NULL) { + Status = TRUE; + } + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + if (Pkey != NULL) { + EVP_PKEY_free (Pkey); + } + + return Status; + #else + return FALSE; + #endif +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c index 38819723c7..c6718e6aeb 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c @@ -292,3 +292,31 @@ X509GetTBSCert ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +EcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Pem/CryptPemNull.c b/CryptoPkg/Library/BaseCryptLibNull/Pem/CryptPemNull.c index 4eeabd91ad..4ca9357c96 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/Pem/CryptPemNull.c +++ b/CryptoPkg/Library/BaseCryptLibNull/Pem/CryptPemNull.c @@ -36,3 +36,33 @@ RsaGetPrivateKeyFromPem ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +EcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c index d9f1004f6c..1129fa7696 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c +++ b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptEcNull.c @@ -494,3 +494,85 @@ EcDhComputeKey ( ASSERT (FALSE); return FALSE; } + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +EcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +EcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c index 38819723c7..c6718e6aeb 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c +++ b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c @@ -292,3 +292,31 @@ X509GetTBSCert ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +EcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ) +{ + ASSERT (FALSE); + return FALSE; +} From e0f19202835e99a72a84eace661fe32a6b43e3f9 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 10:47:59 +0800 Subject: [PATCH 0121/1529] CryptoPkg: Add EC key interface to DXE and protocol The implementation provide EC key interface for EFI driver nad EFI BaseCrypt protocol. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4102 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- CryptoPkg/Driver/Crypto.c | 143 +++++++++++++++++- .../Pcd/PcdCryptoServiceFamilyEnable.h | 4 + .../BaseCryptLibOnProtocolPpi/CryptLib.c | 136 +++++++++++++++++ CryptoPkg/Private/Protocol/Crypto.h | 131 +++++++++++++++- 4 files changed, 412 insertions(+), 2 deletions(-) diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index f1ff77855c..1928adbff7 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -6137,6 +6137,142 @@ CryptoServiceEcDhComputeKey ( return CALL_BASECRYPTLIB (Ec.Services.DhComputeKey, EcDhComputeKey, (EcContext, PeerPublic, PeerPublicSize, CompressFlag, Key, KeySize), FALSE); } +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GetPublicKeyFromX509, EcGetPublicKeyFromX509, (Cert, CertSize, EcContext), FALSE); +} + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +CryptoServiceEcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.GetPrivateKeyFromPem, EcGetPrivateKeyFromPem, (PemData, PemSize, Password, EcContext), FALSE); +} + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +CryptoServiceEcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.DsaSign, EcDsaSign, (EcContext, HashNid, MessageHash, HashSize, Signature, SigSize), FALSE); +} + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +CryptoServiceEcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ) +{ + return CALL_BASECRYPTLIB (Ec.Services.DsaVerify, EcDsaVerify, (EcContext, HashNid, MessageHash, HashSize, Signature, SigSize), FALSE); +} + const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { /// Version CryptoServiceGetCryptoVersion, @@ -6416,5 +6552,10 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceTlsSetSignatureAlgoList, CryptoServiceTlsSetEcCurve, /// TLS Get (continued) - CryptoServiceTlsGetExportKey + CryptoServiceTlsGetExportKey, + /// Ec (Continued) + CryptoServiceEcGetPublicKeyFromX509, + CryptoServiceEcGetPrivateKeyFromPem, + CryptoServiceEcDsaSign, + CryptoServiceEcDsaVerify }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 4740589417..12b0c0583e 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -383,6 +383,10 @@ typedef struct { UINT8 GenerateKey : 1; UINT8 GetPubKey : 1; UINT8 DhComputeKey : 1; + UINT8 GetPublicKeyFromX509 : 1; + UINT8 GetPrivateKeyFromPem : 1; + UINT8 DsaSign : 1; + UINT8 DsaVerify : 1; } Services; UINT32 Family; } Ec; diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 52b934a545..48ec6d3528 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -5164,3 +5164,139 @@ EcDhComputeKey ( { CALL_CRYPTO_SERVICE (EcDhComputeKey, (EcContext, PeerPublic, PeerPublicSize, CompressFlag, Key, KeySize), FALSE); } + +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +BOOLEAN +EFIAPI +EcGetPublicKeyFromX509 ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ) +{ + CALL_CRYPTO_SERVICE (EcGetPublicKeyFromX509, (Cert, CertSize, EcContext), FALSE); +} + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +BOOLEAN +EFIAPI +EcGetPrivateKeyFromPem ( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ) +{ + CALL_CRYPTO_SERVICE (EcGetPrivateKeyFromPem, (PemData, PemSize, Password, EcContext), FALSE); +} + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +BOOLEAN +EFIAPI +EcDsaSign ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ) +{ + CALL_CRYPTO_SERVICE (EcDsaSign, (EcContext, HashNid, MessageHash, HashSize, Signature, SigSize), FALSE); +} + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +BOOLEAN +EFIAPI +EcDsaVerify ( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ) +{ + CALL_CRYPTO_SERVICE (EcDsaVerify, (EcContext, HashNid, MessageHash, HashSize, Signature, SigSize), FALSE); +} diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index 6293efa36b..bfb278d388 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 14 +#define EDKII_CRYPTO_VERSION 15 /// /// EDK II Crypto Protocol forward declaration @@ -4821,6 +4821,130 @@ BOOLEAN IN OUT UINTN *KeySize ); +/** + Retrieve the EC Public Key from one DER-encoded X509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC public key component. Use EcFree() function to free the + resource. + + If Cert is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Public Key was retrieved successfully. + @retval FALSE Fail to retrieve EC public key from X509 certificate. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GET_PUBLIC_KEY_FROM_X509)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT VOID **EcContext + ); + +/** + Retrieve the EC Private Key from the password-protected PEM key data. + + @param[in] PemData Pointer to the PEM-encoded key data to be retrieved. + @param[in] PemSize Size of the PEM key data in bytes. + @param[in] Password NULL-terminated passphrase used for encrypted PEM key data. + @param[out] EcContext Pointer to new-generated EC DSA context which contain the retrieved + EC private key component. Use EcFree() function to free the + resource. + + If PemData is NULL, then return FALSE. + If EcContext is NULL, then return FALSE. + + @retval TRUE EC Private Key was retrieved successfully. + @retval FALSE Invalid PEM key data or incorrect password. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_GET_PRIVATE_KEY_FROM_PEM)( + IN CONST UINT8 *PemData, + IN UINTN PemSize, + IN CONST CHAR8 *Password, + OUT VOID **EcContext + ); + +/** + Carries out the EC-DSA signature. + + This function carries out the EC-DSA signature. + If the Signature buffer is too small to hold the contents of signature, FALSE + is returned and SigSize is set to the required buffer size to obtain the signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + If SigSize is large enough but Signature is NULL, then return FALSE. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature generation. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be signed. + @param[in] HashSize Size of the message hash in bytes. + @param[out] Signature Pointer to buffer to receive EC-DSA signature. + @param[in, out] SigSize On input, the size of Signature buffer in bytes. + On output, the size of data returned in Signature buffer in bytes. + + @retval TRUE Signature successfully generated in EC-DSA. + @retval FALSE Signature generation failed. + @retval FALSE SigSize is too small. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_DSA_SIGN)( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + OUT UINT8 *Signature, + IN OUT UINTN *SigSize + ); + +/** + Verifies the EC-DSA signature. + + If EcContext is NULL, then return FALSE. + If MessageHash is NULL, then return FALSE. + If Signature is NULL, then return FALSE. + If HashSize need match the HashNid. HashNid could be SHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512. + + For P-256, the SigSize is 64. First 32-byte is R, Second 32-byte is S. + For P-384, the SigSize is 96. First 48-byte is R, Second 48-byte is S. + For P-521, the SigSize is 132. First 66-byte is R, Second 66-byte is S. + + @param[in] EcContext Pointer to EC context for signature verification. + @param[in] HashNid hash NID + @param[in] MessageHash Pointer to octet message hash to be checked. + @param[in] HashSize Size of the message hash in bytes. + @param[in] Signature Pointer to EC-DSA signature to be verified. + @param[in] SigSize Size of signature in bytes. + + @retval TRUE Valid signature encoded in EC-DSA. + @retval FALSE Invalid signature or invalid EC context. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_EC_DSA_VERIFY)( + IN VOID *EcContext, + IN UINTN HashNid, + IN CONST UINT8 *MessageHash, + IN UINTN HashSize, + IN CONST UINT8 *Signature, + IN UINTN SigSize + ); + /// /// EDK II Crypto Protocol /// @@ -5084,6 +5208,11 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_TLS_SET_EC_CURVE TlsSetEcCurve; /// TLS Get (continued) EDKII_CRYPTO_TLS_GET_EXPORT_KEY TlsGetExportKey; + /// Ec (Continued) + EDKII_CRYPTO_EC_GET_PUBLIC_KEY_FROM_X509 EcGetPublicKeyFromX509; + EDKII_CRYPTO_EC_GET_PRIVATE_KEY_FROM_PEM EcGetPrivateKeyFromPem; + EDKII_CRYPTO_EC_DSA_SIGN EcDsaSign; + EDKII_CRYPTO_EC_DSA_VERIFY EcDsaVerify; }; extern GUID gEdkiiCryptoProtocolGuid; From 4a5e56c24103a5edbc7f0766283d011e3ae739f2 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 10:48:00 +0800 Subject: [PATCH 0122/1529] CryptoPkg: add unit test for EC key interface. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4102 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- .../UnitTest/Library/BaseCryptLib/EcTests.c | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c index 54ce0b22df..ee1e6e870b 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/EcTests.c @@ -60,6 +60,89 @@ struct Generator EcCurveGenerator[EC_CURVE_NUM_SUPPORTED] = } }; +// +// Root CA X509 Certificate for X509 Verification Routine (Generated by OpenSSL utility). +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mEccTestRootCer[] = { + 0x30, 0x82, 0x01, 0xd2, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03, 0x02, 0x01, + 0x02, 0x02, 0x09, 0x00, 0xcc, 0x10, 0x45, 0x50, 0xaf, 0x50, 0x1b, 0xe2, + 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, + 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, + 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, + 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, + 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, + 0x1e, 0x17, 0x0d, 0x32, 0x30, 0x30, 0x32, 0x32, 0x37, 0x31, 0x32, 0x30, + 0x32, 0x31, 0x30, 0x5a, 0x17, 0x0d, 0x33, 0x30, 0x30, 0x32, 0x32, 0x34, + 0x31, 0x32, 0x30, 0x32, 0x31, 0x30, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, + 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, + 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, + 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, + 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, + 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, + 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x11, 0xa4, 0x06, + 0x65, 0xb6, 0x79, 0x6e, 0x72, 0xb6, 0xd8, 0x09, 0x84, 0x92, 0x86, 0x11, + 0x09, 0xde, 0xea, 0xd0, 0x0c, 0x60, 0xf1, 0x8a, 0xff, 0x7c, 0xde, 0xce, + 0xec, 0x07, 0xba, 0xa5, 0xb8, 0xd5, 0x17, 0xe5, 0x62, 0x33, 0x2d, 0x88, + 0xb1, 0x9a, 0xe6, 0xf3, 0x09, 0x43, 0x0e, 0xa9, 0xf7, 0x3c, 0xe9, 0x20, + 0xba, 0xbd, 0xb1, 0x3c, 0x03, 0x89, 0x1e, 0x2a, 0xff, 0x6e, 0x08, 0xff, + 0x2e, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, + 0x04, 0x16, 0x04, 0x14, 0x62, 0xe6, 0xd9, 0xa0, 0xee, 0x38, 0x18, 0x83, + 0xfa, 0xe3, 0xed, 0x44, 0xa4, 0x37, 0xfd, 0x4a, 0x04, 0xdf, 0xe1, 0xd5, + 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, + 0x14, 0x62, 0xe6, 0xd9, 0xa0, 0xee, 0x38, 0x18, 0x83, 0xfa, 0xe3, 0xed, + 0x44, 0xa4, 0x37, 0xfd, 0x4a, 0x04, 0xdf, 0xe1, 0xd5, 0x30, 0x0c, 0x06, + 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, + 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, + 0x49, 0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0x99, 0x2f, 0x43, 0xeb, 0xdc, + 0x4e, 0x53, 0xc7, 0xc1, 0xbd, 0xed, 0x95, 0xdc, 0xae, 0xd3, 0x75, 0xfa, + 0xc4, 0xf7, 0xa4, 0x61, 0x00, 0x57, 0xce, 0xf3, 0xe0, 0x23, 0xf6, 0xf0, + 0x41, 0x6f, 0xb5, 0x02, 0x21, 0x00, 0xf3, 0x97, 0x11, 0x06, 0x61, 0x10, + 0xc7, 0x35, 0xe9, 0xf8, 0x3b, 0x59, 0xec, 0xf5, 0x51, 0xa0, 0xa6, 0x64, + 0x6e, 0xe1, 0x44, 0xc7, 0xe1, 0xa2, 0xce, 0x90, 0x7f, 0xae, 0xad, 0xf4, + 0xa9, 0xfa, +}; + +// +// PEM key data for EC Private key Retrieving. (Generated by OpenSSL utility). +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mEccTestPemKey[] = { + 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x45, + 0x43, 0x20, 0x50, 0x41, 0x52, 0x41, 0x4d, 0x45, 0x54, 0x45, 0x52, 0x53, + 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x42, 0x67, 0x67, 0x71, 0x68, 0x6b, + 0x6a, 0x4f, 0x50, 0x51, 0x4d, 0x42, 0x42, 0x77, 0x3d, 0x3d, 0x0a, 0x2d, + 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x45, 0x43, 0x20, 0x50, + 0x41, 0x52, 0x41, 0x4d, 0x45, 0x54, 0x45, 0x52, 0x53, 0x2d, 0x2d, 0x2d, + 0x2d, 0x2d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, + 0x4e, 0x20, 0x45, 0x43, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, + 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x48, + 0x63, 0x43, 0x41, 0x51, 0x45, 0x45, 0x49, 0x4d, 0x4a, 0x54, 0x69, 0x75, + 0x34, 0x56, 0x54, 0x54, 0x57, 0x68, 0x78, 0x4b, 0x62, 0x51, 0x65, 0x78, + 0x6e, 0x30, 0x43, 0x58, 0x41, 0x77, 0x33, 0x44, 0x57, 0x6b, 0x6f, 0x78, + 0x79, 0x77, 0x6b, 0x7a, 0x46, 0x50, 0x62, 0x32, 0x48, 0x68, 0x5a, 0x6e, + 0x5a, 0x52, 0x6f, 0x41, 0x6f, 0x47, 0x43, 0x43, 0x71, 0x47, 0x53, 0x4d, + 0x34, 0x39, 0x0a, 0x41, 0x77, 0x45, 0x48, 0x6f, 0x55, 0x51, 0x44, 0x51, + 0x67, 0x41, 0x45, 0x45, 0x61, 0x51, 0x47, 0x5a, 0x62, 0x5a, 0x35, 0x62, + 0x6e, 0x4b, 0x32, 0x32, 0x41, 0x6d, 0x45, 0x6b, 0x6f, 0x59, 0x52, 0x43, + 0x64, 0x37, 0x71, 0x30, 0x41, 0x78, 0x67, 0x38, 0x59, 0x72, 0x2f, 0x66, + 0x4e, 0x37, 0x4f, 0x37, 0x41, 0x65, 0x36, 0x70, 0x62, 0x6a, 0x56, 0x46, + 0x2b, 0x56, 0x69, 0x4d, 0x79, 0x32, 0x49, 0x0a, 0x73, 0x5a, 0x72, 0x6d, + 0x38, 0x77, 0x6c, 0x44, 0x44, 0x71, 0x6e, 0x33, 0x50, 0x4f, 0x6b, 0x67, + 0x75, 0x72, 0x32, 0x78, 0x50, 0x41, 0x4f, 0x4a, 0x48, 0x69, 0x72, 0x2f, + 0x62, 0x67, 0x6a, 0x2f, 0x4c, 0x67, 0x3d, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, + 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x45, 0x43, 0x20, 0x50, 0x52, 0x49, + 0x56, 0x41, 0x54, 0x45, 0x20, 0x4b, 0x45, 0x59, 0x2d, 0x2d, 0x2d, 0x2d, + 0x2d, 0x0a, +}; + +// +// Payload for PKCS#7 Signing & Verification Validation. +// +CONST CHAR8 *mEcPayload = "payload data for PKCS#7 EC Signing"; + VOID *Ec1; VOID *Ec2; VOID *Group; @@ -279,12 +362,85 @@ TestVerifyEcDh ( return UNIT_TEST_PASSED; } +UNIT_TEST_STATUS +EFIAPI +TestVerifyEcKey ( + UNIT_TEST_CONTEXT Context + ) +{ + BOOLEAN Status; + VOID *EcPrivKey; + VOID *EcPubKey; + UINT8 HashValue[SHA256_DIGEST_SIZE]; + UINTN HashSize; + UINT8 Signature[66 * 2]; + UINTN SigSize; + + // + // Retrieve EC private key from PEM data. + // + Status = EcGetPrivateKeyFromPem ( + mEccTestPemKey, + sizeof (mEccTestPemKey), + NULL, + &EcPrivKey + ); + UT_ASSERT_TRUE (Status); + + // + // Retrieve EC public key from X509 Certificate. + // + Status = EcGetPublicKeyFromX509 ( + mEccTestRootCer, + sizeof (mEccTestRootCer), + &EcPubKey + ); + UT_ASSERT_TRUE (Status); + + // + // Verify EC-DSA + // + HashSize = sizeof (HashValue); + SigSize = sizeof (Signature); + // + // EC-DSA Signing ... + // + Status = EcDsaSign ( + EcPrivKey, + CRYPTO_NID_SHA256, + HashValue, + HashSize, + Signature, + &SigSize + ); + UT_ASSERT_TRUE (Status); + + // + // EC-DSA Verification ... + // + Status = EcDsaVerify ( + EcPubKey, + CRYPTO_NID_SHA256, + HashValue, + HashSize, + Signature, + SigSize + ); + UT_ASSERT_TRUE (Status); + + EcFree (EcPrivKey); + EcFree (EcPubKey); + + return UNIT_TEST_PASSED; +} + TEST_DESC mEcTest[] = { // // -----Description-----------------Class------------------Function----Pre----Post----Context // { "TestVerifyEcBasic()", "CryptoPkg.BaseCryptLib.Ec", TestVerifyEcBasic, TestVerifyEcPreReq, TestVerifyEcCleanUp, NULL }, { "TestVerifyEcDh()", "CryptoPkg.BaseCryptLib.Ec", TestVerifyEcDh, TestVerifyEcPreReq, TestVerifyEcCleanUp, NULL }, + { "TestVerifyEcKey()", "CryptoPkg.BaseCryptLib.Ec", TestVerifyEcKey, NULL, NULL, NULL }, }; UINTN mEcTestNum = ARRAY_SIZE (mEcTest); From 5defa682e4d1b1253decdf4b71336bc38f2e1eba Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 12:35:58 +0800 Subject: [PATCH 0123/1529] CryptoPkg: add new X509 function definition. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4082 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- CryptoPkg/Include/Library/BaseCryptLib.h | 374 +++++++++++++++++++++++ 1 file changed, 374 insertions(+) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index dfeb8c7d55..a52bd91ad6 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -2471,6 +2471,380 @@ ImageTimestampVerify ( OUT EFI_TIME *SigningTime ); +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ); + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ); + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ); + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ); + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ); + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[in] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ); + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ); + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +X509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ); + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ); + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ); + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +X509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ); + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. If index is -1 indecate the + last certificate in CertChain. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +X509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ); + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +Asn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ); + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +X509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ); + // ===================================================================================== // DH Key Exchange Primitive // ===================================================================================== From 12533324d0c3d8538742bbe2bc91ebb5aea2a22a Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 12:35:59 +0800 Subject: [PATCH 0124/1529] CryptoPkg: add new X509 function. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4082 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c | 1036 +++++++++++++++++ .../Library/BaseCryptLib/Pk/CryptX509Null.c | 429 +++++++ .../BaseCryptLibNull/Pk/CryptX509Null.c | 429 +++++++ 3 files changed, 1894 insertions(+) diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index 58d3f27b11..1d91ac3b0f 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -8,8 +8,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalCryptLib.h" #include +#include +#include +#include #include +/* OID*/ +#define OID_EXT_KEY_USAGE { 0x55, 0x1D, 0x25 } +#define OID_BASIC_CONSTRAINTS { 0x55, 0x1D, 0x13 } + +static CONST UINT8 mOidExtKeyUsage[] = OID_EXT_KEY_USAGE; +static CONST UINT8 mOidBasicConstraints[] = OID_BASIC_CONSTRAINTS; + +#define CRYPTO_ASN1_TAG_CLASS_MASK 0xC0 +#define CRYPTO_ASN1_TAG_PC_MASK 0x20 +#define CRYPTO_ASN1_TAG_VALUE_MASK 0x1F + /** Construct a X509 object from DER-encoded certificate data. @@ -925,3 +939,1025 @@ EcGetPublicKeyFromX509 ( return FALSE; #endif } + +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ) +{ + BOOLEAN Status; + X509 *X509Cert; + + X509Cert = NULL; + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + // + // Invalid X.509 Certificate + // + Status = FALSE; + } + + if (Status) { + *Version = X509_get_version (X509Cert); + } + + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ) +{ + BOOLEAN Status; + X509 *X509Cert; + ASN1_INTEGER *Asn1Integer; + + Status = FALSE; + // + // Check input parameters. + // + if ((Cert == NULL) || (SerialNumberSize == NULL)) { + return Status; + } + + X509Cert = NULL; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + *SerialNumberSize = 0; + Status = FALSE; + goto _Exit; + } + + // + // Retrieve subject name from certificate object. + // + Asn1Integer = X509_get_serialNumber (X509Cert); + if (Asn1Integer == NULL) { + *SerialNumberSize = 0; + Status = FALSE; + goto _Exit; + } + + if (*SerialNumberSize < (UINTN)Asn1Integer->length) { + *SerialNumberSize = (UINTN)Asn1Integer->length; + Status = FALSE; + goto _Exit; + } + + if (SerialNumber != NULL) { + CopyMem (SerialNumber, Asn1Integer->data, *SerialNumberSize); + Status = TRUE; + } + + *SerialNumberSize = (UINTN)Asn1Integer->length; + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ) +{ + BOOLEAN Status; + X509 *X509Cert; + X509_NAME *X509Name; + UINTN X509NameSize; + + // + // Check input parameters. + // + if ((Cert == NULL) || (CertIssuerSize == NULL)) { + return FALSE; + } + + X509Cert = NULL; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + Status = FALSE; + goto _Exit; + } + + Status = FALSE; + + // + // Retrieve subject name from certificate object. + // + X509Name = X509_get_subject_name (X509Cert); + if (X509Name == NULL) { + goto _Exit; + } + + X509NameSize = i2d_X509_NAME (X509Name, NULL); + if (*CertIssuerSize < X509NameSize) { + *CertIssuerSize = X509NameSize; + goto _Exit; + } + + *CertIssuerSize = X509NameSize; + if (CertIssuer != NULL) { + i2d_X509_NAME (X509Name, &CertIssuer); + Status = TRUE; + } + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ) +{ + BOOLEAN Status; + X509 *X509Cert; + int Nid; + ASN1_OBJECT *Asn1Obj; + + // + // Check input parameters. + // + if ((Cert == NULL) || (OidSize == NULL) || (CertSize == 0)) { + return FALSE; + } + + X509Cert = NULL; + Status = FALSE; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + Status = FALSE; + goto _Exit; + } + + // + // Retrieve subject name from certificate object. + // + Nid = X509_get_signature_nid (X509Cert); + if (Nid == NID_undef) { + *OidSize = 0; + Status = FALSE; + goto _Exit; + } + + Asn1Obj = OBJ_nid2obj (Nid); + if (Asn1Obj == NULL) { + *OidSize = 0; + Status = FALSE; + goto _Exit; + } + + if (*OidSize < (UINTN)Asn1Obj->length) { + *OidSize = Asn1Obj->length; + Status = FALSE; + goto _Exit; + } + + if (Oid != NULL) { + CopyMem (Oid, Asn1Obj->data, Asn1Obj->length); + } + + *OidSize = Asn1Obj->length; + Status = TRUE; + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ) +{ + BOOLEAN Status; + INTN i; + X509 *X509Cert; + + CONST STACK_OF (X509_EXTENSION) *Extensions; + ASN1_OBJECT *Asn1Obj; + ASN1_OCTET_STRING *Asn1Oct; + X509_EXTENSION *Ext; + UINTN ObjLength; + UINTN OctLength; + + // + // Check input parameters. + // + if ((Cert == NULL) || (CertSize == 0) || (Oid == NULL) || (OidSize == 0) || (ExtensionDataSize == NULL)) { + return FALSE; + } + + X509Cert = NULL; + Status = FALSE; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + *ExtensionDataSize = 0; + goto Cleanup; + } + + // + // Retrieve Extensions from certificate object. + // + Extensions = X509_get0_extensions (X509Cert); + if (sk_X509_EXTENSION_num (Extensions) <= 0) { + *ExtensionDataSize = 0; + goto Cleanup; + } + + // + // Traverse Extensions + // + Status = FALSE; + Asn1Oct = NULL; + OctLength = 0; + for (i = 0; i < sk_X509_EXTENSION_num (Extensions); i++) { + Ext = sk_X509_EXTENSION_value (Extensions, (int)i); + if (Ext == NULL) { + continue; + } + + Asn1Obj = X509_EXTENSION_get_object (Ext); + if (Asn1Obj == NULL) { + continue; + } + + Asn1Oct = X509_EXTENSION_get_data (Ext); + if (Asn1Oct == NULL) { + continue; + } + + ObjLength = OBJ_length (Asn1Obj); + OctLength = ASN1_STRING_length (Asn1Oct); + if ((OidSize == ObjLength) && (CompareMem (OBJ_get0_data (Asn1Obj), Oid, OidSize) == 0)) { + // + // Extension Found + // + Status = TRUE; + break; + } + + // + // reset to 0 if not found + // + OctLength = 0; + } + + if (Status) { + if (*ExtensionDataSize < OctLength) { + *ExtensionDataSize = OctLength; + Status = FALSE; + goto Cleanup; + } + + if (Asn1Oct != NULL) { + CopyMem (ExtensionData, ASN1_STRING_get0_data (Asn1Oct), OctLength); + } + + *ExtensionDataSize = OctLength; + } else { + *ExtensionDataSize = 0; + } + +Cleanup: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ) +{ + BOOLEAN Status; + + Status = X509GetExtensionData (Cert, CertSize, mOidExtKeyUsage, sizeof (mOidExtKeyUsage), Usage, UsageSize); + return Status; +} + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[out] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ) +{ + BOOLEAN Status; + X509 *X509Cert; + CONST ASN1_TIME *F; + CONST ASN1_TIME *T; + UINTN TSize; + UINTN FSize; + + // + // Check input parameters. + // + if ((Cert == NULL) || (FromSize == NULL) || (ToSize == NULL) || (CertSize == 0)) { + return FALSE; + } + + X509Cert = NULL; + Status = FALSE; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + goto _Exit; + } + + // + // Retrieve Validity from/to from certificate object. + // + F = X509_get0_notBefore (X509Cert); + T = X509_get0_notAfter (X509Cert); + + if ((F == NULL) || (T == NULL)) { + goto _Exit; + } + + FSize = sizeof (ASN1_TIME) + F->length; + if (*FromSize < FSize) { + *FromSize = FSize; + goto _Exit; + } + + *FromSize = FSize; + if (From != NULL) { + CopyMem (From, F, sizeof (ASN1_TIME)); + ((ASN1_TIME *)From)->data = From + sizeof (ASN1_TIME); + CopyMem (From + sizeof (ASN1_TIME), F->data, F->length); + } + + TSize = sizeof (ASN1_TIME) + T->length; + if (*ToSize < TSize) { + *ToSize = TSize; + goto _Exit; + } + + *ToSize = TSize; + if (To != NULL) { + CopyMem (To, T, sizeof (ASN1_TIME)); + ((ASN1_TIME *)To)->data = To + sizeof (ASN1_TIME); + CopyMem (To + sizeof (ASN1_TIME), T->data, T->length); + } + + Status = TRUE; + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ) +{ + BOOLEAN Status; + INT32 Ret; + ASN1_TIME *Dt; + UINTN DSize; + + Dt = NULL; + Status = FALSE; + + Dt = ASN1_TIME_new (); + if (Dt == NULL) { + Status = FALSE; + goto Cleanup; + } + + Ret = ASN1_TIME_set_string_X509 (Dt, DateTimeStr); + if (Ret != 1) { + Status = FALSE; + goto Cleanup; + } + + DSize = sizeof (ASN1_TIME) + Dt->length; + if (*DateTimeSize < DSize) { + *DateTimeSize = DSize; + Status = FALSE; + goto Cleanup; + } + + *DateTimeSize = DSize; + if (DateTime != NULL) { + CopyMem (DateTime, Dt, sizeof (ASN1_TIME)); + ((ASN1_TIME *)DateTime)->data = (UINT8 *)DateTime + sizeof (ASN1_TIME); + CopyMem ((UINT8 *)DateTime + sizeof (ASN1_TIME), Dt->data, Dt->length); + } + + Status = TRUE; + +Cleanup: + if (Dt != NULL) { + ASN1_TIME_free (Dt); + } + + return Status; +} + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +X509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ) +{ + return (INT32)ASN1_TIME_compare (DateTime1, DateTime2); +} + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ) +{ + BOOLEAN Status; + X509 *X509Cert; + + // + // Check input parameters. + // + if ((Cert == NULL) || (Usage == NULL)) { + return FALSE; + } + + X509Cert = NULL; + Status = FALSE; + + // + // Read DER-encoded X509 Certificate and Construct X509 object. + // + Status = X509ConstructCertificate (Cert, CertSize, (UINT8 **)&X509Cert); + if ((X509Cert == NULL) || (!Status)) { + goto _Exit; + } + + // + // Retrieve subject name from certificate object. + // + *Usage = X509_get_key_usage (X509Cert); + if (*Usage == NID_undef) { + goto _Exit; + } + + Status = TRUE; + +_Exit: + // + // Release Resources. + // + if (X509Cert != NULL) { + X509_free (X509Cert); + } + + return Status; +} + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +X509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ) +{ + CONST UINT8 *TmpPtr; + UINTN Length; + UINT32 Asn1Tag; + UINT32 ObjClass; + CONST UINT8 *CurrentCert; + UINTN CurrentCertLen; + CONST UINT8 *PrecedingCert; + UINTN PrecedingCertLen; + BOOLEAN VerifyFlag; + INT32 Ret; + + PrecedingCert = RootCert; + PrecedingCertLen = RootCertLength; + + CurrentCert = CertChain; + Length = 0; + CurrentCertLen = 0; + + VerifyFlag = FALSE; + while (TRUE) { + TmpPtr = CurrentCert; + Ret = ASN1_get_object ( + (CONST UINT8 **)&TmpPtr, + (long *)&Length, + (int *)&Asn1Tag, + (int *)&ObjClass, + (long)(CertChainLength + CertChain - TmpPtr) + ); + if ((Asn1Tag != V_ASN1_SEQUENCE) || (Ret == 0x80)) { + break; + } + + // + // Calculate CurrentCert length; + // + CurrentCertLen = TmpPtr - CurrentCert + Length; + + // + // Verify CurrentCert with preceding cert; + // + VerifyFlag = X509VerifyCert (CurrentCert, CurrentCertLen, PrecedingCert, PrecedingCertLen); + if (VerifyFlag == FALSE) { + break; + } + + // + // move Current cert to Preceding cert + // + PrecedingCertLen = CurrentCertLen; + PrecedingCert = CurrentCert; + + // + // Move to next + // + CurrentCert = CurrentCert + CurrentCertLen; + } + + return VerifyFlag; +} + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +X509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ) +{ + UINTN Asn1Len; + INT32 CurrentIndex; + UINTN CurrentCertLen; + CONST UINT8 *CurrentCert; + CONST UINT8 *TmpPtr; + INT32 Ret; + UINT32 Asn1Tag; + UINT32 ObjClass; + + // + // Check input parameters. + // + if ((CertChain == NULL) || (Cert == NULL) || + (CertIndex < -1) || (CertLength == NULL)) + { + return FALSE; + } + + Asn1Len = 0; + CurrentCertLen = 0; + CurrentCert = CertChain; + CurrentIndex = -1; + + // + // Traverse the certificate chain + // + while (TRUE) { + TmpPtr = CurrentCert; + + // Get asn1 object and taglen + Ret = ASN1_get_object ( + (CONST UINT8 **)&TmpPtr, + (long *)&Asn1Len, + (int *)&Asn1Tag, + (int *)&ObjClass, + (long)(CertChainLength + CertChain - TmpPtr) + ); + if ((Asn1Tag != V_ASN1_SEQUENCE) || (Ret == 0x80)) { + break; + } + + // + // Calculate CurrentCert length; + // + CurrentCertLen = TmpPtr - CurrentCert + Asn1Len; + CurrentIndex++; + + if (CurrentIndex == CertIndex) { + *Cert = CurrentCert; + *CertLength = CurrentCertLen; + return TRUE; + } + + // + // Move to next + // + CurrentCert = CurrentCert + CurrentCertLen; + } + + // + // If CertIndex is -1, Return the last certificate + // + if ((CertIndex == -1) && (CurrentIndex >= 0)) { + *Cert = CurrentCert - CurrentCertLen; + *CertLength = CurrentCertLen; + return TRUE; + } + + return FALSE; +} + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +Asn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ) +{ + UINT8 *PtrOld; + INT32 ObjTag; + INT32 ObjCls; + long ObjLength; + + // + // Save Ptr position + // + PtrOld = *Ptr; + + ASN1_get_object ((CONST UINT8 **)Ptr, &ObjLength, &ObjTag, &ObjCls, (INT32)(End - (*Ptr))); + if ((ObjTag == (INT32)(Tag & CRYPTO_ASN1_TAG_VALUE_MASK)) && + (ObjCls == (INT32)(Tag & CRYPTO_ASN1_TAG_CLASS_MASK))) + { + *Length = (UINTN)ObjLength; + return TRUE; + } else { + // + // if doesn't match Tag, restore Ptr to origin Ptr + // + *Ptr = PtrOld; + return FALSE; + } +} + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +X509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ) +{ + BOOLEAN Status; + + if ((Cert == NULL) || (CertSize == 0) || (BasicConstraintsSize == NULL)) { + return FALSE; + } + + Status = X509GetExtensionData ( + (UINT8 *)Cert, + CertSize, + mOidBasicConstraints, + sizeof (mOidBasicConstraints), + BasicConstraints, + BasicConstraintsSize + ); + + return Status; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c index c6718e6aeb..7217501948 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509Null.c @@ -320,3 +320,432 @@ EcGetPublicKeyFromX509 ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[in] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +X509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ) +{ + ASSERT (FALSE); + return -3; +} + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +X509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +X509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +Asn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +X509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c index c6718e6aeb..5fb564ca67 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c +++ b/CryptoPkg/Library/BaseCryptLibNull/Pk/CryptX509Null.c @@ -320,3 +320,432 @@ EcGetPublicKeyFromX509 ( ASSERT (FALSE); return FALSE; } + +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[in] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +X509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ) +{ + ASSERT (FALSE); + return -3; +} + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +X509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +X509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +Asn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +X509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ) +{ + ASSERT (FALSE); + return FALSE; +} From 5a069bf5dd9e5f417065df4c1fbfa223dcf19754 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 12:36:00 +0800 Subject: [PATCH 0125/1529] CryptoPkg: add new X509 function to Crypto Service. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4082 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- CryptoPkg/Driver/Crypto.c | 432 +++++++++++++++++- .../Pcd/PcdCryptoServiceFamilyEnable.h | 34 +- .../BaseCryptLibOnProtocolPpi/CryptLib.c | 415 +++++++++++++++++ CryptoPkg/Private/Protocol/Crypto.h | 392 +++++++++++++++- 4 files changed, 1261 insertions(+), 12 deletions(-) diff --git a/CryptoPkg/Driver/Crypto.c b/CryptoPkg/Driver/Crypto.c index 1928adbff7..bdbb4863a9 100644 --- a/CryptoPkg/Driver/Crypto.c +++ b/CryptoPkg/Driver/Crypto.c @@ -3086,6 +3086,421 @@ CryptoServiceX509GetTBSCert ( return CALL_BASECRYPTLIB (X509.Services.GetTBSCert, X509GetTBSCert, (Cert, CertSize, TBSCert, TBSCertSize), FALSE); } +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetVersion, X509GetVersion, (Cert, CertSize, Version), FALSE); +} + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetSerialNumber, X509GetSerialNumber, (Cert, CertSize, SerialNumber, SerialNumberSize), FALSE); +} + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetIssuerName, X509GetIssuerName, (Cert, CertSize, CertIssuer, CertIssuerSize), FALSE); +} + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetSignatureAlgorithm, X509GetSignatureAlgorithm, (Cert, CertSize, Oid, OidSize), FALSE); +} + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetExtensionData, X509GetExtensionData, (Cert, CertSize, Oid, OidSize, ExtensionData, ExtensionDataSize), FALSE); +} + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetExtendedKeyUsage, X509GetExtendedKeyUsage, (Cert, CertSize, Usage, UsageSize), FALSE); +} + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[in] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetValidity, X509GetValidity, (Cert, CertSize, From, FromSize, To, ToSize), FALSE); +} + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.FormatDateTime, X509FormatDateTime, (DateTimeStr, DateTime, DateTimeSize), FALSE); +} + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +CryptoServiceX509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ) +{ + return CALL_BASECRYPTLIB (X509.Services.CompareDateTime, X509CompareDateTime, (DateTime1, DateTime2), FALSE); +} + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetKeyUsage, X509GetKeyUsage, (Cert, CertSize, Usage), FALSE); +} + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ) +{ + return CALL_BASECRYPTLIB (X509.Services.VerifyCertChain, X509VerifyCertChain, (RootCert, RootCertLength, CertChain, CertChainLength), FALSE); +} + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +CryptoServiceX509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetCertFromCertChain, X509GetCertFromCertChain, (CertChain, CertChainLength, CertIndex, Cert, CertLength), FALSE); +} + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +CryptoServiceAsn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ) +{ + return CALL_BASECRYPTLIB (X509.Services.Asn1GetTag, Asn1GetTag, (Ptr, End, Length, Tag), FALSE); +} + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +CryptoServiceX509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ) +{ + return CALL_BASECRYPTLIB (X509.Services.GetExtendedBasicConstraints, X509GetExtendedBasicConstraints, (Cert, CertSize, BasicConstraints, BasicConstraintsSize), FALSE); +} + /** Derives a key from a password using a salt and iteration count, based on PKCS#5 v2.0 password based encryption key derivation function PBKDF2, as specified in RFC 2898. @@ -6557,5 +6972,20 @@ const EDKII_CRYPTO_PROTOCOL mEdkiiCrypto = { CryptoServiceEcGetPublicKeyFromX509, CryptoServiceEcGetPrivateKeyFromPem, CryptoServiceEcDsaSign, - CryptoServiceEcDsaVerify + CryptoServiceEcDsaVerify, + /// X509 (Continued) + CryptoServiceX509GetVersion, + CryptoServiceX509GetSerialNumber, + CryptoServiceX509GetIssuerName, + CryptoServiceX509GetSignatureAlgorithm, + CryptoServiceX509GetExtensionData, + CryptoServiceX509GetExtendedKeyUsage, + CryptoServiceX509GetValidity, + CryptoServiceX509FormatDateTime, + CryptoServiceX509CompareDateTime, + CryptoServiceX509GetKeyUsage, + CryptoServiceX509VerifyCertChain, + CryptoServiceX509GetCertFromCertChain, + CryptoServiceAsn1GetTag, + CryptoServiceX509GetExtendedBasicConstraints }; diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index 12b0c0583e..f1f5084e70 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -187,16 +187,30 @@ typedef struct { } Sha512; union { struct { - UINT8 GetSubjectName : 1; - UINT8 GetCommonName : 1; - UINT8 GetOrganizationName : 1; - UINT8 VerifyCert : 1; - UINT8 ConstructCertificate : 1; - UINT8 ConstructCertificateStack : 1; - UINT8 ConstructCertificateStackV : 1; - UINT8 Free : 1; - UINT8 StackFree : 1; - UINT8 GetTBSCert : 1; + UINT8 GetSubjectName : 1; + UINT8 GetCommonName : 1; + UINT8 GetOrganizationName : 1; + UINT8 VerifyCert : 1; + UINT8 ConstructCertificate : 1; + UINT8 ConstructCertificateStack : 1; + UINT8 ConstructCertificateStackV : 1; + UINT8 Free : 1; + UINT8 StackFree : 1; + UINT8 GetTBSCert : 1; + UINT8 GetVersion : 1; + UINT8 GetSerialNumber : 1; + UINT8 GetIssuerName : 1; + UINT8 GetSignatureAlgorithm : 1; + UINT8 GetExtensionData : 1; + UINT8 GetExtendedKeyUsage : 1; + UINT8 GetValidity : 1; + UINT8 FormatDateTime : 1; + UINT8 CompareDateTime : 1; + UINT8 GetKeyUsage : 1; + UINT8 VerifyCertChain : 1; + UINT8 GetCertFromCertChain : 1; + UINT8 Asn1GetTag : 1; + UINT8 GetExtendedBasicConstraints : 1; } Services; UINT32 Family; } X509; diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c index 48ec6d3528..4e31bc278e 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/CryptLib.c @@ -2322,6 +2322,421 @@ X509GetTBSCert ( CALL_CRYPTO_SERVICE (X509GetTBSCert, (Cert, CertSize, TBSCert, TBSCertSize), FALSE); } +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetVersion ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ) +{ + CALL_CRYPTO_SERVICE (X509GetVersion, (Cert, CertSize, Version), FALSE); +} + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSerialNumber ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetSerialNumber, (Cert, CertSize, SerialNumber, SerialNumberSize), FALSE); +} + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +BOOLEAN +EFIAPI +X509GetIssuerName ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetIssuerName, (Cert, CertSize, CertIssuer, CertIssuerSize), FALSE); +} + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetSignatureAlgorithm ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetSignatureAlgorithm, (Cert, CertSize, Oid, OidSize), FALSE); +} + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtensionData ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetExtensionData, (Cert, CertSize, Oid, OidSize, ExtensionData, ExtensionDataSize), FALSE); +} + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509GetExtendedKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetExtendedKeyUsage, (Cert, CertSize, Usage, UsageSize), FALSE); +} + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[in] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetValidity ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetValidity, (Cert, CertSize, From, FromSize, To, ToSize), FALSE); +} + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +BOOLEAN +EFIAPI +X509FormatDateTime ( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ) +{ + CALL_CRYPTO_SERVICE (X509FormatDateTime, (DateTimeStr, DateTime, DateTimeSize), FALSE); +} + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +INT32 +EFIAPI +X509CompareDateTime ( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ) +{ + CALL_CRYPTO_SERVICE (X509CompareDateTime, (DateTime1, DateTime2), FALSE); +} + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +BOOLEAN +EFIAPI +X509GetKeyUsage ( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ) +{ + CALL_CRYPTO_SERVICE (X509GetKeyUsage, (Cert, CertSize, Usage), FALSE); +} + +/** + Verify one X509 certificate was issued by the trusted CA. + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +BOOLEAN +EFIAPI +X509VerifyCertChain ( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ) +{ + CALL_CRYPTO_SERVICE (X509VerifyCertChain, (RootCert, RootCertLength, CertChain, CertChainLength), FALSE); +} + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +BOOLEAN +EFIAPI +X509GetCertFromCertChain ( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ) +{ + CALL_CRYPTO_SERVICE (X509GetCertFromCertChain, (CertChain, CertChainLength, CertIndex, Cert, CertLength), FALSE); +} + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +BOOLEAN +EFIAPI +Asn1GetTag ( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ) +{ + CALL_CRYPTO_SERVICE (Asn1GetTag, (Ptr, End, Length, Tag), FALSE); +} + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +BOOLEAN +EFIAPI +X509GetExtendedBasicConstraints ( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ) +{ + CALL_CRYPTO_SERVICE (X509GetExtendedBasicConstraints, (Cert, CertSize, BasicConstraints, BasicConstraintsSize), FALSE); +} + /** Derives a key from a password using a salt and iteration count, based on PKCS#5 v2.0 password based encryption key derivation function PBKDF2, as specified in RFC 2898. diff --git a/CryptoPkg/Private/Protocol/Crypto.h b/CryptoPkg/Private/Protocol/Crypto.h index bfb278d388..0e0b1d9401 100644 --- a/CryptoPkg/Private/Protocol/Crypto.h +++ b/CryptoPkg/Private/Protocol/Crypto.h @@ -21,7 +21,7 @@ /// the EDK II Crypto Protocol is extended, this version define must be /// increased. /// -#define EDKII_CRYPTO_VERSION 15 +#define EDKII_CRYPTO_VERSION 16 /// /// EDK II Crypto Protocol forward declaration @@ -2351,6 +2351,381 @@ BOOLEAN OUT UINTN *TBSCertSize ); +/** + Retrieve the version from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Version Pointer to the retrieved version integer. + + @retval TRUE The certificate version retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + @retval FALSE The operation is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_VERSION)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Version + ); + +/** + Retrieve the serialNumber from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertSize is 0, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] SerialNumber Pointer to the retrieved certificate SerialNumber bytes. + @param[in, out] SerialNumberSize The size in bytes of the SerialNumber buffer on input, + and the size of buffer returned SerialNumber on output. + + @retval TRUE The certificate serialNumber retrieved successfully. + @retval FALSE If Cert is NULL or CertSize is Zero. + If SerialNumberSize is NULL. + If Certificate is invalid. + @retval FALSE If no SerialNumber exists. + @retval FALSE If the SerialNumber is NULL. The required buffer size + (including the final null) is returned in the + SerialNumberSize parameter. + @retval FALSE The operation is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_SERIAL_NUMBER)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *SerialNumber, OPTIONAL + IN OUT UINTN *SerialNumberSize + ); + +/** + Retrieve the issuer bytes from one X.509 certificate. + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] CertIssuer Pointer to the retrieved certificate subject bytes. + @param[in, out] CertIssuerSize The size in bytes of the CertIssuer buffer on input, + and the size of buffer returned CertSubject on output. + + @retval TRUE The certificate issuer retrieved successfully. + @retval FALSE Invalid certificate, or the CertIssuerSize is too small for the result. + The CertIssuerSize will be updated with the required size. + @retval FALSE This interface is not supported. + +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_ISSUER_NAME)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *CertIssuer, + IN OUT UINTN *CertIssuerSize + ); + +/** + Retrieve the Signature Algorithm from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Oid Signature Algorithm Object identifier buffer. + @param[in,out] OidSize Signature Algorithm Object identifier buffer size + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If OidSize is NULL. + If Oid is not NULL and *OidSize is 0. + If Certificate is invalid. + @retval FALSE If no SignatureType. + @retval FALSE If the Oid is NULL. The required buffer size + is returned in the OidSize. + @retval FALSE The operation is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_SIGNATURE_ALGORITHM)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Oid, OPTIONAL + IN OUT UINTN *OidSize + ); + +/** + Retrieve Extension data from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[in] Oid Object identifier buffer + @param[in] OidSize Object identifier buffer size + @param[out] ExtensionData Extension bytes. + @param[in, out] ExtensionDataSize Extension bytes size. + + @retval TRUE The certificate Extension data retrieved successfully. + @retval FALSE If Cert is NULL. + If ExtensionDataSize is NULL. + If ExtensionData is not NULL and *ExtensionDataSize is 0. + If Certificate is invalid. + @retval FALSE If no Extension entry match Oid. + @retval FALSE If the ExtensionData is NULL. The required buffer size + is returned in the ExtensionDataSize parameter. + @retval FALSE The operation is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_EXTENSION_DATA)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN CONST UINT8 *Oid, + IN UINTN OidSize, + OUT UINT8 *ExtensionData, + IN OUT UINTN *ExtensionDataSize + ); + +/** + Retrieve the Extended Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage bytes. + @param[in, out] UsageSize Key Usage buffer sizs in bytes. + + @retval TRUE The Usage bytes retrieve successfully. + @retval FALSE If Cert is NULL. + If CertSize is NULL. + If Usage is not NULL and *UsageSize is 0. + If Cert is invalid. + @retval FALSE If the Usage is NULL. The required buffer size + is returned in the UsageSize parameter. + @retval FALSE The operation is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_EXTENDED_KEY_USAGE)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINT8 *Usage, + IN OUT UINTN *UsageSize + ); + +/** + Retrieve the Validity from one X.509 certificate + + If Cert is NULL, then return FALSE. + If CertIssuerSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] From notBefore Pointer to DateTime object. + @param[in,out] FromSize notBefore DateTime object size. + @param[out] To notAfter Pointer to DateTime object. + @param[in,out] ToSize notAfter DateTime object size. + + Note: X509CompareDateTime to compare DateTime oject + x509SetDateTime to get a DateTime object from a DateTimeStr + + @retval TRUE The certificate Validity retrieved successfully. + @retval FALSE Invalid certificate, or Validity retrieve failed. + @retval FALSE This interface is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_VALIDITY)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + IN UINT8 *From, + IN OUT UINTN *FromSize, + IN UINT8 *To, + IN OUT UINTN *ToSize + ); + +/** + Format a DateTimeStr to DataTime object in DataTime Buffer + + If DateTimeStr is NULL, then return FALSE. + If DateTimeSize is NULL, then return FALSE. + If this interface is not supported, then return FALSE. + + @param[in] DateTimeStr DateTime string like YYYYMMDDhhmmssZ + Ref: https://www.w3.org/TR/NOTE-datetime + Z stand for UTC time + @param[in,out] DateTime Pointer to a DateTime object. + @param[in,out] DateTimeSize DateTime object buffer size. + + @retval TRUE The DateTime object create successfully. + @retval FALSE If DateTimeStr is NULL. + If DateTimeSize is NULL. + If DateTime is not NULL and *DateTimeSize is 0. + If Year Month Day Hour Minute Second combination is invalid datetime. + @retval FALSE If the DateTime is NULL. The required buffer size + (including the final null) is returned in the + DateTimeSize parameter. + @retval FALSE The operation is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_FORMAT_DATE_TIME)( + IN CONST CHAR8 *DateTimeStr, + OUT VOID *DateTime, + IN OUT UINTN *DateTimeSize + ); + +/** + Compare DateTime1 object and DateTime2 object. + + If DateTime1 is NULL, then return -2. + If DateTime2 is NULL, then return -2. + If DateTime1 == DateTime2, then return 0 + If DateTime1 > DateTime2, then return 1 + If DateTime1 < DateTime2, then return -1 + + @param[in] DateTime1 Pointer to a DateTime Ojbect + @param[in] DateTime2 Pointer to a DateTime Object + + @retval 0 If DateTime1 == DateTime2 + @retval 1 If DateTime1 > DateTime2 + @retval -1 If DateTime1 < DateTime2 +**/ +typedef +INT32 +(EFIAPI *EDKII_CRYPTO_X509_COMPARE_DATE_TIME)( + IN CONST VOID *DateTime1, + IN CONST VOID *DateTime2 + ); + +/** + Retrieve the Key Usage from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize Size of the X509 certificate in bytes. + @param[out] Usage Key Usage (CRYPTO_X509_KU_*) + + @retval TRUE The certificate Key Usage retrieved successfully. + @retval FALSE Invalid certificate, or Usage is NULL + @retval FALSE This interface is not supported. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_KEY_USAGE)( + IN CONST UINT8 *Cert, + IN UINTN CertSize, + OUT UINTN *Usage + ); + +/** + Verify one X509 certificate was issued by the trusted CA. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] RootCert Trusted Root Certificate buffer + + @param[in] RootCertLength Trusted Root Certificate buffer length + + @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval FALSE Invalid certificate or the certificate was not issued by the given + trusted CA. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_VERIFY_CERT_CHAIN)( + IN CONST UINT8 *RootCert, + IN UINTN RootCertLength, + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength + ); + +/** + Get one X509 certificate from CertChain. + + @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates + where the first certificate is signed by the Root + Certificate or is the Root Cerificate itself. and + subsequent cerificate is signed by the preceding + cerificate. + @param[in] CertChainLength Total length of the certificate chain, in bytes. + + @param[in] CertIndex Index of certificate. + + @param[out] Cert The certificate at the index of CertChain. + @param[out] CertLength The length certificate at the index of CertChain. + + @retval TRUE Success. + @retval FALSE Failed to get certificate from certificate chain. +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_CERT_FROM_CERT_CHAIN)( + IN CONST UINT8 *CertChain, + IN UINTN CertChainLength, + IN CONST INT32 CertIndex, + OUT CONST UINT8 **Cert, + OUT UINTN *CertLength + ); + +/** + Retrieve the tag and length of the tag. + + @param Ptr The position in the ASN.1 data + @param End End of data + @param Length The variable that will receive the length + @param Tag The expected tag + + @retval TRUE Get tag successful + @retval FALSe Failed to get tag or tag not match +**/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_ASN1_GET_TAG)( + IN OUT UINT8 **Ptr, + IN CONST UINT8 *End, + OUT UINTN *Length, + IN UINT32 Tag + ); + +/** + Retrieve the basic constraints from one X.509 certificate. + + @param[in] Cert Pointer to the DER-encoded X509 certificate. + @param[in] CertSize size of the X509 certificate in bytes. + @param[out] BasicConstraints basic constraints bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + + @retval TRUE The basic constraints retrieve successfully. + @retval FALSE If cert is NULL. + If cert_size is NULL. + If basic_constraints is not NULL and *basic_constraints_size is 0. + If cert is invalid. + @retval FALSE The required buffer size is small. + The return buffer size is basic_constraints_size parameter. + @retval FALSE If no Extension entry match oid. + @retval FALSE The operation is not supported. + **/ +typedef +BOOLEAN +(EFIAPI *EDKII_CRYPTO_X509_GET_EXTENDED_BASIC_CONSTRAINTS)( + CONST UINT8 *Cert, + UINTN CertSize, + UINT8 *BasicConstraints, + UINTN *BasicConstraintsSize + ); + // ===================================================================================== // Symmetric Cryptography Primitive // ===================================================================================== @@ -5213,6 +5588,21 @@ struct _EDKII_CRYPTO_PROTOCOL { EDKII_CRYPTO_EC_GET_PRIVATE_KEY_FROM_PEM EcGetPrivateKeyFromPem; EDKII_CRYPTO_EC_DSA_SIGN EcDsaSign; EDKII_CRYPTO_EC_DSA_VERIFY EcDsaVerify; + /// X509 (Continued) + EDKII_CRYPTO_X509_GET_VERSION X509GetVersion; + EDKII_CRYPTO_X509_GET_SERIAL_NUMBER X509GetSerialNumber; + EDKII_CRYPTO_X509_GET_ISSUER_NAME X509GetIssuerName; + EDKII_CRYPTO_X509_GET_SIGNATURE_ALGORITHM X509GetSignatureAlgorithm; + EDKII_CRYPTO_X509_GET_EXTENSION_DATA X509GetExtensionData; + EDKII_CRYPTO_X509_GET_EXTENDED_KEY_USAGE X509GetExtendedKeyUsage; + EDKII_CRYPTO_X509_GET_VALIDITY X509GetValidity; + EDKII_CRYPTO_X509_FORMAT_DATE_TIME X509FormatDateTime; + EDKII_CRYPTO_X509_COMPARE_DATE_TIME X509CompareDateTime; + EDKII_CRYPTO_X509_GET_KEY_USAGE X509GetKeyUsage; + EDKII_CRYPTO_X509_VERIFY_CERT_CHAIN X509VerifyCertChain; + EDKII_CRYPTO_X509_GET_CERT_FROM_CERT_CHAIN X509GetCertFromCertChain; + EDKII_CRYPTO_ASN1_GET_TAG Asn1GetTag; + EDKII_CRYPTO_X509_GET_EXTENDED_BASIC_CONSTRAINTS X509GetExtendedBasicConstraints; }; extern GUID gEdkiiCryptoProtocolGuid; From dba058433d099942287c68645b261e07533ab910 Mon Sep 17 00:00:00 2001 From: Qi Zhang Date: Wed, 12 Oct 2022 12:36:01 +0800 Subject: [PATCH 0126/1529] CryptoPkg: add Unit Test for X509 new function. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4082 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Qi Zhang Reviewed-by: Jiewen Yao --- .../BaseCryptLib/BaseCryptLibUnitTests.c | 1 + .../Library/BaseCryptLib/TestBaseCryptLib.h | 4 + .../BaseCryptLib/TestBaseCryptLibHost.inf | 1 + .../BaseCryptLib/TestBaseCryptLibShell.inf | 1 + .../UnitTest/Library/BaseCryptLib/X509Tests.c | 631 ++++++++++++++++++ 5 files changed, 638 insertions(+) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/X509Tests.c diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c index 63bae35b80..5546259488 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/BaseCryptLibUnitTests.c @@ -29,6 +29,7 @@ SUITE_DESC mSuiteDesc[] = { { "Aead AES Gcm tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mAeadAesGcmTestNum, mAeadAesGcmTest }, { "Bn verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mBnTestNum, mBnTest }, { "EC verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mEcTestNum, mEcTest }, + { "X509 Verify tests", "CryptoPkg.BaseCryptLib", NULL, NULL, &mX509TestNum, mX509Test }, }; EFI_STATUS diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h index 3a84e63a87..91f3ec41d4 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h @@ -97,6 +97,10 @@ extern TEST_DESC mBnTest[]; extern UINTN mEcTestNum; extern TEST_DESC mEcTest[]; + +extern UINTN mX509TestNum; +extern TEST_DESC mX509Test[]; + /** Creates a framework you can use */ EFI_STATUS EFIAPI diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf index 023b796946..07113d6ed6 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf @@ -41,6 +41,7 @@ AeadAesGcmTests.c BnTests.c EcTests.c + X509Tests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf index 5bfd190236..0450b8a29c 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf @@ -40,6 +40,7 @@ AeadAesGcmTests.c BnTests.c EcTests.c + X509Tests.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/X509Tests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/X509Tests.c new file mode 100644 index 0000000000..b3d11ea330 --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/X509Tests.c @@ -0,0 +1,631 @@ +/** @file + Application for X509 Cert Validation. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "TestBaseCryptLib.h" + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mOidSubjectAltName[] = { 0x55, 0x1D, 0x11 }; + +// +// use openssl tool to create the test certificates. +// +// openssl req -nodes -x509 -days 3650 -newkey rsa:4096 -keyout ca.key -out ca.cert -sha256 -subj "/CN=intel test RSA CA" +// openssl rsa -in ca.key -outform der -out ca.key.der +// openssl req -nodes -newkey rsa:3072 -keyout inter.key -out inter.req -sha256 -batch -subj "/CN=intel test RSA intermediate cert" +// openssl req -nodes -newkey rsa:2048 -keyout end_requester.key -out end_requester.req -sha256 -batch -subj "/CN=intel test RSA requseter cert" +// openssl req -nodes -newkey rsa:2048 -keyout end_responder.key -out end_responder.req -sha256 -batch -subj "/CN=intel test RSA responder cert" +// openssl x509 -req -in inter.req -out inter.cert -CA ca.cert -CAkey ca.key -sha256 -days 3650 -set_serial 1 -extensions v3_inter -extfile ../openssl.cnf +// openssl x509 -req -in end_requester.req -out end_requester.cert -CA inter.cert -CAkey inter.key -sha256 -days 3650 -set_serial 2 -extensions v3_end -extfile ../openssl.cnf +// openssl x509 -req -in end_responder.req -out end_responder.cert -CA inter.cert -CAkey inter.key -sha256 -days 3650 -set_serial 3 -extensions v3_end -extfile ../openssl.cnf +// openssl asn1parse -in ca.cert -out ca.cert.der +// openssl asn1parse -in inter.cert -out inter.cert.der +// openssl asn1parse -in end_requester.cert -out end_requester.cert.der +// cat ca.cert.der inter.cert.der end_requester.cert.der > bundle_requester.certchain.der +// openssl rsa -inform PEM -outform DER -in end_requester.key -out end_requester.key.der +// + +// +// dump of inter.cert.der +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mTestCert[] = { + 0x30, 0x82, 0x04, 0xa0, 0x30, 0x82, 0x02, 0x88, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x01, + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, + 0x1c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, 0x6e, 0x74, 0x65, + 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, + 0x0d, 0x32, 0x32, 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x17, 0x0d, + 0x33, 0x32, 0x30, 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x30, 0x2b, 0x31, + 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x20, + 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6d, 0x65, + 0x64, 0x69, 0x61, 0x74, 0x65, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x82, 0x01, 0xa2, 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, + 0x8f, 0x00, 0x30, 0x82, 0x01, 0x8a, 0x02, 0x82, 0x01, 0x81, 0x00, 0xd1, 0xcf, 0x2d, 0x21, 0x38, + 0xe4, 0x81, 0xa6, 0xf2, 0xe5, 0xca, 0xac, 0x09, 0x2b, 0x04, 0x2a, 0x52, 0x76, 0x2f, 0xa3, 0x4b, + 0x43, 0xc2, 0xd6, 0xb5, 0x3e, 0x2b, 0x29, 0x6f, 0x1b, 0x7d, 0x36, 0x60, 0xcd, 0x71, 0xf4, 0xcf, + 0x8a, 0x24, 0xac, 0x8f, 0x5f, 0x78, 0x70, 0xc9, 0x84, 0x48, 0xfb, 0x1d, 0xcb, 0xee, 0x34, 0x3c, + 0x4c, 0xe1, 0x1a, 0x92, 0x54, 0x43, 0x45, 0xe0, 0xdd, 0x14, 0xd5, 0xac, 0x13, 0xae, 0xcc, 0x45, + 0xdc, 0x52, 0xdd, 0x45, 0x22, 0x10, 0xab, 0xb2, 0x1b, 0x3e, 0xad, 0x36, 0x6f, 0x00, 0x59, 0xb6, + 0xfd, 0x27, 0xb8, 0x57, 0xbb, 0x66, 0x72, 0x1e, 0x7b, 0xe8, 0xc7, 0xaf, 0x5e, 0x65, 0x5c, 0x58, + 0x3d, 0x9e, 0x78, 0x26, 0xb7, 0x70, 0x9a, 0xe7, 0x3c, 0xfc, 0x90, 0x64, 0xb2, 0xb2, 0xb2, 0x80, + 0x22, 0xb3, 0x1c, 0x23, 0x73, 0x6a, 0xe3, 0xcb, 0x5b, 0x4e, 0x29, 0x71, 0xdd, 0xfd, 0xd7, 0x15, + 0x3a, 0xd6, 0xa3, 0xe0, 0x4a, 0x53, 0x65, 0xa6, 0xae, 0x6a, 0x83, 0xb0, 0x00, 0x3f, 0x64, 0x4b, + 0x01, 0xcd, 0x97, 0xb1, 0xe1, 0x54, 0x1e, 0xa2, 0x33, 0x4e, 0xf0, 0x13, 0x33, 0x80, 0xe5, 0x41, + 0x9c, 0x5e, 0xb3, 0x5d, 0xae, 0x53, 0x2c, 0x41, 0x51, 0xf2, 0x00, 0x3e, 0x03, 0xe2, 0x0d, 0xa4, + 0xf5, 0x24, 0x08, 0x46, 0xc2, 0xed, 0x6b, 0xf2, 0xe0, 0x1b, 0x04, 0xb7, 0xe8, 0xda, 0x85, 0xa4, + 0x2f, 0x4b, 0x53, 0xfa, 0x76, 0x72, 0x0a, 0x28, 0xbf, 0x3c, 0xa8, 0x85, 0x03, 0xee, 0x51, 0xb5, + 0x5c, 0xa9, 0xa5, 0x70, 0x47, 0x07, 0x11, 0x32, 0xc5, 0x5f, 0x7a, 0x07, 0xfb, 0x5f, 0x4a, 0x52, + 0x65, 0x33, 0x0c, 0x17, 0x8e, 0x74, 0xe5, 0xec, 0x7d, 0x52, 0xa0, 0xd4, 0xef, 0x64, 0xcc, 0x5e, + 0xe2, 0x3d, 0x46, 0x1e, 0x73, 0xab, 0x43, 0x2d, 0x05, 0xfa, 0xa3, 0x6d, 0x86, 0x02, 0xe7, 0xc8, + 0x5f, 0x44, 0xfe, 0xeb, 0x14, 0x73, 0x2d, 0xf4, 0x0b, 0x72, 0x49, 0xe3, 0xef, 0x55, 0x05, 0x1b, + 0x2f, 0xf9, 0x73, 0xeb, 0xed, 0xcc, 0x5e, 0x52, 0x17, 0x43, 0x94, 0x85, 0xc7, 0x0e, 0x73, 0x89, + 0x22, 0xdc, 0x02, 0x5f, 0x99, 0x69, 0x58, 0x16, 0x89, 0x1e, 0x6f, 0x75, 0xf8, 0xd3, 0xe7, 0x0a, + 0xb1, 0x01, 0x42, 0x71, 0xa6, 0xc5, 0xb2, 0xd0, 0xc0, 0x75, 0x96, 0x2e, 0xc2, 0x32, 0x49, 0x0a, + 0xe8, 0x85, 0xbd, 0x22, 0x4c, 0x95, 0xd4, 0xf8, 0x2d, 0x72, 0x05, 0x4f, 0x0e, 0x56, 0x9c, 0xc3, + 0x30, 0x3d, 0xfd, 0x30, 0x63, 0x92, 0x72, 0x6b, 0xaf, 0x80, 0x9d, 0xd0, 0xc2, 0x36, 0xe7, 0xc1, + 0x37, 0xd0, 0x64, 0x88, 0x64, 0x3c, 0x33, 0xdd, 0x87, 0xdd, 0xd9, 0xa2, 0x79, 0x44, 0xd8, 0x25, + 0x84, 0x0e, 0xfd, 0x9d, 0xd6, 0xc1, 0x7a, 0x2d, 0x23, 0x08, 0x9d, 0x02, 0x03, 0x01, 0x00, 0x01, + 0xa3, 0x5e, 0x30, 0x5c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, + 0x01, 0xff, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x01, 0xfe, 0x30, + 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x46, 0xcd, 0xb4, 0x52, 0x02, 0x29, + 0x26, 0xc7, 0x52, 0x23, 0x81, 0x65, 0xcd, 0x87, 0x2f, 0x96, 0x1b, 0x01, 0x2c, 0xc5, 0x30, 0x20, + 0x06, 0x03, 0x55, 0x1d, 0x25, 0x01, 0x01, 0xff, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, + 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, + 0x82, 0x02, 0x01, 0x00, 0x71, 0x14, 0xca, 0xfe, 0x03, 0x92, 0xc6, 0x88, 0x52, 0x76, 0x43, 0xd9, + 0x8a, 0xf7, 0x22, 0x94, 0xef, 0x40, 0xa7, 0xc3, 0x7b, 0x6f, 0xb4, 0xd0, 0x42, 0xc3, 0x59, 0x1f, + 0x77, 0xef, 0xac, 0x18, 0xce, 0x7c, 0xab, 0x48, 0x85, 0x22, 0xf1, 0x50, 0x2c, 0xe0, 0x63, 0x4d, + 0x9d, 0x0e, 0xed, 0x38, 0xff, 0xd9, 0xed, 0x3c, 0x7e, 0x3e, 0x84, 0xb1, 0xa7, 0x78, 0x62, 0x37, + 0x39, 0x6d, 0xd5, 0x5d, 0x46, 0x9a, 0x6f, 0x63, 0xc2, 0xa7, 0x90, 0xf9, 0x7a, 0xa7, 0x4b, 0xa2, + 0x8a, 0xa8, 0x50, 0x13, 0x16, 0x9c, 0x4f, 0xcc, 0x28, 0x58, 0x6c, 0x9f, 0x65, 0x6e, 0xf0, 0x9a, + 0x92, 0x59, 0x94, 0xa4, 0xb5, 0xfd, 0x8f, 0xf0, 0x7c, 0x1e, 0xba, 0xc3, 0x21, 0x13, 0xfb, 0x33, + 0xba, 0xad, 0x4b, 0x1d, 0x42, 0x23, 0x16, 0x8b, 0x3e, 0xcd, 0xb5, 0x69, 0x9c, 0x7c, 0xa1, 0x9b, + 0x92, 0xc1, 0x2f, 0x9c, 0x89, 0x3f, 0x28, 0x24, 0x67, 0x48, 0x47, 0xf0, 0xb1, 0xc0, 0xf0, 0x4c, + 0xbf, 0xf6, 0x64, 0xde, 0x33, 0xc3, 0xd6, 0x5b, 0xe6, 0xc3, 0xdd, 0xa5, 0xba, 0x42, 0x02, 0x0f, + 0xbc, 0xbe, 0xde, 0x14, 0x12, 0x7c, 0xfb, 0xe6, 0xbb, 0xdd, 0xf2, 0x6b, 0xd7, 0x75, 0xe6, 0xf5, + 0xda, 0xbe, 0xe9, 0xbf, 0xa6, 0x87, 0x09, 0x41, 0x6c, 0x9d, 0x19, 0x9c, 0xb1, 0x7c, 0x89, 0x9f, + 0x32, 0xb3, 0x0a, 0x59, 0x10, 0xc6, 0x8c, 0xa0, 0x5b, 0xda, 0xa6, 0xa3, 0xf8, 0x33, 0x77, 0x7a, + 0xf4, 0xb0, 0x8a, 0xcf, 0xc8, 0x3f, 0x2e, 0xb8, 0xf1, 0x9e, 0x7b, 0x47, 0x2d, 0x85, 0x3b, 0x58, + 0xcd, 0x4b, 0xbc, 0x87, 0xd2, 0xf3, 0xcd, 0x36, 0x80, 0x9b, 0x4a, 0x0f, 0x24, 0x30, 0x1d, 0x3f, + 0x6f, 0x56, 0xcf, 0x6e, 0x2d, 0xcf, 0xa8, 0x17, 0xd5, 0x97, 0x0b, 0x22, 0xa6, 0x59, 0xef, 0xef, + 0xd4, 0x9a, 0x0e, 0x6f, 0xb9, 0xf0, 0x48, 0x2a, 0x54, 0x22, 0x77, 0x27, 0x90, 0x84, 0x42, 0x56, + 0x85, 0x80, 0x78, 0x4f, 0xd9, 0x14, 0x2a, 0xf0, 0x5d, 0x6b, 0x46, 0x60, 0x3d, 0xad, 0xa5, 0xa2, + 0xb9, 0x04, 0x23, 0x92, 0x1b, 0x70, 0xa3, 0xdb, 0xaa, 0xf0, 0x5f, 0x1c, 0xd8, 0x26, 0xbb, 0x51, + 0x17, 0xfc, 0x93, 0x6d, 0x70, 0x19, 0x54, 0xe2, 0x6f, 0x82, 0x8a, 0x49, 0xa6, 0x19, 0xcc, 0x97, + 0x53, 0x90, 0x27, 0xd9, 0x8d, 0xaa, 0x8c, 0xc3, 0x2b, 0xbc, 0x0a, 0x72, 0x3a, 0x41, 0xb8, 0xfa, + 0x1e, 0xbb, 0x8b, 0x27, 0x06, 0x75, 0x53, 0x91, 0xac, 0x8d, 0x75, 0xf2, 0xa6, 0xea, 0x85, 0x7e, + 0x34, 0x06, 0x9e, 0xf9, 0xe9, 0x13, 0xa3, 0xfe, 0x2e, 0x38, 0x4b, 0x3f, 0x61, 0x11, 0x1f, 0x6b, + 0xd3, 0xfe, 0xc9, 0x13, 0xbc, 0x12, 0xfe, 0xbc, 0xff, 0xaa, 0x38, 0x73, 0x8a, 0x73, 0x8c, 0xcf, + 0xcc, 0xd3, 0xe7, 0xba, 0x98, 0xfd, 0xf4, 0xf5, 0xf6, 0xa9, 0xc8, 0x07, 0x5b, 0x16, 0xae, 0x76, + 0x86, 0x24, 0x25, 0xcc, 0x7c, 0xdb, 0x1e, 0x7f, 0xc4, 0xe4, 0xd3, 0x89, 0x5a, 0x91, 0x6a, 0x9c, + 0x93, 0x03, 0xd2, 0xd2, 0xc0, 0x29, 0x69, 0x58, 0x52, 0x6c, 0xca, 0x91, 0x7d, 0xd2, 0x3d, 0xc7, + 0x2f, 0x8a, 0x4e, 0x55, 0x03, 0x34, 0x16, 0x01, 0x2f, 0x4f, 0x57, 0xea, 0x10, 0xa7, 0xfb, 0xe3, + 0x2e, 0x2c, 0x7f, 0x5d, 0x27, 0x93, 0x74, 0x95, 0x25, 0x1a, 0x1e, 0x54, 0x1a, 0xb6, 0xe1, 0xdc, + 0xc8, 0xe4, 0x84, 0xeb, 0x38, 0x0f, 0x05, 0x74, 0xf3, 0x3a, 0xf9, 0xd8, 0x00, 0x43, 0xe9, 0x24, + 0x1e, 0x45, 0xb4, 0xe2, 0x38, 0x8b, 0x6a, 0x4f, 0xb6, 0x0b, 0x1d, 0xac, 0xbc, 0xec, 0xda, 0x41, + 0x9c, 0x7f, 0xa8, 0x15, 0x09, 0x3b, 0x0b, 0x99, 0xc4, 0x48, 0xdd, 0xde, 0x0d, 0x65, 0x86, 0x72, + 0xaa, 0x0a, 0x4e, 0x71, +}; + +// +// dump of ca.cert.der +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mTestCaCert[] = { + 0x30, 0x82, 0x05, 0x19, 0x30, 0x82, 0x03, 0x01, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x14, 0x1d, + 0xaf, 0x4e, 0xf1, 0x99, 0xbf, 0xee, 0xe2, 0x6d, 0x7e, 0x4a, 0xac, 0xac, 0x20, 0x00, 0xeb, 0x78, + 0xf6, 0x6a, 0xe9, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, + 0x05, 0x00, 0x30, 0x1c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, + 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, + 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x35, + 0x5a, 0x17, 0x0d, 0x33, 0x32, 0x30, 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x35, 0x5a, + 0x30, 0x1c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, 0x6e, 0x74, + 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, 0x30, 0x82, + 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, + 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00, 0x30, 0x82, 0x02, 0x0a, 0x02, 0x82, 0x02, 0x01, 0x00, 0xd5, + 0x13, 0x55, 0xb1, 0x0d, 0x44, 0x17, 0x6a, 0x06, 0x39, 0x66, 0xee, 0xbc, 0x43, 0x81, 0xea, 0xe0, + 0x93, 0x3f, 0x70, 0xb5, 0x5b, 0x07, 0xde, 0xa0, 0x24, 0x47, 0xd0, 0xf8, 0x99, 0xe6, 0x50, 0x17, + 0xb4, 0x02, 0x60, 0xd9, 0x1a, 0x6c, 0xd3, 0x55, 0x60, 0x61, 0xde, 0x80, 0x6d, 0x38, 0x29, 0x46, + 0xbb, 0x45, 0xa2, 0xeb, 0x24, 0x1c, 0xbb, 0x87, 0x1f, 0x14, 0xed, 0x3a, 0xd5, 0x32, 0xd5, 0x11, + 0x4b, 0xf4, 0x99, 0x78, 0x00, 0x11, 0x8d, 0x6d, 0x6e, 0x5a, 0x0b, 0x81, 0xff, 0x08, 0x59, 0x01, + 0x2b, 0xf0, 0x9b, 0x52, 0x88, 0x41, 0xb6, 0x3e, 0x62, 0x7b, 0xbd, 0x25, 0x96, 0x64, 0x8e, 0xb1, + 0x2b, 0x6a, 0xf8, 0x39, 0x93, 0x0a, 0x6b, 0x3f, 0x8c, 0x2b, 0x35, 0x6e, 0x80, 0x32, 0x86, 0xf6, + 0x0f, 0x1e, 0x8c, 0xd4, 0x4e, 0x77, 0xbe, 0xaf, 0xe5, 0x4c, 0x47, 0x66, 0xdd, 0x62, 0xce, 0x64, + 0x65, 0x80, 0xca, 0xbd, 0x87, 0x94, 0x3e, 0xff, 0x3d, 0x0a, 0xd4, 0x39, 0xcc, 0xd1, 0xef, 0xd1, + 0x1a, 0x55, 0x2c, 0xeb, 0xdc, 0xcf, 0x9a, 0x59, 0x92, 0xda, 0xca, 0xf6, 0xae, 0x88, 0xbc, 0xc0, + 0x43, 0xe5, 0xa9, 0x60, 0xb2, 0x0f, 0x69, 0xa2, 0x2a, 0x98, 0x56, 0x0f, 0x4b, 0x0b, 0x63, 0xb3, + 0x4e, 0x8b, 0x43, 0xb4, 0x7f, 0x52, 0x1e, 0x5a, 0x9e, 0xdf, 0xa7, 0x98, 0x4d, 0xb9, 0x3b, 0x58, + 0x80, 0x69, 0x38, 0xb7, 0xeb, 0x20, 0x91, 0xbf, 0x59, 0x81, 0x44, 0xfc, 0xc6, 0xaf, 0xc2, 0xc8, + 0xe1, 0xae, 0x3d, 0xc5, 0xb6, 0x55, 0xa8, 0xa2, 0xcd, 0xec, 0x0b, 0xbe, 0x9c, 0x34, 0x2b, 0xf5, + 0x4b, 0x2e, 0x3b, 0x26, 0xaa, 0x22, 0x12, 0x29, 0xc2, 0x66, 0xc2, 0x40, 0xdd, 0x12, 0xfa, 0xf0, + 0xb4, 0xe8, 0x95, 0x20, 0x59, 0x91, 0x9e, 0x7d, 0x36, 0x6e, 0x2d, 0x99, 0x53, 0x44, 0x2b, 0x43, + 0x12, 0x08, 0x74, 0x76, 0xd5, 0x21, 0xd3, 0x08, 0x37, 0xe1, 0xe6, 0xe3, 0xc4, 0x67, 0x88, 0x29, + 0xea, 0x06, 0x97, 0x9f, 0x61, 0x0d, 0x5d, 0x39, 0x17, 0x03, 0x87, 0x89, 0x35, 0xe0, 0xd5, 0x87, + 0xa1, 0x5b, 0x0c, 0x3c, 0x35, 0x3d, 0xd6, 0x6f, 0xdd, 0x6f, 0xa5, 0x11, 0x9f, 0x80, 0x20, 0xca, + 0x8b, 0x67, 0xd2, 0x2c, 0x7c, 0x51, 0x68, 0x15, 0x2c, 0x9c, 0x08, 0x86, 0xc8, 0x6c, 0xf0, 0x9d, + 0xc2, 0x98, 0xb9, 0x6e, 0x31, 0xaf, 0x2b, 0x34, 0x9c, 0xe3, 0xd0, 0xe9, 0x85, 0x37, 0x2b, 0x1f, + 0x21, 0xd2, 0xb9, 0xa4, 0x8d, 0x3f, 0xa3, 0x1a, 0x9f, 0x7d, 0x1b, 0xb6, 0xe0, 0xf6, 0x19, 0xf4, + 0x19, 0xf8, 0x50, 0xa7, 0x1b, 0xec, 0xb9, 0xbb, 0xa4, 0xd2, 0x20, 0xf3, 0xed, 0xc7, 0xa7, 0x94, + 0x2b, 0x0b, 0x9a, 0x74, 0xb8, 0xba, 0xd7, 0x42, 0x97, 0xab, 0xb4, 0xe9, 0xbe, 0x1e, 0x07, 0x0c, + 0x05, 0x55, 0x54, 0xba, 0x05, 0x73, 0x99, 0xf2, 0x29, 0x88, 0x69, 0x4f, 0x1b, 0x2e, 0x87, 0x7b, + 0x74, 0x94, 0xae, 0xc2, 0x2f, 0x3c, 0x90, 0xb5, 0x5c, 0x01, 0x46, 0xc6, 0x42, 0xfb, 0xa9, 0xad, + 0x82, 0x1b, 0xd9, 0x38, 0xbe, 0x0d, 0x72, 0x4c, 0x06, 0x03, 0x92, 0xc2, 0xc8, 0x7f, 0x7b, 0xd4, + 0x86, 0x83, 0xb8, 0x62, 0xd9, 0xf7, 0x2f, 0xc1, 0x57, 0x88, 0x85, 0xa5, 0x61, 0xc5, 0x93, 0xfc, + 0x17, 0xe0, 0x98, 0x11, 0x88, 0x0d, 0x03, 0x0b, 0x6e, 0x01, 0x16, 0xcc, 0xf2, 0x3c, 0x5f, 0x61, + 0x8c, 0x27, 0x31, 0xca, 0x4d, 0x35, 0x7a, 0xc1, 0xf3, 0xfe, 0x06, 0xff, 0xca, 0x7b, 0x96, 0xad, + 0x0d, 0xff, 0x9e, 0x12, 0x44, 0x51, 0x6e, 0xf4, 0xaa, 0x2e, 0xce, 0xe8, 0xc7, 0xa6, 0xe9, 0xae, + 0xc0, 0xbe, 0xde, 0x7b, 0x93, 0x3d, 0x1d, 0xf9, 0xfb, 0x4d, 0xa7, 0x0b, 0x73, 0xfb, 0x7b, 0x02, + 0x03, 0x01, 0x00, 0x01, 0xa3, 0x53, 0x30, 0x51, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, + 0x16, 0x04, 0x14, 0x03, 0xfe, 0xb0, 0x3f, 0x09, 0xe5, 0xe1, 0xf4, 0x2e, 0x87, 0xfb, 0x41, 0x86, + 0xf6, 0x76, 0xd3, 0x93, 0xbe, 0x96, 0x85, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, + 0x30, 0x16, 0x80, 0x14, 0x03, 0xfe, 0xb0, 0x3f, 0x09, 0xe5, 0xe1, 0xf4, 0x2e, 0x87, 0xfb, 0x41, + 0x86, 0xf6, 0x76, 0xd3, 0x93, 0xbe, 0x96, 0x85, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, + 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01, 0x00, 0x02, 0x15, 0x73, + 0x60, 0x10, 0xbc, 0x95, 0xac, 0x63, 0x15, 0x09, 0x6b, 0x0c, 0x09, 0x4a, 0x74, 0xcd, 0xe3, 0x58, + 0xcc, 0x6c, 0xf3, 0x55, 0x80, 0xe9, 0x75, 0x47, 0x2c, 0x80, 0x4e, 0x5f, 0xfe, 0xbd, 0x2e, 0xd7, + 0x42, 0x89, 0x44, 0x57, 0xbe, 0x51, 0x84, 0x53, 0xb6, 0x40, 0x80, 0xd6, 0xcc, 0xe2, 0x80, 0x22, + 0x53, 0xd9, 0x31, 0x65, 0xf9, 0x3c, 0x8b, 0x7b, 0xe6, 0xa6, 0x6e, 0xfd, 0x9d, 0x27, 0xe5, 0xcd, + 0xfd, 0x82, 0xcf, 0xd6, 0x18, 0xbe, 0xa6, 0xed, 0x72, 0xce, 0x5f, 0x45, 0x12, 0x6a, 0xaa, 0x95, + 0x42, 0x25, 0x28, 0x8b, 0xfc, 0x4b, 0xc9, 0xad, 0xdd, 0xdb, 0x4c, 0x74, 0x10, 0x2e, 0x90, 0x2a, + 0x06, 0x4f, 0x2e, 0xb4, 0x54, 0xb9, 0xc0, 0x60, 0xb9, 0x4d, 0xee, 0x59, 0x1c, 0x18, 0x8d, 0xd1, + 0x49, 0xc3, 0xe9, 0x1b, 0xf1, 0xfc, 0xc3, 0x83, 0x1f, 0x6a, 0xb0, 0xfc, 0x8d, 0xfc, 0x30, 0xed, + 0x9c, 0xcb, 0x78, 0x52, 0xe8, 0x09, 0x3d, 0x4f, 0xdc, 0xbc, 0xad, 0x84, 0xc1, 0xd5, 0x5a, 0x0a, + 0x07, 0xa3, 0xf6, 0x42, 0xd7, 0x54, 0x55, 0x01, 0x8e, 0x53, 0xce, 0xcb, 0x2a, 0x11, 0xf7, 0x89, + 0x7e, 0xaf, 0x6f, 0x4c, 0xb9, 0x56, 0x4a, 0x67, 0x4a, 0xf9, 0x4f, 0x64, 0x15, 0xfa, 0xb0, 0xf9, + 0x97, 0xe2, 0xf6, 0xa8, 0xf4, 0xe7, 0x0a, 0x7a, 0x83, 0x4e, 0xf6, 0xe9, 0xac, 0x5e, 0xd9, 0xa8, + 0xea, 0x6b, 0x06, 0xcb, 0x2c, 0x41, 0xc1, 0x7e, 0xf5, 0x79, 0xfc, 0x7c, 0x05, 0x06, 0x8f, 0x27, + 0xaa, 0x3b, 0x61, 0x82, 0x72, 0x55, 0xa9, 0xa0, 0xa0, 0xa5, 0x69, 0x2f, 0x95, 0x40, 0xfc, 0xfe, + 0x4a, 0x0f, 0x7d, 0x8c, 0x89, 0xaa, 0xc0, 0x1d, 0x87, 0x03, 0xa1, 0xce, 0xee, 0x23, 0x4f, 0xc5, + 0x7c, 0xb4, 0xb6, 0x2b, 0x6f, 0x05, 0x30, 0xc9, 0x16, 0x51, 0xdf, 0xc7, 0x16, 0x3c, 0x08, 0x38, + 0x20, 0xf9, 0xc5, 0xe0, 0x4a, 0xfa, 0xcb, 0x8c, 0xc3, 0xc5, 0xbb, 0x5c, 0xad, 0xca, 0xc2, 0x52, + 0x45, 0x2f, 0x54, 0x70, 0x78, 0x33, 0x70, 0xc2, 0xed, 0x68, 0xf1, 0x89, 0x67, 0xa3, 0x19, 0x24, + 0xcb, 0x8f, 0x99, 0x1b, 0x28, 0x81, 0x6c, 0x4e, 0x25, 0xb1, 0x27, 0x3d, 0x9f, 0xe7, 0x3d, 0xa7, + 0x73, 0x9e, 0x4c, 0x1a, 0x63, 0x8e, 0xf9, 0xa7, 0xb6, 0x21, 0xe7, 0x4c, 0xdf, 0xfb, 0x36, 0x47, + 0xda, 0x2d, 0xbb, 0x52, 0x55, 0xf8, 0x44, 0x0d, 0x0c, 0xde, 0xe2, 0x13, 0x42, 0x1b, 0xa2, 0xad, + 0xa0, 0x0f, 0x39, 0x6c, 0x78, 0x32, 0x7a, 0x03, 0x9e, 0x55, 0x4e, 0x43, 0xf7, 0x0c, 0x35, 0xd9, + 0x1d, 0x2c, 0x0f, 0x30, 0x30, 0x3e, 0x09, 0xe2, 0x31, 0xa6, 0xb0, 0x1e, 0xa9, 0xf5, 0x4b, 0xa1, + 0x74, 0x09, 0x50, 0xd4, 0xd3, 0xd3, 0x3e, 0x76, 0xb1, 0x67, 0xfc, 0x51, 0xb0, 0x93, 0x22, 0xc4, + 0x6b, 0x8a, 0x27, 0x45, 0x19, 0x3b, 0x35, 0x91, 0x61, 0x36, 0xe7, 0x9c, 0xf6, 0xda, 0x96, 0x30, + 0x7d, 0xf4, 0x11, 0xc4, 0x3f, 0x35, 0x4e, 0x7a, 0xd6, 0x6e, 0xb6, 0xea, 0xe7, 0x66, 0x6f, 0x23, + 0x5c, 0x53, 0x76, 0x53, 0xfc, 0x35, 0x93, 0xe5, 0xfc, 0xb9, 0x6b, 0xb9, 0xd3, 0x6c, 0x48, 0x66, + 0x6f, 0xd7, 0x10, 0x6e, 0x25, 0x72, 0x71, 0x31, 0xfa, 0xc0, 0xdf, 0x31, 0xca, 0xd1, 0xaf, 0xc2, + 0x8e, 0xa5, 0xca, 0xd7, 0x3f, 0x4e, 0xde, 0x47, 0xd5, 0x8e, 0xfc, 0x75, 0xb6, 0x71, 0x83, 0xd9, + 0xfd, 0x11, 0x35, 0x81, 0xbf, 0x10, 0x0d, 0x3e, 0x50, 0x45, 0x07, 0x39, 0x08, 0x73, 0x7a, 0x0b, + 0x21, 0x32, 0xaf, 0xf4, 0x99, 0xeb, 0x4d, 0xd4, 0xe8, 0x2a, 0x06, 0x98, 0x43, 0xbb, 0xbb, 0x11, + 0x63, 0x99, 0xa8, 0x41, 0x22, 0xe8, 0x86, 0x79, 0x4b, 0x53, 0xb7, 0x73, 0x1b, +}; + +// +// dump of bundle_requester.certchain.der +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mTestBundleCert[] = { + 0x30, 0x82, 0x05, 0x19, 0x30, 0x82, 0x03, 0x01, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x14, 0x1d, + 0xaf, 0x4e, 0xf1, 0x99, 0xbf, 0xee, 0xe2, 0x6d, 0x7e, 0x4a, 0xac, 0xac, 0x20, 0x00, 0xeb, 0x78, + 0xf6, 0x6a, 0xe9, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, + 0x05, 0x00, 0x30, 0x1c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, + 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, + 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x35, + 0x5a, 0x17, 0x0d, 0x33, 0x32, 0x30, 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x35, 0x5a, + 0x30, 0x1c, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, 0x6e, 0x74, + 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, 0x30, 0x82, + 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, + 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00, 0x30, 0x82, 0x02, 0x0a, 0x02, 0x82, 0x02, 0x01, 0x00, 0xd5, + 0x13, 0x55, 0xb1, 0x0d, 0x44, 0x17, 0x6a, 0x06, 0x39, 0x66, 0xee, 0xbc, 0x43, 0x81, 0xea, 0xe0, + 0x93, 0x3f, 0x70, 0xb5, 0x5b, 0x07, 0xde, 0xa0, 0x24, 0x47, 0xd0, 0xf8, 0x99, 0xe6, 0x50, 0x17, + 0xb4, 0x02, 0x60, 0xd9, 0x1a, 0x6c, 0xd3, 0x55, 0x60, 0x61, 0xde, 0x80, 0x6d, 0x38, 0x29, 0x46, + 0xbb, 0x45, 0xa2, 0xeb, 0x24, 0x1c, 0xbb, 0x87, 0x1f, 0x14, 0xed, 0x3a, 0xd5, 0x32, 0xd5, 0x11, + 0x4b, 0xf4, 0x99, 0x78, 0x00, 0x11, 0x8d, 0x6d, 0x6e, 0x5a, 0x0b, 0x81, 0xff, 0x08, 0x59, 0x01, + 0x2b, 0xf0, 0x9b, 0x52, 0x88, 0x41, 0xb6, 0x3e, 0x62, 0x7b, 0xbd, 0x25, 0x96, 0x64, 0x8e, 0xb1, + 0x2b, 0x6a, 0xf8, 0x39, 0x93, 0x0a, 0x6b, 0x3f, 0x8c, 0x2b, 0x35, 0x6e, 0x80, 0x32, 0x86, 0xf6, + 0x0f, 0x1e, 0x8c, 0xd4, 0x4e, 0x77, 0xbe, 0xaf, 0xe5, 0x4c, 0x47, 0x66, 0xdd, 0x62, 0xce, 0x64, + 0x65, 0x80, 0xca, 0xbd, 0x87, 0x94, 0x3e, 0xff, 0x3d, 0x0a, 0xd4, 0x39, 0xcc, 0xd1, 0xef, 0xd1, + 0x1a, 0x55, 0x2c, 0xeb, 0xdc, 0xcf, 0x9a, 0x59, 0x92, 0xda, 0xca, 0xf6, 0xae, 0x88, 0xbc, 0xc0, + 0x43, 0xe5, 0xa9, 0x60, 0xb2, 0x0f, 0x69, 0xa2, 0x2a, 0x98, 0x56, 0x0f, 0x4b, 0x0b, 0x63, 0xb3, + 0x4e, 0x8b, 0x43, 0xb4, 0x7f, 0x52, 0x1e, 0x5a, 0x9e, 0xdf, 0xa7, 0x98, 0x4d, 0xb9, 0x3b, 0x58, + 0x80, 0x69, 0x38, 0xb7, 0xeb, 0x20, 0x91, 0xbf, 0x59, 0x81, 0x44, 0xfc, 0xc6, 0xaf, 0xc2, 0xc8, + 0xe1, 0xae, 0x3d, 0xc5, 0xb6, 0x55, 0xa8, 0xa2, 0xcd, 0xec, 0x0b, 0xbe, 0x9c, 0x34, 0x2b, 0xf5, + 0x4b, 0x2e, 0x3b, 0x26, 0xaa, 0x22, 0x12, 0x29, 0xc2, 0x66, 0xc2, 0x40, 0xdd, 0x12, 0xfa, 0xf0, + 0xb4, 0xe8, 0x95, 0x20, 0x59, 0x91, 0x9e, 0x7d, 0x36, 0x6e, 0x2d, 0x99, 0x53, 0x44, 0x2b, 0x43, + 0x12, 0x08, 0x74, 0x76, 0xd5, 0x21, 0xd3, 0x08, 0x37, 0xe1, 0xe6, 0xe3, 0xc4, 0x67, 0x88, 0x29, + 0xea, 0x06, 0x97, 0x9f, 0x61, 0x0d, 0x5d, 0x39, 0x17, 0x03, 0x87, 0x89, 0x35, 0xe0, 0xd5, 0x87, + 0xa1, 0x5b, 0x0c, 0x3c, 0x35, 0x3d, 0xd6, 0x6f, 0xdd, 0x6f, 0xa5, 0x11, 0x9f, 0x80, 0x20, 0xca, + 0x8b, 0x67, 0xd2, 0x2c, 0x7c, 0x51, 0x68, 0x15, 0x2c, 0x9c, 0x08, 0x86, 0xc8, 0x6c, 0xf0, 0x9d, + 0xc2, 0x98, 0xb9, 0x6e, 0x31, 0xaf, 0x2b, 0x34, 0x9c, 0xe3, 0xd0, 0xe9, 0x85, 0x37, 0x2b, 0x1f, + 0x21, 0xd2, 0xb9, 0xa4, 0x8d, 0x3f, 0xa3, 0x1a, 0x9f, 0x7d, 0x1b, 0xb6, 0xe0, 0xf6, 0x19, 0xf4, + 0x19, 0xf8, 0x50, 0xa7, 0x1b, 0xec, 0xb9, 0xbb, 0xa4, 0xd2, 0x20, 0xf3, 0xed, 0xc7, 0xa7, 0x94, + 0x2b, 0x0b, 0x9a, 0x74, 0xb8, 0xba, 0xd7, 0x42, 0x97, 0xab, 0xb4, 0xe9, 0xbe, 0x1e, 0x07, 0x0c, + 0x05, 0x55, 0x54, 0xba, 0x05, 0x73, 0x99, 0xf2, 0x29, 0x88, 0x69, 0x4f, 0x1b, 0x2e, 0x87, 0x7b, + 0x74, 0x94, 0xae, 0xc2, 0x2f, 0x3c, 0x90, 0xb5, 0x5c, 0x01, 0x46, 0xc6, 0x42, 0xfb, 0xa9, 0xad, + 0x82, 0x1b, 0xd9, 0x38, 0xbe, 0x0d, 0x72, 0x4c, 0x06, 0x03, 0x92, 0xc2, 0xc8, 0x7f, 0x7b, 0xd4, + 0x86, 0x83, 0xb8, 0x62, 0xd9, 0xf7, 0x2f, 0xc1, 0x57, 0x88, 0x85, 0xa5, 0x61, 0xc5, 0x93, 0xfc, + 0x17, 0xe0, 0x98, 0x11, 0x88, 0x0d, 0x03, 0x0b, 0x6e, 0x01, 0x16, 0xcc, 0xf2, 0x3c, 0x5f, 0x61, + 0x8c, 0x27, 0x31, 0xca, 0x4d, 0x35, 0x7a, 0xc1, 0xf3, 0xfe, 0x06, 0xff, 0xca, 0x7b, 0x96, 0xad, + 0x0d, 0xff, 0x9e, 0x12, 0x44, 0x51, 0x6e, 0xf4, 0xaa, 0x2e, 0xce, 0xe8, 0xc7, 0xa6, 0xe9, 0xae, + 0xc0, 0xbe, 0xde, 0x7b, 0x93, 0x3d, 0x1d, 0xf9, 0xfb, 0x4d, 0xa7, 0x0b, 0x73, 0xfb, 0x7b, 0x02, + 0x03, 0x01, 0x00, 0x01, 0xa3, 0x53, 0x30, 0x51, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, + 0x16, 0x04, 0x14, 0x03, 0xfe, 0xb0, 0x3f, 0x09, 0xe5, 0xe1, 0xf4, 0x2e, 0x87, 0xfb, 0x41, 0x86, + 0xf6, 0x76, 0xd3, 0x93, 0xbe, 0x96, 0x85, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, + 0x30, 0x16, 0x80, 0x14, 0x03, 0xfe, 0xb0, 0x3f, 0x09, 0xe5, 0xe1, 0xf4, 0x2e, 0x87, 0xfb, 0x41, + 0x86, 0xf6, 0x76, 0xd3, 0x93, 0xbe, 0x96, 0x85, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, + 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01, 0x00, 0x02, 0x15, 0x73, + 0x60, 0x10, 0xbc, 0x95, 0xac, 0x63, 0x15, 0x09, 0x6b, 0x0c, 0x09, 0x4a, 0x74, 0xcd, 0xe3, 0x58, + 0xcc, 0x6c, 0xf3, 0x55, 0x80, 0xe9, 0x75, 0x47, 0x2c, 0x80, 0x4e, 0x5f, 0xfe, 0xbd, 0x2e, 0xd7, + 0x42, 0x89, 0x44, 0x57, 0xbe, 0x51, 0x84, 0x53, 0xb6, 0x40, 0x80, 0xd6, 0xcc, 0xe2, 0x80, 0x22, + 0x53, 0xd9, 0x31, 0x65, 0xf9, 0x3c, 0x8b, 0x7b, 0xe6, 0xa6, 0x6e, 0xfd, 0x9d, 0x27, 0xe5, 0xcd, + 0xfd, 0x82, 0xcf, 0xd6, 0x18, 0xbe, 0xa6, 0xed, 0x72, 0xce, 0x5f, 0x45, 0x12, 0x6a, 0xaa, 0x95, + 0x42, 0x25, 0x28, 0x8b, 0xfc, 0x4b, 0xc9, 0xad, 0xdd, 0xdb, 0x4c, 0x74, 0x10, 0x2e, 0x90, 0x2a, + 0x06, 0x4f, 0x2e, 0xb4, 0x54, 0xb9, 0xc0, 0x60, 0xb9, 0x4d, 0xee, 0x59, 0x1c, 0x18, 0x8d, 0xd1, + 0x49, 0xc3, 0xe9, 0x1b, 0xf1, 0xfc, 0xc3, 0x83, 0x1f, 0x6a, 0xb0, 0xfc, 0x8d, 0xfc, 0x30, 0xed, + 0x9c, 0xcb, 0x78, 0x52, 0xe8, 0x09, 0x3d, 0x4f, 0xdc, 0xbc, 0xad, 0x84, 0xc1, 0xd5, 0x5a, 0x0a, + 0x07, 0xa3, 0xf6, 0x42, 0xd7, 0x54, 0x55, 0x01, 0x8e, 0x53, 0xce, 0xcb, 0x2a, 0x11, 0xf7, 0x89, + 0x7e, 0xaf, 0x6f, 0x4c, 0xb9, 0x56, 0x4a, 0x67, 0x4a, 0xf9, 0x4f, 0x64, 0x15, 0xfa, 0xb0, 0xf9, + 0x97, 0xe2, 0xf6, 0xa8, 0xf4, 0xe7, 0x0a, 0x7a, 0x83, 0x4e, 0xf6, 0xe9, 0xac, 0x5e, 0xd9, 0xa8, + 0xea, 0x6b, 0x06, 0xcb, 0x2c, 0x41, 0xc1, 0x7e, 0xf5, 0x79, 0xfc, 0x7c, 0x05, 0x06, 0x8f, 0x27, + 0xaa, 0x3b, 0x61, 0x82, 0x72, 0x55, 0xa9, 0xa0, 0xa0, 0xa5, 0x69, 0x2f, 0x95, 0x40, 0xfc, 0xfe, + 0x4a, 0x0f, 0x7d, 0x8c, 0x89, 0xaa, 0xc0, 0x1d, 0x87, 0x03, 0xa1, 0xce, 0xee, 0x23, 0x4f, 0xc5, + 0x7c, 0xb4, 0xb6, 0x2b, 0x6f, 0x05, 0x30, 0xc9, 0x16, 0x51, 0xdf, 0xc7, 0x16, 0x3c, 0x08, 0x38, + 0x20, 0xf9, 0xc5, 0xe0, 0x4a, 0xfa, 0xcb, 0x8c, 0xc3, 0xc5, 0xbb, 0x5c, 0xad, 0xca, 0xc2, 0x52, + 0x45, 0x2f, 0x54, 0x70, 0x78, 0x33, 0x70, 0xc2, 0xed, 0x68, 0xf1, 0x89, 0x67, 0xa3, 0x19, 0x24, + 0xcb, 0x8f, 0x99, 0x1b, 0x28, 0x81, 0x6c, 0x4e, 0x25, 0xb1, 0x27, 0x3d, 0x9f, 0xe7, 0x3d, 0xa7, + 0x73, 0x9e, 0x4c, 0x1a, 0x63, 0x8e, 0xf9, 0xa7, 0xb6, 0x21, 0xe7, 0x4c, 0xdf, 0xfb, 0x36, 0x47, + 0xda, 0x2d, 0xbb, 0x52, 0x55, 0xf8, 0x44, 0x0d, 0x0c, 0xde, 0xe2, 0x13, 0x42, 0x1b, 0xa2, 0xad, + 0xa0, 0x0f, 0x39, 0x6c, 0x78, 0x32, 0x7a, 0x03, 0x9e, 0x55, 0x4e, 0x43, 0xf7, 0x0c, 0x35, 0xd9, + 0x1d, 0x2c, 0x0f, 0x30, 0x30, 0x3e, 0x09, 0xe2, 0x31, 0xa6, 0xb0, 0x1e, 0xa9, 0xf5, 0x4b, 0xa1, + 0x74, 0x09, 0x50, 0xd4, 0xd3, 0xd3, 0x3e, 0x76, 0xb1, 0x67, 0xfc, 0x51, 0xb0, 0x93, 0x22, 0xc4, + 0x6b, 0x8a, 0x27, 0x45, 0x19, 0x3b, 0x35, 0x91, 0x61, 0x36, 0xe7, 0x9c, 0xf6, 0xda, 0x96, 0x30, + 0x7d, 0xf4, 0x11, 0xc4, 0x3f, 0x35, 0x4e, 0x7a, 0xd6, 0x6e, 0xb6, 0xea, 0xe7, 0x66, 0x6f, 0x23, + 0x5c, 0x53, 0x76, 0x53, 0xfc, 0x35, 0x93, 0xe5, 0xfc, 0xb9, 0x6b, 0xb9, 0xd3, 0x6c, 0x48, 0x66, + 0x6f, 0xd7, 0x10, 0x6e, 0x25, 0x72, 0x71, 0x31, 0xfa, 0xc0, 0xdf, 0x31, 0xca, 0xd1, 0xaf, 0xc2, + 0x8e, 0xa5, 0xca, 0xd7, 0x3f, 0x4e, 0xde, 0x47, 0xd5, 0x8e, 0xfc, 0x75, 0xb6, 0x71, 0x83, 0xd9, + 0xfd, 0x11, 0x35, 0x81, 0xbf, 0x10, 0x0d, 0x3e, 0x50, 0x45, 0x07, 0x39, 0x08, 0x73, 0x7a, 0x0b, + 0x21, 0x32, 0xaf, 0xf4, 0x99, 0xeb, 0x4d, 0xd4, 0xe8, 0x2a, 0x06, 0x98, 0x43, 0xbb, 0xbb, 0x11, + 0x63, 0x99, 0xa8, 0x41, 0x22, 0xe8, 0x86, 0x79, 0x4b, 0x53, 0xb7, 0x73, 0x1b, 0x30, 0x82, 0x04, + 0xa0, 0x30, 0x82, 0x02, 0x88, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x01, 0x30, 0x0d, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x1c, 0x31, 0x1a, + 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x74, + 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x32, + 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x17, 0x0d, 0x33, 0x32, 0x30, + 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x30, 0x2b, 0x31, 0x29, 0x30, 0x27, + 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, + 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6d, 0x65, 0x64, 0x69, 0x61, + 0x74, 0x65, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x82, 0x01, 0xa2, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x8f, 0x00, 0x30, + 0x82, 0x01, 0x8a, 0x02, 0x82, 0x01, 0x81, 0x00, 0xd1, 0xcf, 0x2d, 0x21, 0x38, 0xe4, 0x81, 0xa6, + 0xf2, 0xe5, 0xca, 0xac, 0x09, 0x2b, 0x04, 0x2a, 0x52, 0x76, 0x2f, 0xa3, 0x4b, 0x43, 0xc2, 0xd6, + 0xb5, 0x3e, 0x2b, 0x29, 0x6f, 0x1b, 0x7d, 0x36, 0x60, 0xcd, 0x71, 0xf4, 0xcf, 0x8a, 0x24, 0xac, + 0x8f, 0x5f, 0x78, 0x70, 0xc9, 0x84, 0x48, 0xfb, 0x1d, 0xcb, 0xee, 0x34, 0x3c, 0x4c, 0xe1, 0x1a, + 0x92, 0x54, 0x43, 0x45, 0xe0, 0xdd, 0x14, 0xd5, 0xac, 0x13, 0xae, 0xcc, 0x45, 0xdc, 0x52, 0xdd, + 0x45, 0x22, 0x10, 0xab, 0xb2, 0x1b, 0x3e, 0xad, 0x36, 0x6f, 0x00, 0x59, 0xb6, 0xfd, 0x27, 0xb8, + 0x57, 0xbb, 0x66, 0x72, 0x1e, 0x7b, 0xe8, 0xc7, 0xaf, 0x5e, 0x65, 0x5c, 0x58, 0x3d, 0x9e, 0x78, + 0x26, 0xb7, 0x70, 0x9a, 0xe7, 0x3c, 0xfc, 0x90, 0x64, 0xb2, 0xb2, 0xb2, 0x80, 0x22, 0xb3, 0x1c, + 0x23, 0x73, 0x6a, 0xe3, 0xcb, 0x5b, 0x4e, 0x29, 0x71, 0xdd, 0xfd, 0xd7, 0x15, 0x3a, 0xd6, 0xa3, + 0xe0, 0x4a, 0x53, 0x65, 0xa6, 0xae, 0x6a, 0x83, 0xb0, 0x00, 0x3f, 0x64, 0x4b, 0x01, 0xcd, 0x97, + 0xb1, 0xe1, 0x54, 0x1e, 0xa2, 0x33, 0x4e, 0xf0, 0x13, 0x33, 0x80, 0xe5, 0x41, 0x9c, 0x5e, 0xb3, + 0x5d, 0xae, 0x53, 0x2c, 0x41, 0x51, 0xf2, 0x00, 0x3e, 0x03, 0xe2, 0x0d, 0xa4, 0xf5, 0x24, 0x08, + 0x46, 0xc2, 0xed, 0x6b, 0xf2, 0xe0, 0x1b, 0x04, 0xb7, 0xe8, 0xda, 0x85, 0xa4, 0x2f, 0x4b, 0x53, + 0xfa, 0x76, 0x72, 0x0a, 0x28, 0xbf, 0x3c, 0xa8, 0x85, 0x03, 0xee, 0x51, 0xb5, 0x5c, 0xa9, 0xa5, + 0x70, 0x47, 0x07, 0x11, 0x32, 0xc5, 0x5f, 0x7a, 0x07, 0xfb, 0x5f, 0x4a, 0x52, 0x65, 0x33, 0x0c, + 0x17, 0x8e, 0x74, 0xe5, 0xec, 0x7d, 0x52, 0xa0, 0xd4, 0xef, 0x64, 0xcc, 0x5e, 0xe2, 0x3d, 0x46, + 0x1e, 0x73, 0xab, 0x43, 0x2d, 0x05, 0xfa, 0xa3, 0x6d, 0x86, 0x02, 0xe7, 0xc8, 0x5f, 0x44, 0xfe, + 0xeb, 0x14, 0x73, 0x2d, 0xf4, 0x0b, 0x72, 0x49, 0xe3, 0xef, 0x55, 0x05, 0x1b, 0x2f, 0xf9, 0x73, + 0xeb, 0xed, 0xcc, 0x5e, 0x52, 0x17, 0x43, 0x94, 0x85, 0xc7, 0x0e, 0x73, 0x89, 0x22, 0xdc, 0x02, + 0x5f, 0x99, 0x69, 0x58, 0x16, 0x89, 0x1e, 0x6f, 0x75, 0xf8, 0xd3, 0xe7, 0x0a, 0xb1, 0x01, 0x42, + 0x71, 0xa6, 0xc5, 0xb2, 0xd0, 0xc0, 0x75, 0x96, 0x2e, 0xc2, 0x32, 0x49, 0x0a, 0xe8, 0x85, 0xbd, + 0x22, 0x4c, 0x95, 0xd4, 0xf8, 0x2d, 0x72, 0x05, 0x4f, 0x0e, 0x56, 0x9c, 0xc3, 0x30, 0x3d, 0xfd, + 0x30, 0x63, 0x92, 0x72, 0x6b, 0xaf, 0x80, 0x9d, 0xd0, 0xc2, 0x36, 0xe7, 0xc1, 0x37, 0xd0, 0x64, + 0x88, 0x64, 0x3c, 0x33, 0xdd, 0x87, 0xdd, 0xd9, 0xa2, 0x79, 0x44, 0xd8, 0x25, 0x84, 0x0e, 0xfd, + 0x9d, 0xd6, 0xc1, 0x7a, 0x2d, 0x23, 0x08, 0x9d, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x5e, 0x30, + 0x5c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, + 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x01, 0xfe, 0x30, 0x1d, 0x06, 0x03, + 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x46, 0xcd, 0xb4, 0x52, 0x02, 0x29, 0x26, 0xc7, 0x52, + 0x23, 0x81, 0x65, 0xcd, 0x87, 0x2f, 0x96, 0x1b, 0x01, 0x2c, 0xc5, 0x30, 0x20, 0x06, 0x03, 0x55, + 0x1d, 0x25, 0x01, 0x01, 0xff, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, + 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0d, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01, + 0x00, 0x71, 0x14, 0xca, 0xfe, 0x03, 0x92, 0xc6, 0x88, 0x52, 0x76, 0x43, 0xd9, 0x8a, 0xf7, 0x22, + 0x94, 0xef, 0x40, 0xa7, 0xc3, 0x7b, 0x6f, 0xb4, 0xd0, 0x42, 0xc3, 0x59, 0x1f, 0x77, 0xef, 0xac, + 0x18, 0xce, 0x7c, 0xab, 0x48, 0x85, 0x22, 0xf1, 0x50, 0x2c, 0xe0, 0x63, 0x4d, 0x9d, 0x0e, 0xed, + 0x38, 0xff, 0xd9, 0xed, 0x3c, 0x7e, 0x3e, 0x84, 0xb1, 0xa7, 0x78, 0x62, 0x37, 0x39, 0x6d, 0xd5, + 0x5d, 0x46, 0x9a, 0x6f, 0x63, 0xc2, 0xa7, 0x90, 0xf9, 0x7a, 0xa7, 0x4b, 0xa2, 0x8a, 0xa8, 0x50, + 0x13, 0x16, 0x9c, 0x4f, 0xcc, 0x28, 0x58, 0x6c, 0x9f, 0x65, 0x6e, 0xf0, 0x9a, 0x92, 0x59, 0x94, + 0xa4, 0xb5, 0xfd, 0x8f, 0xf0, 0x7c, 0x1e, 0xba, 0xc3, 0x21, 0x13, 0xfb, 0x33, 0xba, 0xad, 0x4b, + 0x1d, 0x42, 0x23, 0x16, 0x8b, 0x3e, 0xcd, 0xb5, 0x69, 0x9c, 0x7c, 0xa1, 0x9b, 0x92, 0xc1, 0x2f, + 0x9c, 0x89, 0x3f, 0x28, 0x24, 0x67, 0x48, 0x47, 0xf0, 0xb1, 0xc0, 0xf0, 0x4c, 0xbf, 0xf6, 0x64, + 0xde, 0x33, 0xc3, 0xd6, 0x5b, 0xe6, 0xc3, 0xdd, 0xa5, 0xba, 0x42, 0x02, 0x0f, 0xbc, 0xbe, 0xde, + 0x14, 0x12, 0x7c, 0xfb, 0xe6, 0xbb, 0xdd, 0xf2, 0x6b, 0xd7, 0x75, 0xe6, 0xf5, 0xda, 0xbe, 0xe9, + 0xbf, 0xa6, 0x87, 0x09, 0x41, 0x6c, 0x9d, 0x19, 0x9c, 0xb1, 0x7c, 0x89, 0x9f, 0x32, 0xb3, 0x0a, + 0x59, 0x10, 0xc6, 0x8c, 0xa0, 0x5b, 0xda, 0xa6, 0xa3, 0xf8, 0x33, 0x77, 0x7a, 0xf4, 0xb0, 0x8a, + 0xcf, 0xc8, 0x3f, 0x2e, 0xb8, 0xf1, 0x9e, 0x7b, 0x47, 0x2d, 0x85, 0x3b, 0x58, 0xcd, 0x4b, 0xbc, + 0x87, 0xd2, 0xf3, 0xcd, 0x36, 0x80, 0x9b, 0x4a, 0x0f, 0x24, 0x30, 0x1d, 0x3f, 0x6f, 0x56, 0xcf, + 0x6e, 0x2d, 0xcf, 0xa8, 0x17, 0xd5, 0x97, 0x0b, 0x22, 0xa6, 0x59, 0xef, 0xef, 0xd4, 0x9a, 0x0e, + 0x6f, 0xb9, 0xf0, 0x48, 0x2a, 0x54, 0x22, 0x77, 0x27, 0x90, 0x84, 0x42, 0x56, 0x85, 0x80, 0x78, + 0x4f, 0xd9, 0x14, 0x2a, 0xf0, 0x5d, 0x6b, 0x46, 0x60, 0x3d, 0xad, 0xa5, 0xa2, 0xb9, 0x04, 0x23, + 0x92, 0x1b, 0x70, 0xa3, 0xdb, 0xaa, 0xf0, 0x5f, 0x1c, 0xd8, 0x26, 0xbb, 0x51, 0x17, 0xfc, 0x93, + 0x6d, 0x70, 0x19, 0x54, 0xe2, 0x6f, 0x82, 0x8a, 0x49, 0xa6, 0x19, 0xcc, 0x97, 0x53, 0x90, 0x27, + 0xd9, 0x8d, 0xaa, 0x8c, 0xc3, 0x2b, 0xbc, 0x0a, 0x72, 0x3a, 0x41, 0xb8, 0xfa, 0x1e, 0xbb, 0x8b, + 0x27, 0x06, 0x75, 0x53, 0x91, 0xac, 0x8d, 0x75, 0xf2, 0xa6, 0xea, 0x85, 0x7e, 0x34, 0x06, 0x9e, + 0xf9, 0xe9, 0x13, 0xa3, 0xfe, 0x2e, 0x38, 0x4b, 0x3f, 0x61, 0x11, 0x1f, 0x6b, 0xd3, 0xfe, 0xc9, + 0x13, 0xbc, 0x12, 0xfe, 0xbc, 0xff, 0xaa, 0x38, 0x73, 0x8a, 0x73, 0x8c, 0xcf, 0xcc, 0xd3, 0xe7, + 0xba, 0x98, 0xfd, 0xf4, 0xf5, 0xf6, 0xa9, 0xc8, 0x07, 0x5b, 0x16, 0xae, 0x76, 0x86, 0x24, 0x25, + 0xcc, 0x7c, 0xdb, 0x1e, 0x7f, 0xc4, 0xe4, 0xd3, 0x89, 0x5a, 0x91, 0x6a, 0x9c, 0x93, 0x03, 0xd2, + 0xd2, 0xc0, 0x29, 0x69, 0x58, 0x52, 0x6c, 0xca, 0x91, 0x7d, 0xd2, 0x3d, 0xc7, 0x2f, 0x8a, 0x4e, + 0x55, 0x03, 0x34, 0x16, 0x01, 0x2f, 0x4f, 0x57, 0xea, 0x10, 0xa7, 0xfb, 0xe3, 0x2e, 0x2c, 0x7f, + 0x5d, 0x27, 0x93, 0x74, 0x95, 0x25, 0x1a, 0x1e, 0x54, 0x1a, 0xb6, 0xe1, 0xdc, 0xc8, 0xe4, 0x84, + 0xeb, 0x38, 0x0f, 0x05, 0x74, 0xf3, 0x3a, 0xf9, 0xd8, 0x00, 0x43, 0xe9, 0x24, 0x1e, 0x45, 0xb4, + 0xe2, 0x38, 0x8b, 0x6a, 0x4f, 0xb6, 0x0b, 0x1d, 0xac, 0xbc, 0xec, 0xda, 0x41, 0x9c, 0x7f, 0xa8, + 0x15, 0x09, 0x3b, 0x0b, 0x99, 0xc4, 0x48, 0xdd, 0xde, 0x0d, 0x65, 0x86, 0x72, 0xaa, 0x0a, 0x4e, + 0x71, 0x30, 0x82, 0x03, 0xeb, 0x30, 0x82, 0x02, 0x53, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, + 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, + 0x30, 0x2b, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x69, 0x6e, 0x74, + 0x65, 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x74, 0x65, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x1e, 0x17, + 0x0d, 0x32, 0x32, 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x17, 0x0d, + 0x33, 0x32, 0x30, 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x30, 0x28, 0x31, + 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1d, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x20, + 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x72, 0x65, 0x71, 0x75, 0x73, 0x65, 0x74, + 0x65, 0x72, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, + 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0x93, 0x47, 0xf3, 0x71, 0x6b, 0x24, 0x1e, 0xc0, + 0xeb, 0x6b, 0x22, 0x23, 0xe7, 0xc8, 0x10, 0x9d, 0xb2, 0xef, 0x1e, 0x65, 0xe9, 0xff, 0xd6, 0x37, + 0xee, 0xc5, 0x3f, 0x29, 0x25, 0x94, 0xb4, 0x30, 0x97, 0x51, 0xe3, 0x51, 0xa4, 0x39, 0xd1, 0x27, + 0x32, 0x9e, 0x6b, 0x80, 0xc2, 0x29, 0xf2, 0x28, 0xd1, 0x49, 0xdc, 0x62, 0x27, 0x5b, 0x3f, 0xce, + 0x83, 0xd7, 0x7b, 0x09, 0x37, 0x48, 0x16, 0x7f, 0x2e, 0x6e, 0xfa, 0x67, 0xaa, 0x92, 0x17, 0xcb, + 0xff, 0x4b, 0xe3, 0x1b, 0xd1, 0xa6, 0xe3, 0x6c, 0x4d, 0x9f, 0x9e, 0xc7, 0x01, 0xed, 0x9f, 0x14, + 0xb0, 0x34, 0x44, 0xa2, 0x88, 0x28, 0xf2, 0x3f, 0xad, 0xf2, 0xf7, 0x51, 0x8c, 0xfe, 0x43, 0x73, + 0xfa, 0x8d, 0x2f, 0x63, 0x8c, 0x0e, 0xe5, 0x27, 0xdc, 0x12, 0x81, 0x26, 0xea, 0x92, 0x67, 0x7d, + 0xc9, 0xfc, 0xec, 0x4c, 0xcc, 0x79, 0x4d, 0x2d, 0xfe, 0xf6, 0x63, 0xb7, 0x63, 0xca, 0x70, 0x24, + 0xe0, 0x23, 0x53, 0x92, 0xe8, 0x56, 0xb7, 0x85, 0x6d, 0x25, 0x9e, 0xe0, 0x24, 0xa8, 0x5c, 0xe0, + 0x0f, 0xc1, 0xb6, 0x20, 0x2f, 0x85, 0x2a, 0x67, 0xf6, 0x1b, 0x58, 0x60, 0x5a, 0x14, 0xda, 0xc2, + 0x03, 0x10, 0x79, 0x33, 0x3c, 0x41, 0xc6, 0xbe, 0xd2, 0xee, 0x2f, 0x65, 0xd5, 0xad, 0x9c, 0xc6, + 0x09, 0xae, 0x26, 0xf2, 0xac, 0xc2, 0x65, 0x12, 0x74, 0x09, 0xe8, 0x89, 0x66, 0xf6, 0x95, 0xb8, + 0x6a, 0x5f, 0x96, 0xc2, 0x3c, 0x9f, 0x01, 0x52, 0xa8, 0xc8, 0x4e, 0xd8, 0xba, 0x95, 0x38, 0x5b, + 0xf8, 0xc6, 0x43, 0x54, 0xac, 0x63, 0x90, 0xd4, 0xde, 0x11, 0x40, 0x27, 0xe5, 0x12, 0x1d, 0x72, + 0xa2, 0xec, 0xad, 0x0a, 0x8b, 0x68, 0x21, 0x9d, 0xea, 0x16, 0x70, 0x5f, 0x32, 0x3a, 0xed, 0x4f, + 0x0b, 0xb2, 0x44, 0x1f, 0x44, 0x9b, 0x4c, 0x03, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x81, 0x9c, + 0x30, 0x81, 0x99, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, + 0x00, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x05, 0xe0, 0x30, 0x1d, + 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x7c, 0x69, 0x5e, 0x84, 0xbb, 0xc7, 0x6b, + 0xfc, 0x45, 0x70, 0xa4, 0x4b, 0x1e, 0x67, 0x70, 0x04, 0xa4, 0x37, 0xdd, 0x72, 0x30, 0x31, 0x06, + 0x03, 0x55, 0x1d, 0x11, 0x04, 0x2a, 0x30, 0x28, 0xa0, 0x26, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, + 0x01, 0x83, 0x1c, 0x82, 0x12, 0x01, 0xa0, 0x18, 0x0c, 0x16, 0x41, 0x43, 0x4d, 0x45, 0x3a, 0x57, + 0x49, 0x44, 0x47, 0x45, 0x54, 0x3a, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, + 0x30, 0x2a, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x01, 0x01, 0xff, 0x04, 0x20, 0x30, 0x1e, 0x06, 0x08, + 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, + 0x03, 0x02, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x09, 0x30, 0x0d, 0x06, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x81, 0x00, + 0x8e, 0x19, 0x08, 0xec, 0x7a, 0xcc, 0x6d, 0x04, 0x5f, 0xb7, 0xf9, 0xd2, 0xcd, 0x76, 0xee, 0x44, + 0x1b, 0x7c, 0x19, 0xcb, 0x18, 0xdd, 0x60, 0x50, 0x3a, 0x54, 0xb1, 0x75, 0x17, 0xf6, 0xce, 0x19, + 0x15, 0x09, 0x9e, 0x5b, 0xfc, 0x5c, 0xb3, 0x20, 0x8d, 0xcb, 0x9d, 0xfc, 0x23, 0x12, 0x68, 0x87, + 0x55, 0x0d, 0x3b, 0x5f, 0x9f, 0x4e, 0xb2, 0x17, 0x13, 0x0b, 0xc4, 0x6f, 0xbe, 0x43, 0x75, 0xa6, + 0xb7, 0x3c, 0x0e, 0xe0, 0xdf, 0x84, 0xe5, 0x88, 0x46, 0x08, 0xc3, 0x36, 0x1b, 0x31, 0x02, 0x92, + 0x7c, 0x53, 0xc4, 0x08, 0x63, 0x3e, 0x46, 0x75, 0xd7, 0x35, 0x9a, 0xd0, 0x76, 0x71, 0xf9, 0x57, + 0x97, 0xc7, 0x3c, 0x3b, 0xce, 0x7a, 0x82, 0x95, 0x15, 0x8e, 0x20, 0xcc, 0x7b, 0xa0, 0xc4, 0x68, + 0x21, 0x26, 0x9c, 0xfd, 0x29, 0x83, 0x41, 0x19, 0x98, 0xb6, 0x8a, 0x3a, 0x06, 0x5f, 0x01, 0x1b, + 0x80, 0xac, 0x33, 0xd9, 0x0c, 0x9c, 0xea, 0x70, 0xd7, 0xf5, 0x1e, 0xb0, 0x78, 0x24, 0xbc, 0x59, + 0xaf, 0x07, 0xc6, 0x16, 0x46, 0xdd, 0x9d, 0x00, 0x9a, 0xc8, 0x9a, 0x04, 0x19, 0x4d, 0x62, 0xa9, + 0x4f, 0x7c, 0x05, 0x24, 0x93, 0xc6, 0x01, 0xc5, 0xb2, 0x89, 0xe8, 0x62, 0x47, 0xbe, 0xa3, 0xd1, + 0x9c, 0x47, 0x31, 0x06, 0x16, 0x6b, 0x3b, 0xf8, 0xad, 0xb0, 0x4c, 0xfb, 0x2b, 0x6b, 0x8e, 0x88, + 0x53, 0x70, 0x75, 0x40, 0x30, 0xaf, 0xfe, 0xc5, 0xf3, 0x0f, 0x86, 0x8f, 0x58, 0x56, 0x67, 0xbd, + 0x15, 0x1f, 0x8a, 0x5c, 0xa3, 0x8a, 0x9a, 0x88, 0xe5, 0xf2, 0xd3, 0x7f, 0xac, 0x56, 0x34, 0x21, + 0x24, 0xf7, 0xde, 0x9d, 0x97, 0x9b, 0xe6, 0x20, 0xd6, 0x3d, 0x48, 0x73, 0x29, 0x23, 0xf9, 0x0f, + 0xab, 0x04, 0xe6, 0x1d, 0x70, 0xee, 0xcb, 0x5a, 0xe5, 0x8a, 0xf4, 0xbc, 0x4b, 0xad, 0x18, 0xec, + 0x25, 0x8a, 0xb8, 0x91, 0xf9, 0x53, 0xf4, 0xe4, 0xce, 0xa7, 0x54, 0xf6, 0x83, 0x66, 0x07, 0xc5, + 0x51, 0x48, 0x20, 0x54, 0x5b, 0x5d, 0xc1, 0x80, 0x04, 0x17, 0x89, 0x14, 0x5a, 0x06, 0x34, 0x86, + 0xdb, 0x8b, 0xaf, 0x04, 0x24, 0xd9, 0xbd, 0xa8, 0x27, 0x09, 0x51, 0xfe, 0x6e, 0x47, 0x3c, 0x29, + 0x0a, 0x64, 0x3e, 0x0f, 0x00, 0xf1, 0xd9, 0xdc, 0xe9, 0xd1, 0x3c, 0xcf, 0xa4, 0xa9, 0x4f, 0x54, + 0x02, 0xcf, 0xa1, 0x40, 0x49, 0x61, 0x2a, 0x07, 0xa2, 0x44, 0x35, 0x20, 0x20, 0x56, 0x1c, 0x27, + 0xa2, 0xff, 0x07, 0x3e, 0x8b, 0xfe, 0x60, 0x42, 0x75, 0x0c, 0xe3, 0x8f, 0xee, 0x33, 0x8d, 0xfc, + 0x3b, 0x53, 0x36, 0x39, 0x10, 0x1a, 0xe3, 0xd2, 0x09, 0x7b, 0x00, 0xd0, 0xbd, 0x39, 0xf4, 0xcc, + 0xe3, 0x42, 0xd4, 0xa5, 0x2d, 0x0b, 0x58, 0xdf, 0x24, 0x7f, 0x85, 0x0a, 0xf2, 0x17, 0x76, 0xdd, +}; + +// +// dump of end_requester.key.der +// +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT8 mTestEndCert[] = { + 0x30, 0x82, 0x03, 0xeb, 0x30, 0x82, 0x02, 0x53, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x01, 0x02, + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, + 0x2b, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x69, 0x6e, 0x74, 0x65, + 0x6c, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, + 0x6d, 0x65, 0x64, 0x69, 0x61, 0x74, 0x65, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x1e, 0x17, 0x0d, + 0x32, 0x32, 0x30, 0x31, 0x30, 0x35, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x17, 0x0d, 0x33, + 0x32, 0x30, 0x31, 0x30, 0x33, 0x30, 0x36, 0x31, 0x31, 0x30, 0x36, 0x5a, 0x30, 0x28, 0x31, 0x26, + 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1d, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x74, + 0x65, 0x73, 0x74, 0x20, 0x52, 0x53, 0x41, 0x20, 0x72, 0x65, 0x71, 0x75, 0x73, 0x65, 0x74, 0x65, + 0x72, 0x20, 0x63, 0x65, 0x72, 0x74, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, + 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, + 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0x93, 0x47, 0xf3, 0x71, 0x6b, 0x24, 0x1e, 0xc0, 0xeb, + 0x6b, 0x22, 0x23, 0xe7, 0xc8, 0x10, 0x9d, 0xb2, 0xef, 0x1e, 0x65, 0xe9, 0xff, 0xd6, 0x37, 0xee, + 0xc5, 0x3f, 0x29, 0x25, 0x94, 0xb4, 0x30, 0x97, 0x51, 0xe3, 0x51, 0xa4, 0x39, 0xd1, 0x27, 0x32, + 0x9e, 0x6b, 0x80, 0xc2, 0x29, 0xf2, 0x28, 0xd1, 0x49, 0xdc, 0x62, 0x27, 0x5b, 0x3f, 0xce, 0x83, + 0xd7, 0x7b, 0x09, 0x37, 0x48, 0x16, 0x7f, 0x2e, 0x6e, 0xfa, 0x67, 0xaa, 0x92, 0x17, 0xcb, 0xff, + 0x4b, 0xe3, 0x1b, 0xd1, 0xa6, 0xe3, 0x6c, 0x4d, 0x9f, 0x9e, 0xc7, 0x01, 0xed, 0x9f, 0x14, 0xb0, + 0x34, 0x44, 0xa2, 0x88, 0x28, 0xf2, 0x3f, 0xad, 0xf2, 0xf7, 0x51, 0x8c, 0xfe, 0x43, 0x73, 0xfa, + 0x8d, 0x2f, 0x63, 0x8c, 0x0e, 0xe5, 0x27, 0xdc, 0x12, 0x81, 0x26, 0xea, 0x92, 0x67, 0x7d, 0xc9, + 0xfc, 0xec, 0x4c, 0xcc, 0x79, 0x4d, 0x2d, 0xfe, 0xf6, 0x63, 0xb7, 0x63, 0xca, 0x70, 0x24, 0xe0, + 0x23, 0x53, 0x92, 0xe8, 0x56, 0xb7, 0x85, 0x6d, 0x25, 0x9e, 0xe0, 0x24, 0xa8, 0x5c, 0xe0, 0x0f, + 0xc1, 0xb6, 0x20, 0x2f, 0x85, 0x2a, 0x67, 0xf6, 0x1b, 0x58, 0x60, 0x5a, 0x14, 0xda, 0xc2, 0x03, + 0x10, 0x79, 0x33, 0x3c, 0x41, 0xc6, 0xbe, 0xd2, 0xee, 0x2f, 0x65, 0xd5, 0xad, 0x9c, 0xc6, 0x09, + 0xae, 0x26, 0xf2, 0xac, 0xc2, 0x65, 0x12, 0x74, 0x09, 0xe8, 0x89, 0x66, 0xf6, 0x95, 0xb8, 0x6a, + 0x5f, 0x96, 0xc2, 0x3c, 0x9f, 0x01, 0x52, 0xa8, 0xc8, 0x4e, 0xd8, 0xba, 0x95, 0x38, 0x5b, 0xf8, + 0xc6, 0x43, 0x54, 0xac, 0x63, 0x90, 0xd4, 0xde, 0x11, 0x40, 0x27, 0xe5, 0x12, 0x1d, 0x72, 0xa2, + 0xec, 0xad, 0x0a, 0x8b, 0x68, 0x21, 0x9d, 0xea, 0x16, 0x70, 0x5f, 0x32, 0x3a, 0xed, 0x4f, 0x0b, + 0xb2, 0x44, 0x1f, 0x44, 0x9b, 0x4c, 0x03, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x81, 0x9c, 0x30, + 0x81, 0x99, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, + 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x05, 0xe0, 0x30, 0x1d, 0x06, + 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x7c, 0x69, 0x5e, 0x84, 0xbb, 0xc7, 0x6b, 0xfc, + 0x45, 0x70, 0xa4, 0x4b, 0x1e, 0x67, 0x70, 0x04, 0xa4, 0x37, 0xdd, 0x72, 0x30, 0x31, 0x06, 0x03, + 0x55, 0x1d, 0x11, 0x04, 0x2a, 0x30, 0x28, 0xa0, 0x26, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, + 0x83, 0x1c, 0x82, 0x12, 0x01, 0xa0, 0x18, 0x0c, 0x16, 0x41, 0x43, 0x4d, 0x45, 0x3a, 0x57, 0x49, + 0x44, 0x47, 0x45, 0x54, 0x3a, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x30, + 0x2a, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x01, 0x01, 0xff, 0x04, 0x20, 0x30, 0x1e, 0x06, 0x08, 0x2b, + 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, + 0x02, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x09, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x81, 0x00, 0x8e, + 0x19, 0x08, 0xec, 0x7a, 0xcc, 0x6d, 0x04, 0x5f, 0xb7, 0xf9, 0xd2, 0xcd, 0x76, 0xee, 0x44, 0x1b, + 0x7c, 0x19, 0xcb, 0x18, 0xdd, 0x60, 0x50, 0x3a, 0x54, 0xb1, 0x75, 0x17, 0xf6, 0xce, 0x19, 0x15, + 0x09, 0x9e, 0x5b, 0xfc, 0x5c, 0xb3, 0x20, 0x8d, 0xcb, 0x9d, 0xfc, 0x23, 0x12, 0x68, 0x87, 0x55, + 0x0d, 0x3b, 0x5f, 0x9f, 0x4e, 0xb2, 0x17, 0x13, 0x0b, 0xc4, 0x6f, 0xbe, 0x43, 0x75, 0xa6, 0xb7, + 0x3c, 0x0e, 0xe0, 0xdf, 0x84, 0xe5, 0x88, 0x46, 0x08, 0xc3, 0x36, 0x1b, 0x31, 0x02, 0x92, 0x7c, + 0x53, 0xc4, 0x08, 0x63, 0x3e, 0x46, 0x75, 0xd7, 0x35, 0x9a, 0xd0, 0x76, 0x71, 0xf9, 0x57, 0x97, + 0xc7, 0x3c, 0x3b, 0xce, 0x7a, 0x82, 0x95, 0x15, 0x8e, 0x20, 0xcc, 0x7b, 0xa0, 0xc4, 0x68, 0x21, + 0x26, 0x9c, 0xfd, 0x29, 0x83, 0x41, 0x19, 0x98, 0xb6, 0x8a, 0x3a, 0x06, 0x5f, 0x01, 0x1b, 0x80, + 0xac, 0x33, 0xd9, 0x0c, 0x9c, 0xea, 0x70, 0xd7, 0xf5, 0x1e, 0xb0, 0x78, 0x24, 0xbc, 0x59, 0xaf, + 0x07, 0xc6, 0x16, 0x46, 0xdd, 0x9d, 0x00, 0x9a, 0xc8, 0x9a, 0x04, 0x19, 0x4d, 0x62, 0xa9, 0x4f, + 0x7c, 0x05, 0x24, 0x93, 0xc6, 0x01, 0xc5, 0xb2, 0x89, 0xe8, 0x62, 0x47, 0xbe, 0xa3, 0xd1, 0x9c, + 0x47, 0x31, 0x06, 0x16, 0x6b, 0x3b, 0xf8, 0xad, 0xb0, 0x4c, 0xfb, 0x2b, 0x6b, 0x8e, 0x88, 0x53, + 0x70, 0x75, 0x40, 0x30, 0xaf, 0xfe, 0xc5, 0xf3, 0x0f, 0x86, 0x8f, 0x58, 0x56, 0x67, 0xbd, 0x15, + 0x1f, 0x8a, 0x5c, 0xa3, 0x8a, 0x9a, 0x88, 0xe5, 0xf2, 0xd3, 0x7f, 0xac, 0x56, 0x34, 0x21, 0x24, + 0xf7, 0xde, 0x9d, 0x97, 0x9b, 0xe6, 0x20, 0xd6, 0x3d, 0x48, 0x73, 0x29, 0x23, 0xf9, 0x0f, 0xab, + 0x04, 0xe6, 0x1d, 0x70, 0xee, 0xcb, 0x5a, 0xe5, 0x8a, 0xf4, 0xbc, 0x4b, 0xad, 0x18, 0xec, 0x25, + 0x8a, 0xb8, 0x91, 0xf9, 0x53, 0xf4, 0xe4, 0xce, 0xa7, 0x54, 0xf6, 0x83, 0x66, 0x07, 0xc5, 0x51, + 0x48, 0x20, 0x54, 0x5b, 0x5d, 0xc1, 0x80, 0x04, 0x17, 0x89, 0x14, 0x5a, 0x06, 0x34, 0x86, 0xdb, + 0x8b, 0xaf, 0x04, 0x24, 0xd9, 0xbd, 0xa8, 0x27, 0x09, 0x51, 0xfe, 0x6e, 0x47, 0x3c, 0x29, 0x0a, + 0x64, 0x3e, 0x0f, 0x00, 0xf1, 0xd9, 0xdc, 0xe9, 0xd1, 0x3c, 0xcf, 0xa4, 0xa9, 0x4f, 0x54, 0x02, + 0xcf, 0xa1, 0x40, 0x49, 0x61, 0x2a, 0x07, 0xa2, 0x44, 0x35, 0x20, 0x20, 0x56, 0x1c, 0x27, 0xa2, + 0xff, 0x07, 0x3e, 0x8b, 0xfe, 0x60, 0x42, 0x75, 0x0c, 0xe3, 0x8f, 0xee, 0x33, 0x8d, 0xfc, 0x3b, + 0x53, 0x36, 0x39, 0x10, 0x1a, 0xe3, 0xd2, 0x09, 0x7b, 0x00, 0xd0, 0xbd, 0x39, 0xf4, 0xcc, 0xe3, + 0x42, 0xd4, 0xa5, 0x2d, 0x0b, 0x58, 0xdf, 0x24, 0x7f, 0x85, 0x0a, 0xf2, 0x17, 0x76, 0xdd, +}; + +UNIT_TEST_STATUS +EFIAPI +TestVerifyX509 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + BOOLEAN Status; + CONST UINT8 *LeafCert; + UINTN LeafCertLen; + UINTN CertVersion; + UINT8 Asn1Buffer[1024]; + UINTN Asn1BufferLen; + UINTN SubjectSize; + UINT8 *Subject; + UINT8 EndEertFrom[64]; + UINTN EndEertFromLen; + UINT8 EndEertTo[64]; + UINTN EndEertToLen; + UINT8 DateTime1[64]; + UINT8 DateTime2[64]; + + // + // X509 Certificate Verification. + // + Status = X509VerifyCert (mTestCert, sizeof (mTestCert), mTestCaCert, sizeof (mTestCaCert)); + UT_ASSERT_TRUE (Status); + + // + // X509 Certificate Chain Verification. + // + Status = X509VerifyCertChain (mTestCaCert, sizeof (mTestCaCert), mTestBundleCert, sizeof (mTestBundleCert)); + UT_ASSERT_TRUE (Status); + + // + // X509 Get leaf certificate from cert_chain Verificate. + // + Status = X509GetCertFromCertChain (mTestBundleCert, sizeof (mTestBundleCert), -1, &LeafCert, &LeafCertLen); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_EQUAL (LeafCertLen, sizeof (mTestEndCert)); + UT_ASSERT_MEM_EQUAL (LeafCert, mTestEndCert, LeafCertLen); + + // + // X509 Get leaf certificate from cert_chain Verificate. + // + Status = X509GetCertFromCertChain (mTestBundleCert, sizeof (mTestBundleCert), 2, &LeafCert, &LeafCertLen); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_EQUAL (LeafCertLen, sizeof (mTestEndCert)); + UT_ASSERT_MEM_EQUAL (LeafCert, mTestEndCert, LeafCertLen); + + // + // X509 Get root certificate from cert_chain Verificate. + // + Status = X509GetCertFromCertChain (mTestBundleCert, sizeof (mTestBundleCert), 0, &LeafCert, &LeafCertLen); + UT_ASSERT_TRUE (Status); + + UT_ASSERT_EQUAL (LeafCertLen, sizeof (mTestCaCert)); + UT_ASSERT_MEM_EQUAL (LeafCert, mTestCaCert, LeafCertLen); + + // + // Get version from X509 Certificate. + // + CertVersion = 0; + Status = X509GetVersion (mTestCert, sizeof (mTestCert), &CertVersion); + UT_ASSERT_TRUE (Status); + + // + // Get Serial from X509 Certificate. + // + Asn1BufferLen = 1024; + ZeroMem (Asn1Buffer, Asn1BufferLen); + Status = X509GetSerialNumber (mTestCert, sizeof (mTestCert), Asn1Buffer, &Asn1BufferLen); + UT_ASSERT_TRUE (Status); + + // + // X509 Certificate subject Retrieving. + // + SubjectSize = 0; + Status = X509GetIssuerName (mTestCert, sizeof (mTestCert), NULL, &SubjectSize); + UT_ASSERT_TRUE (!Status); + Subject = AllocatePool (SubjectSize); + Status = X509GetIssuerName (mTestCert, sizeof (mTestCert), Subject, &SubjectSize); + UT_ASSERT_TRUE (Status); + FreePool (Subject); + + // + // Get X509GetSubjectAltName. + // + Asn1BufferLen = 1024; + ZeroMem (Asn1Buffer, Asn1BufferLen); + Status = X509GetExtensionData (mTestEndCert, sizeof (mTestEndCert), mOidSubjectAltName, sizeof (mOidSubjectAltName), Asn1Buffer, &Asn1BufferLen); + UT_ASSERT_TRUE (Status); + + // + // Get X509 Validity. + // + EndEertFromLen = 64; + EndEertToLen = 64; + Status = X509GetValidity ( + mTestEndCert, + sizeof (mTestEndCert), + EndEertFrom, + &EndEertFromLen, + EndEertTo, + &EndEertToLen + ); + UT_ASSERT_TRUE (Status); + + Asn1BufferLen = 64; + Status = X509FormatDateTime ( + "19700101000000Z", + DateTime1, + &Asn1BufferLen + ); + UT_ASSERT_TRUE (Status && (Asn1BufferLen != 0)); + + Asn1BufferLen = 64; + Status = X509FormatDateTime ( + "19700201000000Z", + DateTime2, + &Asn1BufferLen + ); + UT_ASSERT_TRUE (Status && (Asn1BufferLen != 0)); + + UT_ASSERT_TRUE (X509CompareDateTime (DateTime1, DateTime2) < 0); + + return UNIT_TEST_PASSED; +} + +TEST_DESC mX509Test[] = { + // + // -----Description--------------------------------------Class----------------------Function---------------------------------Pre---------------------Post---------Context + // + { "TestVerifyX509()", "CryptoPkg.BaseCryptLib.Hkdf", TestVerifyX509, NULL, NULL, NULL }, +}; + +UINTN mX509TestNum = ARRAY_SIZE (mX509Test); From 3cb4e9a9aa29ca859b58d925b98abb423f3637b9 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Wed, 5 Oct 2022 16:48:05 +0800 Subject: [PATCH 0127/1529] UefiPayloadPkg: Remove deprecate Crypto Service REF : https://bugzilla.tianocore.org/show_bug.cgi?id=4096 TDES and ARC4 services are deprecated so set it as disable. Cc: Guo Dong Cc: Ray Ni Reviewed-by: James Lu Signed-off-by: Gua Guo --- UefiPayloadPkg/UefiPayloadPkg.dsc | 2 -- 1 file changed, 2 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 8f23802199..1150be6acd 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -459,12 +459,10 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tdes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Arc4.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tls.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY From 8dace65c4462abb70d6f805d2f5096c59232fe4f Mon Sep 17 00:00:00 2001 From: Chao Li Date: Wed, 7 Sep 2022 20:53:44 +0800 Subject: [PATCH 0128/1529] MdePkg: Added file of DebugSupport.h to MdePkg.ci.yaml REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 DebugSupport.h is all defined by UEFI Spec, most of the code doesn't fit EDKII coding style, add it to IgnoreFiles field to make CI ECC check pass. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/MdePkg.ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 054233ebc7..9d141aa3cb 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -52,6 +52,7 @@ "Include/IndustryStandard/UefiTcgPlatform.h", "Include/Library/PcdLib.h", "Include/Library/SafeIntLib.h", + "Include/Protocol/DebugSupport.h", "Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c" ] }, From adb82286c5a66fc57612f12a774ddb054c7a7626 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Wed, 7 Sep 2022 21:04:33 +0800 Subject: [PATCH 0129/1529] MdePkg: Added LoongArch jump buffer register definition to MdePkg.ci.yaml REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 If the new Arch register is defined in BaseLib.h when running the CI tests, it will give an ECC check error. Add the LoongArch register defined in the ExceptionList field to make the CI ECC check pass. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/MdePkg.ci.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 9d141aa3cb..19bc0138cb 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -27,6 +27,18 @@ "8005", "void", "8005", "va_list.__ap", "8005", "__stack_chk_guard", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S0", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S1", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S2", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S3", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S4", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S5", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S6", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S7", + "8005", "BASE_LIBRARY_JUMP_BUFFER.S8", + "8005", "BASE_LIBRARY_JUMP_BUFFER.SP", + "8005", "BASE_LIBRARY_JUMP_BUFFER.FP", + "8005", "BASE_LIBRARY_JUMP_BUFFER.RA", "8001", "MSG_IPv6_DP", "8001", "MSG_IPv4_DP", "8001", "DEFAULT_ToS", From 82d6e13958770b279a3fde79e8fb3eaa7bdf7a60 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 20:16:07 +0800 Subject: [PATCH 0130/1529] FatPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture for EDK2 CI testing. Cc: Ray Ni Signed-off-by: Chao Li Reviewed-by: Liming Gao --- FatPkg/FatPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/FatPkg/FatPkg.dsc b/FatPkg/FatPkg.dsc index 6fa439e440..076b577972 100644 --- a/FatPkg/FatPkg.dsc +++ b/FatPkg/FatPkg.dsc @@ -5,6 +5,7 @@ # for EDK II Prime release. # Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -15,7 +16,7 @@ PLATFORM_GUID = 25b55dbc-9d0b-4a32-80da-46e1273d622c PLATFORM_VERSION = 0.3 DSC_SPECIFICATION = 0x00010005 - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 OUTPUT_DIRECTORY = Build/Fat BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From adfe6be1a37f352c3a7bc0e6d2f20edf719a4cc1 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 20:30:43 +0800 Subject: [PATCH 0131/1529] FmpDevicePkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture for EDK2 CI testing. Cc: Liming Gao Cc: Michael D Kinney Cc: Guomin Jiang Cc: Wei6 Xu Signed-off-by: Chao Li Reviewed-by: Liming Gao --- FmpDevicePkg/FmpDevicePkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/FmpDevicePkg/FmpDevicePkg.dsc b/FmpDevicePkg/FmpDevicePkg.dsc index 7b1af285dd..f9f26c54bb 100644 --- a/FmpDevicePkg/FmpDevicePkg.dsc +++ b/FmpDevicePkg/FmpDevicePkg.dsc @@ -9,6 +9,7 @@ # Copyright (c) Microsoft Corporation.
# Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -20,7 +21,7 @@ PLATFORM_VERSION = 0.1 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/FmpDevicePkg - SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From 4aeff44b556236156de09b865a74a6c45c3ddd7e Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 20:34:01 +0800 Subject: [PATCH 0132/1529] NetworkPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture for EDK2 CI testing. Cc: Maciej Rabeda Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Chao Li Reviewed-by: Jiaxin Wu --- NetworkPkg/NetworkPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NetworkPkg/NetworkPkg.dsc b/NetworkPkg/NetworkPkg.dsc index 762134023d..6c231c97b5 100644 --- a/NetworkPkg/NetworkPkg.dsc +++ b/NetworkPkg/NetworkPkg.dsc @@ -4,6 +4,7 @@ # (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -14,7 +15,7 @@ PLATFORM_VERSION = 0.98 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/NetworkPkg - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From 40779d95bdfc423cbece6863144318fc227b9dca Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 10 Dec 2021 12:19:30 +0800 Subject: [PATCH 0133/1529] NetworkPkg/HttpBootDxe: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH architecture for EDK2 CI testing. Cc: Maciej Rabeda Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Chao Li Reviewed-by: Jiaxin Wu --- NetworkPkg/HttpBootDxe/HttpBootDhcp4.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/NetworkPkg/HttpBootDxe/HttpBootDhcp4.h b/NetworkPkg/HttpBootDxe/HttpBootDhcp4.h index d76f0e84d6..f00fabead2 100644 --- a/NetworkPkg/HttpBootDxe/HttpBootDhcp4.h +++ b/NetworkPkg/HttpBootDxe/HttpBootDhcp4.h @@ -3,6 +3,7 @@ Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -40,6 +41,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_HTTP_BOOT_CLIENT_SYSTEM_ARCHITECTURE HTTP_CLIENT_ARCH_RISCV64 #elif defined (MDE_CPU_EBC) #define EFI_HTTP_BOOT_CLIENT_SYSTEM_ARCHITECTURE HTTP_CLIENT_ARCH_EBC +#elif defined (MDE_CPU_LOONGARCH64) +#define EFI_HTTP_BOOT_CLIENT_SYSTEM_ARCHITECTURE HTTP_CLIENT_ARCH_LOONGARCH64 #endif /// DHCP offer types among HTTP boot. From 8417e8c15504bf40a2dd1e48228000cc7b43bf16 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 10 Dec 2021 12:32:47 +0800 Subject: [PATCH 0134/1529] CryptoPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture for EDK2 CI testing. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Chao Li Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 3 ++- CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf | 6 +++++- CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf | 4 ++++ CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf | 3 ++- CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf | 3 ++- CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf | 3 ++- CryptoPkg/Library/Include/CrtLibSupport.h | 3 ++- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 2 ++ CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf | 2 ++ CryptoPkg/Library/TlsLib/TlsLib.inf | 3 ++- CryptoPkg/Library/TlsLibNull/TlsLibNull.inf | 3 ++- 11 files changed, 27 insertions(+), 8 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index e4e7bc0dbf..8c6906acf0 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -4,6 +4,7 @@ # # Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -19,7 +20,7 @@ PLATFORM_VERSION = 0.98 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/CryptoPkg - SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 9634bd5fea..8896e47095 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -8,6 +8,7 @@ # # Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -24,7 +25,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] @@ -78,6 +79,9 @@ [Sources.RISCV64] Rand/CryptRand.c +[Sources.LOONGARCH64] + Rand/CryptRand.c + [Packages] MdePkg/MdePkg.dec CryptoPkg/CryptoPkg.dec diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index 845708bf1a..bb66604e32 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -13,6 +13,7 @@ # # Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
# Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -80,6 +81,9 @@ [Sources.RISCV64] Rand/CryptRand.c +[Sources.LOONGARCH64] + Rand/CryptRand.c + [Packages] MdePkg/MdePkg.dec CryptoPkg/CryptoPkg.dec diff --git a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf index 9cb8d42ff4..80afb62f76 100644 --- a/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +++ b/CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf @@ -8,6 +8,7 @@ # # Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -24,7 +25,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf index baa4433cbe..b4945de336 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf @@ -4,6 +4,7 @@ # # Copyright (C) Microsoft Corporation. All rights reserved. # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -22,7 +23,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Packages] diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf index 038ca71890..e7d153db0b 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf @@ -4,6 +4,7 @@ # # Copyright (C) Microsoft Corporation. All rights reserved. # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -21,7 +22,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Packages] diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index e49060124f..5072c343da 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -4,6 +4,7 @@ Copyright (c) 2010 - 2022, Intel Corporation. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -46,7 +47,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define CONFIG_HEADER_BN_H #if !defined (SIXTY_FOUR_BIT) && !defined (THIRTY_TWO_BIT) - #if defined (MDE_CPU_X64) || defined (MDE_CPU_AARCH64) || defined (MDE_CPU_IA64) || defined (MDE_CPU_RISCV64) + #if defined (MDE_CPU_X64) || defined (MDE_CPU_AARCH64) || defined (MDE_CPU_IA64) || defined (MDE_CPU_RISCV64) || defined (MDE_CPU_LOONGARCH64) // // With GCC we would normally use SIXTY_FOUR_BIT_LONG, but MSVC needs // SIXTY_FOUR_BIT, because 'long' is 32-bit and only 'long long' is diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index c899b811b1..f0ca72eeed 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -675,6 +676,7 @@ GCC:*_*_ARM_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_RISCV64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_*_LOONGARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index 0ec3724541..195016fd3d 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -624,6 +625,7 @@ GCC:*_*_ARM_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_RISCV64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_*_LOONGARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize diff --git a/CryptoPkg/Library/TlsLib/TlsLib.inf b/CryptoPkg/Library/TlsLib/TlsLib.inf index bc61cda745..20b0ea6832 100644 --- a/CryptoPkg/Library/TlsLib/TlsLib.inf +++ b/CryptoPkg/Library/TlsLib/TlsLib.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
# (C) Copyright 2016-2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -19,7 +20,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] diff --git a/CryptoPkg/Library/TlsLibNull/TlsLibNull.inf b/CryptoPkg/Library/TlsLibNull/TlsLibNull.inf index b2920ddacf..12d7cc764a 100644 --- a/CryptoPkg/Library/TlsLibNull/TlsLibNull.inf +++ b/CryptoPkg/Library/TlsLibNull/TlsLibNull.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
# (C) Copyright 2016-2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -19,7 +20,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] From 8f9f1fbdb97318016f363476f67d943df57038a6 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 13 Sep 2022 17:03:33 +0800 Subject: [PATCH 0135/1529] MdePkg/Include: Add LOONGARCH related definitions EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 HTTP/PXE boot LOONGARCH64 related definitions for EDK2 CI. For the LOONGARCH values, please seeing following URL section "Processor Architecture Types": https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Dhcp.h | 45 ++++++++++++++------------ 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/Dhcp.h b/MdePkg/Include/IndustryStandard/Dhcp.h index f209f1b2eb..46ab4f8e75 100644 --- a/MdePkg/Include/IndustryStandard/Dhcp.h +++ b/MdePkg/Include/IndustryStandard/Dhcp.h @@ -4,6 +4,7 @@ Copyright (c) 2016, Intel Corporation. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -256,27 +257,31 @@ typedef enum { /// /// Processor Architecture Types -/// These identifiers are defined by IETF: -/// http://www.ietf.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xml +/// These identifiers are defined by IANA: +/// https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml /// -#define PXE_CLIENT_ARCH_X86_BIOS 0x0000 /// x86 BIOS for PXE -#define PXE_CLIENT_ARCH_IPF 0x0002 /// Itanium for PXE -#define PXE_CLIENT_ARCH_IA32 0x0006 /// x86 uefi for PXE -#define PXE_CLIENT_ARCH_X64 0x0007 /// x64 uefi for PXE -#define PXE_CLIENT_ARCH_EBC 0x0009 /// EBC for PXE -#define PXE_CLIENT_ARCH_ARM 0x000A /// Arm uefi 32 for PXE -#define PXE_CLIENT_ARCH_AARCH64 0x000B /// Arm uefi 64 for PXE -#define PXE_CLIENT_ARCH_RISCV32 0x0019 /// RISC-V uefi 32 for PXE -#define PXE_CLIENT_ARCH_RISCV64 0x001B /// RISC-V uefi 64 for PXE -#define PXE_CLIENT_ARCH_RISCV128 0x001D /// RISC-V uefi 128 for PXE +#define PXE_CLIENT_ARCH_X86_BIOS 0x0000 /// x86 BIOS for PXE +#define PXE_CLIENT_ARCH_IPF 0x0002 /// Itanium for PXE +#define PXE_CLIENT_ARCH_IA32 0x0006 /// x86 uefi for PXE +#define PXE_CLIENT_ARCH_X64 0x0007 /// x64 uefi for PXE +#define PXE_CLIENT_ARCH_EBC 0x0009 /// EBC for PXE +#define PXE_CLIENT_ARCH_ARM 0x000A /// Arm uefi 32 for PXE +#define PXE_CLIENT_ARCH_AARCH64 0x000B /// Arm uefi 64 for PXE +#define PXE_CLIENT_ARCH_RISCV32 0x0019 /// RISC-V uefi 32 for PXE +#define PXE_CLIENT_ARCH_RISCV64 0x001B /// RISC-V uefi 64 for PXE +#define PXE_CLIENT_ARCH_RISCV128 0x001D /// RISC-V uefi 128 for PXE +#define PXE_CLIENT_ARCH_LOONGARCH32 0x0025 /// LoongArch uefi 32 for PXE +#define PXE_CLIENT_ARCH_LOONGARCH64 0x0027 /// LoongArch uefi 64 for PXE -#define HTTP_CLIENT_ARCH_IA32 0x000F /// x86 uefi boot from http -#define HTTP_CLIENT_ARCH_X64 0x0010 /// x64 uefi boot from http -#define HTTP_CLIENT_ARCH_EBC 0x0011 /// EBC boot from http -#define HTTP_CLIENT_ARCH_ARM 0x0012 /// Arm uefi 32 boot from http -#define HTTP_CLIENT_ARCH_AARCH64 0x0013 /// Arm uefi 64 boot from http -#define HTTP_CLIENT_ARCH_RISCV32 0x001A /// RISC-V uefi 32 boot from http -#define HTTP_CLIENT_ARCH_RISCV64 0x001C /// RISC-V uefi 64 boot from http -#define HTTP_CLIENT_ARCH_RISCV128 0x001E /// RISC-V uefi 128 boot from http +#define HTTP_CLIENT_ARCH_IA32 0x000F /// x86 uefi boot from http +#define HTTP_CLIENT_ARCH_X64 0x0010 /// x64 uefi boot from http +#define HTTP_CLIENT_ARCH_EBC 0x0011 /// EBC boot from http +#define HTTP_CLIENT_ARCH_ARM 0x0012 /// Arm uefi 32 boot from http +#define HTTP_CLIENT_ARCH_AARCH64 0x0013 /// Arm uefi 64 boot from http +#define HTTP_CLIENT_ARCH_RISCV32 0x001A /// RISC-V uefi 32 boot from http +#define HTTP_CLIENT_ARCH_RISCV64 0x001C /// RISC-V uefi 64 boot from http +#define HTTP_CLIENT_ARCH_RISCV128 0x001E /// RISC-V uefi 128 boot from http +#define HTTP_CLIENT_ARCH_LOONGARCH32 0x0026 /// LoongArch uefi 32 boot from http +#define HTTP_CLIENT_ARCH_LOONGARCH64 0x0028 /// LoongArch uefi 64 boot from http #endif From c56780c6976bd533b3895063d293490191f176c3 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 20:45:46 +0800 Subject: [PATCH 0136/1529] SecurityPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture to SecurityPkg for EDK2 CI testing. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Chao Li Reviewed-by: Jiewen Yao --- SecurityPkg/SecurityPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index f48187650f..6bf53c5658 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -3,6 +3,7 @@ # # Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2015-2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -13,7 +14,7 @@ PLATFORM_VERSION = 0.98 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/SecurityPkg - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From 2c08c3c76e0c670626e690adef322577647b7eb4 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 20:57:53 +0800 Subject: [PATCH 0137/1529] ShellPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture to ShellPkg for EDK2 CI testing. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Chao Li Reviewed-by: Michael D Kinney Reviewed-by: Zhichao Gao --- ShellPkg/ShellPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ShellPkg/ShellPkg.dsc b/ShellPkg/ShellPkg.dsc index 38fde3dc71..dd0d88603f 100644 --- a/ShellPkg/ShellPkg.dsc +++ b/ShellPkg/ShellPkg.dsc @@ -4,6 +4,7 @@ # Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2018 - 2020, Arm Limited. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -15,7 +16,7 @@ PLATFORM_VERSION = 1.02 DSC_SPECIFICATION = 0x00010006 OUTPUT_DIRECTORY = Build/Shell - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From 50193ce26d93348cdc7d47571aae46eafbfde237 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 12 Oct 2021 21:02:02 +0800 Subject: [PATCH 0138/1529] UnitTestFrameworkPkg: Add LOONGARCH64 architecture for EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture to UnitTestFramworkPkg for LOONGARCH64 EDK2 CI. Cc: Michael D Kinney Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 23baef87d6..e4f9fb6eb6 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -3,6 +3,7 @@ # # Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -14,7 +15,7 @@ PLATFORM_VERSION = 1.00 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg - SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From e6bbe6f0c89bc803e0ce25d3a9accfa44e7e6636 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Wed, 27 Oct 2021 17:59:05 +0800 Subject: [PATCH 0139/1529] MdePkg/DxeServicesLib: Add LOONGARCH64 architecture REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 architecture to MdePkg/DxeServiceLib. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/Library/DxeServicesLib/DxeServicesLib.inf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Library/DxeServicesLib/DxeServicesLib.inf b/MdePkg/Library/DxeServicesLib/DxeServicesLib.inf index ec3e8711c2..a93541847f 100644 --- a/MdePkg/Library/DxeServicesLib/DxeServicesLib.inf +++ b/MdePkg/Library/DxeServicesLib/DxeServicesLib.inf @@ -22,13 +22,13 @@ LIBRARY_CLASS = DxeServicesLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER SMM_CORE UEFI_APPLICATION UEFI_DRIVER # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] DxeServicesLib.c -[Sources.IA32, Sources.EBC, Sources.ARM, Sources.AARCH64, Sources.RISCV64] +[Sources.IA32, Sources.EBC, Sources.ARM, Sources.AARCH64, Sources.RISCV64, Sources.LOONGARCH64] Allocate.c [Sources.X64] From bbb73cb242693cde06fe9ecb74550002da902e8e Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 28 Oct 2021 10:49:01 +0800 Subject: [PATCH 0140/1529] MdeModulePkg: Use LockBoxNullLib for LOONGARCH64 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 LoongArch doesn't have SMM by now. Cc: Jian J Wang Cc: Liming Gao Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdeModulePkg/MdeModulePkg.dsc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc index 45a8ec84ad..659482ab73 100644 --- a/MdeModulePkg/MdeModulePkg.dsc +++ b/MdeModulePkg/MdeModulePkg.dsc @@ -15,7 +15,7 @@ PLATFORM_VERSION = 0.98 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/MdeModule - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT @@ -193,7 +193,7 @@ # NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf -[LibraryClasses.EBC, LibraryClasses.RISCV64] +[LibraryClasses.EBC, LibraryClasses.RISCV64, LibraryClasses.LOONGARCH64] LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf [PcdsFeatureFlag] From 864d236c193959bb28d1d0c26c055833969dafea Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 9 Jun 2022 20:26:47 +0800 Subject: [PATCH 0141/1529] .python/SpellCheck: Add "Loongson" and "LOONGARCH" to "words" section REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add Loongson and LOONGARCH to "words" section in cspell.base.yaml file to avoid spelling check error. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .pytool/Plugin/SpellCheck/cspell.base.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.pytool/Plugin/SpellCheck/cspell.base.yaml b/.pytool/Plugin/SpellCheck/cspell.base.yaml index f0d5791876..92e65ec6f6 100644 --- a/.pytool/Plugin/SpellCheck/cspell.base.yaml +++ b/.pytool/Plugin/SpellCheck/cspell.base.yaml @@ -289,6 +289,8 @@ "unrecovered", "cmocka", "unenrolling", - "unconfigure" + "unconfigure", + "Loongson", + "LOONGARCH" ] } From ff9ad9236907146e0408f2541579d7bc12f3ea75 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 6 Sep 2022 21:00:07 +0800 Subject: [PATCH 0142/1529] BaseTools: Update GenFw/GenFv to support LoongArch platform. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 C code changes for building EDK2 LoongArch platform. For definitions of PE/COFF and LOONGARCH relocation types, see the "Machine Types" and "Basic Relocation Types" sections of this URL for LOONGARCH values: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Co-authored-by: Dongyan Qian Co-authored-by: Baoqi Zhang Co-authored-by: Yang Zhou Co-authored-by: Xiaotian Wu Reviewed-by: Liming Gao --- BaseTools/Source/C/Common/BasePeCoff.c | 15 +- BaseTools/Source/C/Common/PeCoffLoaderEx.c | 79 +++++ BaseTools/Source/C/GenFv/GenFvInternalLib.c | 125 +++++++- BaseTools/Source/C/GenFw/Elf64Convert.c | 293 +++++++++++++++++- BaseTools/Source/C/GenFw/elf_common.h | 94 ++++++ .../C/Include/IndustryStandard/PeImage.h | 57 ++-- BaseTools/Source/C/Makefiles/header.makefile | 6 + 7 files changed, 636 insertions(+), 33 deletions(-) diff --git a/BaseTools/Source/C/Common/BasePeCoff.c b/BaseTools/Source/C/Common/BasePeCoff.c index 62fbb2985c..30400d1341 100644 --- a/BaseTools/Source/C/Common/BasePeCoff.c +++ b/BaseTools/Source/C/Common/BasePeCoff.c @@ -5,6 +5,7 @@ Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -68,6 +69,14 @@ PeCoffLoaderRelocateRiscVImage ( IN UINT64 Adjust ); +RETURN_STATUS +PeCoffLoaderRelocateLoongArch64Image ( + IN UINT16 *Reloc, + IN OUT CHAR8 *Fixup, + IN OUT CHAR8 **FixupData, + IN UINT64 Adjust + ); + STATIC RETURN_STATUS PeCoffLoaderGetPeHeader ( @@ -184,7 +193,8 @@ Routine Description: ImageContext->Machine != EFI_IMAGE_MACHINE_ARMT && \ ImageContext->Machine != EFI_IMAGE_MACHINE_EBC && \ ImageContext->Machine != EFI_IMAGE_MACHINE_AARCH64 && \ - ImageContext->Machine != EFI_IMAGE_MACHINE_RISCV64) { + ImageContext->Machine != EFI_IMAGE_MACHINE_RISCV64 && \ + ImageContext->Machine != EFI_IMAGE_MACHINE_LOONGARCH64) { if (ImageContext->Machine == IMAGE_FILE_MACHINE_ARM) { // // There are two types of ARM images. Pure ARM and ARM/Thumb. @@ -815,6 +825,9 @@ Routine Description: case EFI_IMAGE_MACHINE_RISCV64: Status = PeCoffLoaderRelocateRiscVImage (Reloc, Fixup, &FixupData, Adjust); break; + case EFI_IMAGE_MACHINE_LOONGARCH64: + Status = PeCoffLoaderRelocateLoongArch64Image (Reloc, Fixup, &FixupData, Adjust); + break; default: Status = RETURN_UNSUPPORTED; break; diff --git a/BaseTools/Source/C/Common/PeCoffLoaderEx.c b/BaseTools/Source/C/Common/PeCoffLoaderEx.c index 799f282970..2cc428d733 100644 --- a/BaseTools/Source/C/Common/PeCoffLoaderEx.c +++ b/BaseTools/Source/C/Common/PeCoffLoaderEx.c @@ -4,6 +4,7 @@ IA32 and X64 Specific relocation fixups Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent --*/ @@ -332,3 +333,81 @@ PeCoffLoaderRelocateArmImage ( return RETURN_SUCCESS; } + +/** + Performs a LoongArch specific relocation fixup. + + @param[in] Reloc Pointer to the relocation record. + @param[in, out] Fixup Pointer to the address to fix up. + @param[in, out] FixupData Pointer to a buffer to log the fixups. + @param[in] Adjust The offset to adjust the fixup. + + @return Status code. +**/ +RETURN_STATUS +PeCoffLoaderRelocateLoongArch64Image ( + IN UINT16 *Reloc, + IN OUT CHAR8 *Fixup, + IN OUT CHAR8 **FixupData, + IN UINT64 Adjust + ) +{ + UINT8 RelocType; + UINT64 Value; + UINT64 Tmp1; + UINT64 Tmp2; + + RelocType = ((*Reloc) >> 12); + Value = 0; + Tmp1 = 0; + Tmp2 = 0; + + switch (RelocType) { + case EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA: + // The next four instructions are used to load a 64 bit address, relocate all of them + Value = (*(UINT32 *)Fixup & 0x1ffffe0) << 7 | // lu12i.w 20bits from bit5 + (*((UINT32 *)Fixup + 1) & 0x3ffc00) >> 10; // ori 12bits from bit10 + Tmp1 = *((UINT32 *)Fixup + 2) & 0x1ffffe0; // lu32i.d 20bits from bit5 + Tmp2 = *((UINT32 *)Fixup + 3) & 0x3ffc00; // lu52i.d 12bits from bit10 + Value = Value | (Tmp1 << 27) | (Tmp2 << 42); + Value += Adjust; + + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x1ffffe0) | (((Value >> 12) & 0xfffff) << 5); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x3ffc00) | ((Value & 0xfff) << 10); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x1ffffe0) | (((Value >> 32) & 0xfffff) << 5); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x3ffc00) | (((Value >> 52) & 0xfff) << 10); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + break; + default: + Error (NULL, 0, 3000, "", "PeCoffLoaderRelocateLoongArch64Image: Fixup[0x%x] Adjust[0x%llx] *Reloc[0x%x], type[0x%x].", *(UINT32 *)Fixup, Adjust, *Reloc, RelocType); + return RETURN_UNSUPPORTED; + } + + return RETURN_SUCCESS; +} diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index d28ac8f6eb..5c3d54f5f7 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -5,6 +5,7 @@ Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
Portions Copyright (c) 2016 HP Development Company, L.P.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -57,6 +58,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent BOOLEAN mArm = FALSE; BOOLEAN mRiscV = FALSE; +BOOLEAN mLoongArch = FALSE; STATIC UINT32 MaxFfsAlignment = 0; BOOLEAN VtfFileFlag = FALSE; @@ -2416,6 +2418,98 @@ Routine Description: return EFI_SUCCESS; } +EFI_STATUS +UpdateLoongArchResetVectorIfNeeded ( + IN MEMORY_FILE *FvImage, + IN FV_INFO *FvInfo + ) +/*++ + +Routine Description: + This parses the FV looking for SEC and patches that address into the + beginning of the FV header. + + For LoongArch ISA, the reset vector is at 0x1c000000. + + We relocate it to SecCoreEntry and copy the ResetVector code to the + beginning of the FV. + +Arguments: + FvImage Memory file for the FV memory image + FvInfo Information read from INF file. + +Returns: + + EFI_SUCCESS Function Completed successfully. + EFI_ABORTED Error encountered. + EFI_INVALID_PARAMETER A required parameter was NULL. + EFI_NOT_FOUND PEI Core file not found. + +--*/ +{ + EFI_STATUS Status; + EFI_FILE_SECTION_POINTER SecPe32; + BOOLEAN UpdateVectorSec = FALSE; + UINT16 MachineType = 0; + EFI_PHYSICAL_ADDRESS SecCoreEntryAddress = 0; + + // + // Verify input parameters + // + if (FvImage == NULL || FvInfo == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Locate an SEC Core instance and if found extract the machine type and entry point address + // + Status = FindCorePeSection(FvImage->FileImage, FvInfo->Size, EFI_FV_FILETYPE_SECURITY_CORE, &SecPe32); + if (!EFI_ERROR(Status)) { + + Status = GetCoreMachineType(SecPe32, &MachineType); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 machine type for SEC Core."); + return EFI_ABORTED; + } + + Status = GetCoreEntryPointAddress(FvImage->FileImage, FvInfo, SecPe32, &SecCoreEntryAddress); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 entry point address for SEC Core."); + return EFI_ABORTED; + } + + UpdateVectorSec = TRUE; + } + + if (!UpdateVectorSec) + return EFI_SUCCESS; + + if (MachineType == EFI_IMAGE_MACHINE_LOONGARCH64) { + UINT32 ResetVector[1]; + + memset(ResetVector, 0, sizeof (ResetVector)); + + /* if we found an SEC core entry point then generate a branch instruction */ + if (UpdateVectorSec) { + VerboseMsg("UpdateLoongArchResetVectorIfNeeded updating LOONGARCH64 SEC vector"); + + ResetVector[0] = ((SecCoreEntryAddress - FvInfo->BaseAddress) & 0x3FFFFFF) >> 2; + ResetVector[0] = ((ResetVector[0] & 0x0FFFF) << 10) | ((ResetVector[0] >> 16) & 0x3FF); + ResetVector[0] |= 0x50000000; /* b offset */ + } + + // + // Copy to the beginning of the FV + // + memcpy(FvImage->FileImage, ResetVector, sizeof (ResetVector)); + } else { + Error(NULL, 0, 3000, "Invalid", "Unknown machine type"); + return EFI_ABORTED; + } + + return EFI_SUCCESS; +} + EFI_STATUS GetPe32Info ( IN UINT8 *Pe32, @@ -2509,7 +2603,7 @@ Routine Description: // if ((*MachineType != EFI_IMAGE_MACHINE_IA32) && (*MachineType != EFI_IMAGE_MACHINE_X64) && (*MachineType != EFI_IMAGE_MACHINE_EBC) && (*MachineType != EFI_IMAGE_MACHINE_ARMT) && (*MachineType != EFI_IMAGE_MACHINE_AARCH64) && - (*MachineType != EFI_IMAGE_MACHINE_RISCV64)) { + (*MachineType != EFI_IMAGE_MACHINE_RISCV64) && (*MachineType != EFI_IMAGE_MACHINE_LOONGARCH64)) { Error (NULL, 0, 3000, "Invalid", "Unrecognized machine type in the PE32 file."); return EFI_UNSUPPORTED; } @@ -2953,7 +3047,7 @@ Routine Description: goto Finish; } - if (!mArm && !mRiscV) { + if (!mArm && !mRiscV && !mLoongArch) { // // Update reset vector (SALE_ENTRY for IPF) // Now for IA32 and IA64 platform, the fv which has bsf file must have the @@ -3004,6 +3098,19 @@ Routine Description: FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16)); } + if (mLoongArch) { + Status = UpdateLoongArchResetVectorIfNeeded (&FvImageMemoryFile, &mFvDataInfo); + if (EFI_ERROR (Status)) { + Error (NULL, 0, 3000, "Invalid", "Could not update the reset vector."); + goto Finish; + } + // + // Update Checksum for FvHeader + // + FvHeader->Checksum = 0; + FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16)); + } + // // Update FV Alignment attribute to the largest alignment of all the FFS files in the FV // @@ -3450,6 +3557,12 @@ Routine Description: VerboseMsg("Located ARM/AArch64 SEC/PEI core in child FV"); mArm = TRUE; } + + // Machine type is LOONGARCH64, set a flag so LoongArch64 reset vector processed. + if ((MachineType == EFI_IMAGE_MACHINE_LOONGARCH64)) { + VerboseMsg("Located LoongArch64 SEC core in child FV"); + mLoongArch = TRUE; + } } // @@ -3608,6 +3721,10 @@ Routine Description: mRiscV = TRUE; } + if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) { + mLoongArch = TRUE; + } + // // Keep Image Context for PE image in FV // @@ -3885,6 +4002,10 @@ Routine Description: mArm = TRUE; } + if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) { + mLoongArch = TRUE; + } + // // Keep Image Context for TE image in FV // diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index ca3c8f8bee..c6092269e2 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -4,6 +4,7 @@ Elf64 convert solution Copyright (c) 2010 - 2021, Intel Corporation. All rights reserved.
Portions copyright (c) 2013-2022, ARM Ltd. All rights reserved.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -177,7 +178,7 @@ InitializeElf64 ( Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN"); return FALSE; } - if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64) || (mEhdr->e_machine == EM_RISCV64))) { + if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine == EM_AARCH64) || (mEhdr->e_machine == EM_RISCV64) || (mEhdr->e_machine == EM_LOONGARCH))) { Warning (NULL, 0, 3000, "Unsupported", "ELF e_machine is not Elf64 machine."); } if (mEhdr->e_version != EV_CURRENT) { @@ -799,6 +800,7 @@ ScanSections64 ( case EM_X86_64: case EM_AARCH64: case EM_RISCV64: + case EM_LOONGARCH: mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64); break; default: @@ -1088,6 +1090,10 @@ ScanSections64 ( NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_RISCV64; NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC; break; + case EM_LOONGARCH: + NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_LOONGARCH64; + NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC; + break; default: VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine); @@ -1333,10 +1339,10 @@ WriteSections64 ( } // - // Skip error on EM_RISCV64 becasue no symble name is built - // from RISC-V toolchain. + // Skip error on EM_RISCV64 and EM_LOONGARCH because no symbol name is built + // from RISC-V and LoongArch toolchain. // - if (mEhdr->e_machine != EM_RISCV64) { + if ((mEhdr->e_machine != EM_RISCV64) && (mEhdr->e_machine != EM_LOONGARCH)) { Error (NULL, 0, 3000, "Invalid", "%s: Bad definition for symbol '%s'@%#llx or unsupported symbol type. " "For example, absolute and undefined symbols are not supported.", @@ -1618,6 +1624,178 @@ WriteSections64 ( // Write section for RISC-V 64 architecture. // WriteSectionRiscV64 (Rel, Targ, SymShdr, Sym); + } else if (mEhdr->e_machine == EM_LOONGARCH) { + switch (ELF_R_TYPE(Rel->r_info)) { + INT64 Offset; + INT32 Lo, Hi; + + case R_LARCH_SOP_PUSH_ABSOLUTE: + // + // Absolute relocation. + // + *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]; + break; + + case R_LARCH_MARK_LA: + case R_LARCH_64: + case R_LARCH_NONE: + case R_LARCH_32: + case R_LARCH_RELATIVE: + case R_LARCH_COPY: + case R_LARCH_JUMP_SLOT: + case R_LARCH_TLS_DTPMOD32: + case R_LARCH_TLS_DTPMOD64: + case R_LARCH_TLS_DTPREL32: + case R_LARCH_TLS_DTPREL64: + case R_LARCH_TLS_TPREL32: + case R_LARCH_TLS_TPREL64: + case R_LARCH_IRELATIVE: + case R_LARCH_MARK_PCREL: + case R_LARCH_SOP_PUSH_PCREL: + case R_LARCH_SOP_PUSH_DUP: + case R_LARCH_SOP_PUSH_GPREL: + case R_LARCH_SOP_PUSH_TLS_TPREL: + case R_LARCH_SOP_PUSH_TLS_GOT: + case R_LARCH_SOP_PUSH_TLS_GD: + case R_LARCH_SOP_PUSH_PLT_PCREL: + case R_LARCH_SOP_ASSERT: + case R_LARCH_SOP_NOT: + case R_LARCH_SOP_SUB: + case R_LARCH_SOP_SL: + case R_LARCH_SOP_SR: + case R_LARCH_SOP_ADD: + case R_LARCH_SOP_AND: + case R_LARCH_SOP_IF_ELSE: + case R_LARCH_SOP_POP_32_S_10_5: + case R_LARCH_SOP_POP_32_U_10_12: + case R_LARCH_SOP_POP_32_S_10_12: + case R_LARCH_SOP_POP_32_S_10_16: + case R_LARCH_SOP_POP_32_S_10_16_S2: + case R_LARCH_SOP_POP_32_S_5_20: + case R_LARCH_SOP_POP_32_S_0_5_10_16_S2: + case R_LARCH_SOP_POP_32_S_0_10_10_16_S2: + case R_LARCH_SOP_POP_32_U: + case R_LARCH_ADD8: + case R_LARCH_ADD16: + case R_LARCH_ADD24: + case R_LARCH_ADD32: + case R_LARCH_ADD64: + case R_LARCH_SUB8: + case R_LARCH_SUB16: + case R_LARCH_SUB24: + case R_LARCH_SUB32: + case R_LARCH_SUB64: + case R_LARCH_GNU_VTINHERIT: + case R_LARCH_GNU_VTENTRY: + case R_LARCH_B16: + case R_LARCH_B21: + case R_LARCH_B26: + case R_LARCH_ABS_HI20: + case R_LARCH_ABS_LO12: + case R_LARCH_ABS64_LO20: + case R_LARCH_ABS64_HI12: + case R_LARCH_PCALA_LO12: + case R_LARCH_PCALA64_LO20: + case R_LARCH_PCALA64_HI12: + case R_LARCH_GOT_PC_LO12: + case R_LARCH_GOT64_PC_LO20: + case R_LARCH_GOT64_PC_HI12: + case R_LARCH_GOT64_HI20: + case R_LARCH_GOT64_LO12: + case R_LARCH_GOT64_LO20: + case R_LARCH_GOT64_HI12: + case R_LARCH_TLS_LE_HI20: + case R_LARCH_TLS_LE_LO12: + case R_LARCH_TLS_LE64_LO20: + case R_LARCH_TLS_LE64_HI12: + case R_LARCH_TLS_IE_PC_HI20: + case R_LARCH_TLS_IE_PC_LO12: + case R_LARCH_TLS_IE64_PC_LO20: + case R_LARCH_TLS_IE64_PC_HI12: + case R_LARCH_TLS_IE64_HI20: + case R_LARCH_TLS_IE64_LO12: + case R_LARCH_TLS_IE64_LO20: + case R_LARCH_TLS_IE64_HI12: + case R_LARCH_TLS_LD_PC_HI20: + case R_LARCH_TLS_LD64_HI20: + case R_LARCH_TLS_GD_PC_HI20: + case R_LARCH_TLS_GD64_HI20: + case R_LARCH_RELAX: + // + // These types are not used or do not require fixup. + // + break; + + case R_LARCH_GOT_PC_HI20: + Offset = Sym->st_value - (UINTN)(Targ - mCoffFile); + if (Offset < 0) { + Offset = (UINTN)(Targ - mCoffFile) - Sym->st_value; + Hi = Offset & ~0xfff; + Lo = (INT32)((Offset & 0xfff) << 20) >> 20; + if ((Lo < 0) && (Lo > -2048)) { + Hi += 0x1000; + Lo = ~(0x1000 - Lo) + 1; + } + Hi = ~Hi + 1; + Lo = ~Lo + 1; + } else { + Hi = Offset & ~0xfff; + Lo = (INT32)((Offset & 0xfff) << 20) >> 20; + if (Lo < 0) { + Hi += 0x1000; + Lo = ~(0x1000 - Lo) + 1; + } + } + // Re-encode the offset as PCADDU12I + ADDI.D(Convert LD.D) instruction + *(UINT32 *)Targ &= 0x1f; + *(UINT32 *)Targ |= 0x1c000000; + *(UINT32 *)Targ |= (((Hi >> 12) & 0xfffff) << 5); + *(UINT32 *)(Targ + 4) &= 0x3ff; + *(UINT32 *)(Targ + 4) |= 0x2c00000 | ((Lo & 0xfff) << 10); + break; + + // + // Attempt to convert instruction. + // + case R_LARCH_PCALA_HI20: + // Decode the PCALAU12I instruction and the instruction that following it. + Offset = ((INT32)((*(UINT32 *)Targ & 0x1ffffe0) << 7)); + Offset += ((INT32)((*(UINT32 *)(Targ + 4) & 0x3ffc00) << 10) >> 20); + // + // PCALA offset is relative to the previous page boundary, + // whereas PCADD offset is relative to the instruction itself. + // So fix up the offset so it points to the page containing + // the symbol. + // + Offset -= (UINTN)(Targ - mCoffFile) & 0xfff; + if (Offset < 0) { + Offset = -Offset; + Hi = Offset & ~0xfff; + Lo = (INT32)((Offset & 0xfff) << 20) >> 20; + if ((Lo < 0) && (Lo > -2048)) { + Hi += 0x1000; + Lo = ~(0x1000 - Lo) + 1; + } + Hi = ~Hi + 1; + Lo = ~Lo + 1; + } else { + Hi = Offset & ~0xfff; + Lo = (INT32)((Offset & 0xfff) << 20) >> 20; + if (Lo < 0) { + Hi += 0x1000; + Lo = ~(0x1000 - Lo) + 1; + } + } + // Convert the first instruction from PCALAU12I to PCADDU12I and re-encode the offset into them. + *(UINT32 *)Targ &= 0x1f; + *(UINT32 *)Targ |= 0x1c000000; + *(UINT32 *)Targ |= (((Hi >> 12) & 0xfffff) << 5); + *(UINT32 *)(Targ + 4) &= 0xffc003ff; + *(UINT32 *)(Targ + 4) |= (Lo & 0xfff) << 10; + break; + default: + Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported ELF EM_LOONGARCH relocation 0x%x.", mInImageName, (unsigned) ELF64_R_TYPE(Rel->r_info)); + } } else { Error (NULL, 0, 3000, "Invalid", "Not a supported machine type"); } @@ -1850,6 +2028,113 @@ WriteRelocations64 ( default: Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_RISCV64 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info)); } + } else if (mEhdr->e_machine == EM_LOONGARCH) { + switch (ELF_R_TYPE(Rel->r_info)) { + case R_LARCH_MARK_LA: + CoffAddFixup( + (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info] + + (Rel->r_offset - SecShdr->sh_addr)), + EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA); + break; + case R_LARCH_64: + CoffAddFixup( + (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info] + + (Rel->r_offset - SecShdr->sh_addr)), + EFI_IMAGE_REL_BASED_DIR64); + break; + case R_LARCH_NONE: + case R_LARCH_32: + case R_LARCH_RELATIVE: + case R_LARCH_COPY: + case R_LARCH_JUMP_SLOT: + case R_LARCH_TLS_DTPMOD32: + case R_LARCH_TLS_DTPMOD64: + case R_LARCH_TLS_DTPREL32: + case R_LARCH_TLS_DTPREL64: + case R_LARCH_TLS_TPREL32: + case R_LARCH_TLS_TPREL64: + case R_LARCH_IRELATIVE: + case R_LARCH_MARK_PCREL: + case R_LARCH_SOP_PUSH_PCREL: + case R_LARCH_SOP_PUSH_ABSOLUTE: + case R_LARCH_SOP_PUSH_DUP: + case R_LARCH_SOP_PUSH_GPREL: + case R_LARCH_SOP_PUSH_TLS_TPREL: + case R_LARCH_SOP_PUSH_TLS_GOT: + case R_LARCH_SOP_PUSH_TLS_GD: + case R_LARCH_SOP_PUSH_PLT_PCREL: + case R_LARCH_SOP_ASSERT: + case R_LARCH_SOP_NOT: + case R_LARCH_SOP_SUB: + case R_LARCH_SOP_SL: + case R_LARCH_SOP_SR: + case R_LARCH_SOP_ADD: + case R_LARCH_SOP_AND: + case R_LARCH_SOP_IF_ELSE: + case R_LARCH_SOP_POP_32_S_10_5: + case R_LARCH_SOP_POP_32_U_10_12: + case R_LARCH_SOP_POP_32_S_10_12: + case R_LARCH_SOP_POP_32_S_10_16: + case R_LARCH_SOP_POP_32_S_10_16_S2: + case R_LARCH_SOP_POP_32_S_5_20: + case R_LARCH_SOP_POP_32_S_0_5_10_16_S2: + case R_LARCH_SOP_POP_32_S_0_10_10_16_S2: + case R_LARCH_SOP_POP_32_U: + case R_LARCH_ADD8: + case R_LARCH_ADD16: + case R_LARCH_ADD24: + case R_LARCH_ADD32: + case R_LARCH_ADD64: + case R_LARCH_SUB8: + case R_LARCH_SUB16: + case R_LARCH_SUB24: + case R_LARCH_SUB32: + case R_LARCH_SUB64: + case R_LARCH_GNU_VTINHERIT: + case R_LARCH_GNU_VTENTRY: + case R_LARCH_B16: + case R_LARCH_B21: + case R_LARCH_B26: + case R_LARCH_ABS_HI20: + case R_LARCH_ABS_LO12: + case R_LARCH_ABS64_LO20: + case R_LARCH_ABS64_HI12: + case R_LARCH_PCALA_HI20: + case R_LARCH_PCALA_LO12: + case R_LARCH_PCALA64_LO20: + case R_LARCH_PCALA64_HI12: + case R_LARCH_GOT_PC_HI20: + case R_LARCH_GOT_PC_LO12: + case R_LARCH_GOT64_PC_LO20: + case R_LARCH_GOT64_PC_HI12: + case R_LARCH_GOT64_HI20: + case R_LARCH_GOT64_LO12: + case R_LARCH_GOT64_LO20: + case R_LARCH_GOT64_HI12: + case R_LARCH_TLS_LE_HI20: + case R_LARCH_TLS_LE_LO12: + case R_LARCH_TLS_LE64_LO20: + case R_LARCH_TLS_LE64_HI12: + case R_LARCH_TLS_IE_PC_HI20: + case R_LARCH_TLS_IE_PC_LO12: + case R_LARCH_TLS_IE64_PC_LO20: + case R_LARCH_TLS_IE64_PC_HI12: + case R_LARCH_TLS_IE64_HI20: + case R_LARCH_TLS_IE64_LO12: + case R_LARCH_TLS_IE64_LO20: + case R_LARCH_TLS_IE64_HI12: + case R_LARCH_TLS_LD_PC_HI20: + case R_LARCH_TLS_LD64_HI20: + case R_LARCH_TLS_GD_PC_HI20: + case R_LARCH_TLS_GD64_HI20: + case R_LARCH_RELAX: + // + // These types are not used or do not require fixup in PE format files. + // + break; + default: + Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s unsupported ELF EM_LOONGARCH relocation 0x%x.", mInImageName, (unsigned) ELF64_R_TYPE(Rel->r_info)); + } } else { Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine); } diff --git a/BaseTools/Source/C/GenFw/elf_common.h b/BaseTools/Source/C/GenFw/elf_common.h index b67f59e7a0..7b7fdeb329 100644 --- a/BaseTools/Source/C/GenFw/elf_common.h +++ b/BaseTools/Source/C/GenFw/elf_common.h @@ -4,6 +4,7 @@ Ported ELF include files from FreeBSD Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
Portion Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -181,6 +182,7 @@ typedef struct { #define EM_AARCH64 183 /* ARM 64bit Architecture */ #define EM_RISCV64 243 /* 64bit RISC-V Architecture */ #define EM_RISCV 244 /* 32bit RISC-V Architecture */ +#define EM_LOONGARCH 258 /* LoongArch Architecture */ /* Non-standard or deprecated. */ #define EM_486 6 /* Intel i486. */ @@ -1042,4 +1044,96 @@ typedef struct { #define R_RISCV_SET8 54 #define R_RISCV_SET16 55 #define R_RISCV_SET32 56 + +/* + * LoongArch relocation types + */ +#define R_LARCH_NONE 0 +#define R_LARCH_32 1 +#define R_LARCH_64 2 +#define R_LARCH_RELATIVE 3 +#define R_LARCH_COPY 4 +#define R_LARCH_JUMP_SLOT 5 +#define R_LARCH_TLS_DTPMOD32 6 +#define R_LARCH_TLS_DTPMOD64 7 +#define R_LARCH_TLS_DTPREL32 8 +#define R_LARCH_TLS_DTPREL64 9 +#define R_LARCH_TLS_TPREL32 10 +#define R_LARCH_TLS_TPREL64 11 +#define R_LARCH_IRELATIVE 12 +#define R_LARCH_MARK_LA 20 +#define R_LARCH_MARK_PCREL 21 +#define R_LARCH_SOP_PUSH_PCREL 22 +#define R_LARCH_SOP_PUSH_ABSOLUTE 23 +#define R_LARCH_SOP_PUSH_DUP 24 +#define R_LARCH_SOP_PUSH_GPREL 25 +#define R_LARCH_SOP_PUSH_TLS_TPREL 26 +#define R_LARCH_SOP_PUSH_TLS_GOT 27 +#define R_LARCH_SOP_PUSH_TLS_GD 28 +#define R_LARCH_SOP_PUSH_PLT_PCREL 29 +#define R_LARCH_SOP_ASSERT 30 +#define R_LARCH_SOP_NOT 31 +#define R_LARCH_SOP_SUB 32 +#define R_LARCH_SOP_SL 33 +#define R_LARCH_SOP_SR 34 +#define R_LARCH_SOP_ADD 35 +#define R_LARCH_SOP_AND 36 +#define R_LARCH_SOP_IF_ELSE 37 +#define R_LARCH_SOP_POP_32_S_10_5 38 +#define R_LARCH_SOP_POP_32_U_10_12 39 +#define R_LARCH_SOP_POP_32_S_10_12 40 +#define R_LARCH_SOP_POP_32_S_10_16 41 +#define R_LARCH_SOP_POP_32_S_10_16_S2 42 +#define R_LARCH_SOP_POP_32_S_5_20 43 +#define R_LARCH_SOP_POP_32_S_0_5_10_16_S2 44 +#define R_LARCH_SOP_POP_32_S_0_10_10_16_S2 45 +#define R_LARCH_SOP_POP_32_U 46 +#define R_LARCH_ADD8 47 +#define R_LARCH_ADD16 48 +#define R_LARCH_ADD24 49 +#define R_LARCH_ADD32 50 +#define R_LARCH_ADD64 51 +#define R_LARCH_SUB8 52 +#define R_LARCH_SUB16 53 +#define R_LARCH_SUB24 54 +#define R_LARCH_SUB32 55 +#define R_LARCH_SUB64 56 +#define R_LARCH_GNU_VTINHERIT 57 +#define R_LARCH_GNU_VTENTRY 58 +#define R_LARCH_B16 64 +#define R_LARCH_B21 65 +#define R_LARCH_B26 66 +#define R_LARCH_ABS_HI20 67 +#define R_LARCH_ABS_LO12 68 +#define R_LARCH_ABS64_LO20 69 +#define R_LARCH_ABS64_HI12 70 +#define R_LARCH_PCALA_HI20 71 +#define R_LARCH_PCALA_LO12 72 +#define R_LARCH_PCALA64_LO20 73 +#define R_LARCH_PCALA64_HI12 74 +#define R_LARCH_GOT_PC_HI20 75 +#define R_LARCH_GOT_PC_LO12 76 +#define R_LARCH_GOT64_PC_LO20 77 +#define R_LARCH_GOT64_PC_HI12 78 +#define R_LARCH_GOT64_HI20 79 +#define R_LARCH_GOT64_LO12 80 +#define R_LARCH_GOT64_LO20 81 +#define R_LARCH_GOT64_HI12 82 +#define R_LARCH_TLS_LE_HI20 83 +#define R_LARCH_TLS_LE_LO12 84 +#define R_LARCH_TLS_LE64_LO20 85 +#define R_LARCH_TLS_LE64_HI12 86 +#define R_LARCH_TLS_IE_PC_HI20 87 +#define R_LARCH_TLS_IE_PC_LO12 88 +#define R_LARCH_TLS_IE64_PC_LO20 89 +#define R_LARCH_TLS_IE64_PC_HI12 90 +#define R_LARCH_TLS_IE64_HI20 91 +#define R_LARCH_TLS_IE64_LO12 92 +#define R_LARCH_TLS_IE64_LO20 93 +#define R_LARCH_TLS_IE64_HI12 94 +#define R_LARCH_TLS_LD_PC_HI20 95 +#define R_LARCH_TLS_LD64_HI20 96 +#define R_LARCH_TLS_GD_PC_HI20 97 +#define R_LARCH_TLS_GD64_HI20 98 +#define R_LARCH_RELAX 99 #endif /* !_SYS_ELF_COMMON_H_ */ diff --git a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h index 21c968e650..77ded3f611 100644 --- a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h +++ b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h @@ -7,6 +7,7 @@ Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -36,23 +37,25 @@ // // PE32+ Machine type for EFI images // -#define IMAGE_FILE_MACHINE_I386 0x014c -#define IMAGE_FILE_MACHINE_EBC 0x0EBC -#define IMAGE_FILE_MACHINE_X64 0x8664 -#define IMAGE_FILE_MACHINE_ARM 0x01c0 // Thumb only -#define IMAGE_FILE_MACHINE_ARMT 0x01c2 // 32bit Mixed ARM and Thumb/Thumb 2 Little Endian -#define IMAGE_FILE_MACHINE_ARM64 0xAA64 // 64bit ARM Architecture, Little Endian -#define IMAGE_FILE_MACHINE_RISCV64 0x5064 // 64bit RISC-V ISA +#define IMAGE_FILE_MACHINE_I386 0x014c +#define IMAGE_FILE_MACHINE_EBC 0x0EBC +#define IMAGE_FILE_MACHINE_X64 0x8664 +#define IMAGE_FILE_MACHINE_ARM 0x01c0 // Thumb only +#define IMAGE_FILE_MACHINE_ARMT 0x01c2 // 32bit Mixed ARM and Thumb/Thumb 2 Little Endian +#define IMAGE_FILE_MACHINE_ARM64 0xAA64 // 64bit ARM Architecture, Little Endian +#define IMAGE_FILE_MACHINE_RISCV64 0x5064 // 64bit RISC-V ISA +#define IMAGE_FILE_MACHINE_LOONGARCH64 0x6264 // 64bit LoongArch Architecture // // Support old names for backward compatible // -#define EFI_IMAGE_MACHINE_IA32 IMAGE_FILE_MACHINE_I386 -#define EFI_IMAGE_MACHINE_EBC IMAGE_FILE_MACHINE_EBC -#define EFI_IMAGE_MACHINE_X64 IMAGE_FILE_MACHINE_X64 -#define EFI_IMAGE_MACHINE_ARMT IMAGE_FILE_MACHINE_ARMT -#define EFI_IMAGE_MACHINE_AARCH64 IMAGE_FILE_MACHINE_ARM64 -#define EFI_IMAGE_MACHINE_RISCV64 IMAGE_FILE_MACHINE_RISCV64 +#define EFI_IMAGE_MACHINE_IA32 IMAGE_FILE_MACHINE_I386 +#define EFI_IMAGE_MACHINE_EBC IMAGE_FILE_MACHINE_EBC +#define EFI_IMAGE_MACHINE_X64 IMAGE_FILE_MACHINE_X64 +#define EFI_IMAGE_MACHINE_ARMT IMAGE_FILE_MACHINE_ARMT +#define EFI_IMAGE_MACHINE_AARCH64 IMAGE_FILE_MACHINE_ARM64 +#define EFI_IMAGE_MACHINE_RISCV64 IMAGE_FILE_MACHINE_RISCV64 +#define EFI_IMAGE_MACHINE_LOONGARCH64 IMAGE_FILE_MACHINE_LOONGARCH64 #define EFI_IMAGE_DOS_SIGNATURE 0x5A4D // MZ #define EFI_IMAGE_OS2_SIGNATURE 0x454E // NE @@ -500,19 +503,21 @@ typedef struct { // // Based relocation types. // -#define EFI_IMAGE_REL_BASED_ABSOLUTE 0 -#define EFI_IMAGE_REL_BASED_HIGH 1 -#define EFI_IMAGE_REL_BASED_LOW 2 -#define EFI_IMAGE_REL_BASED_HIGHLOW 3 -#define EFI_IMAGE_REL_BASED_HIGHADJ 4 -#define EFI_IMAGE_REL_BASED_MIPS_JMPADDR 5 -#define EFI_IMAGE_REL_BASED_ARM_MOV32A 5 -#define EFI_IMAGE_REL_BASED_RISCV_HI20 5 -#define EFI_IMAGE_REL_BASED_ARM_MOV32T 7 -#define EFI_IMAGE_REL_BASED_RISCV_LOW12I 7 -#define EFI_IMAGE_REL_BASED_RISCV_LOW12S 8 -#define EFI_IMAGE_REL_BASED_IA64_IMM64 9 -#define EFI_IMAGE_REL_BASED_DIR64 10 +#define EFI_IMAGE_REL_BASED_ABSOLUTE 0 +#define EFI_IMAGE_REL_BASED_HIGH 1 +#define EFI_IMAGE_REL_BASED_LOW 2 +#define EFI_IMAGE_REL_BASED_HIGHLOW 3 +#define EFI_IMAGE_REL_BASED_HIGHADJ 4 +#define EFI_IMAGE_REL_BASED_MIPS_JMPADDR 5 +#define EFI_IMAGE_REL_BASED_ARM_MOV32A 5 +#define EFI_IMAGE_REL_BASED_RISCV_HI20 5 +#define EFI_IMAGE_REL_BASED_ARM_MOV32T 7 +#define EFI_IMAGE_REL_BASED_RISCV_LOW12I 7 +#define EFI_IMAGE_REL_BASED_RISCV_LOW12S 8 +#define EFI_IMAGE_REL_BASED_LOONGARCH32_MARK_LA 8 +#define EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA 8 +#define EFI_IMAGE_REL_BASED_IA64_IMM64 9 +#define EFI_IMAGE_REL_BASED_DIR64 10 /// diff --git a/BaseTools/Source/C/Makefiles/header.makefile b/BaseTools/Source/C/Makefiles/header.makefile index 0df728f327..4e88a4fbd8 100644 --- a/BaseTools/Source/C/Makefiles/header.makefile +++ b/BaseTools/Source/C/Makefiles/header.makefile @@ -31,6 +31,9 @@ ifndef HOST_ARCH ifneq (,$(findstring riscv64,$(uname_m))) HOST_ARCH=RISCV64 endif + ifneq (,$(findstring loongarch64,$(uname_m))) + HOST_ARCH=LOONGARCH64 + endif ifndef HOST_ARCH $(info Could not detected HOST_ARCH from uname results) $(error HOST_ARCH is not defined!) @@ -70,6 +73,9 @@ ARCH_INCLUDE = -I $(MAKEROOT)/Include/AArch64/ else ifeq ($(HOST_ARCH), RISCV64) ARCH_INCLUDE = -I $(MAKEROOT)/Include/RiscV64/ +else ifeq ($(HOST_ARCH), LOONGARCH64) +ARCH_INCLUDE = -I $(MAKEROOT)/Include/LoongArch64/ + else $(error Bad HOST_ARCH) endif From 1d5bd1228f6f2e10cd38478729de277581656666 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 6 Sep 2022 19:25:29 +0800 Subject: [PATCH 0143/1529] BaseTools: Updated for GCC5 tool chain for LoongArch platfrom. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 BaseTools define template files changes for building EDK2 LoongArch platform. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Co-authored-by: Dongyan Qian Co-authored-by: Baoqi Zhang Reviewed-by: Liming Gao --- BaseTools/Conf/tools_def.template | 54 +++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 5ed19810b7..c4e4c7ded0 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -4,6 +4,7 @@ # Portions copyright (c) 2011 - 2019, ARM Ltd. All rights reserved.
# Copyright (c) 2015, Hewlett-Packard Development Company, L.P.
# (C) Copyright 2020, Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# Copyright (c) Microsoft Corporation # # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -267,7 +268,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc # Intel(r) ACPI Compiler from # https://acpica.org/downloads # GCC5 -Linux,Windows- Requires: -# GCC 5 with LTO support, targeting x86_64-linux-gnu, aarch64-linux-gnu, arm-linux-gnueabi or riscv64-linux-gnu +# GCC 5 with LTO support, targeting x86_64-linux-gnu, aarch64-linux-gnu, arm-linux-gnueabi, riscv64-linux-gnu or loongarch64-linux-gnu # Optional: # Required to build platforms or ACPI tables: # Intel(r) ACPI Compiler from @@ -1852,6 +1853,7 @@ DEFINE GCC_ALL_CC_FLAGS = -g -Os -fshort-wchar -fno-builtin -fno-stri DEFINE GCC_IA32_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -m32 -malign-double -freorder-blocks -freorder-blocks-and-partition -O2 -mno-stack-arg-probe DEFINE GCC_X64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mno-red-zone -Wno-address -mno-stack-arg-probe DEFINE GCC_ARM_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -mabi=aapcs -fno-short-enums -funsigned-char -ffunction-sections -fdata-sections -fomit-frame-pointer -Wno-address -mthumb -mfloat-abi=soft -fno-pic -fno-pie +DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mabi=lp64d -fno-asynchronous-unwind-tables -fno-plt -Wno-address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections DEFINE GCC_ARM_CC_XIPFLAGS = -mno-unaligned-access DEFINE GCC_AARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -fno-short-enums -fverbose-asm -funsigned-char -ffunction-sections -fdata-sections -Wno-address -fno-asynchronous-unwind-tables -fno-unwind-tables -fno-pic -fno-pie -ffixed-x18 DEFINE GCC_AARCH64_CC_XIPFLAGS = -mstrict-align -mgeneral-regs-only @@ -1859,12 +1861,15 @@ DEFINE GCC_DLINK_FLAGS_COMMON = -nostdlib --pie DEFINE GCC_DLINK2_FLAGS_COMMON = -Wl,--script=$(EDK_TOOLS_PATH)/Scripts/GccBase.lds DEFINE GCC_IA32_X64_DLINK_COMMON = DEF(GCC_DLINK_FLAGS_COMMON) --gc-sections DEFINE GCC_ARM_AARCH64_DLINK_COMMON= -Wl,--emit-relocs -nostdlib -Wl,--gc-sections -u $(IMAGE_ENTRY_POINT) -Wl,-e,$(IMAGE_ENTRY_POINT),-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map +DEFINE GCC_LOONGARCH64_DLINK_COMMON= -Wl,--emit-relocs -nostdlib -Wl,--gc-sections -u $(IMAGE_ENTRY_POINT) -Wl,-e,$(IMAGE_ENTRY_POINT),-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map DEFINE GCC_ARM_DLINK_FLAGS = DEF(GCC_ARM_AARCH64_DLINK_COMMON) -z common-page-size=0x20 -Wl,--pic-veneer DEFINE GCC_AARCH64_DLINK_FLAGS = DEF(GCC_ARM_AARCH64_DLINK_COMMON) -z common-page-size=0x20 +DEFINE GCC_LOONGARCH64_DLINK_FLAGS = DEF(GCC_LOONGARCH64_DLINK_COMMON) -z common-page-size=0x20 DEFINE GCC_ARM_AARCH64_ASLDLINK_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0 DEF(GCC_DLINK2_FLAGS_COMMON) -z common-page-size=0x20 DEFINE GCC_IA32_X64_ASLDLINK_FLAGS = DEF(GCC_IA32_X64_DLINK_COMMON) --entry _ReferenceAcpiTable -u $(IMAGE_ENTRY_POINT) DEFINE GCC_ARM_ASLDLINK_FLAGS = DEF(GCC_ARM_DLINK_FLAGS) -Wl,--entry,ReferenceAcpiTable -u $(IMAGE_ENTRY_POINT) DEF(GCC_ARM_AARCH64_ASLDLINK_FLAGS) DEFINE GCC_AARCH64_ASLDLINK_FLAGS = DEF(GCC_AARCH64_DLINK_FLAGS) -Wl,--entry,ReferenceAcpiTable -u $(IMAGE_ENTRY_POINT) DEF(GCC_ARM_AARCH64_ASLDLINK_FLAGS) +DEFINE GCC_LOONGARCH64_ASLDLINK_FLAGS = DEF(GCC_LOONGARCH64_DLINK_FLAGS) -Wl,--entry,ReferenceAcpiTable -u $(IMAGE_ENTRY_POINT) DEFINE GCC_IA32_X64_DLINK_FLAGS = DEF(GCC_IA32_X64_DLINK_COMMON) --entry _$(IMAGE_ENTRY_POINT) --file-alignment 0x20 --section-alignment 0x20 -Map $(DEST_DIR_DEBUG)/$(BASE_NAME).map DEFINE GCC_ASM_FLAGS = -c -x assembler -imacros AutoGen.h DEFINE GCC_PP_FLAGS = -E -x assembler-with-cpp -include AutoGen.h @@ -1873,11 +1878,12 @@ DEFINE GCC_ASLPP_FLAGS = -x c -E -include AutoGen.h DEFINE GCC_ASLCC_FLAGS = -x c DEFINE GCC_WINDRES_FLAGS = -J rc -O coff DEFINE GCC_DTCPP_FLAGS = -E -x assembler-with-cpp -imacros AutoGen.h -nostdinc -undef -DEFINE GCC_IA32_RC_FLAGS = -I binary -O elf32-i386 -B i386 --rename-section .data=.hii -DEFINE GCC_X64_RC_FLAGS = -I binary -O elf64-x86-64 -B i386 --rename-section .data=.hii -DEFINE GCC_ARM_RC_FLAGS = -I binary -O elf32-littlearm -B arm --rename-section .data=.hii -DEFINE GCC_AARCH64_RC_FLAGS = -I binary -O elf64-littleaarch64 -B aarch64 --rename-section .data=.hii -DEFINE GCC_RISCV64_RC_FLAGS = -I binary -O elf64-littleriscv -B riscv --rename-section .data=.hii +DEFINE GCC_IA32_RC_FLAGS = -I binary -O elf32-i386 -B i386 --rename-section .data=.hii +DEFINE GCC_X64_RC_FLAGS = -I binary -O elf64-x86-64 -B i386 --rename-section .data=.hii +DEFINE GCC_ARM_RC_FLAGS = -I binary -O elf32-littlearm -B arm --rename-section .data=.hii +DEFINE GCC_AARCH64_RC_FLAGS = -I binary -O elf64-littleaarch64 -B aarch64 --rename-section .data=.hii +DEFINE GCC_RISCV64_RC_FLAGS = -I binary -O elf64-littleriscv -B riscv --rename-section .data=.hii +DEFINE GCC_LOONGARCH64_RC_FLAGS = -I binary -O elf64-loongarch -B loongarch64 --rename-section .data=.hii # GCC Build Flag for included header file list generation DEFINE GCC_DEPS_FLAGS = -MMD -MF $@.deps @@ -1967,6 +1973,14 @@ DEFINE GCC5_RISCV64_CC_FLAGS = DEF(GCC5_RISCV_ALL_CC_FLAGS) DEF(GC DEFINE GCC5_RISCV64_DLINK_FLAGS = DEF(GCC5_RISCV_ALL_DLINK_FLAGS) -Wl,-melf64lriscv,--oformat=elf64-littleriscv,--no-relax DEFINE GCC5_RISCV64_DLINK2_FLAGS = DEF(GCC5_RISCV_ALL_DLINK2_FLAGS) DEFINE GCC5_RISCV64_ASM_FLAGS = DEF(GCC5_RISCV_ALL_ASM_FLAGS) -march=DEF(GCC5_RISCV64_ARCH) -mcmodel=medany -mabi=lp64 + +DEFINE GCC5_LOONGARCH64_CC_FLAGS = DEF(GCC_LOONGARCH64_CC_FLAGS) -march=loongarch64 -mno-memcpy -Werror -Wno-maybe-uninitialized -Wno-stringop-overflow -Wno-pointer-to-int-cast -no-pie -fno-stack-protector -mno-explicit-relocs +DEFINE GCC5_LOONGARCH64_DLINK_FLAGS = DEF(GCC_LOONGARCH64_DLINK_FLAGS) +DEFINE GCC5_LOONGARCH64_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x228 +DEFINE GCC5_LOONGARCH64_ASLDLINK_FLAGS = DEF(GCC_LOONGARCH64_ASLDLINK_FLAGS) DEF(GCC5_LOONGARCH64_DLINK2_FLAGS) +DEFINE GCC5_LOONGARCH64_ASM_FLAGS = -x assembler-with-cpp -mabi=lp64d -march=loongarch64 -fno-builtin -c -Wall -mno-explicit-relocs +DEFINE GCC5_LOONGARCH64_PP_FLAGS = -mabi=lp64d -march=loongarch64 DEF(GCC_PP_FLAGS) + DEFINE GCC_PP_FLAGS = -E -x assembler-with-cpp -include AutoGen.h DEF(GCC5_RISCV_OPENSBI_TYPES) #################################################################################### @@ -2445,6 +2459,34 @@ RELEASE_GCC5_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_GCC5_RISCV64_OBJCOPY_FLAGS = *_GCC5_RISCV64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) +################## +# GCC5 LOONGARCH64 definitions +################## +*_GCC5_LOONGARCH64_OBJCOPY_PATH = ENV(GCC5_LOONGARCH64_PREFIX)objcopy +*_GCC5_LOONGARCH64_CC_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_SLINK_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc-ar +*_GCC5_LOONGARCH64_DLINK_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_ASLDLINK_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_ASM_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_PP_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_VFRPP_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_ASLCC_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_ASLPP_PATH = ENV(GCC5_LOONGARCH64_PREFIX)gcc +*_GCC5_LOONGARCH64_RC_PATH = ENV(GCC5_LOONGARCH64_PREFIX)objcopy + +*_GCC5_LOONGARCH64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) +*_GCC5_LOONGARCH64_ASLDLINK_FLAGS = DEF(GCC5_LOONGARCH64_ASLDLINK_FLAGS) +*_GCC5_LOONGARCH64_ASM_FLAGS = DEF(GCC5_LOONGARCH64_ASM_FLAGS) +*_GCC5_LOONGARCH64_DLINK_FLAGS = DEF(GCC5_LOONGARCH64_DLINK_FLAGS) +*_GCC5_LOONGARCH64_DLINK2_FLAGS = DEF(GCC5_LOONGARCH64_DLINK2_FLAGS) +*_GCC5_LOONGARCH64_RC_FLAGS = DEF(GCC_LOONGARCH64_RC_FLAGS) +*_GCC5_LOONGARCH64_OBJCOPY_FLAGS = +*_GCC5_LOONGARCH64_NASM_FLAGS = -f elf32 +*_GCC5_LOONGARCH64_PP_FLAGS = DEF(GCC5_LOONGARCH64_PP_FLAGS) + +DEBUG_GCC5_LOONGARCH64_CC_FLAGS = DEF(GCC5_LOONGARCH64_CC_FLAGS) +RELEASE_GCC5_LOONGARCH64_CC_FLAGS = DEF(GCC5_LOONGARCH64_CC_FLAGS) -Wno-unused-but-set-variable -Wno-unused-variable + #################################################################################### # # CLANG35 - This configuration is used to compile under Linux to produce From f0bde7559f13e516f36a9e76d28b4da6979de5ef Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 14 Jan 2022 12:19:15 +0800 Subject: [PATCH 0144/1529] BaseTools: Updated build tools to support new LoongArch. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Python code changes for building EDK2 LoongArch platform. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Liming Gao --- BaseTools/Source/Python/Common/DataType.py | 21 ++++++++++++++-- .../Source/Python/UPT/Library/DataType.py | 24 ++++++++++++++++++- BaseTools/Source/Python/build/buildoptions.py | 3 ++- 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/BaseTools/Source/Python/Common/DataType.py b/BaseTools/Source/Python/Common/DataType.py index dc49623333..48dbf16495 100644 --- a/BaseTools/Source/Python/Common/DataType.py +++ b/BaseTools/Source/Python/Common/DataType.py @@ -4,6 +4,7 @@ # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
# Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -52,10 +53,10 @@ TAB_ARCH_ARM = 'ARM' TAB_ARCH_EBC = 'EBC' TAB_ARCH_AARCH64 = 'AARCH64' - TAB_ARCH_RISCV64 = 'RISCV64' +TAB_ARCH_LOONGARCH64 = 'LOONGARCH64' -ARCH_SET_FULL = {TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_ARM, TAB_ARCH_EBC, TAB_ARCH_AARCH64, TAB_ARCH_RISCV64, TAB_ARCH_COMMON} +ARCH_SET_FULL = {TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_ARM, TAB_ARCH_EBC, TAB_ARCH_AARCH64, TAB_ARCH_RISCV64, TAB_ARCH_LOONGARCH64, TAB_ARCH_COMMON} SUP_MODULE_BASE = 'BASE' SUP_MODULE_SEC = 'SEC' @@ -138,6 +139,7 @@ TAB_SOURCES_ARM = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_ARM TAB_SOURCES_EBC = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_EBC TAB_SOURCES_AARCH64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_SOURCES_LOONGARCH64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_BINARIES = 'Binaries' TAB_BINARIES_COMMON = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_COMMON @@ -146,6 +148,7 @@ TAB_BINARIES_ARM = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_ARM TAB_BINARIES_EBC = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_EBC TAB_BINARIES_AARCH64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_BINARIES_LOONGARCH64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_INCLUDES = 'Includes' TAB_INCLUDES_COMMON = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_COMMON @@ -154,6 +157,7 @@ TAB_INCLUDES_ARM = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_ARM TAB_INCLUDES_EBC = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_EBC TAB_INCLUDES_AARCH64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_INCLUDES_LOONGARCH64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_GUIDS = 'Guids' TAB_GUIDS_COMMON = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_COMMON @@ -162,6 +166,7 @@ TAB_GUIDS_ARM = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_ARM TAB_GUIDS_EBC = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_EBC TAB_GUIDS_AARCH64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_GUIDS_LOONGARCH64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PROTOCOLS = 'Protocols' TAB_PROTOCOLS_COMMON = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_COMMON @@ -170,6 +175,7 @@ TAB_PROTOCOLS_ARM = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_ARM TAB_PROTOCOLS_EBC = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_EBC TAB_PROTOCOLS_AARCH64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PROTOCOLS_LOONGARCH64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PPIS = 'Ppis' TAB_PPIS_COMMON = TAB_PPIS + TAB_SPLIT + TAB_ARCH_COMMON @@ -178,6 +184,7 @@ TAB_PPIS_ARM = TAB_PPIS + TAB_SPLIT + TAB_ARCH_ARM TAB_PPIS_EBC = TAB_PPIS + TAB_SPLIT + TAB_ARCH_EBC TAB_PPIS_AARCH64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PPIS_LOONGARCH64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_LIBRARY_CLASSES = 'LibraryClasses' TAB_LIBRARY_CLASSES_COMMON = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_COMMON @@ -186,6 +193,7 @@ TAB_LIBRARY_CLASSES_ARM = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_ARM TAB_LIBRARY_CLASSES_EBC = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_EBC TAB_LIBRARY_CLASSES_AARCH64 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_LIBRARY_CLASSES_LOONGARCH64 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PACKAGES = 'Packages' TAB_PACKAGES_COMMON = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_COMMON @@ -194,6 +202,7 @@ TAB_PACKAGES_ARM = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_ARM TAB_PACKAGES_EBC = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_EBC TAB_PACKAGES_AARCH64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PACKAGES_LOONGARCH64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS = 'Pcds' TAB_PCDS_FIXED_AT_BUILD = 'FixedAtBuild' @@ -221,6 +230,7 @@ TAB_PCDS_FIXED_AT_BUILD_ARM = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_ARM TAB_PCDS_FIXED_AT_BUILD_EBC = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS_FIXED_AT_BUILD_AARCH64 = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PCDS_FIXED_AT_BUILD_LOONGARCH64 = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_PATCHABLE_IN_MODULE_NULL = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE TAB_PCDS_PATCHABLE_IN_MODULE_COMMON = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_COMMON @@ -229,6 +239,7 @@ TAB_PCDS_PATCHABLE_IN_MODULE_ARM = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_ARM TAB_PCDS_PATCHABLE_IN_MODULE_EBC = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS_PATCHABLE_IN_MODULE_AARCH64 = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PCDS_PATCHABLE_IN_MODULE_LOONGARCH64 = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_FEATURE_FLAG_NULL = TAB_PCDS + TAB_PCDS_FEATURE_FLAG TAB_PCDS_FEATURE_FLAG_COMMON = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_COMMON @@ -237,6 +248,7 @@ TAB_PCDS_FEATURE_FLAG_ARM = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_ARM TAB_PCDS_FEATURE_FLAG_EBC = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS_FEATURE_FLAG_AARCH64 = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PCDS_FEATURE_FLAG_LOONGARCH64 = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_DYNAMIC_EX_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX TAB_PCDS_DYNAMIC_EX_DEFAULT_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX_DEFAULT @@ -248,6 +260,7 @@ TAB_PCDS_DYNAMIC_EX_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_ARM TAB_PCDS_DYNAMIC_EX_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS_DYNAMIC_EX_AARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PCDS_DYNAMIC_EX_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_DYNAMIC_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC TAB_PCDS_DYNAMIC_DEFAULT_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_DEFAULT @@ -259,6 +272,7 @@ TAB_PCDS_DYNAMIC_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_ARM TAB_PCDS_DYNAMIC_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS_DYNAMIC_AARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_PCDS_DYNAMIC_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE = 'PcdLoadFixAddressPeiCodePageNumber' TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE = 'UINT32' @@ -285,6 +299,7 @@ TAB_DEPEX_ARM = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_ARM TAB_DEPEX_EBC = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_EBC TAB_DEPEX_AARCH64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_DEPEX_LOONGARCH64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_SKUIDS = 'SkuIds' TAB_DEFAULT_STORES = 'DefaultStores' @@ -297,6 +312,7 @@ TAB_LIBRARIES_ARM = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_ARM TAB_LIBRARIES_EBC = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_EBC TAB_LIBRARIES_AARCH64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_LIBRARIES_LOONGARCH64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_COMPONENTS = 'Components' TAB_COMPONENTS_COMMON = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_COMMON @@ -305,6 +321,7 @@ TAB_COMPONENTS_ARM = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_ARM TAB_COMPONENTS_EBC = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_EBC TAB_COMPONENTS_AARCH64 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_AARCH64 +TAB_COMPONENTS_LOONGARCH64 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_BUILD_OPTIONS = 'BuildOptions' diff --git a/BaseTools/Source/Python/UPT/Library/DataType.py b/BaseTools/Source/Python/UPT/Library/DataType.py index 2033149aa6..0e47f35670 100644 --- a/BaseTools/Source/Python/UPT/Library/DataType.py +++ b/BaseTools/Source/Python/UPT/Library/DataType.py @@ -2,6 +2,7 @@ # This file is used to define class for data type structure # # Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -367,10 +368,11 @@ TAB_ARCH_X64 = 'X64' TAB_ARCH_IPF = 'IPF' TAB_ARCH_ARM = 'ARM' +TAB_ARCH_LOONGARCH64 = 'LOONGARCH64' TAB_ARCH_EBC = 'EBC' ARCH_LIST = \ -[TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_IPF, TAB_ARCH_ARM, TAB_ARCH_EBC] +[TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_IPF, TAB_ARCH_ARM, TAB_ARCH_LOONGARCH64, TAB_ARCH_EBC] SUP_MODULE_BASE = 'BASE' SUP_MODULE_SEC = 'SEC' @@ -454,6 +456,7 @@ TAB_SOURCES_X64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_X64 TAB_SOURCES_IPF = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_IPF TAB_SOURCES_ARM = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_ARM +TAB_SOURCES_LOONGARCH64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_SOURCES_EBC = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_EBC TAB_BINARIES = 'Binaries' @@ -462,6 +465,7 @@ TAB_BINARIES_X64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_X64 TAB_BINARIES_IPF = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_IPF TAB_BINARIES_ARM = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_ARM +TAB_BINARIES_LOONGARCH64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_BINARIES_EBC = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_EBC TAB_INCLUDES = 'Includes' @@ -470,6 +474,7 @@ TAB_INCLUDES_X64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_X64 TAB_INCLUDES_IPF = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_IPF TAB_INCLUDES_ARM = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_ARM +TAB_INCLUDES_LOONGARCH64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_INCLUDES_EBC = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_EBC TAB_GUIDS = 'Guids' @@ -478,6 +483,7 @@ TAB_GUIDS_X64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_X64 TAB_GUIDS_IPF = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_IPF TAB_GUIDS_ARM = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_ARM +TAB_GUIDS_LOONGARCH64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_GUIDS_EBC = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_EBC TAB_PROTOCOLS = 'Protocols' @@ -486,6 +492,7 @@ TAB_PROTOCOLS_X64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_X64 TAB_PROTOCOLS_IPF = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_IPF TAB_PROTOCOLS_ARM = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_ARM +TAB_PROTOCOLS_LOONGARCH64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PROTOCOLS_EBC = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_EBC TAB_PPIS = 'Ppis' @@ -494,6 +501,7 @@ TAB_PPIS_X64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_X64 TAB_PPIS_IPF = TAB_PPIS + TAB_SPLIT + TAB_ARCH_IPF TAB_PPIS_ARM = TAB_PPIS + TAB_SPLIT + TAB_ARCH_ARM +TAB_PPIS_LOONGARCH64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PPIS_EBC = TAB_PPIS + TAB_SPLIT + TAB_ARCH_EBC TAB_LIBRARY_CLASSES = 'LibraryClasses' @@ -502,6 +510,7 @@ TAB_LIBRARY_CLASSES_X64 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_X64 TAB_LIBRARY_CLASSES_IPF = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_IPF TAB_LIBRARY_CLASSES_ARM = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_ARM +TAB_LIBRARY_CLASSES_LOONGARCH64 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_LIBRARY_CLASSES_EBC = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_EBC TAB_PACKAGES = 'Packages' @@ -510,6 +519,7 @@ TAB_PACKAGES_X64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_X64 TAB_PACKAGES_IPF = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_IPF TAB_PACKAGES_ARM = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_ARM +TAB_PACKAGES_LOONGARCH64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PACKAGES_EBC = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_EBC TAB_PCDS = 'Pcds' @@ -548,6 +558,8 @@ TAB_SPLIT + TAB_ARCH_IPF TAB_PCDS_FIXED_AT_BUILD_ARM = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + \ TAB_SPLIT + TAB_ARCH_ARM +TAB_PCDS_FIXED_AT_BUILD_LOONGARCH64 = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + \ +TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_FIXED_AT_BUILD_EBC = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + \ TAB_SPLIT + TAB_ARCH_EBC @@ -562,6 +574,8 @@ TAB_SPLIT + TAB_ARCH_IPF TAB_PCDS_PATCHABLE_IN_MODULE_ARM = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + \ TAB_SPLIT + TAB_ARCH_ARM +TAB_PCDS_PATCHABLE_IN_MODULE_LOONGARCH64 = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + \ +TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_PATCHABLE_IN_MODULE_EBC = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + \ TAB_SPLIT + TAB_ARCH_EBC @@ -576,6 +590,8 @@ TAB_ARCH_IPF TAB_PCDS_FEATURE_FLAG_ARM = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + \ TAB_ARCH_ARM +TAB_PCDS_FEATURE_FLAG_LOONGARCH64 = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + \ +TAB_ARCH_LOONGARCH64 TAB_PCDS_FEATURE_FLAG_EBC = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + \ TAB_ARCH_EBC @@ -593,6 +609,8 @@ TAB_ARCH_IPF TAB_PCDS_DYNAMIC_EX_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + \ TAB_ARCH_ARM +TAB_PCDS_DYNAMIC_EX_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + \ +TAB_ARCH_LOONGARCH64 TAB_PCDS_DYNAMIC_EX_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + \ TAB_ARCH_EBC @@ -606,6 +624,7 @@ TAB_PCDS_DYNAMIC_X64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_X64 TAB_PCDS_DYNAMIC_IPF = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_IPF TAB_PCDS_DYNAMIC_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_ARM +TAB_PCDS_DYNAMIC_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_PCDS_DYNAMIC_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_EBC TAB_PCD_DYNAMIC_TYPE_LIST = [TAB_PCDS_DYNAMIC_DEFAULT_NULL, \ @@ -646,6 +665,7 @@ TAB_DEPEX_X64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_X64 TAB_DEPEX_IPF = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_IPF TAB_DEPEX_ARM = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_ARM +TAB_DEPEX_LOONGARCH64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_DEPEX_EBC = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_EBC TAB_SKUIDS = 'SkuIds' @@ -656,6 +676,7 @@ TAB_LIBRARIES_X64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_X64 TAB_LIBRARIES_IPF = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_IPF TAB_LIBRARIES_ARM = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_ARM +TAB_LIBRARIES_LOONGARCH64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_LIBRARIES_EBC = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_EBC TAB_COMPONENTS = 'Components' @@ -664,6 +685,7 @@ TAB_COMPONENTS_X64 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_X64 TAB_COMPONENTS_IPF = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_IPF TAB_COMPONENTS_ARM = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_ARM +TAB_COMPONENTS_LOONGARCH64 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_LOONGARCH64 TAB_COMPONENTS_EBC = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_EBC TAB_BUILD_OPTIONS = 'BuildOptions' diff --git a/BaseTools/Source/Python/build/buildoptions.py b/BaseTools/Source/Python/build/buildoptions.py index 39d92cff20..8334604b46 100644 --- a/BaseTools/Source/Python/build/buildoptions.py +++ b/BaseTools/Source/Python/build/buildoptions.py @@ -4,6 +4,7 @@ # Copyright (c) 2014, Hewlett-Packard Development Company, L.P.
# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) 2018 - 2020, Hewlett Packard Enterprise Development, L.P.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -41,7 +42,7 @@ def __init__(self): def GetOption(self): Parser = OptionParser(description=__copyright__, version=__version__, prog="build.exe", usage="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]") Parser.add_option("-a", "--arch", action="append", dest="TargetArch", - help="ARCHS is one of list: IA32, X64, ARM, AARCH64, RISCV64 or EBC, which overrides target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option.") + help="ARCHS is one of list: IA32, X64, ARM, AARCH64, RISCV64, LOONGARCH64 or EBC, which overrides target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option.") Parser.add_option("-p", "--platform", action="callback", type="string", dest="PlatformFile", callback=SingleCheckCallback, help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.") Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback, From dcf24e1ea188680e408066531f587ca788d7b0ac Mon Sep 17 00:00:00 2001 From: Chao Li Date: Mon, 15 Nov 2021 17:28:46 +0800 Subject: [PATCH 0145/1529] BaseTools: Add LoongArch64 binding. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 ProcessorBin.h and add LoongArch to Makefiles. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Liming Gao --- BaseTools/Source/C/GNUmakefile | 3 + .../C/Include/LoongArch64/ProcessorBind.h | 80 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 BaseTools/Source/C/Include/LoongArch64/ProcessorBind.h diff --git a/BaseTools/Source/C/GNUmakefile b/BaseTools/Source/C/GNUmakefile index 8c191e0c38..5275f657ef 100644 --- a/BaseTools/Source/C/GNUmakefile +++ b/BaseTools/Source/C/GNUmakefile @@ -29,6 +29,9 @@ ifndef HOST_ARCH ifneq (,$(findstring riscv64,$(uname_m))) HOST_ARCH=RISCV64 endif + ifneq (,$(findstring loongarch64,$(uname_m))) + HOST_ARCH=LOONGARCH64 + endif ifndef HOST_ARCH $(info Could not detected HOST_ARCH from uname results) $(error HOST_ARCH is not defined!) diff --git a/BaseTools/Source/C/Include/LoongArch64/ProcessorBind.h b/BaseTools/Source/C/Include/LoongArch64/ProcessorBind.h new file mode 100644 index 0000000000..0267859dee --- /dev/null +++ b/BaseTools/Source/C/Include/LoongArch64/ProcessorBind.h @@ -0,0 +1,80 @@ +/** @file + Processor or Compiler specific defines and types for LoongArch + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ +#ifndef PROCESSOR_BIND_H_ +#define PROCESSOR_BIND_H_ + +// +// Define the processor type so other code can make processor based choices +// +#define MDE_CPU_LOONGARCH64 + +#define EFIAPI + +// +// Make sure we are using the correct packing rules per EFI specification +// +#ifndef __GNUC__ +#pragma pack() +#endif + +// +// Use ANSI C 2000 stdint.h integer width declarations +// +#include +typedef uint8_t BOOLEAN; +typedef int8_t INT8; +typedef uint8_t UINT8; +typedef int16_t INT16; +typedef uint16_t UINT16; +typedef int32_t INT32; +typedef uint32_t UINT32; +typedef int64_t INT64; +typedef uint64_t UINT64; +typedef char CHAR8; +typedef uint16_t CHAR16; + +// +// Unsigned value of native width. (4 bytes on supported 32-bit processor instructions, +// 8 bytes on supported 64-bit processor instructions) +// +typedef UINT64 UINTN; + +// +// Signed value of native width. (4 bytes on supported 32-bit processor instructions, +// 8 bytes on supported 64-bit processor instructions) +// +typedef INT64 INTN; + +// +// Processor specific defines +// + +// +// A value of native width with the highest bit set. +// +#define MAX_BIT 0x8000000000000000ULL +// +// A value of native width with the two highest bits set. +// +#define MAX_2_BITS 0xC000000000000000ULL + +#if defined (__GNUC__) +// +// For GNU assembly code, .global or .globl can declare global symbols. +// Define this macro to unify the usage. +// +#define ASM_GLOBAL .globl +#endif + +// +// The stack alignment required for LoongArch +// +#define CPU_STACK_ALIGNMENT 16 + +#endif From 4c6194f7624f31328abb4062e8cb462c39dac1fa Mon Sep 17 00:00:00 2001 From: Chao Li Date: Mon, 15 Nov 2021 17:58:05 +0800 Subject: [PATCH 0146/1529] BaseTools: Enable LoongArch64 architecture for LoongArch64 EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 EDK CI for LoongArch64 architecture Enable LoongArch64 architecture for LoongArch64 EDK2 CI testing. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- ...gcc_loongarch64_unknown_linux_ext_dep.yaml | 22 +++++++++++++ .../LinuxGcc5ToolChain/LinuxGcc5ToolChain.py | 31 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml diff --git a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml new file mode 100644 index 0000000000..fe9a244853 --- /dev/null +++ b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml @@ -0,0 +1,22 @@ +## @file +# Download GCC LoongArch64 compiler from LoongArch GitHub release site +# Set shell variable GCC5_LOONGARCH64_INSTALL to this folder +# +# This is only downloaded when a build activates scope gcc_loongarch64_unknown_linux +# +# Copyright (c) Microsoft Corporation. +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "gcc_loongarch64_unknown_linux", + "type": "web", + "name": "gcc_loongarch64_unknown_linux", + "source":"https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-gcc-full.tar.xz", + "version": "13.0.0", + "sha256":"27a43c5bb127794f091d0e75da0003c4d0eec28a958d8f2cc7cd290a6e6133ab", + "compression_type": "tar", + "internal_path": "/cross-tools/", + "flags": ["set_shell_var", ], + "var_name": "GCC5_LOONGARCH64_INSTALL" +} diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py index f0685d8040..dab7a87997 100644 --- a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py +++ b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py @@ -5,6 +5,7 @@ # # Copyright (c) Microsoft Corporation # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## import os @@ -43,6 +44,12 @@ def do_pre_build(self, thebuilder): self.Logger.critical("Failed in check riscv64") return ret + # Check LoongArch64 compiler + ret = self._check_loongarch64() + if ret != 0: + self.Logger.critical("Failed in check loongarch64") + return ret + return 0 def _check_arm(self): @@ -121,3 +128,27 @@ def _check_riscv64(self): shell_environment.GetEnvironment().set_shell_var("LD_LIBRARY_PATH", prefix) return 0 + + def _check_loongarch64(self): + # check to see if full path already configured + if shell_environment.GetEnvironment().get_shell_var("GCC5_LOONGARCH64_PREFIX") is not None: + self.Logger.info("GCC5_LOONGARCH64_PREFIX is already set.") + + else: + # now check for install dir. If set then set the Prefix + install_path = shell_environment.GetEnvironment( + ).get_shell_var("GCC5_LOONGARCH64_INSTALL") + if install_path is None: + return 0 + + # make GCC5_LOONGARCH64_PREFIX to align with tools_def.txt + prefix = os.path.join(install_path, "bin", "loongarch64-unknown-linux-gnu-") + shell_environment.GetEnvironment().set_shell_var("GCC5_LOONGARCH64_PREFIX", prefix) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_LOONGARCH64_PREFIX") + "gcc"): + self.Logger.error( + "Path for GCC5_LOONGARCH64_PREFIX toolchain is invalid") + return -2 + + return 0 From f474b174a1bf8bf6ab7f1fbd3f34243db1944efa Mon Sep 17 00:00:00 2001 From: Chao Li Date: Mon, 15 Nov 2021 17:59:03 +0800 Subject: [PATCH 0147/1529] .azurepipelines: Add LoongArch64 architecture on LoongArch64 EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 architecture on LoongArch64 EDK2 CI. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .azurepipelines/Ubuntu-GCC5.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml index 3760c6efe1..1acd8d2a46 100644 --- a/.azurepipelines/Ubuntu-GCC5.yml +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -3,6 +3,7 @@ # # Copyright (c) Microsoft Corporation. # Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## trigger: @@ -17,5 +18,5 @@ jobs: parameters: tool_chain_tag: 'GCC5' vm_image: 'ubuntu-latest' - arch_list: "IA32,X64,ARM,AARCH64,RISCV64" + arch_list: "IA32,X64,ARM,AARCH64,RISCV64,LOONGARCH64" From 3ecc47903c6be614b4ba2362ec09a3f8f656e126 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Mon, 15 Nov 2021 17:59:53 +0800 Subject: [PATCH 0148/1529] .pytool: Add LoongArch64 architecture on LoongArch64 EDK2 CI. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 architecture on LoongArch64 EDK2 CI testing. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 0c8320b1a3..cc2214071c 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -84,7 +84,8 @@ def GetArchitecturesSupported(self): "X64", "ARM", "AARCH64", - "RISCV64") + "RISCV64", + "LOONGARCH64") def GetTargetsSupported(self): ''' return iterable of edk2 target tags supported by this build ''' @@ -175,6 +176,8 @@ def GetActiveScopes(self): scopes += ("gcc_arm_linux",) if "RISCV64" in self.ActualArchitectures: scopes += ("gcc_riscv64_unknown",) + if "LOONGARCH64" in self.ActualArchitectures: + scopes += ("gcc_loongarch64_unknown_linux",) self.ActualScopes = scopes return self.ActualScopes From 5643f0fd1fe2aaa55b9edb820230aceb4c2f067c Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 19 Nov 2021 18:06:06 +0800 Subject: [PATCH 0149/1529] MdePkg: Add LoongArch LOONGARCH64 binding REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LOONGARCH64 sections in MdePkg.dec and LOONGARCH64 ProcessorBind.h Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Co-authored-by: Dongyan Qian Reviewed-by: Michael D Kinney --- MdePkg/Include/LoongArch64/ProcessorBind.h | 120 +++++++++++++++++++++ MdePkg/MdePkg.dec | 4 + MdePkg/MdePkg.dsc | 3 +- 3 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 MdePkg/Include/LoongArch64/ProcessorBind.h diff --git a/MdePkg/Include/LoongArch64/ProcessorBind.h b/MdePkg/Include/LoongArch64/ProcessorBind.h new file mode 100644 index 0000000000..502d479099 --- /dev/null +++ b/MdePkg/Include/LoongArch64/ProcessorBind.h @@ -0,0 +1,120 @@ +/** @file + Processor or Compiler specific defines and types for LoongArch + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef PROCESSOR_BIND_H_ +#define PROCESSOR_BIND_H_ + +// +// Define the processor type so other code can make processor based choices +// +#define MDE_CPU_LOONGARCH64 + +#define EFIAPI + +// +// Make sure we are using the correct packing rules per EFI specification +// +#ifndef __GNUC__ + #pragma pack() +#endif + +// +// Assume standard LoongArch 64-bit alignment. +// Need to check portability of long long +// +typedef unsigned long UINT64; +typedef long INT64; +typedef unsigned int UINT32; +typedef int INT32; +typedef unsigned short UINT16; +typedef unsigned short CHAR16; +typedef short INT16; +typedef unsigned char BOOLEAN; +typedef unsigned char UINT8; +typedef char CHAR8; +typedef char INT8; + +// +// Unsigned value of native width. (4 bytes on supported 32-bit processor instructions, +// 8 bytes on supported 64-bit processor instructions) +// + +typedef UINT64 UINTN; + +// +// Signed value of native width. (4 bytes on supported 32-bit processor instructions, +// 8 bytes on supported 64-bit processor instructions) +// +typedef INT64 INTN; + +// +// Processor specific defines +// + +// +// A value of native width with the highest bit set. +// +#define MAX_BIT 0x8000000000000000ULL +// +// A value of native width with the two highest bits set. +// +#define MAX_2_BITS 0xC000000000000000ULL + +// +// Maximum legal LoongArch 64-bit address +// +#define MAX_ADDRESS 0xFFFFFFFFFFFFFFFFULL + +// +// Maximum usable address at boot time (48 bits using 4KB pages) +// +#define MAX_ALLOC_ADDRESS 0xFFFFFFFFFFFFULL + +// +// Maximum legal LoongArch 64-bit INTN and UINTN values. +// +#define MAX_INTN ((INTN)0x7FFFFFFFFFFFFFFFULL) +#define MAX_UINTN ((UINTN)0xFFFFFFFFFFFFFFFFULL) + +// +// Page allocation granularity for LoongArch +// +#define DEFAULT_PAGE_ALLOCATION_GRANULARITY (0x1000) +#define RUNTIME_PAGE_ALLOCATION_GRANULARITY (0x10000) + +#if defined (__GNUC__) +// +// For GNU assembly code, .global or .globl can declare global symbols. +// Define this macro to unify the usage. +// +#define ASM_GLOBAL .globl +#endif + +// +// The stack alignment required for LoongArch +// +#define CPU_STACK_ALIGNMENT 16 + +/** + Return the pointer to the first instruction of a function given a function pointer. + On LOONGARCH CPU architectures, these two pointer values are the same, + so the implementation of this macro is very simple. + + @param FunctionPointer A pointer to a function. + + @return The pointer to the first instruction of a function given a function pointer. + +**/ +#define FUNCTION_ENTRY_POINT(FunctionPointer) (VOID *)(UINTN)(FunctionPointer) + +#ifndef __USER_LABEL_PREFIX__ +#define __USER_LABEL_PREFIX__ +#endif + +#endif diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index f1ebf9e251..4c81cbd75a 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -7,6 +7,7 @@ # Copyright (c) 2007 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# (C) Copyright 2016 - 2021 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -43,6 +44,9 @@ [Includes.RISCV64] Include/RiscV64 +[Includes.LOONGARCH64] + Include/LoongArch64 + [LibraryClasses] ## @libraryclass Provides most usb APIs to support the Hid requests defined in Usb Hid 1.1 spec # and the standard requests defined in Usb 1.1 spec. diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index cc1ac196a9..493a13ec91 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -4,6 +4,7 @@ # Copyright (c) 2007 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -15,7 +16,7 @@ PLATFORM_VERSION = 1.08 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/Mde - SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64 + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT From 4c187264a86aacb8def4f5a735e4e13a92f61636 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 6 Sep 2022 15:53:36 +0800 Subject: [PATCH 0150/1529] MdePkg/Include: LoongArch definitions. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch processor related definitions. For the Http boot and PXE boot types seeing this URL section "Processor Architecture Type" for the LOONGARCH values: https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml For definitions of PE/COFF and LOONGARCH relocation types, see the "Machine Types" and "Basic Relocation Types" sections of this URL for LOONGARCH values: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format For the register definitions of exceptions context, see the UEFI V2.10 18.2.2, 18.2.4 and 18.2.5 sections of this URL for LOONGARCH definitions: https://uefi.org/specs/UEFI/2.10/18_Protocols_Debugger_Support.html Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/PeImage.h | 9 ++ MdePkg/Include/Protocol/DebugSupport.h | 107 ++++++++++++++++++++-- MdePkg/Include/Protocol/PxeBaseCode.h | 3 + MdePkg/Include/Uefi/UefiBaseType.h | 14 +++ MdePkg/Include/Uefi/UefiSpec.h | 16 ++-- 5 files changed, 136 insertions(+), 13 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/PeImage.h b/MdePkg/Include/IndustryStandard/PeImage.h index 3109dc20f8..dd4cc25483 100644 --- a/MdePkg/Include/IndustryStandard/PeImage.h +++ b/MdePkg/Include/IndustryStandard/PeImage.h @@ -10,6 +10,7 @@ Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
Portions Copyright (c) 2016 - 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -38,6 +39,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define IMAGE_FILE_MACHINE_RISCV32 0x5032 #define IMAGE_FILE_MACHINE_RISCV64 0x5064 #define IMAGE_FILE_MACHINE_RISCV128 0x5128 +#define IMAGE_FILE_MACHINE_LOONGARCH32 0x6232 +#define IMAGE_FILE_MACHINE_LOONGARCH64 0x6264 // // EXE file formats @@ -503,6 +506,12 @@ typedef struct { #define EFI_IMAGE_REL_BASED_RISCV_LOW12I 7 #define EFI_IMAGE_REL_BASED_RISCV_LOW12S 8 +// +// Relocation types of LoongArch processor. +// +#define EFI_IMAGE_REL_BASED_LOONGARCH32_MARK_LA 8 +#define EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA 8 + /// /// Line number format. /// diff --git a/MdePkg/Include/Protocol/DebugSupport.h b/MdePkg/Include/Protocol/DebugSupport.h index ec5b92a5c5..2b0ae2d157 100644 --- a/MdePkg/Include/Protocol/DebugSupport.h +++ b/MdePkg/Include/Protocol/DebugSupport.h @@ -654,17 +654,110 @@ typedef struct { UINT64 X31; } EFI_SYSTEM_CONTEXT_RISCV64; +// +// LoongArch processor exception types. +// +#define EXCEPT_LOONGARCH_INT 0 +#define EXCEPT_LOONGARCH_PIL 1 +#define EXCEPT_LOONGARCH_PIS 2 +#define EXCEPT_LOONGARCH_PIF 3 +#define EXCEPT_LOONGARCH_PME 4 +#define EXCEPT_LOONGARCH_PNR 5 +#define EXCEPT_LOONGARCH_PNX 6 +#define EXCEPT_LOONGARCH_PPI 7 +#define EXCEPT_LOONGARCH_ADE 8 +#define EXCEPT_LOONGARCH_ALE 9 +#define EXCEPT_LOONGARCH_BCE 10 +#define EXCEPT_LOONGARCH_SYS 11 +#define EXCEPT_LOONGARCH_BRK 12 +#define EXCEPT_LOONGARCH_INE 13 +#define EXCEPT_LOONGARCH_IPE 14 +#define EXCEPT_LOONGARCH_FPD 15 +#define EXCEPT_LOONGARCH_SXD 16 +#define EXCEPT_LOONGARCH_ASXD 17 +#define EXCEPT_LOONGARCH_FPE 18 +#define EXCEPT_LOONGARCH_TBR 64 // For code only, there is no such type in the ISA spec, the TLB refill is defined for an independent exception. + +// +// LoongArch processor Interrupt types. +// +#define EXCEPT_LOONGARCH_INT_SIP0 0 +#define EXCEPT_LOONGARCH_INT_SIP1 1 +#define EXCEPT_LOONGARCH_INT_IP0 2 +#define EXCEPT_LOONGARCH_INT_IP1 3 +#define EXCEPT_LOONGARCH_INT_IP2 4 +#define EXCEPT_LOONGARCH_INT_IP3 5 +#define EXCEPT_LOONGARCH_INT_IP4 6 +#define EXCEPT_LOONGARCH_INT_IP5 7 +#define EXCEPT_LOONGARCH_INT_IP6 8 +#define EXCEPT_LOONGARCH_INT_IP7 9 +#define EXCEPT_LOONGARCH_INT_PMC 10 +#define EXCEPT_LOONGARCH_INT_TIMER 11 +#define EXCEPT_LOONGARCH_INT_IPI 12 + +// +// For coding convenience, define the maximum valid +// LoongArch interrupt. +// +#define MAX_LOONGARCH_INTERRUPT 14 + +typedef struct { + UINT64 R0; + UINT64 R1; + UINT64 R2; + UINT64 R3; + UINT64 R4; + UINT64 R5; + UINT64 R6; + UINT64 R7; + UINT64 R8; + UINT64 R9; + UINT64 R10; + UINT64 R11; + UINT64 R12; + UINT64 R13; + UINT64 R14; + UINT64 R15; + UINT64 R16; + UINT64 R17; + UINT64 R18; + UINT64 R19; + UINT64 R20; + UINT64 R21; + UINT64 R22; + UINT64 R23; + UINT64 R24; + UINT64 R25; + UINT64 R26; + UINT64 R27; + UINT64 R28; + UINT64 R29; + UINT64 R30; + UINT64 R31; + + UINT64 CRMD; // CuRrent MoDe information + UINT64 PRMD; // PRe-exception MoDe information + UINT64 EUEN; // Extended component Unit ENable + UINT64 MISC; // MISCellaneous controller + UINT64 ECFG; // Exception ConFiGuration + UINT64 ESTAT; // Exception STATus + UINT64 ERA; // Exception Return Address + UINT64 BADV; // BAD Virtual address + UINT64 BADI; // BAD Instruction +} EFI_SYSTEM_CONTEXT_LOONGARCH64; + /// /// Universal EFI_SYSTEM_CONTEXT definition. /// typedef union { - EFI_SYSTEM_CONTEXT_EBC *SystemContextEbc; - EFI_SYSTEM_CONTEXT_IA32 *SystemContextIa32; - EFI_SYSTEM_CONTEXT_X64 *SystemContextX64; - EFI_SYSTEM_CONTEXT_IPF *SystemContextIpf; - EFI_SYSTEM_CONTEXT_ARM *SystemContextArm; - EFI_SYSTEM_CONTEXT_AARCH64 *SystemContextAArch64; - EFI_SYSTEM_CONTEXT_RISCV64 *SystemContextRiscV64; + EFI_SYSTEM_CONTEXT_EBC *SystemContextEbc; + EFI_SYSTEM_CONTEXT_IA32 *SystemContextIa32; + EFI_SYSTEM_CONTEXT_X64 *SystemContextX64; + EFI_SYSTEM_CONTEXT_IPF *SystemContextIpf; + EFI_SYSTEM_CONTEXT_ARM *SystemContextArm; + EFI_SYSTEM_CONTEXT_AARCH64 *SystemContextAArch64; + EFI_SYSTEM_CONTEXT_RISCV64 *SystemContextRiscV64; + EFI_SYSTEM_CONTEXT_LOONGARCH64 *SystemContextLoongArch64; } EFI_SYSTEM_CONTEXT; // diff --git a/MdePkg/Include/Protocol/PxeBaseCode.h b/MdePkg/Include/Protocol/PxeBaseCode.h index 11872d602d..6787941a5d 100644 --- a/MdePkg/Include/Protocol/PxeBaseCode.h +++ b/MdePkg/Include/Protocol/PxeBaseCode.h @@ -4,6 +4,7 @@ Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -158,6 +159,8 @@ typedef UINT16 EFI_PXE_BASE_CODE_UDP_PORT; #define EFI_PXE_CLIENT_SYSTEM_ARCHITECTURE 0x000B #elif defined (MDE_CPU_RISCV64) #define EFI_PXE_CLIENT_SYSTEM_ARCHITECTURE 0x001B +#elif defined (MDE_CPU_LOONGARCH64) +#define EFI_PXE_CLIENT_SYSTEM_ARCHITECTURE 0x0027 #endif /// diff --git a/MdePkg/Include/Uefi/UefiBaseType.h b/MdePkg/Include/Uefi/UefiBaseType.h index 4a34ce8e25..83975a08eb 100644 --- a/MdePkg/Include/Uefi/UefiBaseType.h +++ b/MdePkg/Include/Uefi/UefiBaseType.h @@ -4,6 +4,7 @@ Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
Portions copyright (c) 2011 - 2016, ARM Ltd. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -246,6 +247,12 @@ typedef union { #define EFI_IMAGE_MACHINE_RISCV64 0x5064 #define EFI_IMAGE_MACHINE_RISCV128 0x5128 +/// +/// PE32+ Machine type for LoongArch 32/64 images. +/// +#define EFI_IMAGE_MACHINE_LOONGARCH32 0x6232 +#define EFI_IMAGE_MACHINE_LOONGARCH64 0x6264 + #if !defined (EFI_IMAGE_MACHINE_TYPE_VALUE) && !defined (EFI_IMAGE_MACHINE_CROSS_TYPE_VALUE) #if defined (MDE_CPU_IA32) @@ -278,6 +285,13 @@ typedef union { #define EFI_IMAGE_MACHINE_TYPE_SUPPORTED(Machine) \ ((Machine) == EFI_IMAGE_MACHINE_RISCV64) +#define EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED(Machine) (FALSE) + + #elif defined (MDE_CPU_LOONGARCH64) + +#define EFI_IMAGE_MACHINE_TYPE_SUPPORTED(Machine) \ + ((Machine) == EFI_IMAGE_MACHINE_LOONGARCH64) + #define EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED(Machine) (FALSE) #elif defined (MDE_CPU_EBC) diff --git a/MdePkg/Include/Uefi/UefiSpec.h b/MdePkg/Include/Uefi/UefiSpec.h index 2b38b100f6..3abebbb8d9 100644 --- a/MdePkg/Include/Uefi/UefiSpec.h +++ b/MdePkg/Include/Uefi/UefiSpec.h @@ -7,6 +7,7 @@ Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -2195,12 +2196,13 @@ typedef struct { // // EFI File location to boot from on removable media devices // -#define EFI_REMOVABLE_MEDIA_FILE_NAME_IA32 L"\\EFI\\BOOT\\BOOTIA32.EFI" -#define EFI_REMOVABLE_MEDIA_FILE_NAME_IA64 L"\\EFI\\BOOT\\BOOTIA64.EFI" -#define EFI_REMOVABLE_MEDIA_FILE_NAME_X64 L"\\EFI\\BOOT\\BOOTX64.EFI" -#define EFI_REMOVABLE_MEDIA_FILE_NAME_ARM L"\\EFI\\BOOT\\BOOTARM.EFI" -#define EFI_REMOVABLE_MEDIA_FILE_NAME_AARCH64 L"\\EFI\\BOOT\\BOOTAA64.EFI" -#define EFI_REMOVABLE_MEDIA_FILE_NAME_RISCV64 L"\\EFI\\BOOT\\BOOTRISCV64.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_IA32 L"\\EFI\\BOOT\\BOOTIA32.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_IA64 L"\\EFI\\BOOT\\BOOTIA64.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_X64 L"\\EFI\\BOOT\\BOOTX64.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_ARM L"\\EFI\\BOOT\\BOOTARM.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_AARCH64 L"\\EFI\\BOOT\\BOOTAA64.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_RISCV64 L"\\EFI\\BOOT\\BOOTRISCV64.EFI" +#define EFI_REMOVABLE_MEDIA_FILE_NAME_LOONGARCH64 L"\\EFI\\BOOT\\BOOTLOONGARCH64.EFI" #if !defined (EFI_REMOVABLE_MEDIA_FILE_NAME) #if defined (MDE_CPU_IA32) @@ -2214,6 +2216,8 @@ typedef struct { #define EFI_REMOVABLE_MEDIA_FILE_NAME EFI_REMOVABLE_MEDIA_FILE_NAME_AARCH64 #elif defined (MDE_CPU_RISCV64) #define EFI_REMOVABLE_MEDIA_FILE_NAME EFI_REMOVABLE_MEDIA_FILE_NAME_RISCV64 + #elif defined (MDE_CPU_LOONGARCH64) +#define EFI_REMOVABLE_MEDIA_FILE_NAME EFI_REMOVABLE_MEDIA_FILE_NAME_LOONGARCH64 #else #error Unknown Processor Type #endif From f49697486f0c269287e2a186c24cff46137e3599 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Wed, 14 Sep 2022 10:29:15 +0800 Subject: [PATCH 0151/1529] MdePkg/BaseLib: BaseLib for LOONGARCH64 architecture. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch LOONGARCH64 BaseLib functions. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Michael D Kinney --- MdePkg/Include/Library/BaseLib.h | 24 ++++++++ MdePkg/Library/BaseLib/BaseLib.inf | 16 ++++- MdePkg/Library/BaseLib/LoongArch64/Barrier.S | 28 +++++++++ .../BaseLib/LoongArch64/CpuBreakpoint.S | 24 ++++++++ MdePkg/Library/BaseLib/LoongArch64/CpuPause.S | 31 ++++++++++ .../BaseLib/LoongArch64/DisableInterrupts.S | 21 +++++++ .../BaseLib/LoongArch64/EnableInterrupts.S | 21 +++++++ .../BaseLib/LoongArch64/GetInterruptState.S | 35 +++++++++++ .../BaseLib/LoongArch64/InternalSwitchStack.c | 58 +++++++++++++++++++ .../Library/BaseLib/LoongArch64/MemoryFence.S | 18 ++++++ .../BaseLib/LoongArch64/SetJumpLongJump.S | 49 ++++++++++++++++ .../Library/BaseLib/LoongArch64/SwitchStack.S | 39 +++++++++++++ 12 files changed, 363 insertions(+), 1 deletion(-) create mode 100644 MdePkg/Library/BaseLib/LoongArch64/Barrier.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/CpuPause.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c create mode 100644 MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S create mode 100644 MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h index a6f9a194ef..f3f59f21c2 100644 --- a/MdePkg/Include/Library/BaseLib.h +++ b/MdePkg/Include/Library/BaseLib.h @@ -6,6 +6,7 @@ Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
Copyright (c) Microsoft Corporation.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -152,6 +153,29 @@ typedef struct { #endif // defined (MDE_CPU_RISCV64) +#if defined (MDE_CPU_LOONGARCH64) +/// +/// The LoongArch architecture context buffer used by SetJump() and LongJump() +/// +typedef struct { + UINT64 S0; + UINT64 S1; + UINT64 S2; + UINT64 S3; + UINT64 S4; + UINT64 S5; + UINT64 S6; + UINT64 S7; + UINT64 S8; + UINT64 SP; + UINT64 FP; + UINT64 RA; +} BASE_LIBRARY_JUMP_BUFFER; + +#define BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT 8 + +#endif // defined (MDE_CPU_LOONGARCH64) + // // String Services // diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf index 6be5be9428..9ed46a584a 100644 --- a/MdePkg/Library/BaseLib/BaseLib.inf +++ b/MdePkg/Library/BaseLib/BaseLib.inf @@ -21,7 +21,7 @@ LIBRARY_CLASS = BaseLib # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] @@ -402,6 +402,20 @@ RiscV64/RiscVInterrupt.S | GCC RiscV64/FlushCache.S | GCC +[Sources.LOONGARCH64] + Math64.c + Unaligned.c + LoongArch64/InternalSwitchStack.c + LoongArch64/GetInterruptState.S | GCC + LoongArch64/EnableInterrupts.S | GCC + LoongArch64/DisableInterrupts.S | GCC + LoongArch64/Barrier.S | GCC + LoongArch64/MemoryFence.S | GCC + LoongArch64/CpuBreakpoint.S | GCC + LoongArch64/CpuPause.S | GCC + LoongArch64/SetJumpLongJump.S | GCC + LoongArch64/SwitchStack.S | GCC + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BaseLib/LoongArch64/Barrier.S b/MdePkg/Library/BaseLib/LoongArch64/Barrier.S new file mode 100644 index 0000000000..d07da1e4e1 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/Barrier.S @@ -0,0 +1,28 @@ +#------------------------------------------------------------------------------ +# +# LoongArch Barrier Operations +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(AsmDataBarrierLoongArch) +ASM_GLOBAL ASM_PFX(AsmInstructionBarrierLoongArch) + +# +# Data barrier operation for LoongArch. +# +ASM_PFX(AsmDataBarrierLoongArch): + dbar 0 + jirl $zero, $ra, 0 + +# +# Instruction barrier operation for LoongArch. +# +ASM_PFX(AsmInstructionBarrierLoongArch): + ibar 0 + jirl $zero, $ra, 0 + + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S b/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S new file mode 100644 index 0000000000..4e022e9bb5 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S @@ -0,0 +1,24 @@ +#------------------------------------------------------------------------------ +# +# CpuBreakpoint for LoongArch +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(CpuBreakpoint) + +#/** +# Generates a breakpoint on the CPU. +# +# Generates a breakpoint on the CPU. The breakpoint must be implemented such +# that code can resume normal execution after the breakpoint. +# +#**/ + +ASM_PFX(CpuBreakpoint): + break 3 + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S b/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S new file mode 100644 index 0000000000..e9140e8742 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S @@ -0,0 +1,31 @@ +#------------------------------------------------------------------------------ +# +# CpuPause for LoongArch +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(CpuPause) + +#/** +# Requests CPU to pause for a short period of time. +# +# Requests CPU to pause for a short period of time. Typically used in MP +# systems to prevent memory starvation while waiting for a spin lock. +# +#**/ + +ASM_PFX(CpuPause): + nop + nop + nop + nop + nop + nop + nop + nop + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S b/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S new file mode 100644 index 0000000000..0f228339af --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S @@ -0,0 +1,21 @@ +#------------------------------------------------------------------------------ +# +# LoongArch interrupt disable +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(DisableInterrupts) + +#/** +# Disables CPU interrupts. +#**/ + +ASM_PFX(DisableInterrupts): + li.w $t0, 0x4 + csrxchg $zero, $t0, 0x0 + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S b/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S new file mode 100644 index 0000000000..3c34fb2cdd --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S @@ -0,0 +1,21 @@ +#------------------------------------------------------------------------------ +# +# LoongArch interrupt enable +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(EnableInterrupts) + +#/** +# Enables CPU interrupts. +#**/ + +ASM_PFX(EnableInterrupts): + li.w $t0, 0x4 + csrxchg $t0, $t0, 0x0 + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S b/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S new file mode 100644 index 0000000000..bfd1f2d5f7 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S @@ -0,0 +1,35 @@ +#------------------------------------------------------------------------------ +# +# Get LoongArch interrupt status +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(GetInterruptState) + +#/** +# Retrieves the current CPU interrupt state. +# +# Returns TRUE means interrupts are currently enabled. Otherwise, +# returns FALSE. +# +# @retval TRUE CPU interrupts are enabled. +# @retval FALSE CPU interrupts are disabled. +# +#**/ + +ASM_PFX(GetInterruptState): + li.w $t1, 0x4 + csrrd $t0, 0x0 + and $t0, $t0, $t1 + beqz $t0, 1f + li.w $a0, 0x1 + b 2f +1: + li.w $a0, 0x0 +2: + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c b/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c new file mode 100644 index 0000000000..859bc96329 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c @@ -0,0 +1,58 @@ +/** @file + SwitchStack() function for LoongArch. + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include "BaseLibInternals.h" + +UINTN +EFIAPI +InternalSwitchStackAsm ( + IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer + ); + +/** + Transfers control to a function starting with a new stack. + + Transfers control to the function specified by EntryPoint using the + new stack specified by NewStack and passing in the parameters specified + by Context1 and Context2. Context1 and Context2 are optional and may + be NULL. The function EntryPoint must never return. + + If EntryPoint is NULL, then ASSERT(). + If NewStack is NULL, then ASSERT(). + + @param[in] EntryPoint A pointer to function to call with the new stack. + @param[in] Context1 A pointer to the context to pass into the EntryPoint + function. + @param[in] Context2 A pointer to the context to pass into the EntryPoint + function. + @param[in] NewStack A pointer to the new stack to use for the EntryPoint + function. + @param[in] Marker VA_LIST marker for the variable argument list. + +**/ +VOID +EFIAPI +InternalSwitchStack ( + IN SWITCH_STACK_ENTRY_POINT EntryPoint, + IN VOID *Context1 OPTIONAL, + IN VOID *Context2 OPTIONAL, + IN VOID *NewStack, + IN VA_LIST Marker + ) + +{ + BASE_LIBRARY_JUMP_BUFFER JumpBuffer; + + JumpBuffer.RA = (UINTN)EntryPoint; + JumpBuffer.SP = (UINTN)NewStack - sizeof (VOID *); + JumpBuffer.SP -= sizeof (Context1) + sizeof (Context2); + ((VOID **)(UINTN)JumpBuffer.SP)[0] = Context1; + ((VOID **)(UINTN)JumpBuffer.SP)[1] = Context2; + + InternalSwitchStackAsm (&JumpBuffer); +} diff --git a/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S b/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S new file mode 100644 index 0000000000..2b3d34366f --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S @@ -0,0 +1,18 @@ +#------------------------------------------------------------------------------ +# +# MemoryFence() for LoongArch +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(MemoryFence) + +# +# Memory fence for LoongArch +# +ASM_PFX(MemoryFence): + b AsmDataBarrierLoongArch + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S b/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S new file mode 100644 index 0000000000..1c6ee54b6f --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S @@ -0,0 +1,49 @@ +#------------------------------------------------------------------------------ +# +# Set/Long jump for LoongArch +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +#define STORE st.d /* 64 bit mode regsave instruction */ +#define LOAD ld.d /* 64 bit mode regload instruction */ +#define RSIZE 8 /* 64 bit mode register size */ + +ASM_GLOBAL ASM_PFX(SetJump) +ASM_GLOBAL ASM_PFX(InternalLongJump) + +ASM_PFX(SetJump): + STORE $s0, $a0, RSIZE * 0 + STORE $s1, $a0, RSIZE * 1 + STORE $s2, $a0, RSIZE * 2 + STORE $s3, $a0, RSIZE * 3 + STORE $s4, $a0, RSIZE * 4 + STORE $s5, $a0, RSIZE * 5 + STORE $s6, $a0, RSIZE * 6 + STORE $s7, $a0, RSIZE * 7 + STORE $s8, $a0, RSIZE * 8 + STORE $sp, $a0, RSIZE * 9 + STORE $fp, $a0, RSIZE * 10 + STORE $ra, $a0, RSIZE * 11 + li.w $a0, 0 # Setjmp return + jirl $zero, $ra, 0 + +ASM_PFX(InternalLongJump): + LOAD $ra, $a0, RSIZE * 11 + LOAD $s0, $a0, RSIZE * 0 + LOAD $s1, $a0, RSIZE * 1 + LOAD $s2, $a0, RSIZE * 2 + LOAD $s3, $a0, RSIZE * 3 + LOAD $s4, $a0, RSIZE * 4 + LOAD $s5, $a0, RSIZE * 5 + LOAD $s6, $a0, RSIZE * 6 + LOAD $s7, $a0, RSIZE * 7 + LOAD $s8, $a0, RSIZE * 8 + LOAD $sp, $a0, RSIZE * 9 + LOAD $fp, $a0, RSIZE * 10 + move $a0, $a1 + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S b/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S new file mode 100644 index 0000000000..ad9aa8b343 --- /dev/null +++ b/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S @@ -0,0 +1,39 @@ +#------------------------------------------------------------------------------ +# +# InternalSwitchStackAsm for LoongArch +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +#define STORE st.d /* 64 bit mode regsave instruction */ +#define LOAD ld.d /* 64 bit mode regload instruction */ +#define RSIZE 8 /* 64 bit mode register size */ + +ASM_GLOBAL ASM_PFX(InternalSwitchStackAsm) + +/** + This allows the caller to switch the stack and goes to the new entry point + + @param JumpBuffer A pointer to CPU context buffer. +**/ + +ASM_PFX(InternalSwitchStackAsm): + LOAD $ra, $a0, RSIZE * 11 + LOAD $s0, $a0, RSIZE * 0 + LOAD $s1, $a0, RSIZE * 1 + LOAD $s2, $a0, RSIZE * 2 + LOAD $s3, $a0, RSIZE * 3 + LOAD $s4, $a0, RSIZE * 4 + LOAD $s5, $a0, RSIZE * 5 + LOAD $s6, $a0, RSIZE * 6 + LOAD $s7, $a0, RSIZE * 7 + LOAD $s8, $a0, RSIZE * 8 + LOAD $sp, $a0, RSIZE * 9 + LOAD $fp, $a0, RSIZE * 10 + LOAD $a0, $sp, 0 + LOAD $a1, $sp, 8 + jirl $zero, $ra, 0 + .end From 4fe2971f6245ec07431b40ef64e4ec05d787e2ed Mon Sep 17 00:00:00 2001 From: Chao Li Date: Wed, 14 Sep 2022 11:03:27 +0800 Subject: [PATCH 0152/1529] MdePkg/BaseCacheMaintenanceLib: LoongArch cache maintenance implementation. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Implement LoongArch cache maintenance functions in BaseCacheMaintenanceLib. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .../BaseCacheMaintenanceLib.inf | 6 +- .../BaseCacheMaintenanceLib/LoongArchCache.c | 254 ++++++++++++++++++ 2 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c diff --git a/MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf b/MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf index 33114243d5..6fd9cbe5f6 100644 --- a/MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf +++ b/MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf @@ -7,6 +7,7 @@ # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -24,7 +25,7 @@ # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources.IA32] @@ -45,6 +46,9 @@ [Sources.RISCV64] RiscVCache.c +[Sources.LOONGARCH64] + LoongArchCache.c + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c b/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c new file mode 100644 index 0000000000..4c8773278c --- /dev/null +++ b/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c @@ -0,0 +1,254 @@ +/** @file + Cache Maintenance Functions for LoongArch. + LoongArch cache maintenance functions has not yet been completed, and will added in later. + Functions are null functions now. + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +// +// Include common header file for this module. +// +#include +#include +#include + +/** + LoongArch data barrier operation. +**/ +VOID +EFIAPI +AsmDataBarrierLoongArch ( + VOID + ); + +/** + LoongArch instruction barrier operation. +**/ +VOID +EFIAPI +AsmInstructionBarrierLoongArch ( + VOID + ); + +/** + Invalidates the entire instruction cache in cache coherency domain of the + calling CPU. + +**/ +VOID +EFIAPI +InvalidateInstructionCache ( + VOID + ) +{ + AsmInstructionBarrierLoongArch (); +} + +/** + Invalidates a range of instruction cache lines in the cache coherency domain + of the calling CPU. + + Invalidates the instruction cache lines specified by Address and Length. If + Address is not aligned on a cache line boundary, then entire instruction + cache line containing Address is invalidated. If Address + Length is not + aligned on a cache line boundary, then the entire instruction cache line + containing Address + Length -1 is invalidated. This function may choose to + invalidate the entire instruction cache if that is more efficient than + invalidating the specified range. If Length is 0, the no instruction cache + lines are invalidated. Address is returned. + + If Length is greater than (MAX_ADDRESS - Address + 1), then ASSERT(). + + @param[in] Address The base address of the instruction cache lines to + invalidate. If the CPU is in a physical addressing mode, then + Address is a physical address. If the CPU is in a virtual + addressing mode, then Address is a virtual address. + + @param[in] Length The number of bytes to invalidate from the instruction cache. + + @return Address. + +**/ +VOID * +EFIAPI +InvalidateInstructionCacheRange ( + IN VOID *Address, + IN UINTN Length + ) +{ + AsmInstructionBarrierLoongArch (); + return Address; +} + +/** + Writes Back and Invalidates the entire data cache in cache coherency domain + of the calling CPU. + + Writes Back and Invalidates the entire data cache in cache coherency domain + of the calling CPU. This function guarantees that all dirty cache lines are + written back to system memory, and also invalidates all the data cache lines + in the cache coherency domain of the calling CPU. + +**/ +VOID +EFIAPI +WriteBackInvalidateDataCache ( + VOID + ) +{ + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); +} + +/** + Writes Back and Invalidates a range of data cache lines in the cache + coherency domain of the calling CPU. + + Writes Back and Invalidate the data cache lines specified by Address and + Length. If Address is not aligned on a cache line boundary, then entire data + cache line containing Address is written back and invalidated. If Address + + Length is not aligned on a cache line boundary, then the entire data cache + line containing Address + Length -1 is written back and invalidated. This + function may choose to write back and invalidate the entire data cache if + that is more efficient than writing back and invalidating the specified + range. If Length is 0, the no data cache lines are written back and + invalidated. Address is returned. + + If Length is greater than (MAX_ADDRESS - Address + 1), then ASSERT(). + + @param[in] Address The base address of the data cache lines to write back and + invalidate. If the CPU is in a physical addressing mode, then + Address is a physical address. If the CPU is in a virtual + addressing mode, then Address is a virtual address. + @param[in] Length The number of bytes to write back and invalidate from the + data cache. + + @return Address of cache invalidation. + +**/ +VOID * +EFIAPI +WriteBackInvalidateDataCacheRange ( + IN VOID *Address, + IN UINTN Length + ) +{ + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); + return Address; +} + +/** + Writes Back the entire data cache in cache coherency domain of the calling + CPU. + + Writes Back the entire data cache in cache coherency domain of the calling + CPU. This function guarantees that all dirty cache lines are written back to + system memory. This function may also invalidate all the data cache lines in + the cache coherency domain of the calling CPU. + +**/ +VOID +EFIAPI +WriteBackDataCache ( + VOID + ) +{ + WriteBackInvalidateDataCache (); +} + +/** + Writes Back a range of data cache lines in the cache coherency domain of the + calling CPU. + + Writes Back the data cache lines specified by Address and Length. If Address + is not aligned on a cache line boundary, then entire data cache line + containing Address is written back. If Address + Length is not aligned on a + cache line boundary, then the entire data cache line containing Address + + Length -1 is written back. This function may choose to write back the entire + data cache if that is more efficient than writing back the specified range. + If Length is 0, the no data cache lines are written back. This function may + also invalidate all the data cache lines in the specified range of the cache + coherency domain of the calling CPU. Address is returned. + + If Length is greater than (MAX_ADDRESS - Address + 1), then ASSERT(). + + @param[in] Address The base address of the data cache lines to write back. If + the CPU is in a physical addressing mode, then Address is a + physical address. If the CPU is in a virtual addressing + mode, then Address is a virtual address. + @param[in] Length The number of bytes to write back from the data cache. + + @return Address of cache written in main memory. + +**/ +VOID * +EFIAPI +WriteBackDataCacheRange ( + IN VOID *Address, + IN UINTN Length + ) +{ + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); + return Address; +} + +/** + Invalidates the entire data cache in cache coherency domain of the calling + CPU. + + Invalidates the entire data cache in cache coherency domain of the calling + CPU. This function must be used with care because dirty cache lines are not + written back to system memory. It is typically used for cache diagnostics. If + the CPU does not support invalidation of the entire data cache, then a write + back and invalidate operation should be performed on the entire data cache. + +**/ +VOID +EFIAPI +InvalidateDataCache ( + VOID + ) +{ + AsmDataBarrierLoongArch (); +} + +/** + Invalidates a range of data cache lines in the cache coherency domain of the + calling CPU. + + Invalidates the data cache lines specified by Address and Length. If Address + is not aligned on a cache line boundary, then entire data cache line + containing Address is invalidated. If Address + Length is not aligned on a + cache line boundary, then the entire data cache line containing Address + + Length -1 is invalidated. This function must never invalidate any cache lines + outside the specified range. If Length is 0, the no data cache lines are + invalidated. Address is returned. This function must be used with care + because dirty cache lines are not written back to system memory. It is + typically used for cache diagnostics. If the CPU does not support + invalidation of a data cache range, then a write back and invalidate + operation should be performed on the data cache range. + + If Length is greater than (MAX_ADDRESS - Address + 1), then ASSERT(). + + @param[in] Address The base address of the data cache lines to invalidate. If + the CPU is in a physical addressing mode, then Address is a + physical address. If the CPU is in a virtual addressing mode, + then Address is a virtual address. + @param[in] Length The number of bytes to invalidate from the data cache. + + @return Address. + +**/ +VOID * +EFIAPI +InvalidateDataCacheRange ( + IN VOID *Address, + IN UINTN Length + ) +{ + AsmDataBarrierLoongArch (); + return Address; +} From 6eb66520f81625b71ec08d23c006797ce73a1ac7 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 11 Nov 2021 19:09:24 +0800 Subject: [PATCH 0153/1529] MdePkg/BaseIoLibIntrinsic: IoLibNoIo for LoongArch architecture. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 LoongArch MMIO library instance, use the IoLibNoIo. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .../Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf | 10 +++++++--- MdePkg/Library/BaseIoLibIntrinsic/IoLibNoIo.c | 3 ++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf index 27b15d9ae2..aeb072ee95 100644 --- a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf +++ b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf @@ -4,13 +4,14 @@ # I/O Library that uses compiler intrinsics to perform IN and OUT instructions # for IA-32 and x64. On IPF, I/O port requests are translated into MMIO requests. # MMIO requests are forwarded directly to memory. For EBC, I/O port requests -# ASSERT(). For ARM, AARCH64 and RISCV64, this I/O library only provides non I/O -# read and write. +# ASSERT(). For ARM, AARCH64, RISCV64 and LoongArch, this I/O library only provides +# non I/O read and write. # # Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Copyright (c) 2017, AMD Incorporated. All rights reserved.
# Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -27,7 +28,7 @@ # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] @@ -62,6 +63,9 @@ [Sources.RISCV64] IoLibNoIo.c +[Sources.LOONGARCH64] + IoLibNoIo.c + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibNoIo.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibNoIo.c index c71f45b22e..c51e5da39b 100644 --- a/MdePkg/Library/BaseIoLibIntrinsic/IoLibNoIo.c +++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibNoIo.c @@ -1,11 +1,12 @@ /** @file I/O library for non I/O read and write access (memory map I/O read and - write only) architecture, such as ARM and RISC-V processor. + write only) architecture, such as ARM, RISC-V and LoongArch processor. Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent From 0943dc6e9f566c8eb7fcbf79d7c2820baad6f8b2 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Mon, 29 Nov 2021 12:29:58 +0800 Subject: [PATCH 0154/1529] MdePkg/BasePeCoff: Add LoongArch PE/Coff related code. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch image relocation. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Michael D Kinney --- MdePkg/Library/BasePeCoffLib/BasePeCoff.c | 3 +- .../Library/BasePeCoffLib/BasePeCoffLib.inf | 5 + .../Library/BasePeCoffLib/BasePeCoffLib.uni | 2 + .../BasePeCoffLib/LoongArch/PeCoffLoaderEx.c | 137 ++++++++++++++++++ 4 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 MdePkg/Library/BasePeCoffLib/LoongArch/PeCoffLoaderEx.c diff --git a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c index 6d8d9faeb8..97a8aaf8c7 100644 --- a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c +++ b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c @@ -1,6 +1,6 @@ /** @file Base PE/COFF loader supports loading any PE32/PE32+ or TE image, but - only supports relocating IA32, x64, IPF, ARM, RISC-V and EBC images. + only supports relocating IA32, x64, IPF, ARM, RISC-V, LoongArch and EBC images. Caution: This file requires additional review when modified. This library will have external input - PE/COFF image. @@ -18,6 +18,7 @@ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf b/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf index 110b6d5a09..3b8b8eb191 100644 --- a/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf +++ b/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -4,6 +4,7 @@ # The IA32 version library support loading IA32, X64 and EBC PE/COFF images. # The X64 version library support loading IA32, X64 and EBC PE/COFF images. # The RISC-V version library support loading RISC-V images. +# The LoongArch version library support loading LoongArch images. # # Caution: This module requires additional review when modified. # This library will have external input - PE/COFF image. @@ -13,6 +14,7 @@ # Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -46,6 +48,9 @@ [Sources.RISCV64] RiscV/PeCoffLoaderEx.c +[Sources.LOONGARCH64] + LoongArch/PeCoffLoaderEx.c + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.uni b/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.uni index 55417029f2..1f731344e1 100644 --- a/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.uni +++ b/MdePkg/Library/BasePeCoffLib/BasePeCoffLib.uni @@ -5,6 +5,7 @@ // The IA32 version library support loading IA32, X64 and EBC PE/COFF images. // The X64 version library support loading IA32, X64 and EBC PE/COFF images. // The RISC-V version library support loading RISC-V32 and RISC-V64 PE/COFF images. +// The LoongArch version library support loading LoongArch32 and LoongArch64 PE/COFF images. // // Caution: This module requires additional review when modified. // This library will have external input - PE/COFF image. @@ -14,6 +15,7 @@ // Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
// Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
// Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+// Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
// // SPDX-License-Identifier: BSD-2-Clause-Patent // diff --git a/MdePkg/Library/BasePeCoffLib/LoongArch/PeCoffLoaderEx.c b/MdePkg/Library/BasePeCoffLib/LoongArch/PeCoffLoaderEx.c new file mode 100644 index 0000000000..417096f334 --- /dev/null +++ b/MdePkg/Library/BasePeCoffLib/LoongArch/PeCoffLoaderEx.c @@ -0,0 +1,137 @@ +/** @file + PE/Coff loader for LoongArch PE image + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include "BasePeCoffLibInternals.h" +#include + +/** + Performs an LoongArch specific relocation fixup and is a no-op on other + instruction sets. + + @param[in] Reloc Pointer to the relocation record. + @param[in, out] Fixup Pointer to the address to fix up. + @param[in, out] FixupData Pointer to a buffer to log the fixups. + @param[in] Adjust The offset to adjust the fixup. + + @return Status code. + +**/ +RETURN_STATUS +PeCoffLoaderRelocateImageEx ( + IN UINT16 *Reloc, + IN OUT CHAR8 *Fixup, + IN OUT CHAR8 **FixupData, + IN UINT64 Adjust + ) +{ + UINT8 RelocType; + UINT64 Value; + UINT64 Tmp1; + UINT64 Tmp2; + + RelocType = (*Reloc) >> 12; + Value = 0; + Tmp1 = 0; + Tmp2 = 0; + + switch (RelocType) { + case EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA: + // The next four instructions are used to load a 64 bit address, relocate all of them + Value = (*(UINT32 *)Fixup & 0x1ffffe0) << 7 | // lu12i.w 20bits from bit5 + (*((UINT32 *)Fixup + 1) & 0x3ffc00) >> 10; // ori 12bits from bit10 + Tmp1 = *((UINT32 *)Fixup + 2) & 0x1ffffe0; // lu32i.d 20bits from bit5 + Tmp2 = *((UINT32 *)Fixup + 3) & 0x3ffc00; // lu52i.d 12bits from bit10 + Value = Value | (Tmp1 << 27) | (Tmp2 << 42); + Value += Adjust; + + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x1ffffe0) | (((Value >> 12) & 0xfffff) << 5); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x3ffc00) | ((Value & 0xfff) << 10); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x1ffffe0) | (((Value >> 32) & 0xfffff) << 5); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + Fixup += sizeof (UINT32); + *(UINT32 *)Fixup = (*(UINT32 *)Fixup & ~0x3ffc00) | (((Value >> 52) & 0xfff) << 10); + if (*FixupData != NULL) { + *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32)); + *(UINT32 *)(*FixupData) = *(UINT32 *)Fixup; + *FixupData = *FixupData + sizeof (UINT32); + } + + break; + default: + return RETURN_UNSUPPORTED; + } + + return RETURN_SUCCESS; +} + +/** + Returns TRUE if the machine type of PE/COFF image is supported. Supported + does not mean the image can be executed it means the PE/COFF loader supports + loading and relocating of the image type. It's up to the caller to support + the entry point. + + @param[in] Machine Machine type from the PE Header. + + @return TRUE if this PE/COFF loader can load the image + +**/ +BOOLEAN +PeCoffLoaderImageFormatSupported ( + IN UINT16 Machine + ) +{ + if (Machine == IMAGE_FILE_MACHINE_LOONGARCH64) { + return TRUE; + } + + return FALSE; +} + +/** + Performs an LOONGARCH-based specific re-relocation fixup and is a no-op on other + instruction sets. This is used to re-relocated the image into the EFI virtual + space for runtime calls. + + @param[in] Reloc The pointer to the relocation record. + @param[in, out] Fixup The pointer to the address to fix up. + @param[in, out] FixupData The pointer to a buffer to log the fixups. + @param[in] Adjust The offset to adjust the fixup. + + @return Status code. + +**/ +RETURN_STATUS +PeHotRelocateImageEx ( + IN UINT16 *Reloc, + IN OUT CHAR8 *Fixup, + IN OUT CHAR8 **FixupData, + IN UINT64 Adjust + ) +{ + // To check + return PeCoffLoaderRelocateImageEx (Reloc, Fixup, FixupData, Adjust); +} From e097c794cabb1c2fab0608557c8d7c939a0876ce Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 11 Nov 2021 20:14:20 +0800 Subject: [PATCH 0155/1529] MdePkg/BaseCpuLib: LoongArch Base CPU library implementation. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Implement LoongArch CPU related functions in BaseCpuLib. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/Library/BaseCpuLib/BaseCpuLib.inf | 7 ++++++- MdePkg/Library/BaseCpuLib/BaseCpuLib.uni | 5 +++-- MdePkg/Library/BaseCpuLib/LoongArch/CpuFlushTlb.S | 15 +++++++++++++++ MdePkg/Library/BaseCpuLib/LoongArch/CpuSleep.S | 15 +++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 MdePkg/Library/BaseCpuLib/LoongArch/CpuFlushTlb.S create mode 100644 MdePkg/Library/BaseCpuLib/LoongArch/CpuSleep.S diff --git a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf index c4cd29a783..6b230f6e6d 100644 --- a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf +++ b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf @@ -8,6 +8,7 @@ # Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -25,7 +26,7 @@ # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources.IA32] @@ -61,6 +62,10 @@ [Sources.RISCV64] RiscV/Cpu.S +[Sources.LOONGARCH64] + LoongArch/CpuFlushTlb.S | GCC + LoongArch/CpuSleep.S | GCC + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BaseCpuLib/BaseCpuLib.uni b/MdePkg/Library/BaseCpuLib/BaseCpuLib.uni index 80dc495786..7c5c8dfb37 100644 --- a/MdePkg/Library/BaseCpuLib/BaseCpuLib.uni +++ b/MdePkg/Library/BaseCpuLib/BaseCpuLib.uni @@ -1,13 +1,14 @@ // /** @file // Instance of CPU Library for various architecture. // -// CPU Library implemented using ASM functions for IA-32, X64 and RISCV64, +// CPU Library implemented using ASM functions for IA-32, X64, RISCV64 and LoongArch64, // PAL CALLs for IPF, and empty functions for EBC. // // Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.
// Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
// Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
// Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+// Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
// // SPDX-License-Identifier: BSD-2-Clause-Patent // @@ -16,5 +17,5 @@ #string STR_MODULE_ABSTRACT #language en-US "Instance of CPU Library for various architectures" -#string STR_MODULE_DESCRIPTION #language en-US "CPU Library implemented using ASM functions for IA-32, X64 and RISCV64, PAL CALLs for IPF, and empty functions for EBC." +#string STR_MODULE_DESCRIPTION #language en-US "CPU Library implemented using ASM functions for IA-32, X64, RISCV64 and LoongArch64, PAL CALLs for IPF, and empty functions for EBC." diff --git a/MdePkg/Library/BaseCpuLib/LoongArch/CpuFlushTlb.S b/MdePkg/Library/BaseCpuLib/LoongArch/CpuFlushTlb.S new file mode 100644 index 0000000000..8b792f0a37 --- /dev/null +++ b/MdePkg/Library/BaseCpuLib/LoongArch/CpuFlushTlb.S @@ -0,0 +1,15 @@ +#------------------------------------------------------------------------------ +# +# CpuFlushTlb() for LoongArch64 +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ +ASM_GLOBAL ASM_PFX(CpuFlushTlb) + +ASM_PFX(CpuFlushTlb): + tlbflush + jirl $zero, $ra, 0 + .end diff --git a/MdePkg/Library/BaseCpuLib/LoongArch/CpuSleep.S b/MdePkg/Library/BaseCpuLib/LoongArch/CpuSleep.S new file mode 100644 index 0000000000..eb31b10714 --- /dev/null +++ b/MdePkg/Library/BaseCpuLib/LoongArch/CpuSleep.S @@ -0,0 +1,15 @@ +#------------------------------------------------------------------------------ +# +# CpuSleep() for LoongArch64 +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ +ASM_GLOBAL ASM_PFX(CpuSleep) + +ASM_PFX(CpuSleep): + idle 0 + jirl $zero, $ra, 0 + .end From fca27302f3f676a60ea6b74c5008845ac87f4d93 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Sat, 1 Oct 2022 07:38:07 +0800 Subject: [PATCH 0156/1529] MdePkg/BaseSynchronizationLib: LoongArch cache related code. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Support LoongArch cache related functions. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Michael D Kinney --- .../BaseSynchronizationLib.inf | 6 + .../LoongArch64/AsmSynchronization.S | 122 +++++++++ .../LoongArch64/Synchronization.c | 233 ++++++++++++++++++ 3 files changed, 361 insertions(+) create mode 100644 MdePkg/Library/BaseSynchronizationLib/LoongArch64/AsmSynchronization.S create mode 100644 MdePkg/Library/BaseSynchronizationLib/LoongArch64/Synchronization.c diff --git a/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf b/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf index 02ba12961a..dd66ec1d03 100755 --- a/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf +++ b/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf @@ -4,6 +4,7 @@ # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -82,6 +83,11 @@ Synchronization.c RiscV64/Synchronization.S +[Sources.LOONGARCH64] + Synchronization.c + LoongArch64/Synchronization.c | GCC + LoongArch64/AsmSynchronization.S | GCC + [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Library/BaseSynchronizationLib/LoongArch64/AsmSynchronization.S b/MdePkg/Library/BaseSynchronizationLib/LoongArch64/AsmSynchronization.S new file mode 100644 index 0000000000..fdd50c54b5 --- /dev/null +++ b/MdePkg/Library/BaseSynchronizationLib/LoongArch64/AsmSynchronization.S @@ -0,0 +1,122 @@ +#------------------------------------------------------------------------------ +# +# LoongArch synchronization ASM functions. +# +# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#------------------------------------------------------------------------------ + +ASM_GLOBAL ASM_PFX(AsmInternalSyncCompareExchange16) +ASM_GLOBAL ASM_PFX(AsmInternalSyncCompareExchange32) +ASM_GLOBAL ASM_PFX(AsmInternalSyncCompareExchange64) +ASM_GLOBAL ASM_PFX(AsmInternalSyncIncrement) +ASM_GLOBAL ASM_PFX(AsmInternalSyncDecrement) + +/** +UINT32 +EFIAPI +AsmInternalSyncCompareExchange16 ( + IN volatile UINT32 *Ptr32, + IN UINT64 Mask, + IN UINT64 LocalCompareValue, + IN UINT64 LocalExchangeValue + ) +**/ +ASM_PFX(AsmInternalSyncCompareExchange16): +1: + ll.w $t0, $a0, 0x0 + and $t1, $t0, $a1 + bne $t1, $a2, 2f + andn $t1, $t0, $a1 + or $t1, $t1, $a3 + sc.w $t1, $a0, 0x0 + beqz $t1, 1b + b 3f +2: + dbar 0 +3: + move $a0, $t0 + jirl $zero, $ra, 0 + +/** +UINT32 +EFIAPI +AsmInternalSyncCompareExchange32 ( + IN volatile UINT32 *Value, + IN UINT64 CompareValue, + IN UINT64 ExchangeValue + ) +**/ +ASM_PFX(AsmInternalSyncCompareExchange32): +1: + ll.w $t0, $a0, 0x0 + bne $t0, $a1, 2f + move $t0, $a2 + sc.w $t0, $a0, 0x0 + beqz $t0, 1b + b 3f +2: + dbar 0 +3: + move $a0, $t0 + jirl $zero, $ra, 0 + +/** +UINT64 +EFIAPI +AsmInternalSyncCompareExchange64 ( + IN volatile UINT64 *Value, + IN UINT64 CompareValue, + IN UINT64 ExchangeValue + ) +**/ +ASM_PFX(AsmInternalSyncCompareExchange64): +1: + ll.d $t0, $a0, 0x0 + bne $t0, $a1, 2f + move $t0, $a2 + sc.d $t0, $a0, 0x0 + beqz $t0, 1b + b 3f +2: + dbar 0 +3: + move $a0, $t0 + jirl $zero, $ra, 0 + +/** +UINT32 +EFIAPI +AsmInternalSyncIncrement ( + IN volatile UINT32 *Value + ) +**/ +ASM_PFX(AsmInternalSyncIncrement): + move $t0, $a0 + dbar 0 + ld.w $t1, $t0, 0x0 + li.w $t2, 1 + amadd.w $t1, $t2, $t0 + + ld.w $a0, $t0, 0x0 + jirl $zero, $ra, 0 + +/** +UINT32 +EFIAPI +AsmInternalSyncDecrement ( + IN volatile UINT32 *Value + ) +**/ +ASM_PFX(AsmInternalSyncDecrement): + move $t0, $a0 + dbar 0 + ld.w $t1, $t0, 0x0 + li.w $t2, -1 + amadd.w $t1, $t2, $t0 + + ld.w $a0, $t0, 0x0 + jirl $zero, $ra, 0 +.end diff --git a/MdePkg/Library/BaseSynchronizationLib/LoongArch64/Synchronization.c b/MdePkg/Library/BaseSynchronizationLib/LoongArch64/Synchronization.c new file mode 100644 index 0000000000..d696c8ce10 --- /dev/null +++ b/MdePkg/Library/BaseSynchronizationLib/LoongArch64/Synchronization.c @@ -0,0 +1,233 @@ +/** @file + LoongArch synchronization functions. + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +UINT32 +EFIAPI +AsmInternalSyncCompareExchange16 ( + IN volatile UINT32 *, + IN UINT64, + IN UINT64, + IN UINT64 + ); + +UINT32 +EFIAPI +AsmInternalSyncCompareExchange32 ( + IN volatile UINT32 *, + IN UINT64, + IN UINT64 + ); + +UINT64 +EFIAPI +AsmInternalSyncCompareExchange64 ( + IN volatile UINT64 *, + IN UINT64, + IN UINT64 + ); + +UINT32 +EFIAPI +AsmInternalSyncIncrement ( + IN volatile UINT32 * + ); + +UINT32 +EFIAPI +AsmInternalSyncDecrement ( + IN volatile UINT32 * + ); + +/** + Performs an atomic compare exchange operation on a 16-bit + unsigned integer. + + Performs an atomic compare exchange operation on the 16-bit + unsigned integer specified by Value. If Value is equal to + CompareValue, then Value is set to ExchangeValue and + CompareValue is returned. If Value is not equal to + CompareValue, then Value is returned. The compare exchange + operation must be performed using MP safe mechanisms. + + @param[in] Value A pointer to the 16-bit value for the + compare exchange operation. + @param[in] CompareValue 16-bit value used in compare operation. + @param[in] ExchangeValue 16-bit value used in exchange operation. + + @return The original *Value before exchange. + +**/ +UINT16 +EFIAPI +InternalSyncCompareExchange16 ( + IN volatile UINT16 *Value, + IN UINT16 CompareValue, + IN UINT16 ExchangeValue + ) +{ + UINT32 RetValue; + UINT32 Shift; + UINT64 Mask; + UINT64 LocalCompareValue; + UINT64 LocalExchangeValue; + volatile UINT32 *Ptr32; + + /* Check that ptr is naturally aligned */ + ASSERT (!((UINT64)Value & (sizeof (Value) - 1))); + + /* Mask inputs to the correct size. */ + Mask = (((~0UL) - (1UL << (0)) + 1) & (~0UL >> (64 - 1 - ((sizeof (UINT16) * 8) - 1)))); + LocalCompareValue = ((UINT64)CompareValue) & Mask; + LocalExchangeValue = ((UINT64)ExchangeValue) & Mask; + + /* + * Calculate a shift & mask that correspond to the value we wish to + * compare & exchange within the naturally aligned 4 byte integer + * that includes it. + */ + Shift = (UINT64)Value & 0x3; + Shift *= 8; /* BITS_PER_BYTE */ + LocalCompareValue <<= Shift; + LocalExchangeValue <<= Shift; + Mask <<= Shift; + + /* + * Calculate a pointer to the naturally aligned 4 byte integer that + * includes our byte of interest, and load its value. + */ + Ptr32 = (UINT32 *)((UINT64)Value & ~0x3); + + RetValue = AsmInternalSyncCompareExchange16 ( + Ptr32, + Mask, + LocalCompareValue, + LocalExchangeValue + ); + + return (RetValue & Mask) >> Shift; +} + +/** + Performs an atomic compare exchange operation on a 32-bit + unsigned integer. + + Performs an atomic compare exchange operation on the 32-bit + unsigned integer specified by Value. If Value is equal to + CompareValue, then Value is set to ExchangeValue and + CompareValue is returned. If Value is not equal to + CompareValue, then Value is returned. The compare exchange + operation must be performed using MP safe mechanisms. + + @param[in] Value A pointer to the 32-bit value for the + compare exchange operation. + @param[in] CompareValue 32-bit value used in compare operation. + @param[in] ExchangeValue 32-bit value used in exchange operation. + + @return The original *Value before exchange. + +**/ +UINT32 +EFIAPI +InternalSyncCompareExchange32 ( + IN volatile UINT32 *Value, + IN UINT32 CompareValue, + IN UINT32 ExchangeValue + ) +{ + UINT32 RetValue; + + RetValue = AsmInternalSyncCompareExchange32 ( + Value, + CompareValue, + ExchangeValue + ); + + return RetValue; +} + +/** + Performs an atomic compare exchange operation on a 64-bit unsigned integer. + + Performs an atomic compare exchange operation on the 64-bit unsigned integer specified + by Value. If Value is equal to CompareValue, then Value is set to ExchangeValue and + CompareValue is returned. If Value is not equal to CompareValue, then Value is returned. + The compare exchange operation must be performed using MP safe mechanisms. + + @param[in] Value A pointer to the 64-bit value for the compare exchange + operation. + @param[in] CompareValue 64-bit value used in compare operation. + @param[in] ExchangeValue 64-bit value used in exchange operation. + + @return The original *Value before exchange. + +**/ +UINT64 +EFIAPI +InternalSyncCompareExchange64 ( + IN volatile UINT64 *Value, + IN UINT64 CompareValue, + IN UINT64 ExchangeValue + ) +{ + UINT64 RetValue; + + RetValue = AsmInternalSyncCompareExchange64 ( + Value, + CompareValue, + ExchangeValue + ); + + return RetValue; +} + +/** + Performs an atomic increment of an 32-bit unsigned integer. + + Performs an atomic increment of the 32-bit unsigned integer specified by + Value and returns the incremented value. The increment operation must be + performed using MP safe mechanisms. The state of the return value is not + guaranteed to be MP safe. + + @param[in] Value A pointer to the 32-bit value to increment. + + @return The incremented value. + +**/ +UINT32 +EFIAPI +InternalSyncIncrement ( + IN volatile UINT32 *Value + ) +{ + return AsmInternalSyncIncrement (Value); +} + +/** + Performs an atomic decrement of an 32-bit unsigned integer. + + Performs an atomic decrement of the 32-bit unsigned integer specified by + Value and returns the decrement value. The decrement operation must be + performed using MP safe mechanisms. The state of the return value is not + guaranteed to be MP safe. + + @param[in] Value A pointer to the 32-bit value to decrement. + + @return The decrement value. + +**/ +UINT32 +EFIAPI +InternalSyncDecrement ( + IN volatile UINT32 *Value + ) +{ + return AsmInternalSyncDecrement (Value); +} From 4f1fe552362e43d3ccbf359f8f7a56a2ab3f77ea Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 12 Nov 2021 12:37:47 +0800 Subject: [PATCH 0157/1529] MdePkg/BaseSafeIntLib: Add LoongArch64 architecture for BaseSafeIntLib. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 architecture for BaseSafeIntLib library. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf b/MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf index 40017ec88b..9d039f2e5b 100644 --- a/MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf +++ b/MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf @@ -4,9 +4,10 @@ # This library provides helper functions to prevent integer overflow during # type conversion, addition, subtraction, and multiplication. # -# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2018, Intel Corporation. All rights reserved.
# Copyright (c) 2017, Microsoft Corporation -# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # All rights reserved. @@ -25,7 +26,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] @@ -34,7 +35,7 @@ [Sources.Ia32, Sources.ARM] SafeIntLib32.c -[Sources.X64, Sources.AARCH64, Sources.RISCV64] +[Sources.X64, Sources.AARCH64, Sources.RISCV64, Sources.LOONGARCH64] SafeIntLib64.c [Sources.EBC] From eb78d0523da038996ba59b845298f92a039a42de Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 12 Nov 2021 14:18:08 +0800 Subject: [PATCH 0158/1529] MdeModulePkg/Logo: Add LoongArch64 architecture. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 architecture to the Logo. Cc: Zhichao Gao Cc: Ray Ni Signed-off-by: Chao Li Reviewed-by: Michael D Kinney Reviewed-by: Zhichao Gao --- MdeModulePkg/Logo/Logo.inf | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Logo/Logo.inf b/MdeModulePkg/Logo/Logo.inf index 70a66cae98..294482ccdc 100644 --- a/MdeModulePkg/Logo/Logo.inf +++ b/MdeModulePkg/Logo/Logo.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -21,7 +22,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Binaries] From 24485bd60190a9cbce24bf7a8049350de38081c3 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 12 Nov 2021 14:48:25 +0800 Subject: [PATCH 0159/1529] MdeModulePkg/CapsuleRuntimeDxe: Add LoongArch64 architecture. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch in INF for building CapsuleRuntimeDxe LoongArch64 image. Cc: Liming Gao Cc: Guomin Jiang Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- .../Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf b/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf index 8bf5035a69..601eada170 100644 --- a/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf +++ b/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf @@ -6,6 +6,7 @@ # # Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -22,20 +23,20 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # [Sources] CapsuleService.c CapsuleService.h -[Sources.Ia32, Sources.EBC, Sources.ARM, Sources.AARCH64, Sources.RISCV64] +[Sources.Ia32, Sources.EBC, Sources.ARM, Sources.AARCH64, Sources.RISCV64, Sources.LOONGARCH64] SaveLongModeContext.c -[Sources.Ia32, Sources.X64, Sources.ARM, Sources.AARCH64, Sources.RISCV64] +[Sources.Ia32, Sources.X64, Sources.ARM, Sources.AARCH64, Sources.RISCV64, Sources.LOONGARCH64] CapsuleCache.c -[Sources.Ia32, Sources.X64, Sources.EBC, Sources.RISCV64] +[Sources.Ia32, Sources.X64, Sources.EBC, Sources.RISCV64, Sources.LOONGARCH64] CapsuleReset.c [Sources.ARM, Sources.AARCH64] From f588186c691a821d11113a4903d08bc3fdf15dc2 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 12 Nov 2021 15:19:30 +0800 Subject: [PATCH 0160/1529] MdeModulePkg/DxeIplPeim : LoongArch DxeIPL implementation. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Implement LoongArch DxeIPL instance. Cc: Liming Gao Cc: Guomin Jiang Signed-off-by: Chao Li Co-authored-by: Baoqi Zhang Reviewed-by: Liming Gao --- MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf | 6 +- .../Core/DxeIplPeim/LoongArch64/DxeLoadFunc.c | 63 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 MdeModulePkg/Core/DxeIplPeim/LoongArch64/DxeLoadFunc.c diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf index 19b8a4c8ae..052ea0ec1a 100644 --- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf +++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf @@ -8,6 +8,7 @@ # Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
# Copyright (c) 2017, AMD Incorporated. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -26,7 +27,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 EBC (EBC is for build only) AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 EBC (EBC is for build only) AARCH64 RISCV64 LOONGARCH64 # [Sources] @@ -53,6 +54,9 @@ [Sources.RISCV64] RiscV64/DxeLoadFunc.c +[Sources.LOONGARCH64] + LoongArch64/DxeLoadFunc.c + [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec diff --git a/MdeModulePkg/Core/DxeIplPeim/LoongArch64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/LoongArch64/DxeLoadFunc.c new file mode 100644 index 0000000000..95d3af19ea --- /dev/null +++ b/MdeModulePkg/Core/DxeIplPeim/LoongArch64/DxeLoadFunc.c @@ -0,0 +1,63 @@ +/** @file + LoongArch specifc functionality for DxeLoad. + + Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "DxeIpl.h" + +/** + Transfers control to DxeCore. + + This function performs a CPU architecture specific operations to execute + the entry point of DxeCore with the parameters of HobList. + It also installs EFI_END_OF_PEI_PPI to signal the end of PEI phase. + + @param[in] DxeCoreEntryPoint The entry point of DxeCore. + @param[in] HobList The start of HobList passed to DxeCore. + +**/ +VOID +HandOffToDxeCore ( + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList + ) +{ + VOID *BaseOfStack; + VOID *TopOfStack; + EFI_STATUS Status; + + // + // Allocate 128KB for the Stack + // + BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (STACK_SIZE)); + ASSERT (BaseOfStack != NULL); + + // + // Compute the top of the stack we were allocated. Pre-allocate a UINTN + // for safety. + // + TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); + TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); + + // + // End of PEI phase signal + // + Status = PeiServicesInstallPpi (&gEndOfPeiSignalPpi); + ASSERT_EFI_ERROR (Status); + + // + // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. + // + UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE); + + SwitchStack ( + (SWITCH_STACK_ENTRY_POINT)(UINTN)DxeCoreEntryPoint, + HobList.Raw, + NULL, + TopOfStack + ); +} From 098314097655e9d3c3851e1078ecb923c56814a5 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 12 Nov 2021 15:27:29 +0800 Subject: [PATCH 0161/1529] NetworkPkg: Add LoongArch64 architecture. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4053 Add LoongArch64 architecture in to NetworkPkg. Cc: Maciej Rabeda Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- NetworkPkg/Network.dsc.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NetworkPkg/Network.dsc.inc b/NetworkPkg/Network.dsc.inc index 99fad885bf..04b515a0bb 100644 --- a/NetworkPkg/Network.dsc.inc +++ b/NetworkPkg/Network.dsc.inc @@ -9,6 +9,7 @@ # # Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -38,7 +39,7 @@ !include NetworkPkg/NetworkComponents.dsc.inc !else -[Components.IA32, Components.X64, Components.ARM, Components.AARCH64, Components.RISCV64] +[Components.IA32, Components.X64, Components.ARM, Components.AARCH64, Components.RISCV64, Components.LOONGARCH64] !include NetworkPkg/NetworkComponents.dsc.inc !endif From 2ea15ade951bd742621d3278648e2e1176fa2947 Mon Sep 17 00:00:00 2001 From: Foster Nong Date: Wed, 12 Oct 2022 10:36:55 +0800 Subject: [PATCH 0162/1529] MdeModulePkg: Fixed extra 1 SR-IOV reserved bus Below code will calculate the reserved bus number for the each PF. Based on the VF routing ID algorithm, PFRid and LastVF in below code already sure that "All VFs and PFs must have distinct Routing IDs". PF will be assigned Routing ID based on secBusNumber, ReservedBusNum will add into SubBusNumber directly. So the SR-IOV device will be assigned bus range as SecBusNumber ~ (SubBusNumber=(SecBusNumber + ReservedBusNum)). Thus "+1" in below code will cause extra 1 bus, and introduce a bus hole. PFRid = EFI_PCI_RID (Bus, Device, Func); LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride; PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); In SR-IOV spec, there is a note in section 2.1.2: Note: Bus Numbers are a constrained resource. Devices are strongly encouraged to avoid leaving ?holes? in their Bus Number usage to avoid wasting Bus Numbers So the issue can be fixed with below code change. PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus); https://bugzilla.tianocore.org/show_bug.cgi?id=4069 Signed-off-by: Foster Nong Reviewed-by: Ray Ni --- MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index eb250f6f7b..bc20da1f38 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -2425,7 +2425,7 @@ CreatePciIoDevice ( // // Calculate ReservedBusNum for this PF // - PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1); + PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus); } DEBUG (( From 3a43a62b72fc9a9b95dbf538c293e60f0fe577e5 Mon Sep 17 00:00:00 2001 From: Foster Nong Date: Wed, 12 Oct 2022 10:36:56 +0800 Subject: [PATCH 0163/1529] Fix bug on SRIOV ReservedBusNum when ARI enable. If a device which support both features SR-IOV/ARI has multi functions, which maybe support 8-255. After enable ARI forwarding in the root port and ARI Capable Hierarchy in the SR-IOV PF0. The device will support and expose multi functions(0-255) with ARI ID routing. In next device loop in below for() code, actually it still be in the same SR-IOV device, and just some PF which is over 8 or higher one(n*8), PciAllocateBusNumber() will allocate bus number(ReservedBusNum - TempReservedBusNum)) for this PF. if reset TempReservedBusNum as 0 in this case,it will allocate wrong bus number for this PF because TempReservedBusNum should be total previous PF's reserved bus numbers. code: for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { TempReservedBusNum = 0; for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { // // Check to see whether a pci device is present // Status = PciDevicePresent ( PciRootBridgeIo, &Pci, StartBusNumber, Device, Func ); ... Status = PciAllocateBusNumber (PciDevice, *SubBusNumber, (UINT8)(PciDevice->ReservedBusNum - TempReservedBusNum), SubBusNumber); The solution is add a new flag IsAriEnabled to help handle this case. if ARI is enabled, then TempReservedBusNum will not be reset again during all functions(1-255) scan with checking flag IsAriEnabled. Signed-off-by: Foster Nong Reviewed-by: Ray Ni --- MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h | 1 + .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 1 + MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c | 28 ++++++++++++++++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h index 4b58c3ea9b..ca5c06204d 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h @@ -262,6 +262,7 @@ struct _PCI_IO_DEVICE { EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BusNumberRanges; BOOLEAN IsPciExp; + BOOLEAN IsAriEnabled; // // For SR-IOV // diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index bc20da1f38..8eca859695 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -2286,6 +2286,7 @@ CreatePciIoDevice ( &Data32 ); if ((Data32 & EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING) != 0) { + PciIoDevice->IsAriEnabled = TRUE; // // ARI forward support in bridge, so enable it. // diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c index d5e3ef4d3f..84fc0161a1 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c @@ -1106,6 +1106,7 @@ PciScanBus ( EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; BOOLEAN BusPadding; UINT32 TempReservedBusNum; + BOOLEAN IsAriEnabled; PciRootBridgeIo = Bridge->PciRootBridgeIo; SecondBus = 0; @@ -1116,9 +1117,13 @@ PciScanBus ( BusPadding = FALSE; PciDevice = NULL; PciAddress = 0; + IsAriEnabled = FALSE; for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { - TempReservedBusNum = 0; + if (!IsAriEnabled) { + TempReservedBusNum = 0; + } + for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { // // Check to see whether a pci device is present @@ -1158,6 +1163,27 @@ PciScanBus ( continue; } + // + // Per Pcie spec ARI Extended Capability + // This capability must be implemented by each function in an ARI device. + // It is not applicable to a Root Port, a Switch Downstream Port, an RCiEP, or a Root Complex Event Collector + // + if (((Device == 0) && (Func == 0)) && (PciDevice->IsAriEnabled)) { + IsAriEnabled = TRUE; + } + + if (PciDevice->IsAriEnabled != IsAriEnabled) { + DEBUG (( + DEBUG_ERROR, + "ERROR: %02x:%02x:%02x device ARI Feature(%x) is not consistent with others Function\n", + StartBusNumber, + Device, + Func, + PciDevice->IsAriEnabled + )); + return EFI_DEVICE_ERROR; + } + PciAddress = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0); if (!IS_PCI_BRIDGE (&Pci)) { From a3f358ac57c0dfeb8a6337b29ff9b571ac0ce0b5 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 3 Oct 2022 15:47:31 +0800 Subject: [PATCH 0164/1529] BaseTools: Remove duplicated words in C tools In an effort to clean the documentation of the above package, remove duplicated words. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Pierre Gondois --- BaseTools/Source/C/Common/FirmwareVolumeBuffer.c | 6 +++--- BaseTools/Source/C/DevicePath/DevicePathUtilities.c | 2 +- BaseTools/Source/C/GenFv/GenFv.c | 2 +- BaseTools/Source/C/VfrCompile/Pccts/antlr/mrhoist.c | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c b/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c index 70741c8afc..ace26eb71c 100644 --- a/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c +++ b/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c @@ -91,7 +91,7 @@ Routine Description: Arguments: - SourceFv - Address of the Fv in memory, this firmware volume volume will + SourceFv - Address of the Fv in memory, this firmware volume will be modified, if SourceFfsFile exists SourceFfsFile - Input FFS file to replace @@ -141,7 +141,7 @@ Routine Description: Arguments: - SourceFv - Address of the Fv in memory, this firmware volume volume will + SourceFv - Address of the Fv in memory, this firmware volume will be modified, if SourceFfsFile exists SourceFfsFile - Input FFS file to replace @@ -285,7 +285,7 @@ Routine Description: Arguments: - SourceFv - Address of the Fv in memory, this firmware volume volume will + SourceFv - Address of the Fv in memory, this firmware volume will be modified, if SourceFfsFile exists SourceFfsFile - Input FFS file to replace diff --git a/BaseTools/Source/C/DevicePath/DevicePathUtilities.c b/BaseTools/Source/C/DevicePath/DevicePathUtilities.c index 2ffefa8cee..49078aac8c 100644 --- a/BaseTools/Source/C/DevicePath/DevicePathUtilities.c +++ b/BaseTools/Source/C/DevicePath/DevicePathUtilities.c @@ -37,7 +37,7 @@ CONST EFI_DEVICE_PATH_PROTOCOL mUefiDevicePathLibEndDevicePath = { @retval TRUE DevicePath is valid. @retval FALSE DevicePath is NULL. @retval FALSE Maxsize is less than sizeof(EFI_DEVICE_PATH_PROTOCOL). - @retval FALSE The length of any node node in the DevicePath is less + @retval FALSE The length of any node in the DevicePath is less than sizeof (EFI_DEVICE_PATH_PROTOCOL). @retval FALSE If MaxSize is not zero, the size of the DevicePath exceeds MaxSize. diff --git a/BaseTools/Source/C/GenFv/GenFv.c b/BaseTools/Source/C/GenFv/GenFv.c index 43cc5cd3fe..a742d55e52 100644 --- a/BaseTools/Source/C/GenFv/GenFv.c +++ b/BaseTools/Source/C/GenFv/GenFv.c @@ -299,7 +299,7 @@ Routine Description: return STATUS_ERROR; } if (TempNumber == 0) { - Error (NULL, 0, 1003, "Invalid option value", "Fv block size can't be be set to zero"); + Error (NULL, 0, 1003, "Invalid option value", "Fv block size can't be set to zero"); return STATUS_ERROR; } mFvDataInfo.FvBlocks[0].Length = (UINT32) TempNumber; diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/mrhoist.c b/BaseTools/Source/C/VfrCompile/Pccts/antlr/mrhoist.c index b57f5ded84..bf3dd18eaf 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/mrhoist.c +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/mrhoist.c @@ -714,7 +714,7 @@ Tree *MR_compute_pred_tree_ctxXX(p) if (p == NULL) return NULL; /* this appears strange: why do we OR the context - of and AND predicate ? It is because of the way + of an AND predicate ? It is because of the way that predicates are evaluated: if the context is wrong then it's the same as if the predicate was true. That means that even when one leg of an @@ -1531,7 +1531,7 @@ Predicate * MR_find_in_aSubBlk(alt) * 1. if lookahead for alt i is contained in the lookahead for any * alt j then ignore semantic predicate of alt i * 2. if lookahead for alt i is not contained in the lookahead for - * any alt j then add add predicate i to the OR list to be hoisted + * any alt j then add predicate i to the OR list to be hoisted * 3. if lookahead for alt i overlaps the lookahead for some alt j then * add a dummy semantic predicate for alt j * From 90f9eeb2e17549f063f01293c5b984933c3fd6d2 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Wed, 12 Oct 2022 15:27:45 +0800 Subject: [PATCH 0165/1529] UefiCpuPkg:Add RegisterExceptionHandler in PeiCpuExceptionHandlerLib The PEI instance of the CpuExceptionHandlerLib didn't implement the RegisterCpuInterruptHandler() API. This patch adds the missing API. Signed-off-by: Zhiguang Liu Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- .../CpuExceptionHandlerLib/PeiCpuException.c | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuException.c index 940d83a92f..3e38676b23 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuException.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuException.c @@ -100,6 +100,42 @@ CommonExceptionHandler ( CommonExceptionHandlerWorker (ExceptionType, SystemContext, ExceptionHandlerData); } +/** + Registers a function to be called from the processor interrupt handler. + + This function registers and enables the handler specified by InterruptHandler for a processor + interrupt or exception type specified by InterruptType. If InterruptHandler is NULL, then the + handler for the processor interrupt or exception type specified by InterruptType is uninstalled. + The installed handler is called once for each processor interrupt or exception. + NOTE: This function should be invoked after InitializeCpuExceptionHandlers() is invoked, + otherwise EFI_UNSUPPORTED returned. + + @param[in] InterruptType Defines which interrupt or exception to hook. + @param[in] InterruptHandler A pointer to a function of type EFI_CPU_INTERRUPT_HANDLER that is called + when a processor interrupt occurs. If this parameter is NULL, then the handler + will be uninstalled. + + @retval EFI_SUCCESS The handler for the processor interrupt was successfully installed or uninstalled. + @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler for InterruptType was + previously installed. + @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for InterruptType was not + previously installed. + @retval EFI_UNSUPPORTED The interrupt specified by InterruptType is not supported, + or this function is not supported. +**/ +EFI_STATUS +EFIAPI +RegisterCpuInterruptHandler ( + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + ) +{ + EXCEPTION_HANDLER_DATA *ExceptionHandlerData; + + ExceptionHandlerData = GetExceptionHandlerData (); + return RegisterCpuInterruptHandlerWorker (InterruptType, InterruptHandler, ExceptionHandlerData); +} + /** Initializes all CPU exceptions entries and provides the default exception handlers. @@ -135,7 +171,7 @@ InitializeCpuExceptionHandlers ( ASSERT (ExceptionHandlerData != NULL); ExceptionHandlerData->IdtEntryCount = CPU_EXCEPTION_NUM; ExceptionHandlerData->ReservedVectors = ReservedVectors; - ExceptionHandlerData->ExternalInterruptHandler = NULL; + ExceptionHandlerData->ExternalInterruptHandler = AllocateZeroPool (sizeof (EFI_CPU_INTERRUPT_HANDLER) * ExceptionHandlerData->IdtEntryCount); InitializeSpinLock (&ExceptionHandlerData->DisplayMessageSpinLock); Status = InitializeCpuExceptionHandlersWorker (VectorInfo, ExceptionHandlerData); From 0ab2bc5b2c9fcd5711f98a5d01e848927a71f32f Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Tue, 11 Oct 2022 13:59:35 +0800 Subject: [PATCH 0166/1529] UefiCpuPkg/CpuPageTableLib:Support PAE paging for PageTableParse Support PAE paging for PageTableParse API in CpuPageTableLib. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c index e66961e122..65490751ab 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c @@ -270,10 +270,9 @@ PageTableParse ( IA32_MAP_ENTRY OneEntry; UINTN MaxLevel; - if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { + if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. - // PAE paging will be supported later. // return RETURN_UNSUPPORTED; } From b4f68295a4ba5cee790401b1d91efbf842b4a39e Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Mon, 17 Oct 2022 14:35:39 +0800 Subject: [PATCH 0167/1529] UefiCpuPkg: Add Unit tests for DxeCpuExceptionHandlerLib Add target based unit tests for the DxeCpuExceptionHandlerLib. A DXE driver is created to test DxeCpuExceptionHandlerLib. Four test cases are created in this Unit Test module: a.Test if exception handler can be registered/unregistered for no error code exception.In the test case, only no error code exception is triggered and tested by INTn instruction. b.Test if exception handler can be registered/unregistered for GP and PF. In the test case, GP exception is triggered and tested by setting CR4_RESERVED_BIT to 1. PF exception is triggered by writting to not-present or RO address. c.Test if CpuContext is consistent before and after exception. In this test case: 1.Set Cpu register to mExpectedContextInHandler before exception. 2.Trigger exception specified by ExceptionType. 3.Store SystemContext in mActualContextInHandler and set SystemContext to mExpectedContextAfterException in handler. 4.After return from exception, store Cpu registers in mActualContextAfterException. The expectation is: 1.Register values in mActualContextInHandler are the same with register values in mExpectedContextInHandler. 2.Register values in mActualContextAfterException are the same with register values mActualContextAfterException. d.Test if stack overflow can be captured by CpuStackGuard in both Bsp and AP. In this test case, stack overflow is triggered by a funtion which calls itself continuously. This test case triggers stack overflow in both BSP and AP. All AP use same Idt with Bsp. The expectation is: 1. PF exception is triggered (leading to a DF if sepereated stack is not prepared for PF) when Rsp<=StackBase+SIZE_4KB since [StackBase, StackBase + SIZE_4KB] is marked as not present in page table when PcdCpuStackGuard is TRUE. 2. Stack for PF/DF exception handler in both Bsp and AP is succussfully switched by InitializeSeparateExceptionStacks. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- .../UnitTest/CpuExceptionHandlerTest.h | 336 +++++++ .../UnitTest/CpuExceptionHandlerTestCommon.c | 852 ++++++++++++++++++ .../DxeCpuExceptionHandlerLibUnitTest.inf | 58 ++ .../UnitTest/DxeCpuExceptionHandlerUnitTest.c | 196 ++++ .../UnitTest/X64/ArchExceptionHandlerTest.c | 166 ++++ .../X64/ArchExceptionHandlerTestAsm.nasm | 256 ++++++ 6 files changed, 1864 insertions(+) create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTest.c create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTestAsm.nasm diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h new file mode 100644 index 0000000000..936098fde8 --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h @@ -0,0 +1,336 @@ +/** @file + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + + Four test cases are created in this Unit Test module. + a.Test if exception handler can be registered/unregistered for no error code exception + In this test case, only no error code exception is triggered and tested by INTn instruction. + The special hanlder for these exception will modify a global variable for check. + + b.Test if exception handler can be registered/unregistered for GP and PF. + In this test case, GP exception is triggered and tested by setting CR4_RESERVED_BIT to 1. + PF exception is triggered and tested by writting to not-present or RO addres. + The special hanlder for these exceptions will set a global vartiable for check and adjust Rip to return from fault exception. + + c.Test if Cpu Context is consistent before and after exception. + In this test case: + 1. Set Cpu register to mExpectedContextInHandler before exception. + 2. Trigger exception specified by ExceptionType. + 3. Store SystemContext in mActualContextInHandler and set SystemContext to mExpectedContextAfterException in handler. + 4. After return from exception, store Cpu registers in mActualContextAfterException. + The expectation is: + 1. Register values in mActualContextInHandler are the same with register values in mExpectedContextInHandler. + 2. Register values in mActualContextAfterException are the same with register values mActualContextAfterException. + + d.Test if stack overflow can be captured by CpuStackGuard in both Bsp and AP. + In this test case, stack overflow is triggered by a funtion which calls itself continuously. This test case triggers stack + overflow in both BSP and AP. All AP use same Idt with Bsp. The expectation is: + 1. PF exception is triggered (leading to a DF if sepereated stack is not prepared for PF) when Rsp <= StackBase + SIZE_4KB + since [StackBase, StackBase + SIZE_4KB] is marked as not present in page table when PcdCpuStackGuard is TRUE. + 2. Stack for PF/DF exception handler in both Bsp and AP is succussfully switched by InitializeSeparateExceptionStacks. + +**/ + +#ifndef CPU_EXCEPTION_HANDLER_TEST_H_ +#define CPU_EXCEPTION_HANDLER_TEST_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define UNIT_TEST_APP_NAME "Cpu Exception Handler Lib Unit Tests" +#define UNIT_TEST_APP_VERSION "1.0" + +#define CPU_INTERRUPT_NUM 256 +#define SPEC_MAX_EXCEPTION_NUM 22 +#define CR4_RESERVED_BIT BIT15 + +typedef struct { + IA32_DESCRIPTOR OriginalGdtr; + IA32_DESCRIPTOR OriginalIdtr; + UINT16 Tr; +} CPU_REGISTER_BUFFER; + +typedef union { + EDKII_PEI_MP_SERVICES2_PPI *Ppi; + EFI_MP_SERVICES_PROTOCOL *Protocol; +} MP_SERVICES; + +typedef struct { + VOID *Buffer; + UINTN BufferSize; + EFI_STATUS Status; +} EXCEPTION_STACK_SWITCH_CONTEXT; + +typedef struct { + UINT64 Rdi; + UINT64 Rsi; + UINT64 Rbx; + UINT64 Rdx; + UINT64 Rcx; + UINT64 Rax; + UINT64 R8; + UINT64 R9; + UINT64 R10; + UINT64 R11; + UINT64 R12; + UINT64 R13; + UINT64 R14; + UINT64 R15; +} GENERAL_REGISTER; + +extern UINTN mFaultInstructionLength; +extern EFI_EXCEPTION_TYPE mExceptionType; +extern UINTN mRspAddress[]; + +/** + Initialize Bsp Idt with a new Idt table and return the IA32_DESCRIPTOR buffer. + In PEIM, store original PeiServicePointer before new Idt table. + + @return Pointer to the allocated IA32_DESCRIPTOR buffer. +**/ +VOID * +InitializeBspIdt ( + VOID + ); + +/** + Trigger no error code exception by INT n instruction. + + @param[in] ExceptionType No error code exception type. +**/ +VOID +EFIAPI +TriggerINTnException ( + IN EFI_EXCEPTION_TYPE ExceptionType + ); + +/** + Trigger GP exception by setting CR4_RESERVED_BIT to 1. + + @param[in] Cr4ReservedBit Cr4 reserved bit. +**/ +VOID +EFIAPI +TriggerGPException ( + UINTN Cr4ReservedBit + ); + +/** + Trigger PF exception by write to not present or ReadOnly address. + + @param[in] PFAddress Not present or ReadOnly address in page table. +**/ +VOID +EFIAPI +TriggerPFException ( + UINTN PFAddress + ); + +/** + Special handler for fault exception. + This handler sets Rip/Eip in SystemContext to the instruction address after the exception instruction. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +AdjustRipForFaultHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ); + +/** + Test consistency of Cpu context. Four steps: + 1. Set Cpu register to mExpectedContextInHandler before exception. + 2. Trigger exception specified by ExceptionType. + 3. Store SystemContext in mActualContextInHandler and set SystemContext to mExpectedContextAfterException in handler. + 4. After return from exception, store Cpu registers in mActualContextAfterException. + + Rcx/Ecx in mExpectedContextInHandler is decided by different exception type runtime since Rcx/Ecx is needed in assembly code. + For GP and PF, Rcx/Ecx is set to FaultParameter. For other exception triggered by INTn, Rcx/Ecx is set to ExceptionType. + + @param[in] ExceptionType Exception type. + @param[in] FaultParameter Parameter for GP and PF. OPTIONAL +**/ +VOID +EFIAPI +AsmTestConsistencyOfCpuContext ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN UINTN FaultParameter OPTIONAL + ); + +/** + Special handler for ConsistencyOfCpuContext test case. General register in SystemContext + is modified to mExpectedContextInHandler in this handler. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +AdjustCpuContextHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ); + +/** + Compare cpu context in ConsistencyOfCpuContext test case. + 1.Compare mActualContextInHandler with mExpectedContextInHandler. + 2.Compare mActualContextAfterException with mActualContextAfterException. + + @retval UNIT_TEST_PASSED The Unit test has completed and it was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +CompareCpuContext ( + VOID + ); + +/** + Get EFI_MP_SERVICES_PROTOCOL/EDKII_PEI_MP_SERVICES2_PPI pointer. + + @param[out] MpServices Pointer to the MP_SERVICES buffer + + @retval EFI_SUCCESS EFI_MP_SERVICES_PROTOCOL/PPI interface is returned + @retval EFI_NOT_FOUND EFI_MP_SERVICES_PROTOCOL/PPI interface is not found +**/ +EFI_STATUS +GetMpServices ( + OUT MP_SERVICES *MpServices + ); + +/** + Create CpuExceptionLibUnitTestSuite and add test case. + + @param[in] FrameworkHandle Unit test framework. + + @return EFI_SUCCESS The unit test suite was created. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test suite. +**/ +EFI_STATUS +AddCommonTestCase ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ); + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ); + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ); + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ); + +/** + Trigger stack overflow by calling itself continuously. +**/ +VOID +EFIAPI +TriggerStackOverflow ( + VOID + ); + +/** + Special handler for CpuStackGuard test case. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +CpuStackGuardExceptionHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ); + +#endif diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c new file mode 100644 index 0000000000..17afb592d3 --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c @@ -0,0 +1,852 @@ +/** @file + Unit tests of the CpuExceptionHandlerLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuExceptionHandlerTest.h" + +// +// Length of the assembly falut instruction. +// +UINTN mFaultInstructionLength = 0; +EFI_EXCEPTION_TYPE mExceptionType = 256; +UINTN mNumberOfProcessors = 1; +UINTN mRspAddress[2] = { 0 }; + +// +// Error code flag indicating whether or not an error code will be +// pushed on the stack if an exception occurs. +// +// 1 means an error code will be pushed, otherwise 0 +// +CONST UINT32 mErrorCodeExceptionFlag = 0x20227d00; + +/** + Special handler for exception triggered by INTn instruction. + This hanlder only modifies a global variable for check. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +INTnExceptionHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + mExceptionType = ExceptionType; +} + +/** + Restore cpu original registers before exit test case. + + @param[in] Buffer Argument of the procedure. +**/ +VOID +EFIAPI +RestoreRegistersPerCpu ( + IN VOID *Buffer + ) +{ + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + UINT16 Tr; + IA32_TSS_DESCRIPTOR *Tss; + + CpuOriginalRegisterBuffer = (CPU_REGISTER_BUFFER *)Buffer; + + AsmWriteGdtr (&(CpuOriginalRegisterBuffer->OriginalGdtr)); + AsmWriteIdtr (&(CpuOriginalRegisterBuffer->OriginalIdtr)); + Tr = CpuOriginalRegisterBuffer->Tr; + if ((Tr != 0) && (Tr < CpuOriginalRegisterBuffer->OriginalGdtr.Limit)) { + Tss = (IA32_TSS_DESCRIPTOR *)(CpuOriginalRegisterBuffer->OriginalGdtr.Base + Tr); + if (Tss->Bits.P == 1) { + // + // Clear busy bit of TSS before write Tr + // + Tss->Bits.Type &= 0xD; + AsmWriteTr (Tr); + } + } +} + +/** + Restore cpu original registers before exit test case. + + @param[in] MpServices MpServices. + @param[in] CpuOriginalRegisterBuffer Address of CpuOriginalRegisterBuffer. + @param[in] BspProcessorNum Bsp processor number. +**/ +VOID +RestoreAllCpuRegisters ( + MP_SERVICES *MpServices, OPTIONAL + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer, + UINTN BspProcessorNum + ) +{ + UINTN Index; + EFI_STATUS Status; + + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (Index == BspProcessorNum) { + RestoreRegistersPerCpu ((VOID *)&CpuOriginalRegisterBuffer[Index]); + continue; + } + + ASSERT (MpServices != NULL); + Status = MpServicesUnitTestStartupThisAP ( + *MpServices, + (EFI_AP_PROCEDURE)RestoreRegistersPerCpu, + Index, + 0, + (VOID *)&CpuOriginalRegisterBuffer[Index] + ); + ASSERT_EFI_ERROR (Status); + } +} + +/** + Store cpu registers before the test case starts. + + @param[in] Buffer Argument of the procedure. +**/ +VOID +EFIAPI +SaveRegisterPerCpu ( + IN VOID *Buffer + ) +{ + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + IA32_DESCRIPTOR Gdtr; + IA32_DESCRIPTOR Idtr; + + CpuOriginalRegisterBuffer = (CPU_REGISTER_BUFFER *)Buffer; + + AsmReadGdtr (&Gdtr); + AsmReadIdtr (&Idtr); + CpuOriginalRegisterBuffer->OriginalGdtr.Base = Gdtr.Base; + CpuOriginalRegisterBuffer->OriginalGdtr.Limit = Gdtr.Limit; + CpuOriginalRegisterBuffer->OriginalIdtr.Base = Idtr.Base; + CpuOriginalRegisterBuffer->OriginalIdtr.Limit = Idtr.Limit; + CpuOriginalRegisterBuffer->Tr = AsmReadTr (); +} + +/** + Store cpu registers before the test case starts. + + @param[in] MpServices MpServices. + @param[in] BspProcessorNum Bsp processor number. + + @return Pointer to the allocated CPU_REGISTER_BUFFER. +**/ +CPU_REGISTER_BUFFER * +SaveAllCpuRegisters ( + MP_SERVICES *MpServices, OPTIONAL + UINTN BspProcessorNum + ) +{ + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + EFI_STATUS Status; + UINTN Index; + + CpuOriginalRegisterBuffer = AllocateZeroPool (mNumberOfProcessors * sizeof (CPU_REGISTER_BUFFER)); + ASSERT (CpuOriginalRegisterBuffer != NULL); + + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (Index == BspProcessorNum) { + SaveRegisterPerCpu ((VOID *)&CpuOriginalRegisterBuffer[Index]); + continue; + } + + ASSERT (MpServices != NULL); + Status = MpServicesUnitTestStartupThisAP ( + *MpServices, + (EFI_AP_PROCEDURE)SaveRegisterPerCpu, + Index, + 0, + (VOID *)&CpuOriginalRegisterBuffer[Index] + ); + ASSERT_EFI_ERROR (Status); + } + + return CpuOriginalRegisterBuffer; +} + +/** + Initialize Ap Idt Procedure. + + @param[in] Buffer Argument of the procedure. +**/ +VOID +EFIAPI +InitializeIdtPerAp ( + IN VOID *Buffer + ) +{ + AsmWriteIdtr (Buffer); +} + +/** + Initialize all Ap Idt. + + @param[in] MpServices MpServices. + @param[in] BspIdtr Pointer to IA32_DESCRIPTOR allocated by Bsp. +**/ +VOID +InitializeApIdt ( + MP_SERVICES MpServices, + VOID *BspIdtr + ) +{ + EFI_STATUS Status; + + Status = MpServicesUnitTestStartupAllAPs ( + MpServices, + (EFI_AP_PROCEDURE)InitializeIdtPerAp, + FALSE, + 0, + BspIdtr + ); + ASSERT_EFI_ERROR (Status); +} + +/** + Check if exception handler can registered/unregistered for no error code exception. + + @param[in] Context [Optional] An optional parameter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestRegisterHandlerForNoErrorCodeException ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Index; + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + VOID *NewIdtr; + + CpuOriginalRegisterBuffer = SaveAllCpuRegisters (NULL, 0); + NewIdtr = InitializeBspIdt (); + Status = InitializeCpuExceptionHandlers (NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + for (Index = 0; Index < SPEC_MAX_EXCEPTION_NUM; Index++) { + // + // Only test no error code exception by INT n instruction. + // + if ((mErrorCodeExceptionFlag & (1 << Index)) != 0) { + continue; + } + + DEBUG ((DEBUG_INFO, "TestCase1: ExceptionType is %d\n", Index)); + Status = RegisterCpuInterruptHandler (Index, INTnExceptionHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + TriggerINTnException (Index); + UT_ASSERT_EQUAL (mExceptionType, Index); + Status = RegisterCpuInterruptHandler (Index, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + } + + RestoreAllCpuRegisters (NULL, CpuOriginalRegisterBuffer, 0); + FreePool (CpuOriginalRegisterBuffer); + FreePool (NewIdtr); + return UNIT_TEST_PASSED; +} + +/** + Get Bsp stack base. + + @param[out] StackBase Pointer to stack base of BSP. +**/ +VOID +GetBspStackBase ( + OUT UINTN *StackBase + ) +{ + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + + // + // Get the base of stack from Hob. + // + ASSERT (StackBase != NULL); + Hob.Raw = GetHobList (); + while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) { + MemoryHob = Hob.MemoryAllocation; + if (CompareGuid (&gEfiHobMemoryAllocStackGuid, &MemoryHob->AllocDescriptor.Name)) { + DEBUG (( + DEBUG_INFO, + "%a: Bsp StackBase = 0x%016lx StackSize = 0x%016lx\n", + __FUNCTION__, + MemoryHob->AllocDescriptor.MemoryBaseAddress, + MemoryHob->AllocDescriptor.MemoryLength + )); + + *StackBase = (UINTN)MemoryHob->AllocDescriptor.MemoryBaseAddress; + // + // Ensure the base of the stack is page-size aligned. + // + ASSERT ((*StackBase & EFI_PAGE_MASK) == 0); + break; + } + + Hob.Raw = GET_NEXT_HOB (Hob); + } + + ASSERT (*StackBase != 0); +} + +/** + Get Ap stack base procedure. + + @param[out] ApStackBase Pointer to Ap stack base. +**/ +VOID +EFIAPI +GetStackBasePerAp ( + OUT VOID *ApStackBase + ) +{ + UINTN ApTopOfStack; + + ApTopOfStack = ALIGN_VALUE ((UINTN)&ApTopOfStack, (UINTN)PcdGet32 (PcdCpuApStackSize)); + *(UINTN *)ApStackBase = ApTopOfStack - (UINTN)PcdGet32 (PcdCpuApStackSize); +} + +/** + Get all Cpu stack base. + + @param[in] MpServices MpServices. + @param[in] BspProcessorNum Bsp processor number. + + @return Pointer to the allocated CpuStackBaseBuffer. +**/ +UINTN * +GetAllCpuStackBase ( + MP_SERVICES *MpServices, + UINTN BspProcessorNum + ) +{ + UINTN *CpuStackBaseBuffer; + EFI_STATUS Status; + UINTN Index; + + CpuStackBaseBuffer = AllocateZeroPool (mNumberOfProcessors * sizeof (UINTN)); + ASSERT (CpuStackBaseBuffer != NULL); + + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (Index == BspProcessorNum) { + GetBspStackBase (&CpuStackBaseBuffer[Index]); + continue; + } + + ASSERT (MpServices != NULL); + Status = MpServicesUnitTestStartupThisAP ( + *MpServices, + (EFI_AP_PROCEDURE)GetStackBasePerAp, + Index, + 0, + (VOID *)&CpuStackBaseBuffer[Index] + ); + ASSERT_EFI_ERROR (Status); + DEBUG ((DEBUG_INFO, "AP[%d] StackBase = 0x%x\n", Index, CpuStackBaseBuffer[Index])); + } + + return CpuStackBaseBuffer; +} + +/** + Find not present or ReadOnly address in page table. + + @param[out] PFAddress Access to the address which is not permitted will trigger PF exceptions. + + @retval TRUE Found not present or ReadOnly address in page table. + @retval FALSE Failed to found PFAddress in page table. +**/ +BOOLEAN +FindPFAddressInPageTable ( + OUT UINTN *PFAddress + ) +{ + IA32_CR0 Cr0; + IA32_CR4 Cr4; + UINTN PageTable; + PAGING_MODE PagingMode; + BOOLEAN Enable5LevelPaging; + RETURN_STATUS Status; + IA32_MAP_ENTRY *Map; + UINTN MapCount; + UINTN Index; + UINTN PreviousAddress; + + ASSERT (PFAddress != NULL); + + Cr0.UintN = AsmReadCr0 (); + if (Cr0.Bits.PG == 0) { + return FALSE; + } + + PageTable = AsmReadCr3 (); + Cr4.UintN = AsmReadCr4 (); + if (sizeof (UINTN) == sizeof (UINT32)) { + ASSERT (Cr4.Bits.PAE == 1); + PagingMode = PagingPae; + } else { + Enable5LevelPaging = (BOOLEAN)(Cr4.Bits.LA57 == 1); + PagingMode = Enable5LevelPaging ? Paging5Level : Paging4Level; + } + + MapCount = 0; + Status = PageTableParse (PageTable, PagingMode, NULL, &MapCount); + ASSERT (Status == RETURN_BUFFER_TOO_SMALL); + Map = AllocatePages (EFI_SIZE_TO_PAGES (MapCount * sizeof (IA32_MAP_ENTRY))); + Status = PageTableParse (PageTable, PagingMode, Map, &MapCount); + ASSERT (Status == RETURN_SUCCESS); + + PreviousAddress = 0; + for (Index = 0; Index < MapCount; Index++) { + DEBUG (( + DEBUG_ERROR, + "%02d: %016lx - %016lx, %016lx\n", + Index, + Map[Index].LinearAddress, + Map[Index].LinearAddress + Map[Index].Length, + Map[Index].Attribute.Uint64 + )); + + // + // Not present address in page table. + // + if (Map[Index].LinearAddress > PreviousAddress) { + *PFAddress = PreviousAddress; + return TRUE; + } + + PreviousAddress = (UINTN)(Map[Index].LinearAddress + Map[Index].Length); + + // + // ReadOnly address in page table. + // + if ((Cr0.Bits.WP != 0) && (Map[Index].Attribute.Bits.ReadWrite == 0)) { + *PFAddress = (UINTN)Map[Index].LinearAddress; + return TRUE; + } + } + + return FALSE; +} + +/** + Test if exception handler can registered/unregistered for GP and PF. + + @param[in] Context [Optional] An optional parameter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestRegisterHandlerForGPAndPF ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + UINTN PFAddress; + VOID *NewIdtr; + + PFAddress = 0; + CpuOriginalRegisterBuffer = SaveAllCpuRegisters (NULL, 0); + NewIdtr = InitializeBspIdt (); + Status = InitializeCpuExceptionHandlers (NULL); + + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + // + // GP exception. + // + DEBUG ((DEBUG_INFO, "TestCase2: ExceptionType is %d\n", EXCEPT_IA32_GP_FAULT)); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_GP_FAULT, AdjustRipForFaultHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + TriggerGPException (CR4_RESERVED_BIT); + UT_ASSERT_EQUAL (mExceptionType, EXCEPT_IA32_GP_FAULT); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_GP_FAULT, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + // + // PF exception. + // + if (FindPFAddressInPageTable (&PFAddress)) { + DEBUG ((DEBUG_INFO, "TestCase2: ExceptionType is %d\n", EXCEPT_IA32_PAGE_FAULT)); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_PAGE_FAULT, AdjustRipForFaultHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + TriggerPFException (PFAddress); + + UT_ASSERT_EQUAL (mExceptionType, EXCEPT_IA32_PAGE_FAULT); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_PAGE_FAULT, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + } + + RestoreAllCpuRegisters (NULL, CpuOriginalRegisterBuffer, 0); + FreePool (CpuOriginalRegisterBuffer); + FreePool (NewIdtr); + return UNIT_TEST_PASSED; +} + +/** + Test if Cpu Context is consistent before and after exception. + + @param[in] Context [Optional] An optional parameter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestCpuContextConsistency ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Index; + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + UINTN FaultParameter; + VOID *NewIdtr; + + FaultParameter = 0; + CpuOriginalRegisterBuffer = SaveAllCpuRegisters (NULL, 0); + NewIdtr = InitializeBspIdt (); + Status = InitializeCpuExceptionHandlers (NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + for (Index = 0; Index < 22; Index++) { + if (Index == EXCEPT_IA32_PAGE_FAULT) { + if (!FindPFAddressInPageTable (&FaultParameter)) { + continue; + } + } else if (Index == EXCEPT_IA32_GP_FAULT) { + FaultParameter = CR4_RESERVED_BIT; + } else { + if ((mErrorCodeExceptionFlag & (1 << Index)) != 0) { + continue; + } + } + + DEBUG ((DEBUG_INFO, "TestCase3: ExceptionType is %d\n", Index)); + Status = RegisterCpuInterruptHandler (Index, AdjustCpuContextHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + // + // Trigger different type exception and compare different stage cpu context. + // + AsmTestConsistencyOfCpuContext (Index, FaultParameter); + CompareCpuContext (); + Status = RegisterCpuInterruptHandler (Index, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + } + + RestoreAllCpuRegisters (NULL, CpuOriginalRegisterBuffer, 0); + FreePool (CpuOriginalRegisterBuffer); + FreePool (NewIdtr); + return UNIT_TEST_PASSED; +} + +/** + Initializes CPU exceptions handlers for the sake of stack switch requirement. + + This function is a wrapper of InitializeSeparateExceptionStacks. It's mainly + for the sake of AP's init because of EFI_AP_PROCEDURE API requirement. + + @param[in,out] Buffer The pointer to private data buffer. + +**/ +VOID +EFIAPI +InitializeExceptionStackSwitchHandlersPerAp ( + IN OUT VOID *Buffer + ) +{ + EXCEPTION_STACK_SWITCH_CONTEXT *CpuSwitchStackData; + + CpuSwitchStackData = (EXCEPTION_STACK_SWITCH_CONTEXT *)Buffer; + + // + // This may be called twice for each Cpu. Only run InitializeSeparateExceptionStacks + // if this is the first call or the first call failed because of size too small. + // + if ((CpuSwitchStackData->Status == EFI_NOT_STARTED) || (CpuSwitchStackData->Status == EFI_BUFFER_TOO_SMALL)) { + CpuSwitchStackData->Status = InitializeSeparateExceptionStacks (CpuSwitchStackData->Buffer, &CpuSwitchStackData->BufferSize); + } +} + +/** + Initializes MP exceptions handlers for the sake of stack switch requirement. + + This function will allocate required resources required to setup stack switch + and pass them through SwitchStackData to each logic processor. + + @param[in, out] MpServices MpServices. + @param[in, out] BspProcessorNum Bsp processor number. + + @return Pointer to the allocated SwitchStackData. +**/ +EXCEPTION_STACK_SWITCH_CONTEXT * +InitializeMpExceptionStackSwitchHandlers ( + MP_SERVICES MpServices, + UINTN BspProcessorNum + ) +{ + UINTN Index; + EXCEPTION_STACK_SWITCH_CONTEXT *SwitchStackData; + UINTN BufferSize; + EFI_STATUS Status; + UINT8 *Buffer; + + SwitchStackData = AllocateZeroPool (mNumberOfProcessors * sizeof (EXCEPTION_STACK_SWITCH_CONTEXT)); + ASSERT (SwitchStackData != NULL); + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + // + // Because the procedure may runs multiple times, use the status EFI_NOT_STARTED + // to indicate the procedure haven't been run yet. + // + SwitchStackData[Index].Status = EFI_NOT_STARTED; + if (Index == BspProcessorNum) { + InitializeExceptionStackSwitchHandlersPerAp ((VOID *)&SwitchStackData[Index]); + continue; + } + + Status = MpServicesUnitTestStartupThisAP ( + MpServices, + InitializeExceptionStackSwitchHandlersPerAp, + Index, + 0, + (VOID *)&SwitchStackData[Index] + ); + ASSERT_EFI_ERROR (Status); + } + + BufferSize = 0; + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (SwitchStackData[Index].Status == EFI_BUFFER_TOO_SMALL) { + ASSERT (SwitchStackData[Index].BufferSize != 0); + BufferSize += SwitchStackData[Index].BufferSize; + } else { + ASSERT (SwitchStackData[Index].Status == EFI_SUCCESS); + ASSERT (SwitchStackData[Index].BufferSize == 0); + } + } + + if (BufferSize != 0) { + Buffer = AllocateZeroPool (BufferSize); + ASSERT (Buffer != NULL); + BufferSize = 0; + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (SwitchStackData[Index].Status == EFI_BUFFER_TOO_SMALL) { + SwitchStackData[Index].Buffer = (VOID *)(&Buffer[BufferSize]); + BufferSize += SwitchStackData[Index].BufferSize; + DEBUG (( + DEBUG_INFO, + "Buffer[cpu%lu] for InitializeExceptionStackSwitchHandlersPerAp: 0x%lX with size 0x%lX\n", + (UINT64)(UINTN)Index, + (UINT64)(UINTN)SwitchStackData[Index].Buffer, + (UINT64)(UINTN)SwitchStackData[Index].BufferSize + )); + } + } + + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + if (Index == BspProcessorNum) { + InitializeExceptionStackSwitchHandlersPerAp ((VOID *)&SwitchStackData[Index]); + continue; + } + + Status = MpServicesUnitTestStartupThisAP ( + MpServices, + InitializeExceptionStackSwitchHandlersPerAp, + Index, + 0, + (VOID *)&SwitchStackData[Index] + ); + ASSERT_EFI_ERROR (Status); + } + + for (Index = 0; Index < mNumberOfProcessors; ++Index) { + ASSERT (SwitchStackData[Index].Status == EFI_SUCCESS); + } + } + + return SwitchStackData; +} + +/** + Test if stack overflow is captured by CpuStackGuard in both Bsp and AP. + + @param[in] Context [Optional] An optional parameter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestCpuStackGuardInBspAndAp ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN OriginalStackBase; + UINTN NewStackTop; + UINTN NewStackBase; + EXCEPTION_STACK_SWITCH_CONTEXT *SwitchStackData; + MP_SERVICES MpServices; + UINTN ProcessorNumber; + UINTN EnabledProcessorNum; + CPU_REGISTER_BUFFER *CpuOriginalRegisterBuffer; + UINTN Index; + UINTN BspProcessorNum; + VOID *NewIdtr; + UINTN *CpuStackBaseBuffer; + + if (!PcdGetBool (PcdCpuStackGuard)) { + return UNIT_TEST_PASSED; + } + + // + // Get MP Service Protocol + // + Status = GetMpServices (&MpServices); + Status = MpServicesUnitTestGetNumberOfProcessors (MpServices, &ProcessorNumber, &EnabledProcessorNum); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + Status = MpServicesUnitTestWhoAmI (MpServices, &BspProcessorNum); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + mNumberOfProcessors = ProcessorNumber; + + CpuOriginalRegisterBuffer = SaveAllCpuRegisters (&MpServices, BspProcessorNum); + + // + // Initialize Bsp and AP Idt. + // Idt buffer should not be empty or it will hang in MP API. + // + NewIdtr = InitializeBspIdt (); + Status = InitializeCpuExceptionHandlers (NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + InitializeApIdt (MpServices, NewIdtr); + + // + // Get BSP and AP original stack base. + // + CpuStackBaseBuffer = GetAllCpuStackBase (&MpServices, BspProcessorNum); + + // + // InitializeMpExceptionStackSwitchHandlers and register exception handler. + // + SwitchStackData = InitializeMpExceptionStackSwitchHandlers (MpServices, BspProcessorNum); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_PAGE_FAULT, CpuStackGuardExceptionHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_DOUBLE_FAULT, AdjustRipForFaultHandler); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + + for (Index = 0; Index < mNumberOfProcessors; Index++) { + OriginalStackBase = CpuStackBaseBuffer[Index]; + NewStackTop = (UINTN)(SwitchStackData[Index].Buffer) + SwitchStackData[Index].BufferSize; + NewStackBase = (UINTN)(SwitchStackData[Index].Buffer); + if (Index == BspProcessorNum) { + TriggerStackOverflow (); + } else { + MpServicesUnitTestStartupThisAP ( + MpServices, + (EFI_AP_PROCEDURE)TriggerStackOverflow, + Index, + 0, + NULL + ); + } + + DEBUG ((DEBUG_INFO, "TestCase4: mRspAddress[0] is 0x%x, mRspAddress[1] is 0x%x\n", mRspAddress[0], mRspAddress[1])); + UT_ASSERT_TRUE ((mRspAddress[0] >= OriginalStackBase) && (mRspAddress[0] <= (OriginalStackBase + SIZE_4KB))); + UT_ASSERT_TRUE ((mRspAddress[1] >= NewStackBase) && (mRspAddress[1] < NewStackTop)); + } + + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_PAGE_FAULT, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + Status = RegisterCpuInterruptHandler (EXCEPT_IA32_DOUBLE_FAULT, NULL); + UT_ASSERT_EQUAL (Status, EFI_SUCCESS); + RestoreAllCpuRegisters (&MpServices, CpuOriginalRegisterBuffer, BspProcessorNum); + FreePool (SwitchStackData); + FreePool (CpuOriginalRegisterBuffer); + FreePool (NewIdtr); + + return UNIT_TEST_PASSED; +} + +/** + Create CpuExceptionLibUnitTestSuite and add test case. + + @param[in] FrameworkHandle Unit test framework. + + @return EFI_SUCCESS The unit test suite was created. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test suite. +**/ +EFI_STATUS +AddCommonTestCase ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ) +{ + EFI_STATUS Status; + UNIT_TEST_SUITE_HANDLE CpuExceptionLibUnitTestSuite; + + // + // Populate the Manual Test Cases. + // + Status = CreateUnitTestSuite (&CpuExceptionLibUnitTestSuite, Framework, "Test CpuExceptionHandlerLib", "CpuExceptionHandlerLib.Manual", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for CpuExceptionHandlerLib Test Cases\n")); + Status = EFI_OUT_OF_RESOURCES; + return Status; + } + + AddTestCase (CpuExceptionLibUnitTestSuite, "Check if exception handler can be registered/unregistered for no error code exception", "TestRegisterHandlerForNoErrorCodeException", TestRegisterHandlerForNoErrorCodeException, NULL, NULL, NULL); + AddTestCase (CpuExceptionLibUnitTestSuite, "Check if exception handler can be registered/unregistered for GP and PF", "TestRegisterHandlerForGPAndPF", TestRegisterHandlerForGPAndPF, NULL, NULL, NULL); + + AddTestCase (CpuExceptionLibUnitTestSuite, "Check if Cpu Context is consistent before and after exception.", "TestCpuContextConsistency", TestCpuContextConsistency, NULL, NULL, NULL); + AddTestCase (CpuExceptionLibUnitTestSuite, "Check if stack overflow is captured by CpuStackGuard in Bsp and AP", "TestCpuStackGuardInBspAndAp", TestCpuStackGuardInBspAndAp, NULL, NULL, NULL); + + return EFI_SUCCESS; +} diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf new file mode 100644 index 0000000000..e3dbe7b9ab --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf @@ -0,0 +1,58 @@ +## @file +# Unit tests of the DxeCpuExceptionHandlerLib instance. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = CpuExceptionHandlerDxeTest + FILE_GUID = D76BFD9C-0B6D-46BD-AD66-2BBB6FA7031A + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = CpuExceptionHandlerTestEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = X64 +# +[Sources.X64] + X64/ArchExceptionHandlerTestAsm.nasm + X64/ArchExceptionHandlerTest.c + +[Sources.common] + CpuExceptionHandlerTest.h + CpuExceptionHandlerTestCommon.c + DxeCpuExceptionHandlerUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib + MemoryAllocationLib + CpuExceptionHandlerLib + UefiDriverEntryPoint + HobLib + UefiBootServicesTableLib + CpuPageTableLib + +[Guids] + gEfiHobMemoryAllocStackGuid + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize ## CONSUMES + +[Protocols] + gEfiMpServiceProtocolGuid + +[Depex] + gEfiMpServiceProtocolGuid diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c new file mode 100644 index 0000000000..917fc549bf --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c @@ -0,0 +1,196 @@ +/** @file + Unit tests of the CpuExceptionHandlerLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuExceptionHandlerTest.h" +#include + +/** + Initialize Bsp Idt with a new Idt table and return the IA32_DESCRIPTOR buffer. + In PEIM, store original PeiServicePointer before new Idt table. + + @return Pointer to the allocated IA32_DESCRIPTOR buffer. +**/ +VOID * +InitializeBspIdt ( + VOID + ) +{ + UINTN *NewIdtTable; + IA32_DESCRIPTOR *Idtr; + + Idtr = AllocateZeroPool (sizeof (IA32_DESCRIPTOR)); + ASSERT (Idtr != NULL); + NewIdtTable = AllocateZeroPool (sizeof (IA32_IDT_GATE_DESCRIPTOR) * CPU_INTERRUPT_NUM); + ASSERT (NewIdtTable != NULL); + Idtr->Base = (UINTN)NewIdtTable; + Idtr->Limit = (UINT16)(sizeof (IA32_IDT_GATE_DESCRIPTOR) * CPU_INTERRUPT_NUM - 1); + + AsmWriteIdtr (Idtr); + return Idtr; +} + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) +{ + return MpServices.Protocol->GetNumberOfProcessors (MpServices.Protocol, NumberOfProcessors, NumberOfEnabledProcessors); +} + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ) +{ + return MpServices.Protocol->WhoAmI (MpServices.Protocol, ProcessorNumber); +} + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Protocol->StartupThisAP (MpServices.Protocol, Procedure, ProcessorNumber, NULL, TimeoutInMicroSeconds, ProcedureArgument, NULL); +} + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Protocol->StartupAllAPs (MpServices.Protocol, Procedure, SingleThread, NULL, TimeoutInMicroSeconds, ProcedureArgument, NULL); +} + +/** + Get EFI_MP_SERVICES_PROTOCOL pointer. + + @param[out] MpServices Pointer to the buffer where EFI_MP_SERVICES_PROTOCOL is stored + + @retval EFI_SUCCESS EFI_MP_SERVICES_PROTOCOL interface is returned + @retval EFI_NOT_FOUND EFI_MP_SERVICES_PROTOCOL interface is not found +**/ +EFI_STATUS +GetMpServices ( + OUT MP_SERVICES *MpServices + ) +{ + return gBS->LocateProtocol (&gEfiMpServiceProtocolGuid, NULL, (VOID **)&MpServices->Protocol); +} + +/** + Entry for CpuExceptionHandlerDxeTest driver. + + @param ImageHandle Image handle this driver. + @param SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS The driver executed normally. + +**/ +EFI_STATUS +EFIAPI +CpuExceptionHandlerTestEntry ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + Status = AddCommonTestCase (Framework); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in AddCommonTestCase. Status = %r\n", Status)); + goto EXIT; + } + + // + // Execute the tests. + // + Status = RunAllTestSuites (Framework); + +EXIT: + if (Framework) { + FreeUnitTestFramework (Framework); + } + + return Status; +} diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTest.c new file mode 100644 index 0000000000..c0d962f26d --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTest.c @@ -0,0 +1,166 @@ +/** @file + Unit tests of the CpuExceptionHandlerLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuExceptionHandlerTest.h" + +GENERAL_REGISTER mActualContextInHandler; +GENERAL_REGISTER mActualContextAfterException; + +// +// In TestCpuContextConsistency, Cpu registers will be set to mExpectedContextInHandler/mExpectedContextAfterException. +// Rcx in mExpectedContextInHandler is set runtime since Rcx is needed in assembly code. +// For GP and PF, Rcx is set to FaultParameter. For other exception triggered by INTn, Rcx is set to ExceptionType. +// +GENERAL_REGISTER mExpectedContextInHandler = { 1, 2, 3, 4, 5, 0, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe }; +GENERAL_REGISTER mExpectedContextAfterException = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e }; + +/** + Special handler for fault exception. + Rip/Eip in SystemContext will be modified to the instruction after the exception instruction. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +AdjustRipForFaultHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + mExceptionType = ExceptionType; + SystemContext.SystemContextX64->Rip += mFaultInstructionLength; +} + +/** + Special handler for ConsistencyOfCpuContext test case. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +AdjustCpuContextHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + // + // Store SystemContext in mActualContextInHandler. + // + mActualContextInHandler.Rdi = SystemContext.SystemContextX64->Rdi; + mActualContextInHandler.Rsi = SystemContext.SystemContextX64->Rsi; + mActualContextInHandler.Rbx = SystemContext.SystemContextX64->Rbx; + mActualContextInHandler.Rdx = SystemContext.SystemContextX64->Rdx; + mActualContextInHandler.Rcx = SystemContext.SystemContextX64->Rcx; + mActualContextInHandler.Rax = SystemContext.SystemContextX64->Rax; + mActualContextInHandler.R8 = SystemContext.SystemContextX64->R8; + mActualContextInHandler.R9 = SystemContext.SystemContextX64->R9; + mActualContextInHandler.R10 = SystemContext.SystemContextX64->R10; + mActualContextInHandler.R11 = SystemContext.SystemContextX64->R11; + mActualContextInHandler.R12 = SystemContext.SystemContextX64->R12; + mActualContextInHandler.R13 = SystemContext.SystemContextX64->R13; + mActualContextInHandler.R14 = SystemContext.SystemContextX64->R14; + mActualContextInHandler.R15 = SystemContext.SystemContextX64->R15; + + // + // Modify cpu context. These registers will be stored in mActualContextAfterException. + // Do not handle Rsp and Rbp. CpuExceptionHandlerLib doesn't set Rsp and Rbp register + // to the value in SystemContext. + // + SystemContext.SystemContextX64->Rdi = mExpectedContextAfterException.Rdi; + SystemContext.SystemContextX64->Rsi = mExpectedContextAfterException.Rsi; + SystemContext.SystemContextX64->Rbx = mExpectedContextAfterException.Rbx; + SystemContext.SystemContextX64->Rdx = mExpectedContextAfterException.Rdx; + SystemContext.SystemContextX64->Rcx = mExpectedContextAfterException.Rcx; + SystemContext.SystemContextX64->Rax = mExpectedContextAfterException.Rax; + SystemContext.SystemContextX64->R8 = mExpectedContextAfterException.R8; + SystemContext.SystemContextX64->R9 = mExpectedContextAfterException.R9; + SystemContext.SystemContextX64->R10 = mExpectedContextAfterException.R10; + SystemContext.SystemContextX64->R11 = mExpectedContextAfterException.R11; + SystemContext.SystemContextX64->R12 = mExpectedContextAfterException.R12; + SystemContext.SystemContextX64->R13 = mExpectedContextAfterException.R13; + SystemContext.SystemContextX64->R14 = mExpectedContextAfterException.R14; + SystemContext.SystemContextX64->R15 = mExpectedContextAfterException.R15; + + // + // When fault exception happens, eip/rip points to the faulting instruction. + // For now, olny GP and PF are tested in fault exception. + // + if ((ExceptionType == EXCEPT_IA32_PAGE_FAULT) || (ExceptionType == EXCEPT_IA32_GP_FAULT)) { + AdjustRipForFaultHandler (ExceptionType, SystemContext); + } +} + +/** + Compare cpu context in ConsistencyOfCpuContext test case. + 1.Compare mActualContextInHandler with mExpectedContextInHandler. + 2.Compare mActualContextAfterException with mActualContextAfterException. + + @retval UNIT_TEST_PASSED The Unit test has completed and it was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +CompareCpuContext ( + VOID + ) +{ + UT_ASSERT_EQUAL (mActualContextInHandler.Rdi, mExpectedContextInHandler.Rdi); + UT_ASSERT_EQUAL (mActualContextInHandler.Rsi, mExpectedContextInHandler.Rsi); + UT_ASSERT_EQUAL (mActualContextInHandler.Rbx, mExpectedContextInHandler.Rbx); + UT_ASSERT_EQUAL (mActualContextInHandler.Rdx, mExpectedContextInHandler.Rdx); + UT_ASSERT_EQUAL (mActualContextInHandler.Rcx, mExpectedContextInHandler.Rcx); + UT_ASSERT_EQUAL (mActualContextInHandler.Rax, mExpectedContextInHandler.Rax); + UT_ASSERT_EQUAL (mActualContextInHandler.R8, mExpectedContextInHandler.R8); + UT_ASSERT_EQUAL (mActualContextInHandler.R9, mExpectedContextInHandler.R9); + UT_ASSERT_EQUAL (mActualContextInHandler.R10, mExpectedContextInHandler.R10); + UT_ASSERT_EQUAL (mActualContextInHandler.R11, mExpectedContextInHandler.R11); + UT_ASSERT_EQUAL (mActualContextInHandler.R12, mExpectedContextInHandler.R12); + UT_ASSERT_EQUAL (mActualContextInHandler.R13, mExpectedContextInHandler.R13); + UT_ASSERT_EQUAL (mActualContextInHandler.R14, mExpectedContextInHandler.R14); + UT_ASSERT_EQUAL (mActualContextInHandler.R15, mExpectedContextInHandler.R15); + + UT_ASSERT_EQUAL (mActualContextAfterException.Rdi, mExpectedContextAfterException.Rdi); + UT_ASSERT_EQUAL (mActualContextAfterException.Rsi, mExpectedContextAfterException.Rsi); + UT_ASSERT_EQUAL (mActualContextAfterException.Rbx, mExpectedContextAfterException.Rbx); + UT_ASSERT_EQUAL (mActualContextAfterException.Rdx, mExpectedContextAfterException.Rdx); + UT_ASSERT_EQUAL (mActualContextAfterException.Rcx, mExpectedContextAfterException.Rcx); + UT_ASSERT_EQUAL (mActualContextAfterException.Rax, mExpectedContextAfterException.Rax); + UT_ASSERT_EQUAL (mActualContextAfterException.R8, mExpectedContextAfterException.R8); + UT_ASSERT_EQUAL (mActualContextAfterException.R9, mExpectedContextAfterException.R9); + UT_ASSERT_EQUAL (mActualContextAfterException.R10, mExpectedContextAfterException.R10); + UT_ASSERT_EQUAL (mActualContextAfterException.R11, mExpectedContextAfterException.R11); + UT_ASSERT_EQUAL (mActualContextAfterException.R12, mExpectedContextAfterException.R12); + UT_ASSERT_EQUAL (mActualContextAfterException.R13, mExpectedContextAfterException.R13); + UT_ASSERT_EQUAL (mActualContextAfterException.R14, mExpectedContextAfterException.R14); + UT_ASSERT_EQUAL (mActualContextAfterException.R15, mExpectedContextAfterException.R15); + return UNIT_TEST_PASSED; +} + +/** + Special handler for CpuStackGuard test case. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. + +**/ +VOID +EFIAPI +CpuStackGuardExceptionHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + UINTN LocalVariable; + + AdjustRipForFaultHandler (ExceptionType, SystemContext); + mRspAddress[0] = (UINTN)SystemContext.SystemContextX64->Rsp; + mRspAddress[1] = (UINTN)(&LocalVariable); + + return; +} diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTestAsm.nasm b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTestAsm.nasm new file mode 100644 index 0000000000..e229dbed00 --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/X64/ArchExceptionHandlerTestAsm.nasm @@ -0,0 +1,256 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2022, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; ArchExceptionHandlerTestAsm.nasm +; +; Abstract: +; +; x64 CPU Exception Handler Lib Unit test +; +;------------------------------------------------------------------------------ + + DEFAULT REL + SECTION .text + +struc GENERAL_REGISTER + .Rdi: resq 1 + .Rsi: resq 1 + .Rbx: resq 1 + .Rdx: resq 1 + .Rcx: resq 1 + .Rax: resq 1 + .R8: resq 1 + .R9: resq 1 + .R10: resq 1 + .R11: resq 1 + .R12: resq 1 + .R13: resq 1 + .R14: resq 1 + .R15: resq 1 + +endstruc + +extern ASM_PFX(mExpectedContextInHandler) +extern ASM_PFX(mActualContextAfterException) +extern ASM_PFX(mFaultInstructionLength) + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerGPException ( +; UINTN Cr4ReservedBit +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerGPException) +ASM_PFX(TriggerGPException): + ; + ; Set reserved bit 15 of cr4 to 1 + ; + push rcx + lea rcx, [ASM_PFX(mFaultInstructionLength)] + mov qword[rcx], TriggerGPExceptionAfter - TriggerGPExceptionBefore + pop rcx +TriggerGPExceptionBefore: + mov cr4, rcx +TriggerGPExceptionAfter: + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerPFException ( +; UINTN PFAddress +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerPFException) +ASM_PFX(TriggerPFException): + push rcx + lea rcx, [ASM_PFX(mFaultInstructionLength)] + mov qword[rcx], TriggerPFExceptionAfter - TriggerPFExceptionBefore + pop rcx +TriggerPFExceptionBefore: + mov qword[rcx], 0x1 +TriggerPFExceptionAfter: + ret + +;------------------------------------------------------------------------------ +; ModifyRcxInGlobalBeforeException; +; This function is writed by assebly code because it's only called in this file. +; It's used to set Rcx in mExpectedContextInHandler for different exception. +;------------------------------------------------------------------------------ +global ASM_PFX(ModifyRcxInGlobalBeforeException) +ASM_PFX(ModifyRcxInGlobalBeforeException): + push rax + lea rax, [ASM_PFX(mExpectedContextInHandler)] + mov [rax + GENERAL_REGISTER.Rcx], rcx + pop rax + ret + +;------------------------------------------------------------------------------ +;VOID +;EFIAPI +;AsmTestConsistencyOfCpuContext ( +; IN EFI_EXCEPTION_TYPE ExceptionType +; IN UINTN FaultParameter OPTIONAL +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(AsmTestConsistencyOfCpuContext) +ASM_PFX(AsmTestConsistencyOfCpuContext): + ; + ; Push original register + ; + push r15 + push r14 + push r13 + push r12 + push r11 + push r10 + push r9 + push r8 + push rax + push rcx + push rbx + push rsi + push rdi + push rdx + push rdx + + ; + ; Modify registers to mExpectedContextInHandler. Do not handle Rsp and Rbp. + ; CpuExceptionHandlerLib doesn't set Rsp and Rsp register to the value in SystemContext. + ; + lea r15, [ASM_PFX(mExpectedContextInHandler)] + mov rdi, [r15 + GENERAL_REGISTER.Rdi] + mov rsi, [r15 + GENERAL_REGISTER.Rsi] + mov rbx, [r15 + GENERAL_REGISTER.Rbx] + mov rdx, [r15 + GENERAL_REGISTER.Rdx] + mov rax, [r15 + GENERAL_REGISTER.Rax] + mov r8, [r15 + GENERAL_REGISTER.R8] + mov r9, [r15 + GENERAL_REGISTER.R9] + mov r10, [r15 + GENERAL_REGISTER.R10] + mov r11, [r15 + GENERAL_REGISTER.R11] + mov r12, [r15 + GENERAL_REGISTER.R12] + mov r13, [r15 + GENERAL_REGISTER.R13] + mov r14, [r15 + GENERAL_REGISTER.R14] + mov r15, [r15 + GENERAL_REGISTER.R15] + + cmp rcx, 0xd + jz GPException + cmp rcx, 0xe + jz PFException + jmp INTnException + +PFException: + pop rcx ; Pop rdx(PFAddress) to rcx. + call ASM_PFX(ModifyRcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Rcx to PFAddress. + call ASM_PFX(TriggerPFException) + jmp AfterException + +GPException: + pop rcx ; Pop rdx(Cr4ReservedBit) to rcx. + call ASM_PFX(ModifyRcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Rcx to Cr4ReservedBit. + call ASM_PFX(TriggerGPException) + jmp AfterException + +INTnException: + ; + ; Modify Rcx in mExpectedContextInHandler. + ; + add Rsp, 8 ; Discard the extra Rdx in stack. Rcx is ExceptionType now. + call ASM_PFX(ModifyRcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Rcx to ExceptionType. + call ASM_PFX(TriggerINTnException) + +AfterException: + ; + ; Save registers in mActualContextAfterException + ; + push rax + lea rax, [ASM_PFX(mActualContextAfterException)] + mov [rax + GENERAL_REGISTER.Rdi], rdi + mov [rax + GENERAL_REGISTER.Rsi], rsi + mov [rax + GENERAL_REGISTER.Rbx], rbx + mov [rax + GENERAL_REGISTER.Rdx], rdx + mov [rax + GENERAL_REGISTER.Rcx], rcx + pop rcx + mov [rax + GENERAL_REGISTER.Rax], rcx + mov [rax + GENERAL_REGISTER.R8], r8 + mov [rax + GENERAL_REGISTER.R9], r9 + mov [rax + GENERAL_REGISTER.R10], r10 + mov [rax + GENERAL_REGISTER.R11], r11 + mov [rax + GENERAL_REGISTER.R12], r12 + mov [rax + GENERAL_REGISTER.R13], r13 + mov [rax + GENERAL_REGISTER.R14], r14 + mov [rax + GENERAL_REGISTER.R15], r15 + + ; + ; restore original register + ; + pop rdx + pop rdi + pop rsi + pop rbx + pop rcx + pop rax + pop r8 + pop r9 + pop r10 + pop r11 + pop r12 + pop r13 + pop r14 + pop r15 + + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerStackOverflow ( +; VOID +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerStackOverflow) +ASM_PFX(TriggerStackOverflow): + push rcx + lea rcx, [ASM_PFX(mFaultInstructionLength)] + mov qword[rcx], TriggerCpuStackGuardAfter - TriggerCpuStackGuardBefore + pop rcx +TriggerCpuStackGuardBefore: + call TriggerCpuStackGuardBefore +TriggerCpuStackGuardAfter: + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerINTnException ( +; IN EFI_EXCEPTION_TYPE ExceptionType +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerINTnException) +ASM_PFX(TriggerINTnException): + push rax + push rdx + push rcx + lea rax, [AsmTriggerException1 - AsmTriggerException0] + mul rcx + mov rcx, AsmTriggerException0 + add rax, rcx + pop rcx + pop rdx + jmp rax + ; + ; rax = AsmTriggerException0 + (AsmTriggerException1 - AsmTriggerException0) * rcx + ; +%assign Vector 0 +%rep 22 +AsmTriggerException %+ Vector: + pop rax + INT Vector + ret +%assign Vector Vector+1 +%endrep From 3257ebc200910e0d103777ccbf09536a17ea36b1 Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Mon, 17 Oct 2022 14:35:40 +0800 Subject: [PATCH 0168/1529] UefiCpuPkg: Add Unit tests for PeiCpuExceptionHandlerLib The previous change adds unit test for DxeCpuExeptionHandlerLib in 64bit mode. This change create a PEIM to add unit test for PeiCpuExceptionHandlerLib based on previous change.It can run in both 32bit and 64bit modes. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- .../UnitTest/CpuExceptionHandlerTest.h | 9 + .../UnitTest/Ia32/ArchExceptionHandlerTest.c | 135 ++++++++++++ .../Ia32/ArchExceptionHandlerTestAsm.nasm | 208 ++++++++++++++++++ .../PeiCpuExceptionHandlerLibUnitTest.inf | 61 +++++ .../UnitTest/PeiCpuExceptionHandlerUnitTest.c | 204 +++++++++++++++++ 5 files changed, 617 insertions(+) create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTest.c create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTestAsm.nasm create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf create mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h index 936098fde8..bad3387db5 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h @@ -93,6 +93,15 @@ typedef struct { UINT64 R15; } GENERAL_REGISTER; +typedef struct { + UINT32 Edi; + UINT32 Esi; + UINT32 Ebx; + UINT32 Edx; + UINT32 Ecx; + UINT32 Eax; +} GENERAL_REGISTER_IA32; + extern UINTN mFaultInstructionLength; extern EFI_EXCEPTION_TYPE mExceptionType; extern UINTN mRspAddress[]; diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTest.c new file mode 100644 index 0000000000..8bb27249dc --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTest.c @@ -0,0 +1,135 @@ +/** @file + Unit tests of the CpuExceptionHandlerLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuExceptionHandlerTest.h" + +GENERAL_REGISTER_IA32 mActualContextInHandler; +GENERAL_REGISTER_IA32 mActualContextAfterException; + +// +// In TestCpuContextConsistency, Cpu registers will be set to mExpectedContextInHandler/mExpectedContextAfterException. +// Ecx in mExpectedContextInHandler is set runtime since Ecx is needed in assembly code. +// For GP and PF, Ecx is set to FaultParameter. For other exception triggered by INTn, Ecx is set to ExceptionType. +// +GENERAL_REGISTER_IA32 mExpectedContextInHandler = { 1, 2, 3, 4, 5, 0 }; +GENERAL_REGISTER_IA32 mExpectedContextAfterException = { 11, 12, 13, 14, 15, 16 }; + +/** + Special handler for fault exception. + Rip/Eip in SystemContext will be modified to the instruction after the exception instruction. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. + +**/ +VOID +EFIAPI +AdjustRipForFaultHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + mExceptionType = ExceptionType; + SystemContext.SystemContextIa32->Eip += mFaultInstructionLength; +} + +/** + Special handler for ConsistencyOfCpuContext test case. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +AdjustCpuContextHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + // + // Store SystemContext in exception handler. + // + mActualContextInHandler.Edi = SystemContext.SystemContextIa32->Edi; + mActualContextInHandler.Esi = SystemContext.SystemContextIa32->Esi; + mActualContextInHandler.Ebx = SystemContext.SystemContextIa32->Ebx; + mActualContextInHandler.Edx = SystemContext.SystemContextIa32->Edx; + mActualContextInHandler.Ecx = SystemContext.SystemContextIa32->Ecx; + mActualContextInHandler.Eax = SystemContext.SystemContextIa32->Eax; + + // + // Modify cpu context. These registers will be stored in mActualContextAfterException. + // Do not handle Esp and Ebp in SystemContext. CpuExceptionHandlerLib doesn't set Esp and + // Esp register to the value in SystemContext. + // + SystemContext.SystemContextIa32->Edi = mExpectedContextAfterException.Edi; + SystemContext.SystemContextIa32->Esi = mExpectedContextAfterException.Esi; + SystemContext.SystemContextIa32->Ebx = mExpectedContextAfterException.Ebx; + SystemContext.SystemContextIa32->Edx = mExpectedContextAfterException.Edx; + SystemContext.SystemContextIa32->Ecx = mExpectedContextAfterException.Ecx; + SystemContext.SystemContextIa32->Eax = mExpectedContextAfterException.Eax; + + // + // When fault exception happens, eip/rip points to the faulting instruction. + // For now, olny GP and PF are tested in fault exception. + // + if ((ExceptionType == EXCEPT_IA32_PAGE_FAULT) || (ExceptionType == EXCEPT_IA32_GP_FAULT)) { + AdjustRipForFaultHandler (ExceptionType, SystemContext); + } +} + +/** + Compare cpu context in ConsistencyOfCpuContext test case. + 1.Compare mActualContextInHandler with mExpectedContextInHandler. + 2.Compare mActualContextAfterException with mExpectedContextAfterException. + + @retval UNIT_TEST_PASSED The Unit test has completed and it was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +CompareCpuContext ( + VOID + ) +{ + UT_ASSERT_EQUAL (mActualContextInHandler.Edi, mExpectedContextInHandler.Edi); + UT_ASSERT_EQUAL (mActualContextInHandler.Esi, mExpectedContextInHandler.Esi); + UT_ASSERT_EQUAL (mActualContextInHandler.Ebx, mExpectedContextInHandler.Ebx); + UT_ASSERT_EQUAL (mActualContextInHandler.Edx, mExpectedContextInHandler.Edx); + UT_ASSERT_EQUAL (mActualContextInHandler.Ecx, mExpectedContextInHandler.Ecx); + UT_ASSERT_EQUAL (mActualContextInHandler.Eax, mExpectedContextInHandler.Eax); + + UT_ASSERT_EQUAL (mActualContextAfterException.Edi, mExpectedContextAfterException.Edi); + UT_ASSERT_EQUAL (mActualContextAfterException.Esi, mExpectedContextAfterException.Esi); + UT_ASSERT_EQUAL (mActualContextAfterException.Ebx, mExpectedContextAfterException.Ebx); + UT_ASSERT_EQUAL (mActualContextAfterException.Edx, mExpectedContextAfterException.Edx); + UT_ASSERT_EQUAL (mActualContextAfterException.Ecx, mExpectedContextAfterException.Ecx); + UT_ASSERT_EQUAL (mActualContextAfterException.Eax, mExpectedContextAfterException.Eax); + return UNIT_TEST_PASSED; +} + +/** + Special handler for CpuStackGuard test case. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. + +**/ +VOID +EFIAPI +CpuStackGuardExceptionHandler ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + UINTN LocalVariable; + + AdjustRipForFaultHandler (ExceptionType, SystemContext); + mRspAddress[0] = (UINTN)SystemContext.SystemContextIa32->Esp; + mRspAddress[1] = (UINTN)(&LocalVariable); + + return; +} diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTestAsm.nasm b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTestAsm.nasm new file mode 100644 index 0000000000..48031a5109 --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/Ia32/ArchExceptionHandlerTestAsm.nasm @@ -0,0 +1,208 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2022, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; ArchExceptionHandlerTestAsm.nasm +; +; Abstract: +; +; ia32 CPU Exception Handler Lib Unit test +; +;------------------------------------------------------------------------------ + + SECTION .text + +struc GENERAL_REGISTER_IA32 + .Edi: resd 1 + .Esi: resd 1 + .Ebx: resd 1 + .Edx: resd 1 + .Ecx: resd 1 + .Eax: resd 1 + +endstruc + +extern ASM_PFX(mExpectedContextInHandler) +extern ASM_PFX(mActualContextAfterException) +extern ASM_PFX(mFaultInstructionLength) + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerGPException ( +; UINTN Cr4ReservedBit +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerGPException) +ASM_PFX(TriggerGPException): + ; + ; Set reserved bit 15 of cr4 to 1 + ; + lea ecx, [ASM_PFX(mFaultInstructionLength)] + mov dword[ecx], TriggerGPExceptionAfter - TriggerGPExceptionBefore + mov ecx, dword [esp + 0x4] +TriggerGPExceptionBefore: + mov cr4, ecx +TriggerGPExceptionAfter: + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerPFException ( +; UINTN PfAddress +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerPFException) +ASM_PFX(TriggerPFException): + lea ecx, [ASM_PFX(mFaultInstructionLength)] + mov dword[ecx], TriggerPFExceptionAfter - TriggerPFExceptionBefore + mov ecx, dword [esp + 0x4] +TriggerPFExceptionBefore: + mov dword[ecx], 0x1 +TriggerPFExceptionAfter: + ret + +;------------------------------------------------------------------------------ +; ModifyEcxInGlobalBeforeException; +; This function is writed by assebly code because it's only called in this file. +; It's used to set Ecx in mExpectedContextInHandler for different exception. +;------------------------------------------------------------------------------ +global ASM_PFX(ModifyEcxInGlobalBeforeException) +ASM_PFX(ModifyEcxInGlobalBeforeException): + push eax + lea eax, [ASM_PFX(mExpectedContextInHandler)] + mov [eax + GENERAL_REGISTER_IA32.Ecx], ecx + pop eax + ret + +;------------------------------------------------------------------------------ +;VOID +;EFIAPI +;AsmTestConsistencyOfCpuContext ( +; IN EFI_EXCEPTION_TYPE ExceptionType +; IN UINTN FaultParameter OPTIONAL +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(AsmTestConsistencyOfCpuContext) +ASM_PFX(AsmTestConsistencyOfCpuContext): + ; + ; push 7 general register plus 4 bytes + ; + pushad + + ; + ; Modify register to mExpectedContextInHandler. Do not handle Esp and Ebp. + ; CpuExceptionHandlerLib doesn't set Esp and Esp register to the value in SystemContext. + ; + lea eax, [ASM_PFX(mExpectedContextInHandler)] + mov edi, [eax + GENERAL_REGISTER_IA32.Edi] + mov esi, [eax + GENERAL_REGISTER_IA32.Esi] + mov ebx, [eax + GENERAL_REGISTER_IA32.Ebx] + mov edx, [eax + GENERAL_REGISTER_IA32.Edx] + ; + ; Set ecx to ExceptionType + ; + mov ecx, dword [esp + 0x24] + mov eax, [eax + GENERAL_REGISTER_IA32.Eax] + + cmp ecx, 0xd + jz GPException + cmp ecx, 0xe + jz PFException + jmp INTnException + +PFException: + mov ecx, dword [esp + 0x28] ; Set ecx to PFAddress. + call ASM_PFX(ModifyEcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Ecx to PFAddress. + push ecx ; Push PfAddress into stack. + call ASM_PFX(TriggerPFException) + jmp AfterException + +GPException: + mov ecx, dword [esp + 0x28] ; Set ecx to CR4_RESERVED_BIT. + call ASM_PFX(ModifyEcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Ecx to CR4_RESERVED_BIT. + push ecx ; Push CR4_RESERVED_BIT into stack. + call ASM_PFX(TriggerGPException) + jmp AfterException + +INTnException: + call ASM_PFX(ModifyEcxInGlobalBeforeException) ; Set mExpectedContextInHandler.Ecx to ExceptionType. + push ecx ; Push ExceptionType into stack. + call ASM_PFX(TriggerINTnException) + +AfterException: + ; + ; Save register in mActualContextAfterException. + ; + push eax + lea eax, [ASM_PFX(mActualContextAfterException)] + mov [eax + GENERAL_REGISTER_IA32.Edi], edi + mov [eax + GENERAL_REGISTER_IA32.Esi], esi + mov [eax + GENERAL_REGISTER_IA32.Ebx], ebx + mov [eax + GENERAL_REGISTER_IA32.Edx], edx + mov [eax + GENERAL_REGISTER_IA32.Ecx], ecx + pop ecx + mov [eax + GENERAL_REGISTER_IA32.Eax], ecx + add esp, 4 + + ; + ; restore original register + ; + popad + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerStackOverflow ( +; VOID +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerStackOverflow) +ASM_PFX(TriggerStackOverflow): + lea ecx, [ASM_PFX(mFaultInstructionLength)] + mov dword[ecx], TriggerCpuStackGuardAfter - TriggerCpuStackGuardBefore +TriggerCpuStackGuardBefore: + ; + ; Clear CR0.TS since it is set after return from a nested DF + ; + call TriggerCpuStackGuardBefore + clts +TriggerCpuStackGuardAfter: + ret + +;------------------------------------------------------------------------------ +; VOID +; EFIAPI +; TriggerINTnException ( +; IN EFI_EXCEPTION_TYPE ExceptionType +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(TriggerINTnException) +ASM_PFX(TriggerINTnException): + push eax + push edx + lea eax, [AsmTriggerException1 - AsmTriggerException0] + mov ecx, dword [esp + 0xc] + push ecx + mul ecx + mov ecx, AsmTriggerException0 + add eax, ecx + pop ecx + pop edx + jmp eax + ; + ; eax = AsmTriggerException0 + (AsmTriggerException1 - AsmTriggerException0) * ecx + ; +%assign Vector 0 +%rep 22 +AsmTriggerException %+ Vector: + pop eax + INT Vector + ret +%assign Vector Vector+1 +%endrep diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf new file mode 100644 index 0000000000..25f8f8dbe0 --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf @@ -0,0 +1,61 @@ +## @file +# Unit tests of the PeiCpuExceptionHandlerLib instance. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = CpuExceptionHandlerPeiTest + FILE_GUID = 39A96CF7-F369-4357-9234-4B52F98A007F + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = PeiEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# +[Sources.Ia32] + Ia32/ArchExceptionHandlerTestAsm.nasm + Ia32/ArchExceptionHandlerTest.c + +[Sources.X64] + X64/ArchExceptionHandlerTestAsm.nasm + X64/ArchExceptionHandlerTest.c + +[Sources.common] + CpuExceptionHandlerTest.h + CpuExceptionHandlerTestCommon.c + PeiCpuExceptionHandlerUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib + MemoryAllocationLib + CpuExceptionHandlerLib + PeimEntryPoint + HobLib + PeiServicesLib + CpuPageTableLib + PeiServicesTablePointerLib + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize ## CONSUMES + +[Ppis] + gEdkiiPeiMpServices2PpiGuid ## CONSUMES + +[Depex] + gEdkiiPeiMpServices2PpiGuid AND + gEfiPeiMemoryDiscoveredPpiGuid diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c new file mode 100644 index 0000000000..d9408d2f5e --- /dev/null +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c @@ -0,0 +1,204 @@ +/** @file + Unit tests of the CpuExceptionHandlerLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuExceptionHandlerTest.h" +#include +#include +#include + +/** + Initialize Bsp Idt with a new Idt table and return the IA32_DESCRIPTOR buffer. + In PEIM, store original PeiServicePointer before new Idt table. + + @return Pointer to the allocated IA32_DESCRIPTOR buffer. +**/ +VOID * +InitializeBspIdt ( + VOID + ) +{ + UINTN *NewIdtTable; + IA32_DESCRIPTOR *Idtr; + + Idtr = AllocateZeroPool (sizeof (IA32_DESCRIPTOR)); + ASSERT (Idtr != NULL); + NewIdtTable = AllocateZeroPool (sizeof (IA32_IDT_GATE_DESCRIPTOR) * CPU_INTERRUPT_NUM + sizeof (UINTN)); + ASSERT (NewIdtTable != NULL); + // + // Store original PeiServicePointer before new Idt table + // + *NewIdtTable = (UINTN)GetPeiServicesTablePointer (); + NewIdtTable = (UINTN *)((UINTN)NewIdtTable + sizeof (UINTN)); + + Idtr->Base = (UINTN)NewIdtTable; + Idtr->Limit = (UINT16)(sizeof (IA32_IDT_GATE_DESCRIPTOR) * CPU_INTERRUPT_NUM - 1); + + AsmWriteIdtr (Idtr); + return Idtr; +} + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) +{ + return MpServices.Ppi->GetNumberOfProcessors (MpServices.Ppi, NumberOfProcessors, NumberOfEnabledProcessors); +} + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Ppi->StartupThisAP (MpServices.Ppi, Procedure, ProcessorNumber, TimeoutInMicroSeconds, ProcedureArgument); +} + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Ppi->StartupAllAPs (MpServices.Ppi, Procedure, SingleThread, TimeoutInMicroSeconds, ProcedureArgument); +} + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ) +{ + return MpServices.Ppi->WhoAmI (MpServices.Ppi, ProcessorNumber); +} + +/** + Get EDKII_PEI_MP_SERVICES2_PPI pointer. + + @param[out] MpServices Pointer to the buffer where EDKII_PEI_MP_SERVICES2_PPI is stored + + @retval EFI_SUCCESS EDKII_PEI_MP_SERVICES2_PPI interface is returned + @retval EFI_NOT_FOUND EDKII_PEI_MP_SERVICES2_PPI interface is not found +**/ +EFI_STATUS +GetMpServices ( + OUT MP_SERVICES *MpServices + ) +{ + return PeiServicesLocatePpi (&gEdkiiPeiMpServices2PpiGuid, 0, NULL, (VOID **)&MpServices->Ppi); +} + +/** + Entry point of CpuExceptionHandlerPeiTest PEIM. + + @param[in] FileHandle Handle of the file being invoked. + @param[in] PeiServices Describes the list of possible PEI Services. + + @retval EFI_SUCCESS The PEIM executed normally. + +**/ +EFI_STATUS +EFIAPI +PeiEntryPoint ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + Status = AddCommonTestCase (Framework); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in AddCommonTestCase. Status = %r\n", Status)); + goto EXIT; + } + + // + // Execute the tests. + // + Status = RunAllTestSuites (Framework); + +EXIT: + if (Framework) { + FreeUnitTestFramework (Framework); + } + + return Status; +} From f7954f73c02d468463353d16eca3a034d3347efa Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Mon, 17 Oct 2022 14:35:41 +0800 Subject: [PATCH 0169/1529] UefiCpuPkg: Add Pei/DxeCpuExceptionHandlerLibUnitTest in dsc Add Pei/DxeCpuExceptionHandlerLibUnitTest module in UefiCpuPkg.dsc Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- UefiCpuPkg/UefiCpuPkg.dsc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index f694b3a77c..6d89458ecb 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -63,6 +63,9 @@ MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf SmmCpuRendezvousLib|UefiCpuPkg/Library/SmmCpuRendezvousLib/SmmCpuRendezvousLib.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf [LibraryClasses.common.SEC] PlatformSecLib|UefiCpuPkg/Library/PlatformSecLibNull/PlatformSecLibNull.inf @@ -177,6 +180,10 @@ UefiCpuPkg/ResetVector/Vtf0/Bin/ResetVector.inf UefiCpuPkg/Library/SmmCpuRendezvousLib/SmmCpuRendezvousLib.inf UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf + UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf + +[Components.X64] + UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 2564d8d03b73d60c53f7a2b0cb6acc0c71b0a01a Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Mon, 17 Oct 2022 14:35:42 +0800 Subject: [PATCH 0170/1529] UefiCpuPkg: Add R8/R9 etc in EccCheck ExceptionList Add GENERAL_REGISTER.R8/R9 etc in EccCheck ExceptionList of UefiCpuPkg/UefiCpuPkg.ci.yaml to pass CI EccCheck.R8/R9 in structure GENERAL_REGISTER of CpuExceptionHandlerTest.h lead to EccCheck failure since no lower case characters in R8/R9/R10 etc. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- UefiCpuPkg/UefiCpuPkg.ci.yaml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/UefiCpuPkg.ci.yaml b/UefiCpuPkg/UefiCpuPkg.ci.yaml index bbdc44a45b..a377366798 100644 --- a/UefiCpuPkg/UefiCpuPkg.ci.yaml +++ b/UefiCpuPkg/UefiCpuPkg.ci.yaml @@ -15,7 +15,15 @@ ## "", "" ## ] "ExceptionList": [ - "8006", "main" + "8006", "main", + "8005", "GENERAL_REGISTER.R8", + "8005", "GENERAL_REGISTER.R9", + "8005", "GENERAL_REGISTER.R10", + "8005", "GENERAL_REGISTER.R11", + "8005", "GENERAL_REGISTER.R12", + "8005", "GENERAL_REGISTER.R13", + "8005", "GENERAL_REGISTER.R14", + "8005", "GENERAL_REGISTER.R15" ], ## Both file path and directory path are accepted. "IgnoreFiles": [ From 3cb74f839599e380025c047e59474948877a03f0 Mon Sep 17 00:00:00 2001 From: Jason Lou Date: Mon, 10 Oct 2022 21:52:42 +0800 Subject: [PATCH 0171/1529] UefiCpuPkg/Test: Add unit tests for MP service PPI and Protocol The code changes add unit tests based on current UnitTestFramework. EdkiiPeiMpServices2PpiPeiUnitTest PEI module is used to test EdkiiPeiMpServices2Ppi and EfiMpServiceProtocolDxeUnitTest DXE driver is used to test EfiMpServiceProtocol. Signed-off-by: Jason Lou Reviewed-by: Ray Ni Cc: Eric Dong Cc: Laszlo Ersek Cc: Rahul Kumar --- .../EdkiiPeiMpServices2PpiPeiUnitTest.inf | 46 + .../EdkiiPeiMpServices2PpiUnitTest.c | 477 +++++ .../EfiMpServiceProtocolDxeUnitTest.inf | 46 + .../EfiMpServiceProtocolUnitTest.c | 244 +++ .../EfiMpServicesUnitTestCommom.c | 1776 +++++++++++++++++ .../EfiMpServicesUnitTestCommom.h | 627 ++++++ UefiCpuPkg/UefiCpuPkg.dsc | 2 + 7 files changed, 3218 insertions(+) create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiUnitTest.c create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf new file mode 100644 index 0000000000..0b2ddc5585 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf @@ -0,0 +1,46 @@ +## @file +# PEIM that unit tests the EdkiiPeiMpServices2Ppi +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = EdkiiPeiMpServices2PpiPeiUnitTest + FILE_GUID = A4914810-4D1E-445E-BD6F-F6821B852B5D + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = PeiEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + EfiMpServicesUnitTestCommom.c + EfiMpServicesUnitTestCommom.h + EdkiiPeiMpServices2PpiUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + BaseMemoryLib + MemoryAllocationLib + PeimEntryPoint + PeiServicesLib + UnitTestPersistenceLib + UnitTestLib + +[Ppis] + gEdkiiPeiMpServices2PpiGuid ## CONSUMES + +[Depex] + gEdkiiPeiMpServices2PpiGuid diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiUnitTest.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiUnitTest.c new file mode 100644 index 0000000000..5c42a81d29 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiUnitTest.c @@ -0,0 +1,477 @@ +/** @file + PEI Module to test APIs defined in EdkiiPeiMpServices2Ppi. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include "EfiMpServicesUnitTestCommom.h" + +#define UNIT_TEST_NAME "EdkiiPeiMpServices2Ppi Unit Test" +#define UNIT_TEST_VERSION "0.1" + +/** + Get EDKII_PEI_MP_SERVICES2_PPI pointer. + + @param[out] MpServices Pointer to the buffer where EDKII_PEI_MP_SERVICES2_PPI is stored. + + @retval EFI_SUCCESS EDKII_PEI_MP_SERVICES2_PPI interface is returned + @retval EFI_NOT_FOUND EDKII_PEI_MP_SERVICES2_PPI interface is not found +**/ +EFI_STATUS +MpServicesUnitTestGetMpServices ( + OUT MP_SERVICES *MpServices + ) +{ + return PeiServicesLocatePpi (&gEdkiiPeiMpServices2PpiGuid, 0, NULL, (VOID **)&MpServices->Ppi); +} + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) +{ + return MpServices.Ppi->GetNumberOfProcessors (MpServices.Ppi, NumberOfProcessors, NumberOfEnabledProcessors); +} + +/** + Get detailed information on the requested logical processor. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the processor. + @param[out] ProcessorInfoBuffer Pointer to the buffer where the processor information is stored. + + @retval EFI_SUCCESS Get information on the requested logical processor successfully + @retval Others Get information on the requested logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetProcessorInfo ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer + ) +{ + return MpServices.Ppi->GetProcessorInfo (MpServices.Ppi, ProcessorNumber, ProcessorInfoBuffer); +} + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Ppi->StartupAllAPs (MpServices.Ppi, Procedure, SingleThread, TimeoutInMicroSeconds, ProcedureArgument); +} + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Ppi->StartupThisAP (MpServices.Ppi, Procedure, ProcessorNumber, TimeoutInMicroSeconds, ProcedureArgument); +} + +/** + Switch the requested AP to be the BSP from that point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of AP that is to become the new BSP. + @param[in] EnableOldBSP If TRUE, the old BSP will be listed as an enabled AP. Otherwise, it will be disabled. + + @retval EFI_SUCCESS Switch the requested AP to be the BSP successfully + @retval Others Switch the requested AP to be the BSP unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestSwitchBSP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableOldBSP + ) +{ + return MpServices.Ppi->SwitchBSP (MpServices.Ppi, ProcessorNumber, EnableOldBSP); +} + +/** + Caller enables or disables an AP from this point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] EnableAP Specifies the new state for the processor for enabled, FALSE for disabled. + @param[in] HealthFlag If not NULL, a pointer to a value that specifies the new health status of the AP. + + @retval EFI_SUCCESS Caller enables or disables an AP successfully. + @retval Others Caller enables or disables an AP unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestEnableDisableAP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableAP, + IN UINT32 *HealthFlag + ) +{ + return MpServices.Ppi->EnableDisableAP (MpServices.Ppi, ProcessorNumber, EnableAP, HealthFlag); +} + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ) +{ + return MpServices.Ppi->WhoAmI (MpServices.Ppi, ProcessorNumber); +} + +/** + Execute a caller provided function on all enabled CPUs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled CPUs of the system. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all enabled CPUs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled CPUs successfully + @retval Others Execute a caller provided function on all enabled CPUs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllCPUs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Ppi->StartupAllCPUs (MpServices.Ppi, Procedure, TimeoutInMicroSeconds, ProcedureArgument); +} + +/** + Infinite loop procedure to be run on specified AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +ApInfiniteLoopProcedure ( + IN OUT VOID *Buffer + ) +{ + EFI_STATUS Status; + UINTN ProcessorNumber; + volatile BOOLEAN InfiniteLoop; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &ProcessorNumber); + ASSERT_EFI_ERROR (Status); + + if (ProcessorNumber == LocalContext->BspNumber) { + InfiniteLoop = FALSE; + } else { + InfiniteLoop = TRUE; + } + + while (InfiniteLoop) { + } +} + +/** + Procedure to run MP service StartupAllCPUs on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceStartupAllCPUsOnAp ( + IN OUT VOID *Buffer + ) +{ + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestStartupAllCPUs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + 0, + NULL + ); +} + +/** + Unit test of PEI MP service StartupAllCPU. + All CPUs should execute the Procedure. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllCPUs1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + SetMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer), 0xFF); + Status = MpServicesUnitTestStartupAllCPUs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreCpuNumbers, + 0, + (VOID *)LocalContext + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors; ProcessorIndex++) { + UT_ASSERT_TRUE (LocalContext->CommonBuffer[ProcessorIndex] == ProcessorIndex); + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of PEI MP service StartupAllCPU. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllCPUs2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceStartupAllCPUsOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of PEI MP service StartupAllCPU. + When called with all CPUs timeout, the return status should be EFI_TIMEOUT. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllCPUs3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + Status = MpServicesUnitTestStartupAllCPUs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)ApInfiniteLoopProcedure, + RUN_PROCEDURE_TIMEOUT_VALUE, + (VOID *)LocalContext + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_TIMEOUT); + + return UNIT_TEST_PASSED; +} + +/** + Create test suite and unit tests only for EdkiiPeiMpServices2Ppi. + + @param[in] Framework A pointer to the framework that is being persisted. + @param[in] Context A pointer to the private data buffer. + + @retval EFI_SUCCESS Create test suite and unit tests successfully. + @retval Others Create test suite and unit tests unsuccessfully. +**/ +EFI_STATUS +AddTestCaseOnlyForEdkiiPeiMpServices2Ppi ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN MP_SERVICE_UT_CONTEXT *Context + ) +{ + EFI_STATUS Status; + UNIT_TEST_SUITE_HANDLE MpServiceStartupAllCPUsTestSuite; + + MpServiceStartupAllCPUsTestSuite = NULL; + + // + // Test StartupAllCPUs function + // + Status = CreateUnitTestSuite (&MpServiceStartupAllCPUsTestSuite, Framework, "Execute a caller provided function on all enabled CPUs", "MpServices.StartupAllCPUs", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceStartupAllCPUs Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceStartupAllCPUsTestSuite, "Test StartupAllCPUs 1", "TestStartupAllCPUs1", TestStartupAllCPUs1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllCPUsTestSuite, "Test StartupAllCPUs 2", "TestStartupAllCPUs2", TestStartupAllCPUs2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllCPUsTestSuite, "Test StartupAllCPUs 3", "TestStartupAllCPUs3", TestStartupAllCPUs3, InitUTContext, CheckUTContext, Context); + + return EFI_SUCCESS; +} + +/** + Standard PEIM entry point for unit test execution from PEI. + Initialize the unit test framework, suite, and unit tests for the EdkiiPeiMpServices2Ppi and run the unit test. + + @param[in] FileHandle Handle of the file being invoked. + @param[in] PeiServices Pointer to PEI Services table. + +**/ +EFI_STATUS +EFIAPI +PeiEntryPoint ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + MP_SERVICE_UT_CONTEXT Context; + + Framework = NULL; + Context.MpServices.Ppi = NULL; + Context.CommonBuffer = NULL; + Context.DisabledApNumber = NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Create test suite and unit tests only for EdkiiPeiMpServices2Ppi. + // + Status = AddTestCaseOnlyForEdkiiPeiMpServices2Ppi (Framework, &Context); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in AddTestCaseOnlyForEdkiiPeiMpServices2Ppi. Status = %r\n", Status)); + goto EXIT; + } + + // + // Create test suite and unit tests for both EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol. + // + Status = AddCommonTestCase (Framework, &Context); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in AddCommonTestCase. Status = %r\n", Status)); + goto EXIT; + } + + // + // Execute the tests. + // + Status = RunAllTestSuites (Framework); + +EXIT: + if (Framework != NULL) { + FreeUnitTestFramework (Framework); + } + + return Status; +} diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf new file mode 100644 index 0000000000..1389092c06 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf @@ -0,0 +1,46 @@ +## @file +# DXE driver that unit tests the EfiMpServiceProtocol +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = EfiMpServiceProtocolDxeUnitTest + FILE_GUID = F1E468E2-A32D-4574-895D-6D82B27B08BC + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + EfiMpServicesUnitTestCommom.c + EfiMpServicesUnitTestCommom.h + EfiMpServiceProtocolUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + BaseMemoryLib + MemoryAllocationLib + UefiDriverEntryPoint + UefiBootServicesTableLib + UnitTestPersistenceLib + UnitTestLib + +[Protocols] + gEfiMpServiceProtocolGuid ## CONSUMES + +[Depex] + gEfiMpServiceProtocolGuid diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c new file mode 100644 index 0000000000..57f8ba3c06 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c @@ -0,0 +1,244 @@ +/** @file + PEI Module to test EfiMpServiceProtocol. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include "EfiMpServicesUnitTestCommom.h" + +#define UNIT_TEST_NAME "EfiMpServiceProtocol Unit Test" +#define UNIT_TEST_VERSION "0.1" + +/** + Get EFI_MP_SERVICES_PROTOCOL pointer. + + @param[out] MpServices Pointer to the buffer where EFI_MP_SERVICES_PROTOCOL is stored + + @retval EFI_SUCCESS EFI_MP_SERVICES_PROTOCOL interface is returned + @retval EFI_NOT_FOUND EFI_MP_SERVICES_PROTOCOL interface is not found +**/ +EFI_STATUS +MpServicesUnitTestGetMpServices ( + OUT MP_SERVICES *MpServices + ) +{ + return gBS->LocateProtocol (&gEfiMpServiceProtocolGuid, NULL, (VOID **)&MpServices->Protocol); +} + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) +{ + return MpServices.Protocol->GetNumberOfProcessors (MpServices.Protocol, NumberOfProcessors, NumberOfEnabledProcessors); +} + +/** + Get detailed information on the requested logical processor. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the processor. + @param[out] ProcessorInfoBuffer Pointer to the buffer where the processor information is stored. + + @retval EFI_SUCCESS Get information on the requested logical processor successfully + @retval Others Get information on the requested logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetProcessorInfo ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer + ) +{ + return MpServices.Protocol->GetProcessorInfo (MpServices.Protocol, ProcessorNumber, ProcessorInfoBuffer); +} + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Protocol->StartupAllAPs (MpServices.Protocol, Procedure, SingleThread, NULL, TimeoutInMicroSeconds, ProcedureArgument, NULL); +} + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ) +{ + return MpServices.Protocol->StartupThisAP (MpServices.Protocol, Procedure, ProcessorNumber, NULL, TimeoutInMicroSeconds, ProcedureArgument, NULL); +} + +/** + Switch the requested AP to be the BSP from that point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of AP that is to become the new BSP. + @param[in] EnableOldBSP If TRUE, the old BSP will be listed as an enabled AP. Otherwise, it will be disabled. + + @retval EFI_SUCCESS Switch the requested AP to be the BSP successfully + @retval Others Switch the requested AP to be the BSP unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestSwitchBSP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableOldBSP + ) +{ + return MpServices.Protocol->SwitchBSP (MpServices.Protocol, ProcessorNumber, EnableOldBSP); +} + +/** + Caller enables or disables an AP from this point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] EnableAP Specifies the new state for the processor for enabled, FALSE for disabled. + @param[in] HealthFlag If not NULL, a pointer to a value that specifies the new health status of the AP. + + @retval EFI_SUCCESS Caller enables or disables an AP successfully. + @retval Others Caller enables or disables an AP unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestEnableDisableAP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableAP, + IN UINT32 *HealthFlag + ) +{ + return MpServices.Protocol->EnableDisableAP (MpServices.Protocol, ProcessorNumber, EnableAP, HealthFlag); +} + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ) +{ + return MpServices.Protocol->WhoAmI (MpServices.Protocol, ProcessorNumber); +} + +/** + Standard DXE driver or UEFI application entry point for unit test execution from DXE or UEFI Shell. + Initialize the unit test framework, suite, and unit tests for the EfiMpServiceProtocol and run the unit test. + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + +**/ +EFI_STATUS +EFIAPI +DxeEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + MP_SERVICE_UT_CONTEXT Context; + + Framework = NULL; + Context.MpServices.Ppi = NULL; + Context.CommonBuffer = NULL; + Context.DisabledApNumber = NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Create test suite and unit tests for both EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol. + // + Status = AddCommonTestCase (Framework, &Context); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in AddCommonTestCase. Status = %r\n", Status)); + goto EXIT; + } + + // + // Execute the tests. + // + Status = RunAllTestSuites (Framework); + +EXIT: + if (Framework != NULL) { + FreeUnitTestFramework (Framework); + } + + return Status; +} diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c new file mode 100644 index 0000000000..ff79c5e8d4 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c @@ -0,0 +1,1776 @@ +/** @file + Common code to test EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "EfiMpServicesUnitTestCommom.h" + +/** + Prep routine for Unit test function. + To save the ProcessorNumber of disabled AP and temporarily enable it. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED Prep routine runs successful. + @retval UNIT_TEST_ERROR_TEST_FAILED Prep routine runs unsuccessful. +**/ +UNIT_TEST_STATUS +EFIAPI +InitUTContext ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + UINTN NumberOfDisabledAPs; + UINTN IndexOfDisabledAPs; + UINTN BspNumber; + UINTN ProcessorNumber; + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + if (LocalContext->MpServices.Ppi != NULL) { + return UNIT_TEST_PASSED; + } + + Status = MpServicesUnitTestGetMpServices (&LocalContext->MpServices); + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &BspNumber); + UT_ASSERT_NOT_EFI_ERROR (Status); + DEBUG ((DEBUG_INFO, "%a: BspNumber = 0x%x\n", __FUNCTION__, BspNumber)); + + Status = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + DEBUG (( + DEBUG_INFO, + "%a: NumberOfProcessors = 0x%x, NumberOfEnabledProcessors = 0x%x\n", + __FUNCTION__, + NumberOfProcessors, + NumberOfEnabledProcessors + )); + + LocalContext->BspNumber = BspNumber; + LocalContext->NumberOfProcessors = NumberOfProcessors; + LocalContext->NumberOfEnabledProcessors = NumberOfEnabledProcessors; + + LocalContext->CommonBuffer = AllocatePages (EFI_SIZE_TO_PAGES (NumberOfProcessors * sizeof (*LocalContext->CommonBuffer))); + UT_ASSERT_NOT_NULL (LocalContext->CommonBuffer); + + NumberOfDisabledAPs = NumberOfProcessors - NumberOfEnabledProcessors; + if ((NumberOfDisabledAPs > 0) && (LocalContext->DisabledApNumber == NULL)) { + LocalContext->DisabledApNumber = AllocatePages (EFI_SIZE_TO_PAGES (NumberOfDisabledAPs * sizeof (*LocalContext->DisabledApNumber))); + UT_ASSERT_NOT_NULL (LocalContext->DisabledApNumber); + ZeroMem (LocalContext->DisabledApNumber, NumberOfDisabledAPs * sizeof (*LocalContext->DisabledApNumber)); + + for (ProcessorNumber = 0, IndexOfDisabledAPs = 0; ProcessorNumber < LocalContext->NumberOfProcessors; ProcessorNumber++) { + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + ProcessorNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + if (!(ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT)) { + // + // Save ProcessorNumber of disabled AP. + // + LocalContext->DisabledApNumber[IndexOfDisabledAPs] = ProcessorNumber; + IndexOfDisabledAPs++; + + DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled and temporarily enable it.\n", __FUNCTION__, ProcessorNumber)); + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ProcessorNumber, + TRUE, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + UT_ASSERT_TRUE (IndexOfDisabledAPs == NumberOfDisabledAPs); + } + + return UNIT_TEST_PASSED; +} + +/** + Cleanup routine for Unit test function. + If any processor is disabled unexpectedly then reenable it. + + @param[in] Context Context pointer for this test. +**/ +VOID +EFIAPI +CheckUTContext ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + UINTN BspNumber; + UINTN ProcessorNumber; + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + ASSERT (LocalContext->MpServices.Ppi != NULL); + + Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &BspNumber); + ASSERT_EFI_ERROR (Status); + + if (BspNumber != LocalContext->BspNumber) { + LocalContext->BspNumber = BspNumber; + DEBUG ((DEBUG_INFO, "%a: New BspNumber = 0x%x\n", __FUNCTION__, BspNumber)); + } + + ASSERT (BspNumber == LocalContext->BspNumber); + + Status = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); + ASSERT_EFI_ERROR (Status); + + if (NumberOfProcessors != LocalContext->NumberOfProcessors) { + LocalContext->NumberOfProcessors = NumberOfProcessors; + DEBUG ((DEBUG_INFO, "%a: New NumberOfProcessors = 0x%x\n", __FUNCTION__, NumberOfProcessors)); + } + + if (NumberOfEnabledProcessors != LocalContext->NumberOfProcessors) { + DEBUG ((DEBUG_INFO, "%a: New NumberOfEnabledProcessors = 0x%x\n", __FUNCTION__, NumberOfEnabledProcessors)); + + for (ProcessorNumber = 0; ProcessorNumber < LocalContext->NumberOfProcessors; ProcessorNumber++) { + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + ProcessorNumber, + &ProcessorInfoBuffer + ); + ASSERT_EFI_ERROR (Status); + + if (!(ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT)) { + DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled unexpectedly and reenable it.\n", __FUNCTION__, ProcessorNumber)); + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ProcessorNumber, + TRUE, + NULL + ); + ASSERT_EFI_ERROR (Status); + } + } + } +} + +/** + Cleanup routine for Unit test function. + It will be called by the last "AddTestCase" to restore AP state and free pointer. + + @param[in] Context Context pointer for this test. +**/ +VOID +EFIAPI +FreeUTContext ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NumberOfDisabledAPs; + UINTN IndexOfDisabledAPs; + MP_SERVICE_UT_CONTEXT *LocalContext; + + CheckUTContext (Context); + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + ASSERT (LocalContext->MpServices.Ppi != NULL); + + if (LocalContext->DisabledApNumber != NULL) { + NumberOfDisabledAPs = LocalContext->NumberOfProcessors - LocalContext->NumberOfEnabledProcessors; + for (IndexOfDisabledAPs = 0; IndexOfDisabledAPs < NumberOfDisabledAPs; IndexOfDisabledAPs++) { + DEBUG (( + DEBUG_INFO, + "%a: Disable AP(0x%x) to restore its state.\n", + __FUNCTION__, + LocalContext->DisabledApNumber[IndexOfDisabledAPs] + )); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + LocalContext->DisabledApNumber[IndexOfDisabledAPs], + FALSE, + NULL + ); + ASSERT_EFI_ERROR (Status); + } + + FreePages (LocalContext->DisabledApNumber, EFI_SIZE_TO_PAGES (NumberOfDisabledAPs * sizeof (*LocalContext->DisabledApNumber))); + } + + if (LocalContext->CommonBuffer != NULL) { + FreePages (LocalContext->CommonBuffer, EFI_SIZE_TO_PAGES (LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer))); + } +} + +/** + Produce to store ProcessorNumber in the corresponding location of CommonBuffer. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +StoreCpuNumbers ( + IN OUT VOID *Buffer + ) +{ + EFI_STATUS Status; + UINTN ProcessorNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &ProcessorNumber); + ASSERT_EFI_ERROR (Status); + + // + // The layout of CommonBuffer (E.g. BspNumber = 2 and NumberOfProcessors = 6) + // Index 00 01 02 03 04 05 + // Value 00 01 02 03 04 05 + // + if (ProcessorNumber < LocalContext->NumberOfProcessors) { + LocalContext->CommonBuffer[ProcessorNumber] = ProcessorNumber; + } +} + +/** + Produce to store the ProcessorNumber of AP execution order in CommonBuffer. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +StoreAPsExecutionOrder ( + IN OUT VOID *Buffer + ) +{ + EFI_STATUS Status; + UINTN ProcessorNumber; + UINTN *ApCounter; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &ProcessorNumber); + ASSERT_EFI_ERROR (Status); + + // + // The layout of CommonBuffer (E.g. BspNumber = 2 and NumberOfProcessors = 6) + // Index 00 01 02 03 04 05 + // Value 00 01 03 04 05 ApCounter(5) + // + ApCounter = &(LocalContext->CommonBuffer[LocalContext->NumberOfProcessors - 1]); + LocalContext->CommonBuffer[*ApCounter] = ProcessorNumber; + (*ApCounter)++; +} + +/** + Infinite loop procedure to be run on specified CPU. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +InfiniteLoopProcedure ( + IN OUT VOID *Buffer + ) +{ + volatile BOOLEAN InfiniteLoop; + + InfiniteLoop = TRUE; + + while (InfiniteLoop) { + } +} + +/** + Empty procedure to be run on specified CPU. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +EmptyProcedure ( + IN OUT VOID *Buffer + ) +{ +} + +/** + Procedure to run MP service GetNumberOfProcessors on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceGetNumberOfProcessorsOnAp ( + IN OUT VOID *Buffer + ) +{ + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); +} + +/** + Procedure to run MP service GetProcessorInfo on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceGetProcessorInfoOnAp ( + IN OUT VOID *Buffer + ) +{ + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + LocalContext->ApNumber, + &ProcessorInfoBuffer + ); +} + +/** + Procedure to run MP service EnableDisableAP on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceEnableDisableAPOnAp ( + IN OUT VOID *Buffer + ) +{ + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + LocalContext->ApNumber, + FALSE, + NULL + ); +} + +/** + Procedure to run MP service StartupThisAP on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceStartupThisAPOnAp ( + IN OUT VOID *Buffer + ) +{ + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + LocalContext->ApNumber, + 0, + NULL + ); +} + +/** + Procedure to run MP service StartupAllAPs on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceStartupAllAPsOnAp ( + IN OUT VOID *Buffer + ) +{ + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + FALSE, + 0, + NULL + ); +} + +/** + Procedure to run MP service SwitchBSP on AP. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +RunMpServiceSwitchBSPOnAp ( + IN OUT VOID *Buffer + ) +{ + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Buffer; + + LocalContext->ApProcedureReturnStatus = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + LocalContext->ApNumber, + TRUE + ); +} + +/** + Unit test of MP service WhoAmI. + The range of ProcessorNumber should be from 0 to NumberOfCPUs minus 1. + The ProcessorNumbers of all CPUs are unique. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestWhoAmI1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ProcessorNumber; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + Status = MpServicesUnitTestWhoAmI ( + LocalContext->MpServices, + &ProcessorNumber + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE (ProcessorNumber < LocalContext->NumberOfProcessors); + + SetMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer), 0xFF); + LocalContext->CommonBuffer[ProcessorNumber] = ProcessorNumber; + + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreCpuNumbers, + FALSE, + 0, + (VOID *)LocalContext + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + // + // The layout of CommonBuffer (E.g. BspNumber = 2 and NumberOfProcessors = 6) + // Index 00 01 02 03 04 05 + // Value 00 01 02 03 04 05 + // + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors; ProcessorIndex++) { + UT_ASSERT_TRUE (LocalContext->CommonBuffer[ProcessorIndex] == ProcessorIndex); + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service GetNumberOfProcessors. + NumberOfProcessors should be greater that 0 and not less than NumberOfEnabledProcessors. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + Status = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE (NumberOfProcessors > 0 && NumberOfProcessors >= NumberOfEnabledProcessors); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service GetNumberOfProcessors. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceGetNumberOfProcessorsOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service GetNumberOfProcessors. + Call EnableDisableAP() to change the number of enabled AP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + FALSE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE (NumberOfProcessors == LocalContext->NumberOfProcessors); + + if (ApNumber < LocalContext->BspNumber) { + UT_ASSERT_TRUE (NumberOfEnabledProcessors == LocalContext->NumberOfProcessors - (ApNumber + 1)); + } else { + UT_ASSERT_TRUE (NumberOfEnabledProcessors == LocalContext->NumberOfProcessors - ApNumber); + } + } + } + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestGetNumberOfProcessors ( + LocalContext->MpServices, + &NumberOfProcessors, + &NumberOfEnabledProcessors + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE (NumberOfProcessors == LocalContext->NumberOfProcessors); + + if (ApNumber < LocalContext->BspNumber) { + UT_ASSERT_TRUE (NumberOfEnabledProcessors == ApNumber + 2); + } else { + UT_ASSERT_TRUE (NumberOfEnabledProcessors == ApNumber + 1); + } + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service GetProcessorInfo. + When all the parameters are valid, all reserved bits of StatusFlag in ProcessorInfoBuffer should be set to zero. + When all the parameters are valid, the StatusFlag should not have an invalid value (The BSP can never be in the disabled state.). + When called with nonexistent processor handle, the return status should be EFI_NOT_FOUND. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetProcessorInfo1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ProcessorNumber; + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ProcessorNumber = 0; ProcessorNumber <= LocalContext->NumberOfProcessors; ProcessorNumber++) { + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + ProcessorNumber, + &ProcessorInfoBuffer + ); + + if (ProcessorNumber == LocalContext->NumberOfProcessors) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_NOT_FOUND); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ((ProcessorInfoBuffer.StatusFlag & (UINT32) ~(PROCESSOR_AS_BSP_BIT|PROCESSOR_ENABLED_BIT|PROCESSOR_HEALTH_STATUS_BIT)) == 0); + + if (ProcessorNumber == LocalContext->BspNumber) { + UT_ASSERT_TRUE ((ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT) && (ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT)); + } else { + UT_ASSERT_TRUE (!(ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT)); + } + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service GetProcessorInfo. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetProcessorInfo2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceGetProcessorInfoOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service EnableDisableAP. + When called with BSP number, the return status should be EFI_INVALID_PARAMETER. + When called with a nonexistent processor handle, the return status should be EFI_NOT_FOUND. + The AP should be really Enable/Disabled. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber <= LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + FALSE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else if (ApNumber == LocalContext->NumberOfProcessors) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_NOT_FOUND); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + ApNumber, + 0, + NULL + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + ApNumber, + 0, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service EnableDisableAP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceEnableDisableAPOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service EnableDisableAP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + UINT32 OldHealthFlag; + UINT32 NewHealthFlag; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + ApNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + OldHealthFlag = ProcessorInfoBuffer.StatusFlag & PROCESSOR_HEALTH_STATUS_BIT; + NewHealthFlag = OldHealthFlag ^ PROCESSOR_HEALTH_STATUS_BIT; + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + &NewHealthFlag + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + ApNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ((ProcessorInfoBuffer.StatusFlag & PROCESSOR_HEALTH_STATUS_BIT) == NewHealthFlag); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + &OldHealthFlag + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupThisAP. + When called to startup a BSP, the return status should be EFI_INVALID_PARAMETER. + When called with a nonexistent processor handle, the return status should be EFI_NOT_FOUND. + The requested AP should execute the Procedure when called by StartupThisAP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber <= LocalContext->NumberOfProcessors; ApNumber++) { + SetMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer), 0xFF); + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreCpuNumbers, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else if (ApNumber == LocalContext->NumberOfProcessors) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_NOT_FOUND); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors; ProcessorIndex++) { + UT_ASSERT_TRUE ( + ((ProcessorIndex == ApNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == ProcessorIndex)) || + ((ProcessorIndex != ApNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == (UINTN) ~0)) + ); + } + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupThisAP. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceStartupThisAPOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupThisAP. + When timeout expired before the requested AP has finished, the return status should be EFI_TIMEOUT. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)InfiniteLoopProcedure, + ApNumber, + RUN_PROCEDURE_TIMEOUT_VALUE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_STATUS_EQUAL (Status, EFI_TIMEOUT); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupThisAP. + When called with disabled AP, the return status should be EFI_INVALID_PARAMETER. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP4 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + FALSE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + ApNumber, + 0, + NULL + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + ApNumber, + 0, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupAllAPs. + All APs should execute the Procedure when called by StartupAllAPs. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + SetMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer), 0xFF); + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreCpuNumbers, + FALSE, + 0, + (VOID *)LocalContext + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors; ProcessorIndex++) { + UT_ASSERT_TRUE ( + ((ProcessorIndex == LocalContext->BspNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == (UINTN) ~0)) || + ((ProcessorIndex != LocalContext->BspNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == ProcessorIndex)) + ); + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupAllAPs. + When called in single thread, the return status should be EFI_SUCCESS and AP executes in ascending order + of processor handle number. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + ZeroMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer)); + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreAPsExecutionOrder, + TRUE, + 0, + (VOID *)LocalContext + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + // + // The layout of CommonBuffer (E.g. BspNumber = 2 and NumberOfProcessors = 6) + // Index 00 01 02 03 04 05 + // Value 00 01 03 04 05 ApCounter(5) + // + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors - 2; ProcessorIndex++) { + UT_ASSERT_TRUE (LocalContext->CommonBuffer[ProcessorIndex] < LocalContext->CommonBuffer[ProcessorIndex + 1]); + } + + UT_ASSERT_EQUAL (LocalContext->CommonBuffer[LocalContext->NumberOfProcessors - 1], LocalContext->NumberOfProcessors - 1); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupAllAPs. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceStartupAllAPsOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupAllAPs. + When called with all AP timeout, the return status should be EFI_TIMEOUT. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs4 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)InfiniteLoopProcedure, + TRUE, + RUN_PROCEDURE_TIMEOUT_VALUE, + NULL + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_TIMEOUT); + + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)InfiniteLoopProcedure, + FALSE, + RUN_PROCEDURE_TIMEOUT_VALUE, + NULL + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_TIMEOUT); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service StartupAllAPs. + When called with the empty Procedure on all disabled APs, the return status should be EFI_NOT_STARTED. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs5 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + FALSE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)EmptyProcedure, + FALSE, + 0, + NULL + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_NOT_STARTED); + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + ApNumber, + TRUE, + NULL + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service SwitchBSP. + When switch current BSP to be BSP, the return status should be EFI_INVALID_PARAMETER. + When switch nonexistent processor to be BSP, the return status should be EFI_NOT_FOUND. + After switch BSP, all APs(includes new AP) should execute the Procedure when called by StartupAllAP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP1 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NewBspNumber; + UINTN ProcessorIndex; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (NewBspNumber = 0; NewBspNumber <= LocalContext->NumberOfProcessors; NewBspNumber++) { + Status = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + NewBspNumber, + TRUE + ); + + if (NewBspNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else if (NewBspNumber == LocalContext->NumberOfProcessors) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_NOT_FOUND); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + SetMem (LocalContext->CommonBuffer, LocalContext->NumberOfProcessors * sizeof (*LocalContext->CommonBuffer), 0xFF); + Status = MpServicesUnitTestStartupAllAPs ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)StoreCpuNumbers, + FALSE, + 0, + (VOID *)LocalContext + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + for (ProcessorIndex = 0; ProcessorIndex < LocalContext->NumberOfProcessors; ProcessorIndex++) { + UT_ASSERT_TRUE ( + ((ProcessorIndex == NewBspNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == (UINTN) ~0)) || + ((ProcessorIndex != NewBspNumber) && (LocalContext->CommonBuffer[ProcessorIndex] == ProcessorIndex)) + ); + } + + Status = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + LocalContext->BspNumber, + TRUE + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service SwitchBSP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP2 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN ApNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (ApNumber = 0; ApNumber < LocalContext->NumberOfProcessors; ApNumber++) { + LocalContext->ApNumber = ApNumber; + Status = MpServicesUnitTestStartupThisAP ( + LocalContext->MpServices, + (EFI_AP_PROCEDURE)RunMpServiceSwitchBSPOnAp, + ApNumber, + 0, + (VOID *)LocalContext + ); + + if (ApNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_STATUS_EQUAL (LocalContext->ApProcedureReturnStatus, EFI_DEVICE_ERROR); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service SwitchBSP. + When switch a disabled AP to be BSP, the return status should be EFI_INVALID_PARAMETER. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP3 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NewBspNumber; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (NewBspNumber = 0; NewBspNumber < LocalContext->NumberOfProcessors; NewBspNumber++) { + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + NewBspNumber, + FALSE, + NULL + ); + + if (NewBspNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + NewBspNumber, + TRUE + ); + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + NewBspNumber, + TRUE, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MP service SwitchBSP. + When SwitchBSP and EnableOldBSP is TRUE, the new BSP should be in the enabled state and the old BSP should + be in the enabled state. + When SwitchBSP and EnableOldBSP is False, the new BSP should be in the enabled state and the old BSP should + be in the disabled state. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP4 ( + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN NewBspNumber; + EFI_PROCESSOR_INFORMATION ProcessorInfoBuffer; + MP_SERVICE_UT_CONTEXT *LocalContext; + + LocalContext = (MP_SERVICE_UT_CONTEXT *)Context; + + for (NewBspNumber = 0; NewBspNumber < LocalContext->NumberOfProcessors; NewBspNumber++) { + Status = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + NewBspNumber, + FALSE + ); + + if (NewBspNumber == LocalContext->BspNumber) { + UT_ASSERT_STATUS_EQUAL (Status, EFI_INVALID_PARAMETER); + } else { + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + NewBspNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ( + (ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT) && + (ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT) + ); + + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + LocalContext->BspNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ( + !(ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT) && + !(ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT) + ); + + Status = MpServicesUnitTestEnableDisableAP ( + LocalContext->MpServices, + LocalContext->BspNumber, + TRUE, + NULL + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestSwitchBSP ( + LocalContext->MpServices, + LocalContext->BspNumber, + TRUE + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + LocalContext->BspNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ( + (ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT) && + (ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT) + ); + + Status = MpServicesUnitTestGetProcessorInfo ( + LocalContext->MpServices, + NewBspNumber, + &ProcessorInfoBuffer + ); + UT_ASSERT_NOT_EFI_ERROR (Status); + UT_ASSERT_TRUE ( + !(ProcessorInfoBuffer.StatusFlag & PROCESSOR_AS_BSP_BIT) && + (ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT) + ); + } + } + + return UNIT_TEST_PASSED; +} + +/** + Create test suite and unit tests for both EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol. + + @param[in] Framework A pointer to the framework that is being persisted. + @param[in] Context A pointer to the private data buffer. + + @retval EFI_SUCCESS Create test suite and unit tests successfully. + @retval Others Create test suite and unit tests unsuccessfully. +**/ +EFI_STATUS +AddCommonTestCase ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN MP_SERVICE_UT_CONTEXT *Context + ) +{ + EFI_STATUS Status; + UNIT_TEST_SUITE_HANDLE MpServiceWhoAmITestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceGetNumberOfProcessorsTestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceGetProcessorInfoTestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceEnableDisableAPTestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceStartupThisAPTestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceStartupAllAPsTestSuite; + UNIT_TEST_SUITE_HANDLE MpServiceSwitchBSPTestSuite; + + MpServiceWhoAmITestSuite = NULL; + MpServiceGetNumberOfProcessorsTestSuite = NULL; + MpServiceGetProcessorInfoTestSuite = NULL; + MpServiceEnableDisableAPTestSuite = NULL; + MpServiceStartupThisAPTestSuite = NULL; + MpServiceStartupAllAPsTestSuite = NULL; + MpServiceSwitchBSPTestSuite = NULL; + + // + // Test WhoAmI function + // + Status = CreateUnitTestSuite (&MpServiceWhoAmITestSuite, Framework, "Identify the currently executing processor", "MpServices.WhoAmI", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceWhoAmI Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceWhoAmITestSuite, "Test WhoAmI 1", "TestWhoAmI1", TestWhoAmI1, InitUTContext, CheckUTContext, Context); + + // + // Test GetNumberOfProcessors function + // + Status = CreateUnitTestSuite (&MpServiceGetNumberOfProcessorsTestSuite, Framework, "Retrieve the number of logical processor", "MpServices.GetNumberOfProcessors", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceGetNumberOfProcessors Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceGetNumberOfProcessorsTestSuite, "Test GetNumberOfProcessors 1", "TestGetNumberOfProcessors1", TestGetNumberOfProcessors1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceGetNumberOfProcessorsTestSuite, "Test GetNumberOfProcessors 2", "TestGetNumberOfProcessors2", TestGetNumberOfProcessors2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceGetNumberOfProcessorsTestSuite, "Test GetNumberOfProcessors 3", "TestGetNumberOfProcessors3", TestGetNumberOfProcessors3, InitUTContext, CheckUTContext, Context); + + // + // Test GetProcessorInfo function + // + Status = CreateUnitTestSuite (&MpServiceGetProcessorInfoTestSuite, Framework, "Get detailed information on the requested logical processor", "MpServices.GetProcessorInfo", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceGetProcessorInfo Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceGetProcessorInfoTestSuite, "Test GetProcessorInfo 1", "TestGetProcessorInfo1", TestGetProcessorInfo1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceGetProcessorInfoTestSuite, "Test GetProcessorInfo 2", "TestGetProcessorInfo2", TestGetProcessorInfo2, InitUTContext, CheckUTContext, Context); + + // + // Test EnableDisableAP function + // + Status = CreateUnitTestSuite (&MpServiceEnableDisableAPTestSuite, Framework, "Caller enables or disables an AP from this point onward", "MpServices.EnableDisableAP", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceEnableDisableAP Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceEnableDisableAPTestSuite, "Test EnableDisableAP 1", "TestEnableDisableAP1", TestEnableDisableAP1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceEnableDisableAPTestSuite, "Test EnableDisableAP 2", "TestEnableDisableAP2", TestEnableDisableAP2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceEnableDisableAPTestSuite, "Test EnableDisableAP 3", "TestEnableDisableAP3", TestEnableDisableAP3, InitUTContext, CheckUTContext, Context); + + // + // Test StartupThisAP function + // + Status = CreateUnitTestSuite (&MpServiceStartupThisAPTestSuite, Framework, "Get the requested AP to execute a caller-provided function", "MpServices.StartupThisAP", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceStartupThisAP Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceStartupThisAPTestSuite, "Test StartupThisAP 1", "TestStartupThisAP1", TestStartupThisAP1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupThisAPTestSuite, "Test StartupThisAP 2", "TestStartupThisAP2", TestStartupThisAP2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupThisAPTestSuite, "Test StartupThisAP 3", "TestStartupThisAP3", TestStartupThisAP3, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupThisAPTestSuite, "Test StartupThisAP 4", "TestStartupThisAP4", TestStartupThisAP4, InitUTContext, CheckUTContext, Context); + + // + // Test StartupAllAPs function + // + Status = CreateUnitTestSuite (&MpServiceStartupAllAPsTestSuite, Framework, "Execute a caller provided function on all enabled APs", "MpServices.StartupAllAPs", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceStartupAllAPs Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceStartupAllAPsTestSuite, "Test StartupAllAPs 1", "TestStartupAllAPs1", TestStartupAllAPs1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllAPsTestSuite, "Test StartupAllAPs 2", "TestStartupAllAPs2", TestStartupAllAPs2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllAPsTestSuite, "Test StartupAllAPs 3", "TestStartupAllAPs3", TestStartupAllAPs3, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllAPsTestSuite, "Test StartupAllAPs 4", "TestStartupAllAPs4", TestStartupAllAPs4, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceStartupAllAPsTestSuite, "Test StartupAllAPs 5", "TestStartupAllAPs5", TestStartupAllAPs5, InitUTContext, CheckUTContext, Context); + + // + // Test SwitchBSP function + // + Status = CreateUnitTestSuite (&MpServiceSwitchBSPTestSuite, Framework, "Switch the requested AP to be the BSP from that point onward", "MpServices.SwitchBSP", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MpServiceSwitchBSP Test Suite\n")); + return Status; + } + + AddTestCase (MpServiceSwitchBSPTestSuite, "Test SwitchBSP 1", "TestSwitchBSP1", TestSwitchBSP1, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceSwitchBSPTestSuite, "Test SwitchBSP 2", "TestSwitchBSP2", TestSwitchBSP2, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceSwitchBSPTestSuite, "Test SwitchBSP 3", "TestSwitchBSP3", TestSwitchBSP3, InitUTContext, CheckUTContext, Context); + AddTestCase (MpServiceSwitchBSPTestSuite, "Test SwitchBSP 4", "TestSwitchBSP4", TestSwitchBSP4, InitUTContext, FreeUTContext, Context); + + return EFI_SUCCESS; +} diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h new file mode 100644 index 0000000000..abbbd2faba --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h @@ -0,0 +1,627 @@ +/** @file + Common header file for EfiMpServiceProtocolUnitTest DXE driver. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef EFI_MP_SERVICES_UNIT_TEST_COMMOM_H_ +#define EFI_MP_SERVICES_UNIT_TEST_COMMOM_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define RUN_PROCEDURE_TIMEOUT_VALUE 100000 // microseconds + +typedef union { + EDKII_PEI_MP_SERVICES2_PPI *Ppi; + EFI_MP_SERVICES_PROTOCOL *Protocol; +} MP_SERVICES; + +typedef struct { + MP_SERVICES MpServices; + UINTN BspNumber; + UINTN ApNumber; + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + UINTN *CommonBuffer; + EFI_STATUS ApProcedureReturnStatus; + UINTN *DisabledApNumber; +} MP_SERVICE_UT_CONTEXT; + +/** + Get EFI_MP_SERVICES_PROTOCOL pointer. + + @param[out] MpServices Pointer to the buffer where EFI_MP_SERVICES_PROTOCOL is stored + + @retval EFI_SUCCESS EFI_MP_SERVICES_PROTOCOL interface is returned + @retval EFI_NOT_FOUND EFI_MP_SERVICES_PROTOCOL interface is not found +**/ +EFI_STATUS +MpServicesUnitTestGetMpServices ( + OUT MP_SERVICES *MpServices + ); + +/** + Retrieve the number of logical processor in the platform and the number of those logical processors that + are enabled on this boot. + + @param[in] MpServices MP_SERVICES structure. + @param[out] NumberOfProcessors Pointer to the total number of logical processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of processors in the system that are enabled. + + @retval EFI_SUCCESS Retrieve the number of logical processor successfully + @retval Others Retrieve the number of logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetNumberOfProcessors ( + IN MP_SERVICES MpServices, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ); + +/** + Get detailed information on the requested logical processor. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the processor. + @param[out] ProcessorInfoBuffer Pointer to the buffer where the processor information is stored. + + @retval EFI_SUCCESS Get information on the requested logical processor successfully + @retval Others Get information on the requested logical processor unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestGetProcessorInfo ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer + ); + +/** + Execute a caller provided function on all enabled APs. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] SingleThread If TRUE, then all the enabled APs execute the function specified by Procedure + one by one, in ascending order of processor handle number. + If FALSE, then all the enabled APs execute the function specified by Procedure + simultaneously. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Execute a caller provided function on all enabled APs successfully + @retval Others Execute a caller provided function on all enabled APs unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupAllAPs ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ); + +/** + Caller gets one enabled AP to execute a caller-provided function. + + @param[in] MpServices MP_SERVICES structure. + @param[in] Procedure Pointer to the function to be run on enabled APs of the system. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] TimeoutInMicroSeconds Indicates the time limit in microseconds for APs to return from Procedure, + for blocking mode only. Zero means infinity. + @param[in] ProcedureArgument The parameter passed into Procedure for all APs. + + @retval EFI_SUCCESS Caller gets one enabled AP to execute a caller-provided function successfully + @retval Others Caller gets one enabled AP to execute a caller-provided function unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestStartupThisAP ( + IN MP_SERVICES MpServices, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN UINTN TimeoutInMicroSeconds, + IN VOID *ProcedureArgument + ); + +/** + Switch the requested AP to be the BSP from that point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of AP that is to become the new BSP. + @param[in] EnableOldBSP If TRUE, the old BSP will be listed as an enabled AP. Otherwise, it will be disabled. + + @retval EFI_SUCCESS Switch the requested AP to be the BSP successfully + @retval Others Switch the requested AP to be the BSP unsuccessfully +**/ +EFI_STATUS +MpServicesUnitTestSwitchBSP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableOldBSP + ); + +/** + Caller enables or disables an AP from this point onward. + + @param[in] MpServices MP_SERVICES structure. + @param[in] ProcessorNumber The handle number of the AP. + @param[in] EnableAP Specifies the new state for the processor for enabled, FALSE for disabled. + @param[in] HealthFlag If not NULL, a pointer to a value that specifies the new health status of the AP. + + @retval EFI_SUCCESS Caller enables or disables an AP successfully. + @retval Others Caller enables or disables an AP unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestEnableDisableAP ( + IN MP_SERVICES MpServices, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableAP, + IN UINT32 *HealthFlag + ); + +/** + Get the handle number for the calling processor. + + @param[in] MpServices MP_SERVICES structure. + @param[out] ProcessorNumber The handle number for the calling processor. + + @retval EFI_SUCCESS Get the handle number for the calling processor successfully. + @retval Others Get the handle number for the calling processor unsuccessfully. +**/ +EFI_STATUS +MpServicesUnitTestWhoAmI ( + IN MP_SERVICES MpServices, + OUT UINTN *ProcessorNumber + ); + +/** + Empty procedure to be run on specified CPU. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +EmptyProcedure ( + IN OUT VOID *Buffer + ); + +/** + Produce to store ProcessorNumber in CommonBuffer and be run on specified CPU. + + @param[in,out] Buffer The pointer to private data buffer. +**/ +VOID +StoreCpuNumbers ( + IN OUT VOID *Buffer + ); + +/** + Prep routine for Unit test function. + To save the ProcessorNumber of disabled AP and temporarily enable it. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED Prep routine runs successful. + @retval UNIT_TEST_ERROR_TEST_FAILED Prep routine runs unsuccessful. +**/ +UNIT_TEST_STATUS +EFIAPI +InitUTContext ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Cleanup routine for Unit test function. + If any processor is disabled unexpectedly then reenable it. + + @param[in] Context Context pointer for this test. +**/ +VOID +EFIAPI +CheckUTContext ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Cleanup routine for Unit test function. + It will be called by the last "AddTestCase" to restore AP state and free pointer. + + @param[in] Context Context pointer for this test. +**/ +VOID +EFIAPI +FreeUTContext ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service WhoAmI. + The range of ProcessorNumber should be from 0 to NumberOfCPUs minus 1. + The ProcessorNumbers of all CPUs are unique. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestWhoAmI1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service GetNumberOfProcessors. + NumberOfProcessors should be greater that 0 and not less than NumberOfEnabledProcessors. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service GetNumberOfProcessors. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service GetNumberOfProcessors. + Call EnableDisableAP() to change the number of enabled AP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetNumberOfProcessors3 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service GetProcessorInfo. + When all the parameters are valid, all reserved bits of StatusFlag in ProcessorInfoBuffer should be set to zero. + When all the parameters are valid, the StatusFlag should not have an invalid value (The BSP can never be in the disabled state.). + When called with nonexistent processor handle, the return status should be EFI_NOT_FOUND. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetProcessorInfo1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service GetProcessorInfo. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestGetProcessorInfo2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service EnableDisableAP. + When called with BSP number, the return status should be EFI_INVALID_PARAMETER. + When called with a nonexistent processor handle, the return status should be EFI_NOT_FOUND. + The AP should be really Enable/Disabled. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service EnableDisableAP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service EnableDisableAP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestEnableDisableAP3 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupThisAP. + When called to startup a BSP, the return status should be EFI_INVALID_PARAMETER. + When called with a nonexistent processor handle, the return status should be EFI_NOT_FOUND. + The requested AP should execute the Procedure when called by StartupThisAP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupThisAP. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupThisAP. + When timeout expired before the requested AP has finished, the return status should be EFI_TIMEOUT. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP3 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupThisAP. + When called with disabled AP, the return status should be EFI_INVALID_PARAMETER. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupThisAP4 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupAllAPs. + All APs should execute the Procedure when called by StartupAllAPs. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupAllAPs. + When called in single thread, the return status should be EFI_SUCCESS and AP executes in ascending order + of processor handle number. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupAllAPs. + When this service is called from an AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs3 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupAllAPs. + When called with all AP timeout, the return status should be EFI_TIMEOUT. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs4 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service StartupAllAPs. + When called with the empty Procedure on all disabled APs, the return status should be EFI_NOT_STARTED. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestStartupAllAPs5 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service SwitchBSP. + When switch current BSP to be BSP, the return status should be EFI_INVALID_PARAMETER. + When switch nonexistent processor to be BSP, the return status should be EFI_NOT_FOUND. + After switch BSP, all APs(includes new AP) should execute the Procedure when called by StartupAllAP. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP1 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service SwitchBSP. + When run this procedure on AP, the return status should be EFI_DEVICE_ERROR. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP2 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service SwitchBSP. + When switch a disabled AP to be BSP, the return status should be EFI_INVALID_PARAMETER. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP3 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Unit test of MP service SwitchBSP. + When SwitchBSP and EnableOldBSP is TRUE, the new BSP should be in the enabled state and the old BSP should + be in the enabled state. + When SwitchBSP and EnableOldBSP is False, the new BSP should be in the enabled state and the old BSP should + be in the disabled state. + + @param[in] Context Context pointer for this test. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestSwitchBSP4 ( + IN UNIT_TEST_CONTEXT Context + ); + +/** + Create test suite and unit tests for both EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol. + + @param[in] Framework A pointer to the framework that is being persisted. + @param[in] Context A pointer to the private data buffer. + + @retval EFI_SUCCESS Create test suite and unit tests successfully. + @retval Others Create test suite and unit tests unsuccessfully. +**/ +EFI_STATUS +AddCommonTestCase ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN MP_SERVICE_UT_CONTEXT *Context + ); + +#endif diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index 6d89458ecb..0e1a99ddc0 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -181,6 +181,8 @@ UefiCpuPkg/Library/SmmCpuRendezvousLib/SmmCpuRendezvousLib.inf UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf + UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf + UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf [Components.X64] UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf From 3807725eb4f98c3d50629be722f0ba2554337a7d Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Sun, 16 Oct 2022 14:46:10 +0800 Subject: [PATCH 0172/1529] pip-requirement: Upgrade the edk2-basetools version from 0.1.29 to 0.1.39 features and bug fixes: 1. Revert "BaseTools: Fix DSC LibraryClass precedence rule" 2. BaseTools: Correct BPDG tool error prints 3. BaseTools: Remove duplicated words in Python tools 4. BaseTools/FMMT: Add Extract FV function 5. BaseTools/FMMT: Add Shrink Fv function 6. BaseTools: Add support for SUBTYPE_GUID section generation 7. BaseTools: Support COMPAT16 section generation 8. BaseTools/GenFds: Correct file type set for the PIC section 9. BaseTools: Correct initialization data size check for array PCDs 10. BaseTools: Add missing spaces for PCD expression values in AutoGenC Signed-off-by: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Reviewed-by: Liming Gao Reviewed-by: Yuwei Chen --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 967da7cb37..40e9ad72ee 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -14,5 +14,5 @@ edk2-pytool-library==0.11.2 edk2-pytool-extensions~=0.16.0 -edk2-basetools==0.1.29 +edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 From 151666fed98a0493d9a626cb3b7fc97b178f20ef Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 3 Oct 2022 15:47:32 +0800 Subject: [PATCH 0173/1529] BaseTools: Remove duplicated words in Python tools In an effort to clean the documentation of the above package, remove duplicated words. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Pierre Gondois --- BaseTools/Source/Python/Ecc/EccToolError.py | 2 +- BaseTools/Source/Python/build/build.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Ecc/EccToolError.py b/BaseTools/Source/Python/Ecc/EccToolError.py index d97bf7948c..2ff36c8329 100644 --- a/BaseTools/Source/Python/Ecc/EccToolError.py +++ b/BaseTools/Source/Python/Ecc/EccToolError.py @@ -186,7 +186,7 @@ ERROR_META_DATA_FILE_CHECK_BINARY_INF_IN_FDF : "An INF file is specified in the FDF file, but not in the DSC file, therefore the INF file must be for a Binary module only", ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE : "Duplicate PCDs found", ERROR_META_DATA_FILE_CHECK_PCD_FLASH : "PCD settings in the FDF file should only be related to flash", - ERROR_META_DATA_FILE_CHECK_PCD_NO_USE : "There should be no PCDs declared in INF files that are not specified in in either a DSC or FDF file", + ERROR_META_DATA_FILE_CHECK_PCD_NO_USE : "There should be no PCDs declared in INF files that are not specified in either a DSC or FDF file", ERROR_META_DATA_FILE_CHECK_DUPLICATE_GUID : "Duplicate GUID found", ERROR_META_DATA_FILE_CHECK_DUPLICATE_PROTOCOL : "Duplicate PROTOCOL found", ERROR_META_DATA_FILE_CHECK_DUPLICATE_PPI : "Duplicate PPI found", diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 07187c0361..51fb1f433e 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -205,7 +205,7 @@ def __init__(self,*args, **argv): # # This method will call subprocess.Popen to execute an external program with # given options in specified directory. Because of the dead-lock issue during -# redirecting output of the external program, threads are used to to do the +# redirecting output of the external program, threads are used to do the # redirection work. # # @param Command A list or string containing the call of the program From 306f479036d20611aa9a7ed64faf4bc5a3822299 Mon Sep 17 00:00:00 2001 From: "Chen, Christine" Date: Fri, 16 Sep 2022 09:50:56 +0800 Subject: [PATCH 0174/1529] BaseTools/FMMT: Add Extract FV function REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3938 With this patch "-e" parameter supports extract FV function. Usage: FMMT -e Inputfile TargetFv Outputfile Cc: Bob Feng Cc: Liming Gao Signed-off-by: Yuwei Chen Reviewed-by: Bob Feng --- BaseTools/Source/Python/FMMT/FMMT.py | 3 +- .../Source/Python/FMMT/core/FMMTOperation.py | 45 +++++++++++-------- .../Source/Python/FMMT/core/FvHandler.py | 5 +-- 3 files changed, 31 insertions(+), 22 deletions(-) diff --git a/BaseTools/Source/Python/FMMT/FMMT.py b/BaseTools/Source/Python/FMMT/FMMT.py index 10800e776a..3590f3340e 100644 --- a/BaseTools/Source/Python/FMMT/FMMT.py +++ b/BaseTools/Source/Python/FMMT/FMMT.py @@ -24,7 +24,8 @@ If not given TargetFvName, all the existed target Ffs will be deleted'") parser.add_argument("-e", "--Extract", dest="Extract", nargs='+', help="Extract a Ffs Info: '-e inputfile TargetFvName(Optional) TargetFfsName outputfile\ - If not given TargetFvName, the first found target Ffs will be extracted'") + If not given TargetFvName, the first found target Ffs will be extracted.\ + If only given TargetFvName, not given TargetFfsName, the TargetFv will be extracted to output file'") parser.add_argument("-a", "--Add", dest="Add", nargs='+', help="Add a Ffs into a FV:'-a inputfile TargetFvName newffsfile outputfile'") parser.add_argument("-r", "--Replace", dest="Replace", nargs='+', diff --git a/BaseTools/Source/Python/FMMT/core/FMMTOperation.py b/BaseTools/Source/Python/FMMT/core/FMMTOperation.py index c2cc2e2467..4e58c91b5c 100644 --- a/BaseTools/Source/Python/FMMT/core/FMMTOperation.py +++ b/BaseTools/Source/Python/FMMT/core/FMMTOperation.py @@ -63,9 +63,10 @@ def DeleteFfs(inputfile: str, TargetFfs_name: str, outputfile: str, Fv_name: str FmmtParser.WholeFvTree.FindNode(TargetFfs_name, FmmtParser.WholeFvTree.Findlist) # Choose the Specfic DeleteFfs with Fv info if Fv_name: - for item in FmmtParser.WholeFvTree.Findlist: - if item.Parent.key != Fv_name and item.Parent.Data.Name != Fv_name: - FmmtParser.WholeFvTree.Findlist.remove(item) + FindNum = len(FmmtParser.WholeFvTree.Findlist) + for index in range(FindNum-1, -1, -1): + if FmmtParser.WholeFvTree.Findlist[index].Parent.key != Fv_name and FmmtParser.WholeFvTree.Findlist[index].Parent.Data.Name != Fv_name: + FmmtParser.WholeFvTree.Findlist.remove(FmmtParser.WholeFvTree.Findlist[index]) Status = False if FmmtParser.WholeFvTree.Findlist != []: for Delete_Ffs in FmmtParser.WholeFvTree.Findlist: @@ -149,9 +150,10 @@ def ReplaceFfs(inputfile: str, Ffs_name: str, newffsfile: str, outputfile: str, new_ffs.Data.PadData = GetPadSize(new_ffs.Data.Size, FFS_COMMON_ALIGNMENT) * b'\xff' FmmtParser.WholeFvTree.FindNode(Ffs_name, FmmtParser.WholeFvTree.Findlist) if Fv_name: - for item in FmmtParser.WholeFvTree.Findlist: - if item.Parent.key != Fv_name and item.Parent.Data.Name != Fv_name: - FmmtParser.WholeFvTree.Findlist.remove(item) + FindNum = len(FmmtParser.WholeFvTree.Findlist) + for index in range(FindNum-1, -1, -1): + if FmmtParser.WholeFvTree.Findlist[index].Parent.key != Fv_name and FmmtParser.WholeFvTree.Findlist[index].Parent.Data.Name != Fv_name: + FmmtParser.WholeFvTree.Findlist.remove(FmmtParser.WholeFvTree.Findlist[index]) if FmmtParser.WholeFvTree.Findlist != []: for TargetFfs in FmmtParser.WholeFvTree.Findlist: FfsMod = FvHandler(newFmmtParser.WholeFvTree.Child[0], TargetFfs) @@ -180,18 +182,25 @@ def ExtractFfs(inputfile: str, Ffs_name: str, outputfile: str, Fv_name: str=None logger.debug('Done!') FmmtParser.WholeFvTree.FindNode(Ffs_name, FmmtParser.WholeFvTree.Findlist) if Fv_name: - for item in FmmtParser.WholeFvTree.Findlist: - if item.Parent.key != Fv_name and item.Parent.Data.Name != Fv_name: - FmmtParser.WholeFvTree.Findlist.remove(item) + FindNum = len(FmmtParser.WholeFvTree.Findlist) + for index in range(FindNum-1, -1, -1): + if FmmtParser.WholeFvTree.Findlist[index].Parent.key != Fv_name and FmmtParser.WholeFvTree.Findlist[index].Parent.Data.Name != Fv_name: + FmmtParser.WholeFvTree.Findlist.remove(FmmtParser.WholeFvTree.Findlist[index]) if FmmtParser.WholeFvTree.Findlist != []: TargetNode = FmmtParser.WholeFvTree.Findlist[0] - TargetFv = TargetNode.Parent - if TargetFv.Data.Header.Attributes & EFI_FVB2_ERASE_POLARITY: - TargetNode.Data.Header.State = c_uint8( - ~TargetNode.Data.Header.State) - FinalData = struct2stream(TargetNode.Data.Header) + TargetNode.Data.Data - with open(outputfile, "wb") as f: - f.write(FinalData) - logger.debug('Extract ffs data is saved in {}.'.format(outputfile)) + if TargetNode.type == FV_TREE or SEC_FV_TREE or DATA_FV_TREE: + FinalData = struct2stream(TargetNode.Data.Header) + TargetNode.Data.Data + with open(outputfile, "wb") as f: + f.write(FinalData) + logger.debug('Extract fv data is saved in {}.'.format(outputfile)) + else: + TargetFv = TargetNode.Parent + if TargetFv.Data.Header.Attributes & EFI_FVB2_ERASE_POLARITY: + TargetNode.Data.Header.State = c_uint8( + ~TargetNode.Data.Header.State) + FinalData = struct2stream(TargetNode.Data.Header) + TargetNode.Data.Data + with open(outputfile, "wb") as f: + f.write(FinalData) + logger.debug('Extract ffs data is saved in {}.'.format(outputfile)) else: - logger.error('Target Ffs not found!!!') + logger.error('Target Ffs/Fv not found!!!') diff --git a/BaseTools/Source/Python/FMMT/core/FvHandler.py b/BaseTools/Source/Python/FMMT/core/FvHandler.py index c81541ec18..e8b8480098 100644 --- a/BaseTools/Source/Python/FMMT/core/FvHandler.py +++ b/BaseTools/Source/Python/FMMT/core/FvHandler.py @@ -155,7 +155,6 @@ def __init__(self, NewFfs, TargetFfs) -> None: def CompressData(self, TargetTree) -> None: TreePath = TargetTree.GetTreePath() pos = len(TreePath) - self.Status = False while pos: if not self.Status: if TreePath[pos-1].type == SECTION_TREE and TreePath[pos-1].Data.Type == 0x02: @@ -487,7 +486,6 @@ def AddFfs(self) -> bool: ~self.NewFfs.Data.Header.State) # If TargetFv have enough free space, just move part of the free space to NewFfs, split free space to NewFfs and new free space. if TargetLen < 0: - self.Status = True self.TargetFfs.Data.Data = b'\xff' * (-TargetLen) TargetFv.Data.Free_Space = (-TargetLen) TargetFv.Data.ModFvExt() @@ -498,13 +496,14 @@ def AddFfs(self) -> bool: ModifyFfsType(self.NewFfs) # Recompress from the Fv node to update all the related node data. self.CompressData(TargetFv) - elif TargetLen == 0: self.Status = True + elif TargetLen == 0: TargetFv.Child.remove(self.TargetFfs) TargetFv.insertChild(self.NewFfs) ModifyFfsType(self.NewFfs) # Recompress from the Fv node to update all the related node data. self.CompressData(TargetFv) + self.Status = True # If TargetFv do not have enough free space, need move part of the free space of TargetFv's parent Fv to TargetFv/NewFfs. else: if TargetFv.type == FV_TREE: From 0a96cb34ccaab54c520119f893561bb5b12d0242 Mon Sep 17 00:00:00 2001 From: "Chen, Christine" Date: Fri, 16 Sep 2022 09:51:18 +0800 Subject: [PATCH 0175/1529] BaseTools/FMMT: Add Shrink Fv function REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3938 This function is used to remove the useless FV free space. Usage: FMMT -s Inputfile Outputfile Cc: Bob Feng Cc: Liming Gao Signed-off-by: Yuwei Chen Reviewed-by: Bob Feng --- BaseTools/Source/Python/FMMT/FMMT.py | 7 +++++ .../Source/Python/FMMT/core/FMMTOperation.py | 26 +++++++++++++++++ .../Source/Python/FMMT/core/FvHandler.py | 28 ++++++++++++++++++- 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/FMMT/FMMT.py b/BaseTools/Source/Python/FMMT/FMMT.py index 3590f3340e..bf580b3843 100644 --- a/BaseTools/Source/Python/FMMT/FMMT.py +++ b/BaseTools/Source/Python/FMMT/FMMT.py @@ -41,6 +41,8 @@ FmmtConf file saves the target guidtool used in compress/uncompress process.\ If do not provide, FMMT tool will search the inputfile folder for FmmtConf.ini firstly, if not found,\ the FmmtConf.ini saved in FMMT tool's folder will be used as default.") +parser.add_argument("-s", "--ShrinkFv", dest="ShrinkFv", nargs='+', + help="Shrink the Fv file: '-s InputFvfile OutputFvfile") def print_banner(): print("") @@ -111,6 +113,9 @@ def Replace(self,inputfile: str, Ffs_name: str, newffsfile: str, outputfile: str else: ReplaceFfs(inputfile, self.CheckFfsName(Ffs_name), newffsfile, outputfile) + def Shrink(self,inputfile: str, outputfile: str) -> None: + self.SetDestPath(inputfile) + ShrinkFv(inputfile, outputfile) def main(): args=parser.parse_args() @@ -142,6 +147,8 @@ def main(): fmmt.Replace(args.Replace[0],args.Replace[2],args.Replace[3],args.Replace[4],args.Replace[1]) else: fmmt.Replace(args.Replace[0],args.Replace[1],args.Replace[2],args.Replace[3]) + elif args.ShrinkFv: + fmmt.Shrink(args.ShrinkFv[0], args.ShrinkFv[1]) else: parser.print_help() except Exception as e: diff --git a/BaseTools/Source/Python/FMMT/core/FMMTOperation.py b/BaseTools/Source/Python/FMMT/core/FMMTOperation.py index 4e58c91b5c..a86f8dda9a 100644 --- a/BaseTools/Source/Python/FMMT/core/FMMTOperation.py +++ b/BaseTools/Source/Python/FMMT/core/FMMTOperation.py @@ -204,3 +204,29 @@ def ExtractFfs(inputfile: str, Ffs_name: str, outputfile: str, Fv_name: str=None logger.debug('Extract ffs data is saved in {}.'.format(outputfile)) else: logger.error('Target Ffs/Fv not found!!!') + +def ShrinkFv(inputfile: str, outputfile: str) -> None: + if not os.path.exists(inputfile): + logger.error("Invalid inputfile, can not open {}.".format(inputfile)) + raise Exception("Process Failed: Invalid inputfile!") + # 1. Data Prepare + with open(inputfile, "rb") as f: + whole_data = f.read() + FmmtParser = FMMTParser(inputfile, ROOT_TREE) + # 2. DataTree Create + logger.debug('Parsing inputfile data......') + FmmtParser.ParserFromRoot(FmmtParser.WholeFvTree, whole_data) + logger.debug('Done!') + TargetFv = FmmtParser.WholeFvTree.Child[0] + if TargetFv: + FvMod = FvHandler(TargetFv) + Status = FvMod.ShrinkFv() + else: + logger.error('Target Fv not found!!!') + # 4. Data Encapsulation + if Status: + logger.debug('Start encapsulating data......') + FmmtParser.Encapsulation(FmmtParser.WholeFvTree, False) + with open(outputfile, "wb") as f: + f.write(FmmtParser.FinalData) + logger.debug('Encapsulated data is saved in {}.'.format(outputfile)) diff --git a/BaseTools/Source/Python/FMMT/core/FvHandler.py b/BaseTools/Source/Python/FMMT/core/FvHandler.py index e8b8480098..ff3d637623 100644 --- a/BaseTools/Source/Python/FMMT/core/FvHandler.py +++ b/BaseTools/Source/Python/FMMT/core/FvHandler.py @@ -145,7 +145,7 @@ def ModifyFvSystemGuid(TargetFv) -> None: TargetFv.Data.Data += struct2stream(item.Data.Header)+ item.Data.Data + item.Data.PadData class FvHandler: - def __init__(self, NewFfs, TargetFfs) -> None: + def __init__(self, NewFfs, TargetFfs=None) -> None: self.NewFfs = NewFfs self.TargetFfs = TargetFfs self.Status = False @@ -638,3 +638,29 @@ def DeleteFfs(self) -> bool: self.Status = True logger.debug('Done!') return self.Status + + def ShrinkFv(self) -> bool: + TargetFv = self.NewFfs + TargetFv.Data.Data = b'' + if not TargetFv.Data.Free_Space: + self.Status = True + else: + BlockSize = TargetFv.Data.Header.BlockMap[0].Length + New_Free_Space = TargetFv.Data.Free_Space%BlockSize + Removed_Space = TargetFv.Data.Free_Space - New_Free_Space + TargetFv.Child[-1].Data.Data = b'\xff' * New_Free_Space + TargetFv.Data.Size -= Removed_Space + TargetFv.Data.Header.Fvlength = TargetFv.Data.Size + ModifyFvSystemGuid(TargetFv) + for item in TargetFv.Child: + if item.type == FFS_FREE_SPACE: + TargetFv.Data.Data += item.Data.Data + item.Data.PadData + else: + TargetFv.Data.Data += struct2stream(item.Data.Header)+ item.Data.Data + item.Data.PadData + TargetFv.Data.ModFvExt() + TargetFv.Data.ModFvSize() + TargetFv.Data.ModExtHeaderData() + ModifyFvExtData(TargetFv) + TargetFv.Data.ModCheckSum() + self.Status = True + return self.Status From 31f80eb3df2fc33525d05452c2222f8c229e3ab0 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Mon, 5 Sep 2022 17:19:23 +0800 Subject: [PATCH 0176/1529] BaseTools: Correct BPDG tool error prints Popen communication returns bytestrings. It is necessary to perform decode on these strings before passing them to the EdkLogger that works with ordinary strings. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/Python/Common/VpdInfoFile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Common/VpdInfoFile.py b/BaseTools/Source/Python/Common/VpdInfoFile.py index 4249b9f899..1e0c3dfe76 100644 --- a/BaseTools/Source/Python/Common/VpdInfoFile.py +++ b/BaseTools/Source/Python/Common/VpdInfoFile.py @@ -248,8 +248,8 @@ def CallExtenalBPDGTool(ToolPath, VpdFileName): PopenObject.wait() if PopenObject.returncode != 0: - EdkLogger.debug(EdkLogger.DEBUG_1, "Fail to call BPDG tool", str(error)) + EdkLogger.debug(EdkLogger.DEBUG_1, "Fail to call BPDG tool", str(error.decode())) EdkLogger.error("BPDG", BuildToolError.COMMAND_FAILURE, "Fail to execute BPDG tool with exit code: %d, the error message is: \n %s" % \ - (PopenObject.returncode, str(error))) + (PopenObject.returncode, str(error.decode()))) return PopenObject.returncode From a752b16732495da3947ab25cd9655f385692cd21 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Wed, 20 Jul 2022 22:01:17 +0800 Subject: [PATCH 0177/1529] BaseTools: Add support for SUBTYPE_GUID section generation EFI_SECTION_FREEFORM_SUBTYPE_GUID is a leaf section type that contains a single EFI_GUID in the header to describe the raw data. Currently is is not possible to generate such section. This patch adds initial support for the generation of such sections. The added syntax for this type of section corresponds to EDKII "[FV] section" documentation from the FDF Specification: ``` SECTION SUBTYPE_GUID = ``` Signed-off-by: Konstantin Aladyshev Reviewed-by: Bob Feng --- .../Source/Python/CommonDataClass/FdfClass.py | 12 +++ BaseTools/Source/Python/GenFds/FdfParser.py | 22 ++++++ .../Python/GenFds/SubTypeGuidSection.py | 76 +++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 BaseTools/Source/Python/GenFds/SubTypeGuidSection.py diff --git a/BaseTools/Source/Python/CommonDataClass/FdfClass.py b/BaseTools/Source/Python/CommonDataClass/FdfClass.py index 2fbb7b436a..c8cfdaae32 100644 --- a/BaseTools/Source/Python/CommonDataClass/FdfClass.py +++ b/BaseTools/Source/Python/CommonDataClass/FdfClass.py @@ -190,6 +190,18 @@ def __init__(self): self.FvParentAddr = None self.IncludeFvSection = False +## SubType GUID section data in FDF +# +# +class SubTypeGuidSectionClassObject (SectionClassObject) : + ## The constructor + # + # @param self The object pointer + # + def __init__(self): + SectionClassObject.__init__(self) + self.SubTypeGuid = None + ## UI section data in FDF # # diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source/Python/GenFds/FdfParser.py index 5c8263f9bc..aa18fef09e 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -42,6 +42,7 @@ from .DepexSection import DepexSection from .CompressSection import CompressSection from .GuidSection import GuidSection +from .SubTypeGuidSection import SubTypeGuidSection from .Capsule import EFI_CERT_TYPE_PKCS7_GUID, EFI_CERT_TYPE_RSA2048_SHA256_GUID, Capsule from .CapsuleData import CapsuleFfs, CapsulePayload, CapsuleFv, CapsuleFd, CapsuleAnyFile, CapsuleAfile from .RuleComplexFile import RuleComplexFile @@ -2892,6 +2893,27 @@ def _GetLeafSection(self, Obj): DepexSectionObj.Expression = self._SkippedChars.rstrip(T_CHAR_BRACE_R) Obj.SectionList.append(DepexSectionObj) + elif self._IsKeyword("SUBTYPE_GUID"): + if AlignValue == 'Auto': + raise Warning("Auto alignment can only be used in PE32 or TE section ", self.FileName, self.CurrentLineNumber) + SubTypeGuidValue = None + if not self._GetNextGuid(): + raise Warning.Expected("GUID", self.FileName, self.CurrentLineNumber) + else: + SubTypeGuidValue = self._Token + + if not self._IsToken(TAB_EQUAL_SPLIT): + raise Warning.ExpectedEquals(self.FileName, self.CurrentLineNumber) + if not self._GetNextToken(): + raise Warning.Expected("section file path", self.FileName, self.CurrentLineNumber) + FileName = self._Token + + SubTypeGuidSectionObj = SubTypeGuidSection() + SubTypeGuidSectionObj.Alignment = AlignValue + SubTypeGuidSectionObj.SubTypeGuid = SubTypeGuidValue + SubTypeGuidSectionObj.SectFileName = FileName + Obj.SectionList.append(SubTypeGuidSectionObj) + else: if not self._GetNextWord(): raise Warning.Expected("section type", self.FileName, self.CurrentLineNumber) diff --git a/BaseTools/Source/Python/GenFds/SubTypeGuidSection.py b/BaseTools/Source/Python/GenFds/SubTypeGuidSection.py new file mode 100644 index 0000000000..d522380117 --- /dev/null +++ b/BaseTools/Source/Python/GenFds/SubTypeGuidSection.py @@ -0,0 +1,76 @@ +## @file +# process Subtype GUIDed section generation +# +# Copyright (c) 2022, Konstantin Aladyshev +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +from __future__ import absolute_import +from . import Section +import subprocess +from .Ffs import SectionSuffix +import Common.LongFilePathOs as os +from .GenFdsGlobalVariable import GenFdsGlobalVariable +from .GenFdsGlobalVariable import FindExtendTool +from CommonDataClass.FdfClass import SubTypeGuidSectionClassObject +import sys +from Common import EdkLogger +from Common.BuildToolError import * +from .FvImageSection import FvImageSection +from Common.LongFilePathSupport import OpenLongFilePath as open +from Common.DataType import * + +## generate SubType GUIDed section +# +# +class SubTypeGuidSection(SubTypeGuidSectionClassObject) : + + ## The constructor + # + # @param self The object pointer + # + def __init__(self): + SubTypeGuidSectionClassObject.__init__(self) + + ## GenSection() method + # + # Generate GUIDed section + # + # @param self The object pointer + # @param OutputPath Where to place output file + # @param ModuleName Which module this section belongs to + # @param SecNum Index of section + # @param KeyStringList Filter for inputs of section generation + # @param FfsInf FfsInfStatement object that contains this section data + # @param Dict dictionary contains macro and its value + # @retval tuple (Generated file name, section alignment) + # + def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf=None, Dict=None, IsMakefile=False): + # + # Generate all section + # + self.KeyStringList = KeyStringList + self.CurrentArchList = GenFdsGlobalVariable.ArchList + if FfsInf is not None: + self.Alignment = FfsInf.__ExtendMacro__(self.Alignment) + self.SubTypeGuid = FfsInf.__ExtendMacro__(self.SubTypeGuid) + self.SectionType = FfsInf.__ExtendMacro__(self.SectionType) + self.CurrentArchList = [FfsInf.CurrentArch] + + if Dict is None: + Dict = {} + + self.SectFileName = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.SectFileName) + self.SectFileName = GenFdsGlobalVariable.MacroExtend(self.SectFileName, Dict) + + OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + SectionSuffix.get("SUBTYPE_GUID")) + GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileName], 'EFI_SECTION_FREEFORM_SUBTYPE_GUID', Guid=self.SubTypeGuid, IsMakefile=IsMakefile) + + OutputFileList = [] + OutputFileList.append(OutputFile) + return OutputFileList, self.Alignment + From 9325dd5a164509a9ec3719f0d8501d2cab5fe7f9 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 30 Aug 2022 18:19:57 +0800 Subject: [PATCH 0178/1529] BaseTools: Support COMPAT16 section generation Currently COMPAT16 section type is not recognized and GenSec is called without the "-s [SectionType]" argument. Add COMPAT16 type to the SectionType dictionary to fix the issue. Now this syntax works correctly: ``` FILE FREEFORM = { SECTION COMPAT16 = } ``` Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/Python/GenFds/Section.py | 1 + 1 file changed, 1 insertion(+) diff --git a/BaseTools/Source/Python/GenFds/Section.py b/BaseTools/Source/Python/GenFds/Section.py index 447828c8e5..859db7230a 100644 --- a/BaseTools/Source/Python/GenFds/Section.py +++ b/BaseTools/Source/Python/GenFds/Section.py @@ -28,6 +28,7 @@ class Section (SectionClassObject): BINARY_FILE_TYPE_PIC : 'EFI_SECTION_PIC', BINARY_FILE_TYPE_TE : 'EFI_SECTION_TE', 'FV_IMAGE' : 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', + 'COMPAT16' : 'EFI_SECTION_COMPATIBILITY16', BINARY_FILE_TYPE_DXE_DEPEX : 'EFI_SECTION_DXE_DEPEX', BINARY_FILE_TYPE_PEI_DEPEX : 'EFI_SECTION_PEI_DEPEX', 'GUIDED' : 'EFI_SECTION_GUID_DEFINED', From b5ac36fe6480e553ea7f4c20caa8ab965aad26d0 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 30 Aug 2022 18:18:31 +0800 Subject: [PATCH 0179/1529] BaseTools/GenFds: Correct file type set for the PIC section Corrently the set of file types for the PIC section contains two duplicate values. Replace the duplicate value with the correct one to fix the issue. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/Python/GenFds/FdfParser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source/Python/GenFds/FdfParser.py index aa18fef09e..a9a14ca2bb 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -4018,7 +4018,7 @@ def _CheckRuleSectionFileType(self, SectionType, FileType): if FileType not in {BINARY_FILE_TYPE_PE32, "SEC_PE32"}: raise Warning(WarningString % FileType, self.FileName, self.CurrentLineNumber) elif SectionType == BINARY_FILE_TYPE_PIC: - if FileType not in {BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_PIC}: + if FileType not in {BINARY_FILE_TYPE_PIC, "SEC_PIC"}: raise Warning(WarningString % FileType, self.FileName, self.CurrentLineNumber) elif SectionType == BINARY_FILE_TYPE_TE: if FileType not in {BINARY_FILE_TYPE_TE, "SEC_TE"}: From b11dcfad79f7145c06e3e8bd2703d636904102bb Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 30 Aug 2022 18:20:54 +0800 Subject: [PATCH 0180/1529] BaseTools: Correct initialization data size check for array PCDs Currently it is not possible to initialize all elements in the array PCD. For example, this PCD would result to a build failure: gTokenSpaceGuid.PcdArray|{0x11, 0x22}|UINT8[2]|0x4C4CB9A3 Correct logical operator in the initialization data size checks to fix the issue. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- .../Source/Python/Workspace/DscBuildData.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/Source/Python/Workspace/DscBuildData.py index e9f68384b4..73c6ee4006 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -2089,12 +2089,12 @@ def GenerateDefaultValueAssignFunction(self, Pcd): pcdarraysize = Pcd.PcdArraySize() if "{CODE(" in Pcd.DefaultValueFromDec: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_INIT_Value) < %d * sizeof(%s), "Pcd %s.%s Value in Dec exceed the array capability %s"); // From %s Line %s \n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,Pcd.DefaultValueFromDecInfo[0],Pcd.DefaultValueFromDecInfo[1]) + CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_INIT_Value) <= %d * sizeof(%s), "Pcd %s.%s Value in Dec exceed the array capability %s"); // From %s Line %s \n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,Pcd.DefaultValueFromDecInfo[0],Pcd.DefaultValueFromDecInfo[1]) CApp = CApp + ' PcdArraySize = sizeof(%s_%s_INIT_Value);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) CApp = CApp + ' memcpy (Pcd, %s_%s_INIT_Value,PcdArraySize);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) else: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(%d < %d * sizeof(%s), "Pcd %s.%s Value in Dec exceed the array capability %s"); // From %s Line %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,Pcd.DefaultValueFromDecInfo[0],Pcd.DefaultValueFromDecInfo[1]) + CApp = CApp + '__STATIC_ASSERT(%d <= %d * sizeof(%s), "Pcd %s.%s Value in Dec exceed the array capability %s"); // From %s Line %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,Pcd.DefaultValueFromDecInfo[0],Pcd.DefaultValueFromDecInfo[1]) CApp = CApp + ' PcdArraySize = %d;\n' % ValueSize CApp = CApp + ' Value = %s; // From DEC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DefaultValueFromDec) CApp = CApp + ' memcpy (Pcd, Value, PcdArraySize);\n' @@ -2204,7 +2204,7 @@ def GenerateInitValueFunction(self, Pcd, SkuName, DefaultStoreName): if "{CODE(" in Value: if Pcd.IsArray() and Pcd.Capacity[-1] != "-1": pcdarraysize = Pcd.PcdArraySize() - CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType, valuefrom) + CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType, valuefrom) CApp = CApp+ ' PcdArraySize = sizeof(%s_%s_%s_%s_Value);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) CApp = CApp + ' memcpy (Pcd, &%s_%s_%s_%s_Value,PcdArraySize);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) else: @@ -2217,12 +2217,12 @@ def GenerateInitValueFunction(self, Pcd, SkuName, DefaultStoreName): pcdarraysize = Pcd.PcdArraySize() if "{CODE(" in pcddefaultvalue: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) + CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) CApp = CApp + ' PcdArraySize = sizeof(%s_%s_%s_%s_Value);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) CApp = CApp + ' memcpy (Pcd, %s_%s_%s_%s_Value, PcdArraySize);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) else: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(%d < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) + CApp = CApp + '__STATIC_ASSERT(%d <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) CApp = CApp + ' PcdArraySize = %d;\n' % ValueSize CApp = CApp + ' Value = %s; // From DSC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DefaultFromDSC.get(TAB_DEFAULT, {}).get(TAB_DEFAULT_STORES_DEFAULT, Pcd.DefaultValue) if Pcd.DefaultFromDSC else Pcd.DefaultValue) CApp = CApp + ' memcpy (Pcd, Value, PcdArraySize);\n' @@ -2238,7 +2238,7 @@ def GenerateInitValueFunction(self, Pcd, SkuName, DefaultStoreName): if "{CODE(" in Value: if Pcd.IsArray() and Pcd.Capacity[-1] != "-1": pcdarraysize = Pcd.PcdArraySize() - CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) + CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) CApp = CApp + ' PcdArraySize = sizeof(%s_%s_%s_%s_Value);\n '% (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) CApp = CApp + ' memcpy (Pcd, &%s_%s_%s_%s_Value, PcdArraySize);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) else: @@ -2251,12 +2251,12 @@ def GenerateInitValueFunction(self, Pcd, SkuName, DefaultStoreName): pcdarraysize = Pcd.PcdArraySize() if "{CODE(" in pcddefaultvalue: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) + CApp = CApp + '__STATIC_ASSERT(sizeof(%s_%s_%s_%s_Value) <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) CApp + ' PcdArraySize = sizeof(%s_%s_%s_%s_Value);\n ' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) CApp = CApp + ' memcpy (Pcd, %s_%s_%s_%s_Value, PcdArraySize);\n' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName,SkuName, DefaultStoreName) else: if Pcd.Capacity[-1] != "-1": - CApp = CApp + '__STATIC_ASSERT(%d < %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) + CApp = CApp + '__STATIC_ASSERT(%d <= %d * sizeof(%s), "Pcd %s.%s Value in Dsc exceed the array capability %s"); // From %s \n' % (ValueSize,pcdarraysize,Pcd.BaseDatumType,Pcd.TokenSpaceGuidCName, Pcd.TokenCName,Pcd.DatumType,valuefrom) CApp = CApp + ' PcdArraySize = %d;\n' % ValueSize CApp = CApp + ' Value = %s; // From DSC Default Value %s\n' % (DscBuildData.IntToCString(Value, ValueSize), Pcd.DscRawValue.get(TAB_DEFAULT, {}).get(TAB_DEFAULT_STORES_DEFAULT, Pcd.DefaultValue) if Pcd.DefaultFromDSC else Pcd.DefaultValue) CApp = CApp + ' memcpy (Pcd, Value, PcdArraySize);\n' From 7f159e5d8bc4cd19810fe58690b0c7579404729a Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Tue, 30 Aug 2022 18:20:27 +0800 Subject: [PATCH 0181/1529] BaseTools: Add missing spaces for PCD expression values in AutoGenC Currently the PCD values calculated from the expressions have different formating from the simple byte arrays in AutoGenC. Example: The following definition in DEC: gTokenSpaceGuid.PcdArray|{0x44, 0x33, 0x22, 0x11}|VOID*|0x55555555 gTokenSpaceGuid.PcdArrayByExpression|{UINT32(0x11223344)}|VOID*|0x66666666 Produces these strings in AutoGenC: <...> _gPcd_<...>_PcdArray[4] = {0x44, 0x33, 0x22, 0x11}; <...> _gPcd_<...>_PcdArrayByExpression[4] = {0x44,0x33,0x22,0x11}; Add missing space character between the array elements to unify PCD value formatting. Signed-off-by: Konstantin Aladyshev Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/Python/Common/Expression.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Source/Python/Common/Expression.py index 31bf0e4b6c..b62efe6f9b 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -1026,7 +1026,7 @@ def __call__(self, RealValue=False, Depth=0): Size += ItemSize if Size > 0: - PcdValue = '{' + ','.join(AllPcdValueList) + '}' + PcdValue = '{' + ', '.join(AllPcdValueList) + '}' else: raise BadExpression("Type: %s, Value: %s, %s"%(self.PcdType, PcdValue, Value)) From 872cf83ed66fa8876b3614bccd0606f90b69a7dc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 3 Jul 2022 09:29:26 +0200 Subject: [PATCH 0182/1529] ArmPkg/ArmMmuLib: don't replace table entries with block entries Drop the optimization that replaces table entries with block entries and frees the page tables in the subhierarchy that is being replaced. This rarely occurs in practice anyway, and will require more elaborate TLB maintenance once we switch to a different approach where we no longer disable the MMU and nuke the TLB entirely every time we update a descriptor in a way that requires break-before-make (BBM). Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 20 ++----------------- 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index e5ecc73751..34f1031c4d 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -197,12 +197,9 @@ UpdateRegionMappingRecursive ( // than a block, and recurse to create the block or page entries at // the next level. No block mappings are allowed at all at level 0, // so in that case, we have to recurse unconditionally. - // If we are changing a table entry and the AttributeClearMask is non-zero, - // we cannot replace it with a block entry without potentially losing - // attribute information, so keep the table entry in that case. // if ((Level == 0) || (((RegionStart | BlockEnd) & BlockMask) != 0) || - (IsTableEntry (*Entry, Level) && (AttributeClearMask != 0))) + IsTableEntry (*Entry, Level)) { ASSERT (Level < 3); @@ -294,20 +291,7 @@ UpdateRegionMappingRecursive ( EntryValue |= (Level == 3) ? TT_TYPE_BLOCK_ENTRY_LEVEL3 : TT_TYPE_BLOCK_ENTRY; - if (IsTableEntry (*Entry, Level)) { - // - // We are replacing a table entry with a block entry. This is only - // possible if we are keeping none of the original attributes. - // We can free the table entry's page table, and all the ones below - // it, since we are dropping the only possible reference to it. - // - ASSERT (AttributeClearMask == 0); - TranslationTable = (VOID *)(UINTN)(*Entry & TT_ADDRESS_MASK_BLOCK_ENTRY); - ReplaceTableEntry (Entry, EntryValue, RegionStart, TRUE); - FreePageTablesRecursive (TranslationTable, Level + 1); - } else { - ReplaceTableEntry (Entry, EntryValue, RegionStart, FALSE); - } + ReplaceTableEntry (Entry, EntryValue, RegionStart, FALSE); } } From 2e3ca2e2d769737b19af8d4618a88392d4e2f509 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 24 Sep 2022 18:26:19 +0200 Subject: [PATCH 0183/1529] ArmPkg/ArmMmuLib: Disable and re-enable MMU only when needed When updating a page table descriptor in a way that requires break before make, we temporarily disable the MMU to ensure that we don't unmap the memory region that the code itself is executing from. However, this is a condition we can check in a straight-forward manner, and if the regions are disjoint, we don't have to bother with the MMU controls, and we can just perform an ordinary break before make. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Include/Library/ArmMmuLib.h | 7 +- .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 102 ++++++++++++++---- .../ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S | 43 ++++++-- 3 files changed, 123 insertions(+), 29 deletions(-) diff --git a/ArmPkg/Include/Library/ArmMmuLib.h b/ArmPkg/Include/Library/ArmMmuLib.h index 7538a8274a..b745e2230e 100644 --- a/ArmPkg/Include/Library/ArmMmuLib.h +++ b/ArmPkg/Include/Library/ArmMmuLib.h @@ -52,9 +52,10 @@ ArmClearMemoryRegionReadOnly ( VOID EFIAPI ArmReplaceLiveTranslationEntry ( - IN UINT64 *Entry, - IN UINT64 Value, - IN UINT64 RegionStart + IN UINT64 *Entry, + IN UINT64 Value, + IN UINT64 RegionStart, + IN BOOLEAN DisableMmu ); EFI_STATUS diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 34f1031c4d..4d75788ed2 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -18,6 +18,17 @@ #include #include #include +#include + +STATIC +VOID ( + EFIAPI *mReplaceLiveEntryFunc + )( + IN UINT64 *Entry, + IN UINT64 Value, + IN UINT64 RegionStart, + IN BOOLEAN DisableMmu + ) = ArmReplaceLiveTranslationEntry; STATIC UINT64 @@ -83,14 +94,40 @@ ReplaceTableEntry ( IN UINT64 *Entry, IN UINT64 Value, IN UINT64 RegionStart, + IN UINT64 BlockMask, IN BOOLEAN IsLiveBlockMapping ) { - if (!ArmMmuEnabled () || !IsLiveBlockMapping) { + BOOLEAN DisableMmu; + + // + // Replacing a live block entry with a table entry (or vice versa) requires a + // break-before-make sequence as per the architecture. This means the mapping + // must be made invalid and cleaned from the TLBs first, and this is a bit of + // a hassle if the mapping in question covers the code that is actually doing + // the mapping and the unmapping, and so we only bother with this if actually + // necessary. + // + + if (!IsLiveBlockMapping || !ArmMmuEnabled ()) { + // If the mapping is not a live block mapping, or the MMU is not on yet, we + // can simply overwrite the entry. *Entry = Value; ArmUpdateTranslationTableEntry (Entry, (VOID *)(UINTN)RegionStart); } else { - ArmReplaceLiveTranslationEntry (Entry, Value, RegionStart); + // If the mapping in question does not cover the code that updates the + // entry in memory, or the entry that we are intending to update, we can + // use an ordinary break before make. Otherwise, we will need to + // temporarily disable the MMU. + DisableMmu = FALSE; + if ((((RegionStart ^ (UINTN)ArmReplaceLiveTranslationEntry) & ~BlockMask) == 0) || + (((RegionStart ^ (UINTN)Entry) & ~BlockMask) == 0)) + { + DisableMmu = TRUE; + DEBUG ((DEBUG_WARN, "%a: splitting block entry with MMU disabled\n", __FUNCTION__)); + } + + ArmReplaceLiveTranslationEntry (Entry, Value, RegionStart, DisableMmu); } } @@ -155,12 +192,13 @@ IsTableEntry ( STATIC EFI_STATUS UpdateRegionMappingRecursive ( - IN UINT64 RegionStart, - IN UINT64 RegionEnd, - IN UINT64 AttributeSetMask, - IN UINT64 AttributeClearMask, - IN UINT64 *PageTable, - IN UINTN Level + IN UINT64 RegionStart, + IN UINT64 RegionEnd, + IN UINT64 AttributeSetMask, + IN UINT64 AttributeClearMask, + IN UINT64 *PageTable, + IN UINTN Level, + IN BOOLEAN TableIsLive ) { UINTN BlockShift; @@ -170,6 +208,7 @@ UpdateRegionMappingRecursive ( UINT64 EntryValue; VOID *TranslationTable; EFI_STATUS Status; + BOOLEAN NextTableIsLive; ASSERT (((RegionStart | RegionEnd) & EFI_PAGE_MASK) == 0); @@ -198,7 +237,14 @@ UpdateRegionMappingRecursive ( // the next level. No block mappings are allowed at all at level 0, // so in that case, we have to recurse unconditionally. // + // One special case to take into account is any region that covers the page + // table itself: if we'd cover such a region with block mappings, we are + // more likely to end up in the situation later where we need to disable + // the MMU in order to update page table entries safely, so prefer page + // mappings in that particular case. + // if ((Level == 0) || (((RegionStart | BlockEnd) & BlockMask) != 0) || + ((Level < 3) && (((UINT64)PageTable & ~BlockMask) == RegionStart)) || IsTableEntry (*Entry, Level)) { ASSERT (Level < 3); @@ -234,7 +280,8 @@ UpdateRegionMappingRecursive ( *Entry & TT_ATTRIBUTES_MASK, 0, TranslationTable, - Level + 1 + Level + 1, + FALSE ); if (EFI_ERROR (Status)) { // @@ -246,8 +293,11 @@ UpdateRegionMappingRecursive ( return Status; } } + + NextTableIsLive = FALSE; } else { TranslationTable = (VOID *)(UINTN)(*Entry & TT_ADDRESS_MASK_BLOCK_ENTRY); + NextTableIsLive = TableIsLive; } // @@ -259,7 +309,8 @@ UpdateRegionMappingRecursive ( AttributeSetMask, AttributeClearMask, TranslationTable, - Level + 1 + Level + 1, + NextTableIsLive ); if (EFI_ERROR (Status)) { if (!IsTableEntry (*Entry, Level)) { @@ -282,7 +333,8 @@ UpdateRegionMappingRecursive ( Entry, EntryValue, RegionStart, - IsBlockEntry (*Entry, Level) + BlockMask, + TableIsLive && IsBlockEntry (*Entry, Level) ); } } else { @@ -291,7 +343,7 @@ UpdateRegionMappingRecursive ( EntryValue |= (Level == 3) ? TT_TYPE_BLOCK_ENTRY_LEVEL3 : TT_TYPE_BLOCK_ENTRY; - ReplaceTableEntry (Entry, EntryValue, RegionStart, FALSE); + ReplaceTableEntry (Entry, EntryValue, RegionStart, BlockMask, FALSE); } } @@ -301,10 +353,11 @@ UpdateRegionMappingRecursive ( STATIC EFI_STATUS UpdateRegionMapping ( - IN UINT64 RegionStart, - IN UINT64 RegionLength, - IN UINT64 AttributeSetMask, - IN UINT64 AttributeClearMask + IN UINT64 RegionStart, + IN UINT64 RegionLength, + IN UINT64 AttributeSetMask, + IN UINT64 AttributeClearMask, + IN BOOLEAN TableIsLive ) { UINTN T0SZ; @@ -321,7 +374,8 @@ UpdateRegionMapping ( AttributeSetMask, AttributeClearMask, ArmGetTTBR0BaseAddress (), - GetRootTableLevel (T0SZ) + GetRootTableLevel (T0SZ), + TableIsLive ); } @@ -336,7 +390,8 @@ FillTranslationTable ( MemoryRegion->VirtualBase, MemoryRegion->Length, ArmMemoryAttributeToPageAttribute (MemoryRegion->Attributes) | TT_AF, - 0 + 0, + FALSE ); } @@ -410,7 +465,8 @@ ArmSetMemoryAttributes ( BaseAddress, Length, PageAttributes, - PageAttributeMask + PageAttributeMask, + TRUE ); } @@ -423,7 +479,13 @@ SetMemoryRegionAttribute ( IN UINT64 BlockEntryMask ) { - return UpdateRegionMapping (BaseAddress, Length, Attributes, BlockEntryMask); + return UpdateRegionMapping ( + BaseAddress, + Length, + Attributes, + BlockEntryMask, + TRUE + ); } EFI_STATUS diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S index 66ebca571e..e936a5be4e 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S @@ -12,6 +12,14 @@ .macro __replace_entry, el + // check whether we should disable the MMU + cbz x3, .L1_\@ + + // clean and invalidate first so that we don't clobber + // adjacent entries that are dirty in the caches + dc civac, x0 + dsb nsh + // disable the MMU mrs x8, sctlr_el\el bic x9, x8, #CTRL_M_BIT @@ -38,8 +46,33 @@ // re-enable the MMU msr sctlr_el\el, x8 isb + b .L2_\@ + +.L1_\@: + // write invalid entry + str xzr, [x0] + dsb nshst + + // flush translations for the target address from the TLBs + lsr x2, x2, #12 + .if \el == 1 + tlbi vaae1, x2 + .else + tlbi vae\el, x2 + .endif + dsb nsh + + // write updated entry + str x1, [x0] + dsb nshst + +.L2_\@: .endm + // Align this routine to a log2 upper bound of its size, so that it is + // guaranteed not to cross a page or block boundary. + .balign 0x200 + //VOID //ArmReplaceLiveTranslationEntry ( // IN UINT64 *Entry, @@ -53,12 +86,7 @@ ASM_FUNC(ArmReplaceLiveTranslationEntry) msr daifset, #0xf isb - // clean and invalidate first so that we don't clobber - // adjacent entries that are dirty in the caches - dc civac, x0 - dsb nsh - - EL1_OR_EL2_OR_EL3(x3) + EL1_OR_EL2_OR_EL3(x5) 1:__replace_entry 1 b 4f 2:__replace_entry 2 @@ -72,3 +100,6 @@ ASM_GLOBAL ASM_PFX(ArmReplaceLiveTranslationEntrySize) ASM_PFX(ArmReplaceLiveTranslationEntrySize): .long . - ArmReplaceLiveTranslationEntry + + // Double check that we did not overrun the assumed maximum size + .org ArmReplaceLiveTranslationEntry + 0x200 From 93e84e15fdb5c7c263d2481db448c33a3cb3202f Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 2 Jul 2022 15:14:28 +0200 Subject: [PATCH 0184/1529] ArmPkg/ArmMmuLib: permit initial configuration with MMU enabled Permit the use of this library with the MMU and caches already enabled. This removes the need for any cache maintenance for coherency, and is generally better for robustness and performance, especially when running under virtualization. Note that this means we have to defer assignment of TTBR0 until the page tables are ready to be used, and so UpdateRegionMapping() can no longer read back TTBR0 directly to discover the root table address. Signed-off-by: Ard Biesheuvel Acked-by: Leif Lindholm --- .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 48 ++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 4d75788ed2..ae59e9a7d0 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -357,6 +357,7 @@ UpdateRegionMapping ( IN UINT64 RegionLength, IN UINT64 AttributeSetMask, IN UINT64 AttributeClearMask, + IN UINT64 *RootTable, IN BOOLEAN TableIsLive ) { @@ -373,7 +374,7 @@ UpdateRegionMapping ( RegionStart + RegionLength, AttributeSetMask, AttributeClearMask, - ArmGetTTBR0BaseAddress (), + RootTable, GetRootTableLevel (T0SZ), TableIsLive ); @@ -391,6 +392,7 @@ FillTranslationTable ( MemoryRegion->Length, ArmMemoryAttributeToPageAttribute (MemoryRegion->Attributes) | TT_AF, 0, + RootTable, FALSE ); } @@ -466,6 +468,7 @@ ArmSetMemoryAttributes ( Length, PageAttributes, PageAttributeMask, + ArmGetTTBR0BaseAddress (), TRUE ); } @@ -484,6 +487,7 @@ SetMemoryRegionAttribute ( Length, Attributes, BlockEntryMask, + ArmGetTTBR0BaseAddress (), TRUE ); } @@ -675,14 +679,6 @@ ArmConfigureMmu ( return EFI_OUT_OF_RESOURCES; } - // - // We set TTBR0 just after allocating the table to retrieve its location from - // the subsequent functions without needing to pass this value across the - // functions. The MMU is only enabled after the translation tables are - // populated. - // - ArmSetTTBR0 (TranslationTable); - if (TranslationTableBase != NULL) { *TranslationTableBase = TranslationTable; } @@ -691,14 +687,17 @@ ArmConfigureMmu ( *TranslationTableSize = RootTableEntryCount * sizeof (UINT64); } - // - // Make sure we are not inadvertently hitting in the caches - // when populating the page tables. - // - InvalidateDataCacheRange ( - TranslationTable, - RootTableEntryCount * sizeof (UINT64) - ); + if (!ArmMmuEnabled ()) { + // + // Make sure we are not inadvertently hitting in the caches + // when populating the page tables. + // + InvalidateDataCacheRange ( + TranslationTable, + RootTableEntryCount * sizeof (UINT64) + ); + } + ZeroMem (TranslationTable, RootTableEntryCount * sizeof (UINT64)); while (MemoryTable->Length != 0) { @@ -723,12 +722,17 @@ ArmConfigureMmu ( MAIR_ATTR (TT_ATTR_INDX_MEMORY_WRITE_BACK, MAIR_ATTR_NORMAL_MEMORY_WRITE_BACK) ); - ArmDisableAlignmentCheck (); - ArmEnableStackAlignmentCheck (); - ArmEnableInstructionCache (); - ArmEnableDataCache (); + ArmSetTTBR0 (TranslationTable); + + if (!ArmMmuEnabled ()) { + ArmDisableAlignmentCheck (); + ArmEnableStackAlignmentCheck (); + ArmEnableInstructionCache (); + ArmEnableDataCache (); + + ArmEnableMmu (); + } - ArmEnableMmu (); return EFI_SUCCESS; FreeTranslationTable: From 6ed8c8b8fa00df3599d418ce8e684f05efa85899 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 24 Sep 2022 22:31:44 +0200 Subject: [PATCH 0185/1529] ArmPkg/ArmMmuLib: Reuse XIP MMU routines when splitting entries In order to reduce the likelihood that we will need to rely on the logic that disables and re-enables the MMU for updating a page table entry safely, expose the XIP version of the helper routine via a HOB and use it instead of the one that is copied into DRAM. Since the XIP copy is already clean to the PoC, and will never end up getting unmapped during a block entry split, we can use it safely without any cache maintenance, and without running the risk of pulling the rug from under our feet when updating an entry by going through an invalid mapping. Signed-off-by: Ard Biesheuvel Acked-by: Leif Lindholm --- ArmPkg/ArmPkg.dec | 2 ++ .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 27 ++++++++++++------- .../AArch64/ArmMmuPeiLibConstructor.c | 17 ++++++++++++ ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf | 4 +++ ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf | 4 +++ 5 files changed, 44 insertions(+), 10 deletions(-) diff --git a/ArmPkg/ArmPkg.dec b/ArmPkg/ArmPkg.dec index 9da1bbc9f2..cfb6fe6024 100644 --- a/ArmPkg/ArmPkg.dec +++ b/ArmPkg/ArmPkg.dec @@ -99,6 +99,8 @@ # Include/Guid/ArmMpCoreInfo.h gArmMpCoreInfoGuid = { 0xa4ee0728, 0xe5d7, 0x4ac5, {0xb2, 0x1e, 0x65, 0x8e, 0xd8, 0x57, 0xe8, 0x34} } + gArmMmuReplaceLiveTranslationEntryFuncGuid = { 0xa8b50ff3, 0x08ec, 0x4dd3, {0xbf, 0x04, 0x28, 0xbf, 0x71, 0x75, 0xc7, 0x4a} } + [Protocols.common] ## Arm System Control and Management Interface(SCMI) Base protocol ## ArmPkg/Include/Protocol/ArmScmiBaseProtocol.h diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index ae59e9a7d0..764c7d362e 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -10,6 +10,7 @@ **/ #include +#include #include #include #include @@ -120,14 +121,14 @@ ReplaceTableEntry ( // use an ordinary break before make. Otherwise, we will need to // temporarily disable the MMU. DisableMmu = FALSE; - if ((((RegionStart ^ (UINTN)ArmReplaceLiveTranslationEntry) & ~BlockMask) == 0) || + if ((((RegionStart ^ (UINTN)mReplaceLiveEntryFunc) & ~BlockMask) == 0) || (((RegionStart ^ (UINTN)Entry) & ~BlockMask) == 0)) { DisableMmu = TRUE; DEBUG ((DEBUG_WARN, "%a: splitting block entry with MMU disabled\n", __FUNCTION__)); } - ArmReplaceLiveTranslationEntry (Entry, Value, RegionStart, DisableMmu); + mReplaceLiveEntryFunc (Entry, Value, RegionStart, DisableMmu); } } @@ -747,15 +748,21 @@ ArmMmuBaseLibConstructor ( ) { extern UINT32 ArmReplaceLiveTranslationEntrySize; + VOID *Hob; - // - // The ArmReplaceLiveTranslationEntry () helper function may be invoked - // with the MMU off so we have to ensure that it gets cleaned to the PoC - // - WriteBackDataCacheRange ( - (VOID *)(UINTN)ArmReplaceLiveTranslationEntry, - ArmReplaceLiveTranslationEntrySize - ); + Hob = GetFirstGuidHob (&gArmMmuReplaceLiveTranslationEntryFuncGuid); + if (Hob != NULL) { + mReplaceLiveEntryFunc = *(VOID **)GET_GUID_HOB_DATA (Hob); + } else { + // + // The ArmReplaceLiveTranslationEntry () helper function may be invoked + // with the MMU off so we have to ensure that it gets cleaned to the PoC + // + WriteBackDataCacheRange ( + (VOID *)(UINTN)ArmReplaceLiveTranslationEntry, + ArmReplaceLiveTranslationEntrySize + ); + } return RETURN_SUCCESS; } diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuPeiLibConstructor.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuPeiLibConstructor.c index caace2c17c..5f50a605a3 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuPeiLibConstructor.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuPeiLibConstructor.c @@ -12,6 +12,7 @@ #include #include #include +#include EFI_STATUS EFIAPI @@ -21,6 +22,8 @@ ArmMmuPeiLibConstructor ( ) { extern UINT32 ArmReplaceLiveTranslationEntrySize; + VOID *ArmReplaceLiveTranslationEntryFunc; + VOID *Hob; EFI_FV_FILE_INFO FileInfo; EFI_STATUS Status; @@ -42,6 +45,20 @@ ArmMmuPeiLibConstructor ( (UINTN)ArmReplaceLiveTranslationEntry + ArmReplaceLiveTranslationEntrySize)) { DEBUG ((DEBUG_INFO, "ArmMmuLib: skipping cache maintenance on XIP PEIM\n")); + + // + // Expose the XIP version of the ArmReplaceLiveTranslationEntry() routine + // via a HOB so we can fall back to it later when we need to split block + // mappings in a way that adheres to break-before-make requirements. + // + ArmReplaceLiveTranslationEntryFunc = ArmReplaceLiveTranslationEntry; + + Hob = BuildGuidDataHob ( + &gArmMmuReplaceLiveTranslationEntryFuncGuid, + &ArmReplaceLiveTranslationEntryFunc, + sizeof ArmReplaceLiveTranslationEntryFunc + ); + ASSERT (Hob != NULL); } else { DEBUG ((DEBUG_INFO, "ArmMmuLib: performing cache maintenance on shadowed PEIM\n")); // diff --git a/ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf b/ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf index 3d78e7dabf..57cb71f90e 100644 --- a/ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf +++ b/ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf @@ -36,7 +36,11 @@ [LibraryClasses] ArmLib CacheMaintenanceLib + HobLib MemoryAllocationLib +[Guids] + gArmMmuReplaceLiveTranslationEntryFuncGuid + [Pcd.ARM] gArmTokenSpaceGuid.PcdNormalMemoryNonshareableOverride diff --git a/ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf b/ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf index ce9674ea99..02f874a1a9 100644 --- a/ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf +++ b/ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf @@ -29,4 +29,8 @@ [LibraryClasses] ArmLib CacheMaintenanceLib + HobLib MemoryAllocationLib + +[Guids] + gArmMmuReplaceLiveTranslationEntryFuncGuid From fd0cc4ba0f43d637c435993f1ead4fede33dd9b4 Mon Sep 17 00:00:00 2001 From: jdzhang Date: Tue, 18 Oct 2022 10:56:02 +0800 Subject: [PATCH 0186/1529] MdeModulePkg/XhciDxe: Add boundary check for TRB ring allocation According the Xhci Spec, TRB Rings may be larger than a Page, however they shall not cross a 64K byte boundary, so add a parameter to indicate whether the memory allocation is for TRB Rings or not. It will ensure the allocation not crossing 64K boundary in UsbHcAllocMemFromBlock if the memory is allocated for TRB Rings. Signed-off-by: jdzhang Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c | 43 ++++++++++++++++++------ MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h | 10 ++++-- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 16 ++++----- 3 files changed, 47 insertions(+), 22 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c index 99fb3521d5..d0ad1582e4 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c @@ -132,8 +132,9 @@ UsbHcFreeMemBlock ( /** Alloc some memory from the block. - @param Block The memory block to allocate memory from. - @param Units Number of memory units to allocate. + @param Block The memory block to allocate memory from. + @param Units Number of memory units to allocate. + @param AllocationForRing The allocated memory is for Ring or not. @return The pointer to the allocated memory. If couldn't allocate the needed memory, the return value is NULL. @@ -142,7 +143,8 @@ UsbHcFreeMemBlock ( VOID * UsbHcAllocMemFromBlock ( IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN UINTN Units, + IN BOOLEAN AllocationForRing ) { UINTN Byte; @@ -151,12 +153,15 @@ UsbHcAllocMemFromBlock ( UINT8 StartBit; UINTN Available; UINTN Count; + UINTN MemUnitAddr; + UINTN AlignmentMask; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; + AlignmentMask = ~((UINTN)USBHC_MEM_TRB_RINGS_BOUNDARY - 1); for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -165,6 +170,20 @@ UsbHcAllocMemFromBlock ( // Available counts the consective number of zero bit. // if (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)) { + if (AllocationForRing && (Available != 0)) { + MemUnitAddr = (UINTN)Block->BufHost + (Byte * 8 + Bit) * USBHC_MEM_UNIT; + if ((MemUnitAddr & AlignmentMask) != ((MemUnitAddr - USBHC_MEM_UNIT) & AlignmentMask)) { + // + // If the TRB Ring memory cross 64K-byte boundary, then restart the + // search starting at current memory unit. + // Doing so is to meet the TRB Ring boundary requirement in XHCI spec. + // + Available = 0; + StartByte = Byte; + StartBit = Bit; + } + } + Available++; if (Available >= Units) { @@ -438,8 +457,9 @@ UsbHcFreeMemPool ( Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. - @param Pool The host controller's memory pool. - @param Size Size of the memory to allocate. + @param Pool The host controller's memory pool. + @param Size Size of the memory to allocate. + @param AllocationForRing The allocated memory is for Ring or not. @return The allocated memory or NULL. @@ -447,7 +467,8 @@ UsbHcFreeMemPool ( VOID * UsbHcAllocateMem ( IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN UINTN Size, + IN BOOLEAN AllocationForRing ) { USBHC_MEM_BLOCK *Head; @@ -466,7 +487,7 @@ UsbHcAllocateMem ( // First check whether current memory blocks can satisfy the allocation. // for (Block = Head; Block != NULL; Block = Block->Next) { - Mem = UsbHcAllocMemFromBlock (Block, AllocSize / USBHC_MEM_UNIT); + Mem = UsbHcAllocMemFromBlock (Block, AllocSize / USBHC_MEM_UNIT, AllocationForRing); if (Mem != NULL) { ZeroMem (Mem, Size); @@ -501,7 +522,7 @@ UsbHcAllocateMem ( // Add the new memory block to the pool, then allocate memory from it // UsbHcInsertMemBlockToPool (Head, NewBlock); - Mem = UsbHcAllocMemFromBlock (NewBlock, AllocSize / USBHC_MEM_UNIT); + Mem = UsbHcAllocMemFromBlock (NewBlock, AllocSize / USBHC_MEM_UNIT, AllocationForRing); if (Mem != NULL) { ZeroMem (Mem, Size); diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h index 48ae86141c..c85b0b919f 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h @@ -48,6 +48,8 @@ typedef struct _USBHC_MEM_POOL { #define USBHC_MEM_ROUND(Len) (((Len) + USBHC_MEM_UNIT_MASK) & (~USBHC_MEM_UNIT_MASK)) +#define USBHC_MEM_TRB_RINGS_BOUNDARY SIZE_64KB + // // Advance the byte and bit to the next bit, adjust byte accordingly. // @@ -92,8 +94,9 @@ UsbHcFreeMemPool ( Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. - @param Pool The host controller's memory pool. - @param Size Size of the memory to allocate. + @param Pool The host controller's memory pool. + @param Size Size of the memory to allocate. + @param AllocationForRing The allocated memory is for Ring or not. @return The allocated memory or NULL. @@ -101,7 +104,8 @@ UsbHcFreeMemPool ( VOID * UsbHcAllocateMem ( IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN UINTN Size, + IN BOOLEAN AllocationForRing ); /** diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index 4ae0297607..13b0400e83 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -506,7 +506,7 @@ XhcInitSched ( // Software shall set Device Context Base Address Array entries for unallocated Device Slots to '0'. // Entries = (Xhc->MaxSlotsEn + 1) * sizeof (UINT64); - Dcbaa = UsbHcAllocateMem (Xhc->MemPool, Entries); + Dcbaa = UsbHcAllocateMem (Xhc->MemPool, Entries, FALSE); ASSERT (Dcbaa != NULL); ZeroMem (Dcbaa, Entries); @@ -795,7 +795,7 @@ CreateEventRing ( ASSERT (EventRing != NULL); Size = sizeof (TRB_TEMPLATE) * EVENT_RING_TRB_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size, TRUE); ASSERT (Buf != NULL); ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); @@ -814,7 +814,7 @@ CreateEventRing ( EventRing->EventRingCCS = 1; Size = sizeof (EVENT_RING_SEG_TABLE_ENTRY) * ERST_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size, FALSE); ASSERT (Buf != NULL); ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); @@ -892,7 +892,7 @@ CreateTransferRing ( LINK_TRB *EndTrb; EFI_PHYSICAL_ADDRESS PhyAddr; - Buf = UsbHcAllocateMem (Xhc->MemPool, sizeof (TRB_TEMPLATE) * TrbNum); + Buf = UsbHcAllocateMem (Xhc->MemPool, sizeof (TRB_TEMPLATE) * TrbNum, TRUE); ASSERT (Buf != NULL); ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, sizeof (TRB_TEMPLATE) * TrbNum); @@ -2182,7 +2182,7 @@ XhcInitializeDeviceSlot ( // 4.3.3 Device Slot Initialization // 1) Allocate an Input Context data structure (6.2.5) and initialize all fields to '0'. // - InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT)); + InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT), FALSE); ASSERT (InputContext != NULL); ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT)); @@ -2284,7 +2284,7 @@ XhcInitializeDeviceSlot ( // // 6) Allocate the Output Device Context data structure (6.2.1) and initialize it to '0'. // - OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT)); + OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT), FALSE); ASSERT (OutputContext != NULL); ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT)); @@ -2398,7 +2398,7 @@ XhcInitializeDeviceSlot64 ( // 4.3.3 Device Slot Initialization // 1) Allocate an Input Context data structure (6.2.5) and initialize all fields to '0'. // - InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT_64)); + InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT_64), FALSE); ASSERT (InputContext != NULL); ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT_64)); @@ -2500,7 +2500,7 @@ XhcInitializeDeviceSlot64 ( // // 6) Allocate the Output Device Context data structure (6.2.1) and initialize it to '0'. // - OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT_64)); + OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT_64), FALSE); ASSERT (OutputContext != NULL); ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT_64)); From 790d33b81af80e429985f725d71af79adb8ae85f Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Sun, 16 Oct 2022 11:41:05 +0800 Subject: [PATCH 0187/1529] BaseTools/Scripts/PatchCheck.py: Allow tab in Makefile The syntax for Makefiles requires that indented lines s tart with a tab, but not a space. This change of PatchCheck.py make the patch for Makefile/GNUmakefile pass the PatchCheck.py. Signed-off-by: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Reviewed-by: Liming Gao --- BaseTools/Scripts/PatchCheck.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 63e6223f8e..475b3a8c27 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -383,6 +383,9 @@ def run(self): # self.force_crlf = False self.force_notabs = False + if os.path.basename(self.filename) == 'GNUmakefile' or \ + os.path.basename(self.filename) == 'Makefile': + self.force_notabs = False elif len(line.rstrip()) != 0: self.format_error("didn't find diff command") self.line_num += 1 From 8b7bf5a00631fbbe4336de3f303fd90b20b35818 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 20 Sep 2022 05:39:10 +0800 Subject: [PATCH 0188/1529] BaseTools: Fix check for ${PYTHON_COMMAND} in Tests/GNUmakefile When checking if $PYTHON_COMMAND exists, curly braces should be used instead of parentheses. Also, "1" causes an error on FreeBSD: it's likely supposed to be 2>&1 like other scripts. Signed-off-by: Rebecca Cran Reviewed-by: Bob Feng --- BaseTools/Tests/GNUmakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Tests/GNUmakefile b/BaseTools/Tests/GNUmakefile index 1cb77f84b1..caa4d26c9b 100644 --- a/BaseTools/Tests/GNUmakefile +++ b/BaseTools/Tests/GNUmakefile @@ -8,7 +8,7 @@ all: test test: - @if command -v $(PYTHON_COMMAND) >/dev/null 1; then $(PYTHON_COMMAND) RunTests.py; else python RunTests.py; fi + @if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then ${PYTHON_COMMAND} RunTests.py; else python RunTests.py; fi clean: find . -name '*.pyc' -exec rm '{}' ';' From ae94c2a2402831cbcb16d08f32aad571a49bb496 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 20 Oct 2022 17:25:01 +0800 Subject: [PATCH 0189/1529] BaseTools: Fixed the multiple pairs brackets issue in GenFv If operation Werro is turned on when compiling BaseTools, the multi-brackets warning will be reported. This issue is comes from on of the LoongArch enabled patche. Removed extra pairs brackets to fix it. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4111 Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Chao Li Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/C/GenFv/GenFvInternalLib.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index 5c3d54f5f7..b5b9425003 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -3559,7 +3559,7 @@ Routine Description: } // Machine type is LOONGARCH64, set a flag so LoongArch64 reset vector processed. - if ((MachineType == EFI_IMAGE_MACHINE_LOONGARCH64)) { + if (MachineType == EFI_IMAGE_MACHINE_LOONGARCH64) { VerboseMsg("Located LoongArch64 SEC core in child FV"); mLoongArch = TRUE; } @@ -3721,7 +3721,7 @@ Routine Description: mRiscV = TRUE; } - if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) { + if (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) { mLoongArch = TRUE; } @@ -4002,7 +4002,7 @@ Routine Description: mArm = TRUE; } - if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) { + if (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) { mLoongArch = TRUE; } From 36dbdecc3ee977a2a7e787b7b2e65d449235f1eb Mon Sep 17 00:00:00 2001 From: "Wu, JessyX" Date: Tue, 4 Oct 2022 10:03:54 +0800 Subject: [PATCH 0190/1529] remove GCC build warning Fix gcc: warning: -x c after last input file has no effect These kind of flag can only affect the source code after them. For the build command in build_rule.template, we have no other source code or object after these two flag. It seems we don't need them here. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: JessyX Wu Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Conf/build_rule.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index 5895b48fd8..af4819de92 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -463,7 +463,7 @@ "$(ASLCC)" $(DEPS_FLAGS) -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} - "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) + "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) From 615a647d43665e3a4049453c8168335435a52934 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 29 Sep 2022 09:32:54 -0700 Subject: [PATCH 0191/1529] CryptoPkg: Document and disable deprecated crypto services Also note services that are recommended to be disabled and update CryptoPkg.dsc PcdCryptoServiceFamilyEnable settings to disable all deprecated services. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 10 +- .../Pcd/PcdCryptoServiceFamilyEnable.h | 122 ++++++++++-------- 2 files changed, 77 insertions(+), 55 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 8c6906acf0..032b9e6377 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -151,7 +151,6 @@ !if $(CRYPTO_SERVICES) IN "PACKAGE ALL" gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Md5.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Dh.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Random.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -161,8 +160,10 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tdes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Arc4.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -173,7 +174,7 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.ParallelHash.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Bn.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Ec.Family | 0 + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Ec.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif !if $(CRYPTO_SERVICES) == MIN_PEI @@ -217,6 +218,7 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tls.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsSet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsGet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE diff --git a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h index f1f5084e70..74eaf44cca 100644 --- a/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h +++ b/CryptoPkg/Include/Pcd/PcdCryptoServiceFamilyEnable.h @@ -1,6 +1,26 @@ /** @file Defines the PCD_CRYPTO_SERVICE_FAMILY_ENABLE structure associated with - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable. + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable that is used + to enable/disable crypto services at either the family scope or the + individual service scope. Platforms can minimize the number of enabled + services to reduce size. + + The following services have been deprecated and must never be enabled. + The associated fields in this data structure are never removed or replaced + to preseve the binary layout of the data structure. New services are + always added to the end of the data structure. + * HmacMd5 family + * HmacSha1 family + * Md4 family + * Md5 family + * Tdes family + * Arc4 family + * Aes.Services.EcbEncrypt service + * Aes.Services.EcbDecrypt service + + Is is recommended that the following services always be disabled and may + be deprecated in the future. + * Sha1 family Copyright (c) 2019 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -25,25 +45,25 @@ typedef struct { union { struct { - UINT8 New : 1; - UINT8 Free : 1; - UINT8 SetKey : 1; - UINT8 Duplicate : 1; - UINT8 Update : 1; - UINT8 Final : 1; + UINT8 New : 1; // Deprecated + UINT8 Free : 1; // Deprecated + UINT8 SetKey : 1; // Deprecated + UINT8 Duplicate : 1; // Deprecated + UINT8 Update : 1; // Deprecated + UINT8 Final : 1; // Deprecated } Services; - UINT32 Family; + UINT32 Family; // Deprecated } HmacMd5; union { struct { - UINT8 New : 1; - UINT8 Free : 1; - UINT8 SetKey : 1; - UINT8 Duplicate : 1; - UINT8 Update : 1; - UINT8 Final : 1; + UINT8 New : 1; // Deprecated + UINT8 Free : 1; // Deprecated + UINT8 SetKey : 1; // Deprecated + UINT8 Duplicate : 1; // Deprecated + UINT8 Update : 1; // Deprecated + UINT8 Final : 1; // Deprecated } Services; - UINT32 Family; + UINT32 Family; // Deprecated } HmacSha1; union { struct { @@ -71,26 +91,26 @@ typedef struct { } HmacSha384; union { struct { - UINT8 GetContextSize : 1; - UINT8 Init : 1; - UINT8 Duplicate : 1; - UINT8 Update : 1; - UINT8 Final : 1; - UINT8 HashAll : 1; + UINT8 GetContextSize : 1; // Deprecated + UINT8 Init : 1; // Deprecated + UINT8 Duplicate : 1; // Deprecated + UINT8 Update : 1; // Deprecated + UINT8 Final : 1; // Deprecated + UINT8 HashAll : 1; // Deprecated } Services; - UINT32 Family; + UINT32 Family; // Deprecated } Md4; union { struct { - UINT8 GetContextSize : 1; - UINT8 Init : 1; - UINT8 Duplicate : 1; - UINT8 Update : 1; - UINT8 Final : 1; - UINT8 HashAll : 1; + UINT8 GetContextSize : 1; // Deprecated + UINT8 Init : 1; // Deprecated + UINT8 Duplicate : 1; // Deprecated + UINT8 Update : 1; // Deprecated + UINT8 Final : 1; // Deprecated + UINT8 HashAll : 1; // Deprecated } Services; UINT32 Family; - } Md5; + } Md5; // Deprecated union { struct { UINT8 Pkcs1v2Encrypt : 1; @@ -143,14 +163,14 @@ typedef struct { } Rsa; union { struct { - UINT8 GetContextSize : 1; - UINT8 Init : 1; - UINT8 Duplicate : 1; - UINT8 Update : 1; - UINT8 Final : 1; - UINT8 HashAll : 1; + UINT8 GetContextSize : 1; // Recommend disable + UINT8 Init : 1; // Recommend disable + UINT8 Duplicate : 1; // Recommend disable + UINT8 Update : 1; // Recommend disable + UINT8 Final : 1; // Recommend disable + UINT8 HashAll : 1; // Recommend disable } Services; - UINT32 Family; + UINT32 Family; // Recommend disable } Sha1; union { struct { @@ -216,21 +236,21 @@ typedef struct { } X509; union { struct { - UINT8 GetContextSize : 1; - UINT8 Init : 1; - UINT8 EcbEncrypt : 1; - UINT8 EcbDecrypt : 1; - UINT8 CbcEncrypt : 1; - UINT8 CbcDecrypt : 1; + UINT8 GetContextSize : 1; // Deprecated + UINT8 Init : 1; // Deprecated + UINT8 EcbEncrypt : 1; // Deprecated + UINT8 EcbDecrypt : 1; // Deprecated + UINT8 CbcEncrypt : 1; // Deprecated + UINT8 CbcDecrypt : 1; // Deprecated } Services; - UINT32 Family; + UINT32 Family; // Deprecated } Tdes; union { struct { UINT8 GetContextSize : 1; UINT8 Init : 1; - UINT8 EcbEncrypt : 1; - UINT8 EcbDecrypt : 1; + UINT8 EcbEncrypt : 1; // Deprecated + UINT8 EcbDecrypt : 1; // Deprecated UINT8 CbcEncrypt : 1; UINT8 CbcDecrypt : 1; } Services; @@ -238,13 +258,13 @@ typedef struct { } Aes; union { struct { - UINT8 GetContextSize : 1; - UINT8 Init : 1; - UINT8 Encrypt : 1; - UINT8 Decrypt : 1; - UINT8 Reset : 1; + UINT8 GetContextSize : 1; // Deprecated + UINT8 Init : 1; // Deprecated + UINT8 Encrypt : 1; // Deprecated + UINT8 Decrypt : 1; // Deprecated + UINT8 Reset : 1; // Deprecated } Services; - UINT32 Family; + UINT32 Family; // Deprecated } Arc4; union { struct { From a0035a72815251a1009dfc94e13eb02ac1431fcf Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 4 Oct 2022 16:34:25 -0700 Subject: [PATCH 0192/1529] CryptoPkg/Library/BaseCryptLib: Add missing UNI file and fix format Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/BaseCryptLib.uni | 2 -- CryptoPkg/Library/BaseCryptLib/PeiCryptLib.uni | 2 -- .../Library/BaseCryptLib/RuntimeCryptLib.uni | 2 -- CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf | 1 + CryptoPkg/Library/BaseCryptLib/SecCryptLib.uni | 17 +++++++++++++++++ CryptoPkg/Library/BaseCryptLib/SmmCryptLib.uni | 2 -- 6 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 CryptoPkg/Library/BaseCryptLib/SecCryptLib.uni diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.uni b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.uni index ed1852efbe..d9d53d099c 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.uni +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.uni @@ -12,8 +12,6 @@ // // **/ - #string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library Instance for DXE_DRIVER" #string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow." - diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.uni b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.uni index 20ae64e8bf..8cffc00daf 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.uni +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.uni @@ -18,8 +18,6 @@ // // **/ - #string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library Instance for PEIM" #string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow. Note: AES functions, RSA external functions, PKCS#7 SignedData sign functions, Diffie-Hellman functions, X.509 certificate handler functions, authenticode signature verification functions, PEM handler functions, and pseudorandom number generator functions are not supported in this instance." - diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.uni b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.uni index 0cf378c5ab..786738a99d 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.uni +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.uni @@ -17,8 +17,6 @@ // // **/ - #string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library Instance for DXE_RUNTIME_DRIVER" #string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow. Note: AES functions, RSA external functions, PKCS#7 SignedData sign functions, Diffie-Hellman functions, and authenticode signature verification functions are not supported in this instance." - diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf index 0b1dd31c41..4f652be46a 100644 --- a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf @@ -14,6 +14,7 @@ [Defines] INF_VERSION = 0x00010005 BASE_NAME = SecCryptLib + MODULE_UNI_FILE = SecCryptLib.uni FILE_GUID = 3689D343-0D32-4284-8053-BF10537990E8 MODULE_TYPE = BASE VERSION_STRING = 1.0 diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.uni b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.uni new file mode 100644 index 0000000000..c0dd1eb0f3 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.uni @@ -0,0 +1,17 @@ +// /** @file +// Cryptographic Library Instance for SEC driver. +// +// Caution: This module requires additional review when modified. +// This library will have external input - signature. +// This external input must be validated carefully to avoid security issues such as +// buffer overflow or integer overflow. +// +// Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library Instance for SEC driver" + +#string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow. Note: AES functions, RSA external functions, PKCS#7 SignedData sign functions, Diffie-Hellman functions, and authenticode signature verification functions are not supported in this instance." diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.uni b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.uni index f0c33abbcf..7e0f55f792 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.uni +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.uni @@ -17,8 +17,6 @@ // // **/ - #string STR_MODULE_ABSTRACT #language en-US "Cryptographic Library Instance for SMM driver" #string STR_MODULE_DESCRIPTION #language en-US "Caution: This module requires additional review when modified. This library will have external input - signature. This external input must be validated carefully to avoid security issues such as buffer overflow or integer overflow. Note: AES functions, RSA external functions, PKCS#7 SignedData sign functions, Diffie-Hellman functions, and authenticode signature verification functions are not supported in this instance." - From 92be47255586a6ed67adc6792605e3d56526a6dc Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 3 Oct 2022 20:45:20 -0700 Subject: [PATCH 0193/1529] CryptoPkg/Library/BaseCryptLib: Update internal functions/variables * Update BaseCryptLib internal worker functions to be 'STATIC' * Update BaseCryptLib internal working functions to not use EFIAPI * Add GLOBAL_REMOVE_IF_UNREFERENCED to BaseCryptLib global variables Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.ci.yaml | 3 +- .../Library/BaseCryptLib/Hmac/CryptHmac.c | 7 +++ .../Library/BaseCryptLib/Kdf/CryptHkdf.c | 5 ++- .../BaseCryptLib/Pk/CryptAuthenticode.c | 2 +- .../BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c | 3 +- .../BaseCryptLib/Pk/CryptPkcs7VerifyEku.c | 3 ++ CryptoPkg/Library/BaseCryptLib/Pk/CryptTs.c | 44 +++++++++++++------ 7 files changed, 50 insertions(+), 17 deletions(-) diff --git a/CryptoPkg/CryptoPkg.ci.yaml b/CryptoPkg/CryptoPkg.ci.yaml index 2fa3a3d5ee..ca129d6ae5 100644 --- a/CryptoPkg/CryptoPkg.ci.yaml +++ b/CryptoPkg/CryptoPkg.ci.yaml @@ -24,7 +24,8 @@ "ExceptionList": [ "8001", "IsLeap", "8001", "OBJ_get0_data", - "8001", "OBJ_length" + "8001", "OBJ_length", + "5005", "X509PopCertificate" ], ## Both file path and directory path are accepted. "IgnoreFiles": [ diff --git a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c index 2786267a0b..1ae33b6709 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c +++ b/CryptoPkg/Library/BaseCryptLib/Hmac/CryptHmac.c @@ -16,6 +16,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent If the allocations fails, HmacMdNew() returns NULL. **/ +STATIC VOID * HmacMdNew ( VOID @@ -33,6 +34,7 @@ HmacMdNew ( @param[in] HmacMdCtx Pointer to the HMAC_CTX context to be released. **/ +STATIC VOID HmacMdFree ( IN VOID *HmacMdCtx @@ -59,6 +61,7 @@ HmacMdFree ( @retval FALSE The Key is set unsuccessfully. **/ +STATIC BOOLEAN HmacMdSetKey ( IN CONST EVP_MD *Md, @@ -94,6 +97,7 @@ HmacMdSetKey ( @retval FALSE HMAC-MD context copy failed. **/ +STATIC BOOLEAN HmacMdDuplicate ( IN CONST VOID *HmacMdContext, @@ -132,6 +136,7 @@ HmacMdDuplicate ( @retval FALSE HMAC-MD data digest failed. **/ +STATIC BOOLEAN HmacMdUpdate ( IN OUT VOID *HmacMdContext, @@ -183,6 +188,7 @@ HmacMdUpdate ( @retval FALSE HMAC-MD digest computation failed. **/ +STATIC BOOLEAN HmacMdFinal ( IN OUT VOID *HmacMdContext, @@ -233,6 +239,7 @@ HmacMdFinal ( @retval FALSE This interface is not supported. **/ +STATIC BOOLEAN HmacMdAll ( IN CONST EVP_MD *Md, diff --git a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c index ffaf5fb131..34e81246ed 100644 --- a/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c +++ b/CryptoPkg/Library/BaseCryptLib/Kdf/CryptHkdf.c @@ -6,7 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include +#include "InternalCryptLib.h" #include #include @@ -27,6 +27,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @retval FALSE Hkdf generation failed. **/ +STATIC BOOLEAN HkdfMdExtractAndExpand ( IN CONST EVP_MD *Md, @@ -95,6 +96,7 @@ HkdfMdExtractAndExpand ( @retval false Hkdf generation failed. **/ +STATIC BOOLEAN HkdfMdExtract ( IN CONST EVP_MD *Md, @@ -174,6 +176,7 @@ HkdfMdExtract ( @retval FALSE Hkdf generation failed. **/ +STATIC BOOLEAN HkdfMdExpand ( IN CONST EVP_MD *Md, diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptAuthenticode.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptAuthenticode.c index aa4a33364d..6b0dddd4af 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptAuthenticode.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptAuthenticode.c @@ -23,7 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // OID ASN.1 Value for SPC_INDIRECT_DATA_OBJID // -UINT8 mSpcIndirectOidValue[] = { +GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 mSpcIndirectOidValue[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x04 }; diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c index f8028181e4..4e5a14e352 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c @@ -22,7 +22,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -UINT8 mOidValue[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02 }; +GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 mOidValue[9] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02 }; /** Check input P7Data is a wrapped ContentInfo structure or not. If not construct @@ -145,6 +145,7 @@ WrapPkcs7Data ( @retval FALSE The pop operation failed. **/ +STATIC BOOLEAN X509PopCertificate ( IN VOID *X509Stack, diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyEku.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyEku.c index 833b29ae97..63cd49434e 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyEku.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyEku.c @@ -62,6 +62,7 @@ @retval EFI_NOT_FOUND The number of signers found was not 1. **/ +STATIC EFI_STATUS GetSignerCertificate ( IN CONST PKCS7 *CertChain, @@ -132,6 +133,7 @@ GetSignerCertificate ( @retval EFI_NOT_FOUND One or more EKU's were not found in the signature. **/ +STATIC EFI_STATUS IsEkuInCertificate ( IN CONST X509 *Cert, @@ -255,6 +257,7 @@ IsEkuInCertificate ( @retval EFI_INVALID_PARAMETER A parameter was invalid. @retval EFI_NOT_FOUND One or more EKU's were not found in the signature. **/ +STATIC EFI_STATUS CheckEKUs ( IN CONST X509 *SignerCert, diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptTs.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptTs.c index f118f2e9d6..027dbb6842 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptTs.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptTs.c @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // OID ASN.1 Value for SPC_RFC3161_OBJID ("1.3.6.1.4.1.311.3.3.1") // -UINT8 mSpcRFC3161OidValue[] = { +GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 mSpcRFC3161OidValue[] = { 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x03, 0x03, 0x01 }; @@ -43,11 +43,17 @@ typedef struct { // // ASN.1 Functions for TS_MESSAGE_IMPRINT // -DECLARE_ASN1_FUNCTIONS (TS_MESSAGE_IMPRINT) -ASN1_SEQUENCE (TS_MESSAGE_IMPRINT) = { +GLOBAL_REMOVE_IF_UNREFERENCED +DECLARE_ASN1_FUNCTIONS ( + TS_MESSAGE_IMPRINT + ) +ASN1_SEQUENCE (TS_MESSAGE_IMPRINT) = +{ ASN1_SIMPLE (TS_MESSAGE_IMPRINT, HashAlgorithm, X509_ALGOR), ASN1_SIMPLE (TS_MESSAGE_IMPRINT, HashedMessage, ASN1_OCTET_STRING) -} ASN1_SEQUENCE_END (TS_MESSAGE_IMPRINT) +} + +ASN1_SEQUENCE_END (TS_MESSAGE_IMPRINT) IMPLEMENT_ASN1_FUNCTIONS (TS_MESSAGE_IMPRINT) /// @@ -68,12 +74,18 @@ typedef struct { // // ASN.1 Functions for TS_ACCURACY // -DECLARE_ASN1_FUNCTIONS (TS_ACCURACY) -ASN1_SEQUENCE (TS_ACCURACY) = { +GLOBAL_REMOVE_IF_UNREFERENCED +DECLARE_ASN1_FUNCTIONS ( + TS_ACCURACY + ) +ASN1_SEQUENCE (TS_ACCURACY) = +{ ASN1_OPT (TS_ACCURACY, Seconds, ASN1_INTEGER), ASN1_IMP_OPT (TS_ACCURACY, Millis, ASN1_INTEGER, 0), ASN1_IMP_OPT (TS_ACCURACY, Micros, ASN1_INTEGER, 1) -} ASN1_SEQUENCE_END (TS_ACCURACY) +} + +ASN1_SEQUENCE_END (TS_ACCURACY) IMPLEMENT_ASN1_FUNCTIONS (TS_ACCURACY) /// @@ -114,8 +126,12 @@ typedef struct { // // ASN.1 Functions for TS_TST_INFO // -DECLARE_ASN1_FUNCTIONS (TS_TST_INFO) -ASN1_SEQUENCE (TS_TST_INFO) = { +GLOBAL_REMOVE_IF_UNREFERENCED +DECLARE_ASN1_FUNCTIONS ( + TS_TST_INFO + ) +ASN1_SEQUENCE (TS_TST_INFO) = +{ ASN1_SIMPLE (TS_TST_INFO, Version, ASN1_INTEGER), ASN1_SIMPLE (TS_TST_INFO, Policy, ASN1_OBJECT), ASN1_SIMPLE (TS_TST_INFO, MessageImprint, TS_MESSAGE_IMPRINT), @@ -126,7 +142,9 @@ ASN1_SEQUENCE (TS_TST_INFO) = { ASN1_OPT (TS_TST_INFO, Nonce, ASN1_INTEGER), ASN1_EXP_OPT (TS_TST_INFO, Tsa, GENERAL_NAME, 0), ASN1_IMP_SEQUENCE_OF_OPT (TS_TST_INFO, Extensions, X509_EXTENSION, 1) -} ASN1_SEQUENCE_END (TS_TST_INFO) +} + +ASN1_SEQUENCE_END (TS_TST_INFO) IMPLEMENT_ASN1_FUNCTIONS (TS_TST_INFO) /** @@ -139,8 +157,8 @@ IMPLEMENT_ASN1_FUNCTIONS (TS_TST_INFO) @retval FALSE Invalid parameters. **/ +STATIC BOOLEAN -EFIAPI ConvertAsn1TimeToEfiTime ( IN ASN1_TIME *Asn1Time, OUT EFI_TIME *EfiTime @@ -222,8 +240,8 @@ ConvertAsn1TimeToEfiTime ( @retval FALSE Invalid TimeStamp Token Information. **/ +STATIC BOOLEAN -EFIAPI CheckTSTInfo ( IN CONST TS_TST_INFO *TstInfo, IN CONST UINT8 *TimestampedData, @@ -352,8 +370,8 @@ CheckTSTInfo ( @retval FALSE Invalid timestamp token. **/ +STATIC BOOLEAN -EFIAPI TimestampTokenVerify ( IN CONST UINT8 *TSToken, IN UINTN TokenSize, From b9db4b9f78da45b244cc3685386b4199aca14670 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 30 Sep 2022 13:59:30 -0700 Subject: [PATCH 0194/1529] CryptoPkg/Test/UnitTest/Library/BaseCryptLib: Unit test fixes * Update ImageTimeStampTest to return UNIT_TEST_PASSED instead of Status. On success Status is TRUE(1), which was returning a unit test status of UNIT_TEST_ERROR_PREREQUISITE_NOT_MET. * Update HmacTests to use the *Free() service from the HMAC family instead of FreePool(). Using FreePool() generates ASSERT() because the context being freed was not allocated using AllocatePool(). Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- .../UnitTest/Library/BaseCryptLib/HmacTests.c | 17 ++++++++++++----- .../UnitTest/Library/BaseCryptLib/TSTests.c | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c index 9c5b39410d..b347cb4cb4 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/HmacTests.c @@ -87,6 +87,12 @@ VOID * VOID ); +typedef +VOID +(EFIAPI *EFI_HMAC_FREE)( + IN VOID *HashContext + ); + typedef BOOLEAN (EFIAPI *EFI_HMAC_INIT)( @@ -113,6 +119,7 @@ BOOLEAN typedef struct { UINT32 DigestSize; EFI_HMAC_NEW HmacNew; + EFI_HMAC_FREE HmacFree; EFI_HMAC_INIT HmacInit; EFI_HMAC_UPDATE HmacUpdate; EFI_HMAC_FINAL HmacFinal; @@ -123,10 +130,10 @@ typedef struct { } HMAC_TEST_CONTEXT; // These functions have been deprecated but they've been left commented out for future reference -// HMAC_TEST_CONTEXT mHmacMd5TestCtx = {MD5_DIGEST_SIZE, HmacMd5New, HmacMd5SetKey, HmacMd5Update, HmacMd5Final, HmacMd5Key, sizeof(HmacMd5Key), HmacMd5Digest}; -// HMAC_TEST_CONTEXT mHmacSha1TestCtx = {SHA1_DIGEST_SIZE, HmacSha1New, HmacSha1SetKey, HmacSha1Update, HmacSha1Final, HmacSha1Key, sizeof(HmacSha1Key), HmacSha1Digest}; -HMAC_TEST_CONTEXT mHmacSha256TestCtx = { SHA256_DIGEST_SIZE, HmacSha256New, HmacSha256SetKey, HmacSha256Update, HmacSha256Final, HmacSha256Key, sizeof (HmacSha256Key), HmacSha256Digest }; -HMAC_TEST_CONTEXT mHmacSha384TestCtx = { SHA384_DIGEST_SIZE, HmacSha384New, HmacSha384SetKey, HmacSha384Update, HmacSha384Final, HmacSha384Key, sizeof (HmacSha384Key), HmacSha384Digest }; +// HMAC_TEST_CONTEXT mHmacMd5TestCtx = {MD5_DIGEST_SIZE, HmacMd5New, HmacMd5Free, HmacMd5SetKey, HmacMd5Update, HmacMd5Final, HmacMd5Key, sizeof(HmacMd5Key), HmacMd5Digest}; +// HMAC_TEST_CONTEXT mHmacSha1TestCtx = {SHA1_DIGEST_SIZE, HmacSha1New, HmacSha1Free, HmacSha1SetKey, HmacSha1Update, HmacSha1Final, HmacSha1Key, sizeof(HmacSha1Key), HmacSha1Digest}; +HMAC_TEST_CONTEXT mHmacSha256TestCtx = { SHA256_DIGEST_SIZE, HmacSha256New, HmacSha256Free, HmacSha256SetKey, HmacSha256Update, HmacSha256Final, HmacSha256Key, sizeof (HmacSha256Key), HmacSha256Digest }; +HMAC_TEST_CONTEXT mHmacSha384TestCtx = { SHA384_DIGEST_SIZE, HmacSha384New, HmacSha384Free, HmacSha384SetKey, HmacSha384Update, HmacSha384Final, HmacSha384Key, sizeof (HmacSha384Key), HmacSha384Digest }; UNIT_TEST_STATUS EFIAPI @@ -155,7 +162,7 @@ TestVerifyHmacCleanUp ( HmacTestContext = Context; if (HmacTestContext->HmacCtx != NULL) { - FreePool (HmacTestContext->HmacCtx); + HmacTestContext->HmacFree (HmacTestContext->HmacCtx); } } diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TSTests.c b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TSTests.c index 225ec3e597..226e57e66f 100644 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TSTests.c +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TSTests.c @@ -322,7 +322,7 @@ TestVerifyImageTimestampVerify ( UT_ASSERT_EQUAL (SigningTime.Minute, 50); UT_ASSERT_EQUAL (SigningTime.Second, 3); - return Status; + return UNIT_TEST_PASSED; } TEST_DESC mImageTimestampTest[] = { From 0391bf33204a23ef3fa5c5c6963f03bc09577e60 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 3 Oct 2022 14:38:13 -0700 Subject: [PATCH 0195/1529] CryptoPkg/Library: Cleanup BaseCryptLib and TlsLib * Move SysCall/inet_pton.c from BaseCryptLib to TlsLib. The functions in this file are only used by TlsLib instances and not any CryptLib instances. * Fix type mismatch in call to FreePool() in TlsConfig.c * Remove use of gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled from TslLib and CryptLib instances * Add missing *Null.c files to SecCryptLib.inf and RuntimeCryptLib.inf. * Remove ARM and AARCH64 sections from SmmCryptLib.inf that does not support those architectures. * Add missing PrintLib dependencies to [LibraryClasses] sections of CryptLib INF files * Remove extra library classes from [LibraryClasses] sections of CryptLib INF files * Remove unnecessary warning disables from [BuildOptions] sections of TlsLib and CryptLib INF files * Remove RVCT support from SecCryptLib.inf Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Cc: Rebecca Cran Cc: Ard Biesheuvel Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf | 10 +--------- CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf | 8 +------- CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c | 4 ---- CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c | 4 ---- CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf | 9 ++------- CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf | 12 ++++-------- CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf | 12 ------------ .../{BaseCryptLib => TlsLib}/SysCall/inet_pton.c | 0 CryptoPkg/Library/TlsLib/TlsConfig.c | 12 ++++-------- CryptoPkg/Library/TlsLib/TlsLib.inf | 12 +----------- 10 files changed, 13 insertions(+), 70 deletions(-) rename CryptoPkg/Library/{BaseCryptLib => TlsLib}/SysCall/inet_pton.c (100%) diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 8896e47095..213813cad9 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -54,15 +54,13 @@ Pk/CryptTs.c Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c - Pk/CryptEcNull.c |*|*|*|!gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - Pk/CryptEc.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + Pk/CryptEc.c Pem/CryptPem.c Bn/CryptBn.c SysCall/CrtWrapper.c SysCall/TimerWrapper.c SysCall/BaseMemAllocation.c - SysCall/inet_pton.c [Sources.Ia32] Rand/CryptRandTsc.c @@ -96,19 +94,13 @@ IntrinsicLib PrintLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - # # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers # - MSFT:*_*_*_CC_FLAGS = /wd4090 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 3799780c9f..b1629647f9 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -79,9 +79,7 @@ DebugLib OpensslLib IntrinsicLib - -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + PrintLib # # Remove these [BuildOptions] after this library is cleaned up @@ -89,11 +87,7 @@ [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers - # C4718: 'function call' : recursive call has no side effects, deleting # - MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4718 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c index 559a6b4df0..d64cf3d680 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c +++ b/CryptoPkg/Library/BaseCryptLib/Pem/CryptPem.c @@ -153,7 +153,6 @@ EcGetPrivateKeyFromPem ( OUT VOID **EcContext ) { - #if FixedPcdGetBool (PcdOpensslEcEnabled) BOOLEAN Status; BIO *PemBio; @@ -209,7 +208,4 @@ EcGetPrivateKeyFromPem ( BIO_free (PemBio); return Status; - #else - return FALSE; - #endif } diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index 1d91ac3b0f..2333157e0d 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -881,7 +881,6 @@ EcGetPublicKeyFromX509 ( OUT VOID **EcContext ) { - #if FixedPcdGetBool (PcdOpensslEcEnabled) BOOLEAN Status; EVP_PKEY *Pkey; X509 *X509Cert; @@ -935,9 +934,6 @@ EcGetPublicKeyFromX509 ( } return Status; - #else - return FALSE; - #endif } /** diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index bb66604e32..07dbc0e7a8 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -60,7 +60,9 @@ Pk/CryptTsNull.c Pk/CryptRsaPssNull.c Pk/CryptRsaPssSignNull.c + Pk/CryptEcNull.c Pem/CryptPem.c + Bn/CryptBnNull.c SysCall/CrtWrapper.c SysCall/TimerWrapper.c @@ -91,26 +93,19 @@ [LibraryClasses] BaseLib BaseMemoryLib - UefiBootServicesTableLib UefiRuntimeServicesTableLib DebugLib OpensslLib IntrinsicLib PrintLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - # # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers # - MSFT:*_*_*_CC_FLAGS = /wd4090 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf index 4f652be46a..4ad59b7bbc 100644 --- a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf @@ -38,6 +38,7 @@ Hmac/CryptHmacNull.c Kdf/CryptHkdfNull.c Cipher/CryptAesNull.c + Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasicNull.c Pk/CryptRsaExtNull.c Pk/CryptPkcs1OaepNull.c @@ -53,6 +54,8 @@ Rand/CryptRandNull.c Pk/CryptRsaPssNull.c Pk/CryptRsaPssSignNull.c + Pk/CryptEcNull.c + Bn/CryptBnNull.c SysCall/CrtWrapper.c SysCall/ConstantTimeClock.c @@ -69,6 +72,7 @@ DebugLib OpensslLib IntrinsicLib + PrintLib # # Remove these [BuildOptions] after this library is cleaned up @@ -76,15 +80,7 @@ [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers - # C4718: 'function call' : recursive call has no side effects, deleting # - MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4718 - - # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT - # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline" - RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1 - GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 9318052a51..0af7a3f96e 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -74,19 +74,12 @@ [Sources.X64] Rand/CryptRandTsc.c -[Sources.ARM] - Rand/CryptRand.c - -[Sources.AARCH64] - Rand/CryptRand.c - [Packages] MdePkg/MdePkg.dec CryptoPkg/CryptoPkg.dec [LibraryClasses] BaseLib - IoLib BaseMemoryLib MemoryAllocationLib OpensslLib @@ -95,18 +88,13 @@ MmServicesTableLib SynchronizationLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - # # Remove these [BuildOptions] after this library is cleaned up # [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers # - MSFT:*_*_*_CC_FLAGS = /wd4090 XCODE:*_*_*_CC_FLAGS = -mmmx -msse -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c b/CryptoPkg/Library/TlsLib/SysCall/inet_pton.c similarity index 100% rename from CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c rename to CryptoPkg/Library/TlsLib/SysCall/inet_pton.c diff --git a/CryptoPkg/Library/TlsLib/TlsConfig.c b/CryptoPkg/Library/TlsLib/TlsConfig.c index dbe1f06529..60559de4a7 100644 --- a/CryptoPkg/Library/TlsLib/TlsConfig.c +++ b/CryptoPkg/Library/TlsLib/TlsConfig.c @@ -478,7 +478,7 @@ TlsSetCipherList ( FreePool (CipherString); FreeMappedCipher: - FreePool (MappedCipher); + FreePool ((VOID *)MappedCipher); return Status; } @@ -1136,9 +1136,6 @@ TlsSetEcCurve ( IN UINTN DataSize ) { - #if !FixedPcdGetBool (PcdOpensslEcEnabled) - return EFI_UNSUPPORTED; - #else TLS_CONNECTION *TlsConn; EC_KEY *EcKey; INT32 Nid; @@ -1170,23 +1167,22 @@ TlsSetEcCurve ( } if (SSL_set1_curves (TlsConn->Ssl, &Nid, 1) != 1) { - return EFI_INVALID_PARAMETER; + return EFI_UNSUPPORTED; } EcKey = EC_KEY_new_by_curve_name (Nid); if (EcKey == NULL) { - return EFI_INVALID_PARAMETER; + return EFI_UNSUPPORTED; } Ret = SSL_set_tmp_ecdh (TlsConn->Ssl, EcKey); EC_KEY_free (EcKey); if (Ret != 1) { - return EFI_INVALID_PARAMETER; + return EFI_UNSUPPORTED; } return EFI_SUCCESS; - #endif } /** diff --git a/CryptoPkg/Library/TlsLib/TlsLib.inf b/CryptoPkg/Library/TlsLib/TlsLib.inf index 20b0ea6832..4e7b3e535a 100644 --- a/CryptoPkg/Library/TlsLib/TlsLib.inf +++ b/CryptoPkg/Library/TlsLib/TlsLib.inf @@ -28,6 +28,7 @@ TlsInit.c TlsConfig.c TlsProcess.c + SysCall/inet_pton.c [Packages] MdePkg/MdePkg.dec @@ -41,14 +42,3 @@ MemoryAllocationLib OpensslLib SafeIntLib - -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - -[BuildOptions] - # - # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers - # - MSFT:*_*_*_CC_FLAGS = /wd4090 - From e7faf0544071b94c8087896eba19aae37d7e2346 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 24 Sep 2022 13:40:26 -0700 Subject: [PATCH 0196/1529] CryptoPkg/Library/OpensslLib: Combine all performance optimized INFs * Remove IA32/X64 specific INF files for performance optimized OpensslLib and combine into OpensslLibAccel.inf and OpensslLibFullAccel.inf. * Remove use of PcdOpensslEcEnabled and let the platform select the EC feature by using either OpensslLibFull.inf or OpensslLibFullAccel.inf. * With PcdOpensslEcEnabled removed, roll back style of opensslconf.h and remove opensslconf_generated.h. Move the choice to disable EC/SM2 into OpensslLib INF files using OPENSSL_FLAGS define. * Update OpensslLibContructor() API to be compatible with all FW phases by using types from Base.h and using RETURN_STATUS type and values instead of EFI_STATUS type and values. * Add /wd4718 to VS2015x86 for IA32 and X64 to disable warning for recursive call with no side effects. This is a false positive warning that is not produced with VS2017 or VS2019. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.ci.yaml | 8 +- .../Library/Include/openssl/opensslconf.h | 328 +++++++- .../Include/openssl/opensslconf_generated.h | 333 --------- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 138 ++-- CryptoPkg/Library/OpensslLib/OpensslLib.uni | 10 +- ...{OpensslLibX64.inf => OpensslLibAccel.inf} | 199 +++-- .../Library/OpensslLib/OpensslLibAccel.uni | 14 + .../OpensslLib/OpensslLibConstructor.c | 6 +- .../Library/OpensslLib/OpensslLibCrypto.inf | 190 +++-- .../Library/OpensslLib/OpensslLibCrypto.uni | 11 +- ...{OpensslLibIa32.inf => OpensslLibFull.inf} | 169 +++-- .../Library/OpensslLib/OpensslLibFull.uni | 12 + ...lLibX64Gcc.inf => OpensslLibFullAccel.inf} | 202 +++-- .../OpensslLib/OpensslLibFullAccel.uni | 14 + .../Library/OpensslLib/OpensslLibIa32Gcc.inf | 699 ------------------ 15 files changed, 913 insertions(+), 1420 deletions(-) delete mode 100644 CryptoPkg/Library/Include/openssl/opensslconf_generated.h rename CryptoPkg/Library/OpensslLib/{OpensslLibX64.inf => OpensslLibAccel.inf} (78%) create mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibAccel.uni rename CryptoPkg/Library/OpensslLib/{OpensslLibIa32.inf => OpensslLibFull.inf} (79%) create mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibFull.uni rename CryptoPkg/Library/OpensslLib/{OpensslLibX64Gcc.inf => OpensslLibFullAccel.inf} (78%) create mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.uni delete mode 100644 CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf diff --git a/CryptoPkg/CryptoPkg.ci.yaml b/CryptoPkg/CryptoPkg.ci.yaml index ca129d6ae5..47f2975967 100644 --- a/CryptoPkg/CryptoPkg.ci.yaml +++ b/CryptoPkg/CryptoPkg.ci.yaml @@ -73,13 +73,7 @@ }, "DscCompleteCheck": { "DscPath": "CryptoPkg.dsc", - "IgnoreInf": [ - # These are alternatives to OpensslLib.inf - "CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf", - "CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf", - "CryptoPkg/Library/OpensslLib/OpensslLibX64.inf", - "CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf" - ] + "IgnoreInf": [] }, "GuidCheck": { "IgnoreGuidName": [], diff --git a/CryptoPkg/Library/Include/openssl/opensslconf.h b/CryptoPkg/Library/Include/openssl/opensslconf.h index 53dd8c3efb..b98b068b3d 100644 --- a/CryptoPkg/Library/Include/openssl/opensslconf.h +++ b/CryptoPkg/Library/Include/openssl/opensslconf.h @@ -9,32 +9,324 @@ * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ -#include -#include + +#include #ifdef __cplusplus extern "C" { #endif -/* Autogenerated conditional openssl feature list starts here */ -#if !FixedPcdGetBool (PcdOpensslEcEnabled) -# ifndef OPENSSL_NO_EC -# define OPENSSL_NO_EC -# endif -# ifndef OPENSSL_NO_ECDH -# define OPENSSL_NO_ECDH -# endif -# ifndef OPENSSL_NO_ECDSA -# define OPENSSL_NO_ECDSA -# endif -# ifndef OPENSSL_NO_TLS1_3 -# define OPENSSL_NO_TLS1_3 +#ifdef OPENSSL_ALGORITHM_DEFINES +# error OPENSSL_ALGORITHM_DEFINES no longer supported +#endif + +/* + * OpenSSL was configured with the following options: + */ + +#ifndef OPENSSL_SYS_UEFI +# define OPENSSL_SYS_UEFI 1 +#endif +#define OPENSSL_MIN_API 0x10100000L +#ifndef OPENSSL_NO_BF +# define OPENSSL_NO_BF +#endif +#ifndef OPENSSL_NO_BLAKE2 +# define OPENSSL_NO_BLAKE2 +#endif +#ifndef OPENSSL_NO_CAMELLIA +# define OPENSSL_NO_CAMELLIA +#endif +#ifndef OPENSSL_NO_CAST +# define OPENSSL_NO_CAST +#endif +#ifndef OPENSSL_NO_CHACHA +# define OPENSSL_NO_CHACHA +#endif +#ifndef OPENSSL_NO_CMS +# define OPENSSL_NO_CMS +#endif +#ifndef OPENSSL_NO_CT +# define OPENSSL_NO_CT +#endif +#ifndef OPENSSL_NO_DES +# define OPENSSL_NO_DES +#endif +#ifndef OPENSSL_NO_DSA +# define OPENSSL_NO_DSA +#endif +#ifndef OPENSSL_NO_IDEA +# define OPENSSL_NO_IDEA +#endif +#ifndef OPENSSL_NO_MD2 +# define OPENSSL_NO_MD2 +#endif +#ifndef OPENSSL_NO_MD4 +# define OPENSSL_NO_MD4 +#endif +#ifndef OPENSSL_NO_MDC2 +# define OPENSSL_NO_MDC2 +#endif +#ifndef OPENSSL_NO_POLY1305 +# define OPENSSL_NO_POLY1305 +#endif +#ifndef OPENSSL_NO_RC2 +# define OPENSSL_NO_RC2 +#endif +#ifndef OPENSSL_NO_RC4 +# define OPENSSL_NO_RC4 +#endif +#ifndef OPENSSL_NO_RC5 +# define OPENSSL_NO_RC5 +#endif +#ifndef OPENSSL_NO_RMD160 +# define OPENSSL_NO_RMD160 +#endif +#ifndef OPENSSL_NO_SEED +# define OPENSSL_NO_SEED +#endif +#ifndef OPENSSL_NO_SRP +# define OPENSSL_NO_SRP +#endif +#ifndef OPENSSL_NO_TS +# define OPENSSL_NO_TS +#endif +#ifndef OPENSSL_NO_WHIRLPOOL +# define OPENSSL_NO_WHIRLPOOL +#endif +#ifndef OPENSSL_RAND_SEED_NONE +# define OPENSSL_RAND_SEED_NONE +#endif +#ifndef OPENSSL_NO_AFALGENG +# define OPENSSL_NO_AFALGENG +#endif +#ifndef OPENSSL_NO_APPS +# define OPENSSL_NO_APPS +#endif +#ifndef OPENSSL_NO_ASAN +# define OPENSSL_NO_ASAN +#endif +#ifndef OPENSSL_NO_ASYNC +# define OPENSSL_NO_ASYNC +#endif +#ifndef OPENSSL_NO_AUTOERRINIT +# define OPENSSL_NO_AUTOERRINIT +#endif +#ifndef OPENSSL_NO_AUTOLOAD_CONFIG +# define OPENSSL_NO_AUTOLOAD_CONFIG +#endif +#ifndef OPENSSL_NO_CAPIENG +# define OPENSSL_NO_CAPIENG +#endif +#ifndef OPENSSL_NO_CRYPTO_MDEBUG +# define OPENSSL_NO_CRYPTO_MDEBUG +#endif +#ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE +# define OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE +#endif +#ifndef OPENSSL_NO_DEPRECATED +# define OPENSSL_NO_DEPRECATED +#endif +#ifndef OPENSSL_NO_DEVCRYPTOENG +# define OPENSSL_NO_DEVCRYPTOENG +#endif +#ifndef OPENSSL_NO_DGRAM +# define OPENSSL_NO_DGRAM +#endif +#ifndef OPENSSL_NO_DTLS +# define OPENSSL_NO_DTLS +#endif +#ifndef OPENSSL_NO_DTLS1 +# define OPENSSL_NO_DTLS1 +#endif +#ifndef OPENSSL_NO_DTLS1_2 +# define OPENSSL_NO_DTLS1_2 +#endif +#ifndef OPENSSL_NO_EC2M +# define OPENSSL_NO_EC2M +#endif +#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 +# define OPENSSL_NO_EC_NISTP_64_GCC_128 +#endif +#ifndef OPENSSL_NO_EGD +# define OPENSSL_NO_EGD +#endif +#ifndef OPENSSL_NO_ENGINE +# define OPENSSL_NO_ENGINE +#endif +#ifndef OPENSSL_NO_ERR +# define OPENSSL_NO_ERR +#endif +#ifndef OPENSSL_NO_EXTERNAL_TESTS +# define OPENSSL_NO_EXTERNAL_TESTS +#endif +#ifndef OPENSSL_NO_FILENAMES +# define OPENSSL_NO_FILENAMES +#endif +#ifndef OPENSSL_NO_FUZZ_AFL +# define OPENSSL_NO_FUZZ_AFL +#endif +#ifndef OPENSSL_NO_FUZZ_LIBFUZZER +# define OPENSSL_NO_FUZZ_LIBFUZZER +#endif +#ifndef OPENSSL_NO_GOST +# define OPENSSL_NO_GOST +#endif +#ifndef OPENSSL_NO_HEARTBEATS +# define OPENSSL_NO_HEARTBEATS +#endif +#ifndef OPENSSL_NO_HW +# define OPENSSL_NO_HW +#endif +#ifndef OPENSSL_NO_MSAN +# define OPENSSL_NO_MSAN +#endif +#ifndef OPENSSL_NO_OCB +# define OPENSSL_NO_OCB +#endif +#ifndef OPENSSL_NO_POSIX_IO +# define OPENSSL_NO_POSIX_IO +#endif +#ifndef OPENSSL_NO_RFC3779 +# define OPENSSL_NO_RFC3779 +#endif +#ifndef OPENSSL_NO_SCRYPT +# define OPENSSL_NO_SCRYPT +#endif +#ifndef OPENSSL_NO_SCTP +# define OPENSSL_NO_SCTP +#endif +#ifndef OPENSSL_NO_SOCK +# define OPENSSL_NO_SOCK +#endif +#ifndef OPENSSL_NO_SSL_TRACE +# define OPENSSL_NO_SSL_TRACE +#endif +#ifndef OPENSSL_NO_SSL3 +# define OPENSSL_NO_SSL3 +#endif +#ifndef OPENSSL_NO_SSL3_METHOD +# define OPENSSL_NO_SSL3_METHOD +#endif +#ifndef OPENSSL_NO_STDIO +# define OPENSSL_NO_STDIO +#endif +#ifndef OPENSSL_NO_TESTS +# define OPENSSL_NO_TESTS +#endif +#ifndef OPENSSL_NO_UBSAN +# define OPENSSL_NO_UBSAN +#endif +#ifndef OPENSSL_NO_UI_CONSOLE +# define OPENSSL_NO_UI_CONSOLE +#endif +#ifndef OPENSSL_NO_UNIT_TEST +# define OPENSSL_NO_UNIT_TEST +#endif +#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS +# define OPENSSL_NO_WEAK_SSL_CIPHERS +#endif +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +# define OPENSSL_NO_DYNAMIC_ENGINE +#endif + + +/* + * Sometimes OPENSSSL_NO_xxx ends up with an empty file and some compilers + * don't like that. This will hopefully silence them. + */ +#define NON_EMPTY_TRANSLATION_UNIT static void *dummy = &dummy; + +/* + * Applications should use -DOPENSSL_API_COMPAT= to suppress the + * declarations of functions deprecated in or before . Otherwise, they + * still won't see them if the library has been built to disable deprecated + * functions. + */ +#ifndef DECLARE_DEPRECATED +# define DECLARE_DEPRECATED(f) f; +# ifdef __GNUC__ +# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 0) +# undef DECLARE_DEPRECATED +# define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); +# endif +#elif defined(__SUNPRO_C) +#if (__SUNPRO_C >= 0x5130) +#undef DECLARE_DEPRECATED +#define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); +#endif # endif -# ifndef OPENSSL_NO_SM2 -# define OPENSSL_NO_SM2 +#endif + +#ifndef OPENSSL_FILE +# ifdef OPENSSL_NO_FILENAMES +# define OPENSSL_FILE "" +# define OPENSSL_LINE 0 +# else +# define OPENSSL_FILE __FILE__ +# define OPENSSL_LINE __LINE__ # endif #endif -/* Autogenerated conditional openssl feature list ends here */ + +#ifndef OPENSSL_MIN_API +# define OPENSSL_MIN_API 0 +#endif + +#if !defined(OPENSSL_API_COMPAT) || OPENSSL_API_COMPAT < OPENSSL_MIN_API +# undef OPENSSL_API_COMPAT +# define OPENSSL_API_COMPAT OPENSSL_MIN_API +#endif + +/* + * Do not deprecate things to be deprecated in version 1.2.0 before the + * OpenSSL version number matches. + */ +#if OPENSSL_VERSION_NUMBER < 0x10200000L +# define DEPRECATEDIN_1_2_0(f) f; +#elif OPENSSL_API_COMPAT < 0x10200000L +# define DEPRECATEDIN_1_2_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_2_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x10100000L +# define DEPRECATEDIN_1_1_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_1_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x10000000L +# define DEPRECATEDIN_1_0_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_0_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x00908000L +# define DEPRECATEDIN_0_9_8(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_0_9_8(f) +#endif + +/* Generate 80386 code? */ +#undef I386_ONLY + +#undef OPENSSL_UNISTD +#define OPENSSL_UNISTD + +#undef OPENSSL_EXPORT_VAR_AS_FUNCTION + +/* + * The following are cipher-specific, but are part of the public API. + */ +#if !defined(OPENSSL_SYS_UEFI) +# undef BN_LLONG +/* Only one for the following should be defined */ +# undef SIXTY_FOUR_BIT_LONG +# undef SIXTY_FOUR_BIT +# define THIRTY_TWO_BIT +#endif + +#define RC4_INT unsigned int #ifdef __cplusplus } diff --git a/CryptoPkg/Library/Include/openssl/opensslconf_generated.h b/CryptoPkg/Library/Include/openssl/opensslconf_generated.h deleted file mode 100644 index 09a6641ffc..0000000000 --- a/CryptoPkg/Library/Include/openssl/opensslconf_generated.h +++ /dev/null @@ -1,333 +0,0 @@ -/* - * WARNING: do not edit! - * Generated from include/openssl/opensslconf.h.in - * - * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef OPENSSL_ALGORITHM_DEFINES -# error OPENSSL_ALGORITHM_DEFINES no longer supported -#endif - -/* - * OpenSSL was configured with the following options: - */ - -#ifndef OPENSSL_SYS_UEFI -# define OPENSSL_SYS_UEFI 1 -#endif -#define OPENSSL_MIN_API 0x10100000L -#ifndef OPENSSL_NO_BF -# define OPENSSL_NO_BF -#endif -#ifndef OPENSSL_NO_BLAKE2 -# define OPENSSL_NO_BLAKE2 -#endif -#ifndef OPENSSL_NO_CAMELLIA -# define OPENSSL_NO_CAMELLIA -#endif -#ifndef OPENSSL_NO_CAST -# define OPENSSL_NO_CAST -#endif -#ifndef OPENSSL_NO_CHACHA -# define OPENSSL_NO_CHACHA -#endif -#ifndef OPENSSL_NO_CMS -# define OPENSSL_NO_CMS -#endif -#ifndef OPENSSL_NO_CT -# define OPENSSL_NO_CT -#endif -#ifndef OPENSSL_NO_DES -# define OPENSSL_NO_DES -#endif -#ifndef OPENSSL_NO_DSA -# define OPENSSL_NO_DSA -#endif -#ifndef OPENSSL_NO_IDEA -# define OPENSSL_NO_IDEA -#endif -#ifndef OPENSSL_NO_MD2 -# define OPENSSL_NO_MD2 -#endif -#ifndef OPENSSL_NO_MD4 -# define OPENSSL_NO_MD4 -#endif -#ifndef OPENSSL_NO_MDC2 -# define OPENSSL_NO_MDC2 -#endif -#ifndef OPENSSL_NO_POLY1305 -# define OPENSSL_NO_POLY1305 -#endif -#ifndef OPENSSL_NO_RC2 -# define OPENSSL_NO_RC2 -#endif -#ifndef OPENSSL_NO_RC4 -# define OPENSSL_NO_RC4 -#endif -#ifndef OPENSSL_NO_RC5 -# define OPENSSL_NO_RC5 -#endif -#ifndef OPENSSL_NO_RMD160 -# define OPENSSL_NO_RMD160 -#endif -#ifndef OPENSSL_NO_SEED -# define OPENSSL_NO_SEED -#endif -#ifndef OPENSSL_NO_SRP -# define OPENSSL_NO_SRP -#endif -#ifndef OPENSSL_NO_TS -# define OPENSSL_NO_TS -#endif -#ifndef OPENSSL_NO_WHIRLPOOL -# define OPENSSL_NO_WHIRLPOOL -#endif -#ifndef OPENSSL_RAND_SEED_NONE -# define OPENSSL_RAND_SEED_NONE -#endif -#ifndef OPENSSL_NO_AFALGENG -# define OPENSSL_NO_AFALGENG -#endif -#ifndef OPENSSL_NO_APPS -# define OPENSSL_NO_APPS -#endif -#ifndef OPENSSL_NO_ASAN -# define OPENSSL_NO_ASAN -#endif -#ifndef OPENSSL_NO_ASYNC -# define OPENSSL_NO_ASYNC -#endif -#ifndef OPENSSL_NO_AUTOERRINIT -# define OPENSSL_NO_AUTOERRINIT -#endif -#ifndef OPENSSL_NO_AUTOLOAD_CONFIG -# define OPENSSL_NO_AUTOLOAD_CONFIG -#endif -#ifndef OPENSSL_NO_CAPIENG -# define OPENSSL_NO_CAPIENG -#endif -#ifndef OPENSSL_NO_CRYPTO_MDEBUG -# define OPENSSL_NO_CRYPTO_MDEBUG -#endif -#ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE -# define OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE -#endif -#ifndef OPENSSL_NO_DEPRECATED -# define OPENSSL_NO_DEPRECATED -#endif -#ifndef OPENSSL_NO_DEVCRYPTOENG -# define OPENSSL_NO_DEVCRYPTOENG -#endif -#ifndef OPENSSL_NO_DGRAM -# define OPENSSL_NO_DGRAM -#endif -#ifndef OPENSSL_NO_DTLS -# define OPENSSL_NO_DTLS -#endif -#ifndef OPENSSL_NO_DTLS1 -# define OPENSSL_NO_DTLS1 -#endif -#ifndef OPENSSL_NO_DTLS1_2 -# define OPENSSL_NO_DTLS1_2 -#endif -#ifndef OPENSSL_NO_EC2M -# define OPENSSL_NO_EC2M -#endif -#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 -# define OPENSSL_NO_EC_NISTP_64_GCC_128 -#endif -#ifndef OPENSSL_NO_EGD -# define OPENSSL_NO_EGD -#endif -#ifndef OPENSSL_NO_ENGINE -# define OPENSSL_NO_ENGINE -#endif -#ifndef OPENSSL_NO_ERR -# define OPENSSL_NO_ERR -#endif -#ifndef OPENSSL_NO_EXTERNAL_TESTS -# define OPENSSL_NO_EXTERNAL_TESTS -#endif -#ifndef OPENSSL_NO_FILENAMES -# define OPENSSL_NO_FILENAMES -#endif -#ifndef OPENSSL_NO_FUZZ_AFL -# define OPENSSL_NO_FUZZ_AFL -#endif -#ifndef OPENSSL_NO_FUZZ_LIBFUZZER -# define OPENSSL_NO_FUZZ_LIBFUZZER -#endif -#ifndef OPENSSL_NO_GOST -# define OPENSSL_NO_GOST -#endif -#ifndef OPENSSL_NO_HEARTBEATS -# define OPENSSL_NO_HEARTBEATS -#endif -#ifndef OPENSSL_NO_HW -# define OPENSSL_NO_HW -#endif -#ifndef OPENSSL_NO_MSAN -# define OPENSSL_NO_MSAN -#endif -#ifndef OPENSSL_NO_OCB -# define OPENSSL_NO_OCB -#endif -#ifndef OPENSSL_NO_POSIX_IO -# define OPENSSL_NO_POSIX_IO -#endif -#ifndef OPENSSL_NO_RFC3779 -# define OPENSSL_NO_RFC3779 -#endif -#ifndef OPENSSL_NO_SCRYPT -# define OPENSSL_NO_SCRYPT -#endif -#ifndef OPENSSL_NO_SCTP -# define OPENSSL_NO_SCTP -#endif -#ifndef OPENSSL_NO_SOCK -# define OPENSSL_NO_SOCK -#endif -#ifndef OPENSSL_NO_SSL_TRACE -# define OPENSSL_NO_SSL_TRACE -#endif -#ifndef OPENSSL_NO_SSL3 -# define OPENSSL_NO_SSL3 -#endif -#ifndef OPENSSL_NO_SSL3_METHOD -# define OPENSSL_NO_SSL3_METHOD -#endif -#ifndef OPENSSL_NO_STDIO -# define OPENSSL_NO_STDIO -#endif -#ifndef OPENSSL_NO_TESTS -# define OPENSSL_NO_TESTS -#endif -#ifndef OPENSSL_NO_UBSAN -# define OPENSSL_NO_UBSAN -#endif -#ifndef OPENSSL_NO_UI_CONSOLE -# define OPENSSL_NO_UI_CONSOLE -#endif -#ifndef OPENSSL_NO_UNIT_TEST -# define OPENSSL_NO_UNIT_TEST -#endif -#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS -# define OPENSSL_NO_WEAK_SSL_CIPHERS -#endif -#ifndef OPENSSL_NO_DYNAMIC_ENGINE -# define OPENSSL_NO_DYNAMIC_ENGINE -#endif - - -/* - * Sometimes OPENSSSL_NO_xxx ends up with an empty file and some compilers - * don't like that. This will hopefully silence them. - */ -#define NON_EMPTY_TRANSLATION_UNIT static void *dummy = &dummy; - -/* - * Applications should use -DOPENSSL_API_COMPAT= to suppress the - * declarations of functions deprecated in or before . Otherwise, they - * still won't see them if the library has been built to disable deprecated - * functions. - */ -#ifndef DECLARE_DEPRECATED -# define DECLARE_DEPRECATED(f) f; -# ifdef __GNUC__ -# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 0) -# undef DECLARE_DEPRECATED -# define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); -# endif -# elif defined(__SUNPRO_C) -# if (__SUNPRO_C >= 0x5130) -# undef DECLARE_DEPRECATED -# define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); -# endif -# endif -#endif - -#ifndef OPENSSL_FILE -# ifdef OPENSSL_NO_FILENAMES -# define OPENSSL_FILE "" -# define OPENSSL_LINE 0 -# else -# define OPENSSL_FILE __FILE__ -# define OPENSSL_LINE __LINE__ -# endif -#endif - -#ifndef OPENSSL_MIN_API -# define OPENSSL_MIN_API 0 -#endif - -#if !defined(OPENSSL_API_COMPAT) || OPENSSL_API_COMPAT < OPENSSL_MIN_API -# undef OPENSSL_API_COMPAT -# define OPENSSL_API_COMPAT OPENSSL_MIN_API -#endif - -/* - * Do not deprecate things to be deprecated in version 1.2.0 before the - * OpenSSL version number matches. - */ -#if OPENSSL_VERSION_NUMBER < 0x10200000L -# define DEPRECATEDIN_1_2_0(f) f; -#elif OPENSSL_API_COMPAT < 0x10200000L -# define DEPRECATEDIN_1_2_0(f) DECLARE_DEPRECATED(f) -#else -# define DEPRECATEDIN_1_2_0(f) -#endif - -#if OPENSSL_API_COMPAT < 0x10100000L -# define DEPRECATEDIN_1_1_0(f) DECLARE_DEPRECATED(f) -#else -# define DEPRECATEDIN_1_1_0(f) -#endif - -#if OPENSSL_API_COMPAT < 0x10000000L -# define DEPRECATEDIN_1_0_0(f) DECLARE_DEPRECATED(f) -#else -# define DEPRECATEDIN_1_0_0(f) -#endif - -#if OPENSSL_API_COMPAT < 0x00908000L -# define DEPRECATEDIN_0_9_8(f) DECLARE_DEPRECATED(f) -#else -# define DEPRECATEDIN_0_9_8(f) -#endif - -/* Generate 80386 code? */ -#undef I386_ONLY - -#undef OPENSSL_UNISTD -#define OPENSSL_UNISTD - -#undef OPENSSL_EXPORT_VAR_AS_FUNCTION - -/* - * The following are cipher-specific, but are part of the public API. - */ -#if !defined(OPENSSL_SYS_UEFI) -# undef BN_LLONG -/* Only one for the following should be defined */ -# undef SIXTY_FOUR_BIT_LONG -# undef SIXTY_FOUR_BIT -# define THIRTY_TWO_BIT -#endif - -#define RC4_INT unsigned int - -#ifdef __cplusplus -} -#endif diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index f0ca72eeed..25f4f1635e 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -1,5 +1,5 @@ ## @file -# This module provides OpenSSL Library implementation. +# This module provides OpenSSL Library implementation with TLS features. # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
@@ -16,14 +16,18 @@ MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = OpensslLib + CONSTRUCTOR = OpensslLibConstructor + DEFINE OPENSSL_PATH = openssl - DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_ASM + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_EC -DOPENSSL_NO_ECDH -DOPENSSL_NO_ECDSA -DOPENSSL_NO_TLS1_3 -DOPENSSL_NO_SM2 -DOPENSSL_NO_ASM + DEFINE OPENSSL_FLAGS_CONFIG = # # VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 # [Sources] + OpensslLibConstructor.c $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here @@ -200,43 +204,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/curve25519.c +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c +# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c +# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c +# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c +# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c +# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c +# $(OPENSSL_PATH)/crypto/ec/ec_check.c +# $(OPENSSL_PATH)/crypto/ec/ec_curve.c +# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c +# $(OPENSSL_PATH)/crypto/ec/ec_err.c +# $(OPENSSL_PATH)/crypto/ec/ec_key.c +# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_lib.c +# $(OPENSSL_PATH)/crypto/ec/ec_mult.c +# $(OPENSSL_PATH)/crypto/ec/ec_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_print.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c +# $(OPENSSL_PATH)/crypto/ec/eck_prn.c +# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c +# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c +# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -422,10 +426,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -538,15 +542,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/ec_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h +# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/field.h +# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/word.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -638,15 +642,13 @@ [LibraryClasses.ARM] ArmSoftFloatLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES - [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, # so we do not break the build with /WX option: # C4090: 'function' : different 'const' qualifiers # C4132: 'object' : const object should be initialized (tls13_enc.c) + # C4210: nonstandard extension used: function given file scope # C4244: conversion from type1 to type2, possible loss of data # C4245: conversion from type1 to type2, signed/unsigned mismatch # C4267: conversion from size_t to type, possible loss of data @@ -658,11 +660,19 @@ # C4706: assignment within conditional expression # C4819: The file contains a character that cannot be represented in the current code page # - MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) /wd4090 /wd4132 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 - MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) /wd4090 /wd4132 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 + MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + + # + # Disable following Visual Studio 2015 compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4718: recursive call has no side effects, deleting + # + MSFT:*_VS2015x86_IA32_CC_FLAGS = /wd4718 + MSFT:*_VS2015x86_X64_CC_FLAGS = /wd4718 - INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) /w - INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) /w + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w + INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w # # Suppress the following build warnings in openssl so we don't break the build with -Werror @@ -671,10 +681,10 @@ # types appropriate to the format string specified. # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). # - GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable - GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS GCC:*_*_ARM_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable - GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable -Wno-error=format GCC:*_*_RISCV64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_LOONGARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized @@ -700,8 +710,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized # # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.uni b/CryptoPkg/Library/OpensslLib/OpensslLib.uni index abaff8a3c3..6b62c46040 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.uni +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.uni @@ -1,7 +1,5 @@ // /** @file -// This module provides openSSL Library implementation. -// -// This module provides OpenSSL Library implementation. +// This module provides OpenSSL Library implementation with TLS features. // // Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
// @@ -9,8 +7,6 @@ // // **/ +#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation with TLS features." -#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation" - -#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation." - +#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation with TLS features." diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf similarity index 78% rename from CryptoPkg/Library/OpensslLib/OpensslLibX64.inf rename to CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 5e92ba0844..6d43556a40 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibX64.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -1,5 +1,7 @@ ## @file -# This module provides OpenSSL Library implementation. +# This module provides OpenSSL Library implementation with TLS features +# along with performance optimized implementations of SHA1, SHA256, SHA512, +# AESNI, VPAED, and GHASH for IA32 and X64. # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
@@ -9,39 +11,27 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = OpensslLibX64 - MODULE_UNI_FILE = OpensslLib.uni - FILE_GUID = 18125E50-0117-4DD0-BE54-4784AD995FEF + BASE_NAME = OpensslLibAccel + MODULE_UNI_FILE = OpensslLibAccel.uni + FILE_GUID = 96A34760-B04A-44EB-9680-AC7606E9776B MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = OpensslLib + CONSTRUCTOR = OpensslLibConstructor + DEFINE OPENSSL_PATH = openssl - DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_EC -DOPENSSL_NO_ECDH -DOPENSSL_NO_ECDSA -DOPENSSL_NO_TLS1_3 -DOPENSSL_NO_SM2 DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM - CONSTRUCTOR = OpensslLibConstructor # -# VALID_ARCHITECTURES = X64 +# VALID_ARCHITECTURES = IA32 X64 # -[Sources.X64] +[Sources] OpensslLibConstructor.c $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here - X64/crypto/aes/aesni-mb-x86_64.nasm - X64/crypto/aes/aesni-sha1-x86_64.nasm - X64/crypto/aes/aesni-sha256-x86_64.nasm - X64/crypto/aes/aesni-x86_64.nasm - X64/crypto/aes/vpaes-x86_64.nasm - X64/crypto/modes/aesni-gcm-x86_64.nasm - X64/crypto/modes/ghash-x86_64.nasm - X64/crypto/sha/sha1-mb-x86_64.nasm - X64/crypto/sha/sha1-x86_64.nasm - X64/crypto/sha/sha256-mb-x86_64.nasm - X64/crypto/sha/sha256-x86_64.nasm - X64/crypto/sha/sha512-x86_64.nasm - X64/crypto/x86_64cpuid.nasm $(OPENSSL_PATH)/crypto/aes/aes_cbc.c $(OPENSSL_PATH)/crypto/aes/aes_cfb.c $(OPENSSL_PATH)/crypto/aes/aes_core.c @@ -215,43 +205,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/curve25519.c +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c +# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c +# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c +# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c +# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c +# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c +# $(OPENSSL_PATH)/crypto/ec/ec_check.c +# $(OPENSSL_PATH)/crypto/ec/ec_curve.c +# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c +# $(OPENSSL_PATH)/crypto/ec/ec_err.c +# $(OPENSSL_PATH)/crypto/ec/ec_key.c +# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_lib.c +# $(OPENSSL_PATH)/crypto/ec/ec_mult.c +# $(OPENSSL_PATH)/crypto/ec/ec_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_print.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c +# $(OPENSSL_PATH)/crypto/ec/eck_prn.c +# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c +# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c +# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -330,6 +320,7 @@ $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c $(OPENSSL_PATH)/crypto/mem.c +# $(OPENSSL_PATH)/crypto/mem_clr.c # Replaced by assembly optimized NASM/S files $(OPENSSL_PATH)/crypto/mem_dbg.c $(OPENSSL_PATH)/crypto/mem_sec.c $(OPENSSL_PATH)/crypto/modes/cbc128.c @@ -436,10 +427,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -552,15 +543,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/ec_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h +# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/field.h +# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/word.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -638,7 +629,53 @@ buildinf.h ossl_store.c rand_pool.c + +[Sources.IA32] + IA32/crypto/aes/aesni-x86.nasm | MSFT + IA32/crypto/aes/vpaes-x86.nasm | MSFT + IA32/crypto/modes/ghash-x86.nasm | MSFT + IA32/crypto/sha/sha1-586.nasm | MSFT + IA32/crypto/sha/sha256-586.nasm | MSFT + IA32/crypto/sha/sha512-586.nasm | MSFT + IA32/crypto/x86cpuid.nasm | MSFT + + IA32Gcc/crypto/aes/aesni-x86.S | GCC + IA32Gcc/crypto/aes/vpaes-x86.S | GCC + IA32Gcc/crypto/modes/ghash-x86.S | GCC + IA32Gcc/crypto/sha/sha1-586.S | GCC + IA32Gcc/crypto/sha/sha256-586.S | GCC + IA32Gcc/crypto/sha/sha512-586.S | GCC + IA32Gcc/crypto/x86cpuid.S | GCC + +[Sources.X64] X64/ApiHooks.c + X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT + X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT + X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT + X64/crypto/aes/aesni-x86_64.nasm | MSFT + X64/crypto/aes/vpaes-x86_64.nasm | MSFT + X64/crypto/modes/aesni-gcm-x86_64.nasm | MSFT + X64/crypto/modes/ghash-x86_64.nasm | MSFT + X64/crypto/sha/sha1-mb-x86_64.nasm | MSFT + X64/crypto/sha/sha1-x86_64.nasm | MSFT + X64/crypto/sha/sha256-mb-x86_64.nasm | MSFT + X64/crypto/sha/sha256-x86_64.nasm | MSFT + X64/crypto/sha/sha512-x86_64.nasm | MSFT + X64/crypto/x86_64cpuid.nasm | MSFT + + X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-x86_64.S | GCC + X64Gcc/crypto/aes/vpaes-x86_64.S | GCC + X64Gcc/crypto/modes/aesni-gcm-x86_64.S | GCC + X64Gcc/crypto/modes/ghash-x86_64.S | GCC + X64Gcc/crypto/sha/sha1-mb-x86_64.S | GCC + X64Gcc/crypto/sha/sha1-x86_64.S | GCC + X64Gcc/crypto/sha/sha256-mb-x86_64.S | GCC + X64Gcc/crypto/sha/sha256-x86_64.S | GCC + X64Gcc/crypto/sha/sha512-x86_64.S | GCC + X64Gcc/crypto/x86_64cpuid.S | GCC [Packages] MdePkg/MdePkg.dec @@ -650,9 +687,6 @@ RngLib PrintLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES - [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, @@ -671,8 +705,18 @@ # C4706: assignment within conditional expression # C4819: The file contains a character that cannot be represented in the current code page # + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + # + # Disable following Visual Studio 2015 compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4718: recursive call has no side effects, deleting + # + MSFT:*_VS2015x86_IA32_CC_FLAGS = /wd4718 + MSFT:*_VS2015x86_X64_CC_FLAGS = /wd4718 + + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w # @@ -682,7 +726,11 @@ # types appropriate to the format string specified. # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). # - GCC:*_*_X64_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types @@ -703,4 +751,5 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.uni b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.uni new file mode 100644 index 0000000000..e547a0c1e8 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.uni @@ -0,0 +1,14 @@ +// /** @file +// This module provides OpenSSL Library implementation with TLS features +// along with performance optimized implementations of SHA1, SHA256, SHA512, +// AESNI, VPAED, and GHASH for IA32 and X64. +// +// Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation with TLS features and performance optimizations" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation with TLS features along with performance optimized implementations of SHA1, SHA256, SHA512, AESNI, VPAED, and GHASH for IA32 and X64." diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibConstructor.c b/CryptoPkg/Library/OpensslLib/OpensslLibConstructor.c index 18d8a56128..5daf73a547 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibConstructor.c +++ b/CryptoPkg/Library/OpensslLib/OpensslLibConstructor.c @@ -6,7 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include +#include /** An internal OpenSSL function which fetches a local copy of the hardware @@ -30,7 +30,7 @@ OPENSSL_cpuid_setup ( @retval EFI_SUCCESS The construction succeeded. **/ -EFI_STATUS +RETURN_STATUS EFIAPI OpensslLibConstructor ( VOID @@ -38,5 +38,5 @@ OpensslLibConstructor ( { OPENSSL_cpuid_setup (); - return EFI_SUCCESS; + return RETURN_SUCCESS; } diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index 195016fd3d..3e344f8515 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -1,5 +1,6 @@ ## @file -# This module provides OpenSSL Library implementation. +# This module provides OpenSSL Library implementation with ECC and TLS +# features removed and features have performance optimizations enabled. # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
@@ -16,14 +17,18 @@ MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = OpensslLib + CONSTRUCTOR = OpensslLibConstructor + DEFINE OPENSSL_PATH = openssl - DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_ASM + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_EC -DOPENSSL_NO_ECDH -DOPENSSL_NO_ECDSA -DOPENSSL_NO_TLS1_3 -DOPENSSL_NO_SM2 -DOPENSSL_NO_ASM + DEFINE OPENSSL_FLAGS_CONFIG = # # VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 # [Sources] + OpensslLibConstructor.c $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here @@ -200,43 +205,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/curve25519.c +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c +# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c +# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c +# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c +# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c +# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c +# $(OPENSSL_PATH)/crypto/ec/ec_check.c +# $(OPENSSL_PATH)/crypto/ec/ec_curve.c +# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c +# $(OPENSSL_PATH)/crypto/ec/ec_err.c +# $(OPENSSL_PATH)/crypto/ec/ec_key.c +# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_lib.c +# $(OPENSSL_PATH)/crypto/ec/ec_mult.c +# $(OPENSSL_PATH)/crypto/ec/ec_oct.c +# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c +# $(OPENSSL_PATH)/crypto/ec/ec_print.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c +# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c +# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c +# $(OPENSSL_PATH)/crypto/ec/eck_prn.c +# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c +# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c +# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c +# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c +# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -422,10 +427,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c +# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -538,15 +543,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled +# $(OPENSSL_PATH)/crypto/ec/ec_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h +# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h +# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/field.h +# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h +# $(OPENSSL_PATH)/crypto/ec/curve448/word.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h +# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -569,6 +574,57 @@ $(OPENSSL_PATH)/crypto/x509v3/pcy_local.h $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h +# $(OPENSSL_PATH)/ssl/bio_ssl.c +# $(OPENSSL_PATH)/ssl/d1_lib.c +# $(OPENSSL_PATH)/ssl/d1_msg.c +# $(OPENSSL_PATH)/ssl/d1_srtp.c +# $(OPENSSL_PATH)/ssl/methods.c +# $(OPENSSL_PATH)/ssl/packet.c +# $(OPENSSL_PATH)/ssl/pqueue.c +# $(OPENSSL_PATH)/ssl/record/dtls1_bitmap.c +# $(OPENSSL_PATH)/ssl/record/rec_layer_d1.c +# $(OPENSSL_PATH)/ssl/record/rec_layer_s3.c +# $(OPENSSL_PATH)/ssl/record/ssl3_buffer.c +# $(OPENSSL_PATH)/ssl/record/ssl3_record.c +# $(OPENSSL_PATH)/ssl/record/ssl3_record_tls13.c +# $(OPENSSL_PATH)/ssl/s3_cbc.c +# $(OPENSSL_PATH)/ssl/s3_enc.c +# $(OPENSSL_PATH)/ssl/s3_lib.c +# $(OPENSSL_PATH)/ssl/s3_msg.c +# $(OPENSSL_PATH)/ssl/ssl_asn1.c +# $(OPENSSL_PATH)/ssl/ssl_cert.c +# $(OPENSSL_PATH)/ssl/ssl_ciph.c +# $(OPENSSL_PATH)/ssl/ssl_conf.c +# $(OPENSSL_PATH)/ssl/ssl_err.c +# $(OPENSSL_PATH)/ssl/ssl_init.c +# $(OPENSSL_PATH)/ssl/ssl_lib.c +# $(OPENSSL_PATH)/ssl/ssl_mcnf.c +# $(OPENSSL_PATH)/ssl/ssl_rsa.c +# $(OPENSSL_PATH)/ssl/ssl_sess.c +# $(OPENSSL_PATH)/ssl/ssl_stat.c +# $(OPENSSL_PATH)/ssl/ssl_txt.c +# $(OPENSSL_PATH)/ssl/ssl_utst.c +# $(OPENSSL_PATH)/ssl/statem/extensions.c +# $(OPENSSL_PATH)/ssl/statem/extensions_clnt.c +# $(OPENSSL_PATH)/ssl/statem/extensions_cust.c +# $(OPENSSL_PATH)/ssl/statem/extensions_srvr.c +# $(OPENSSL_PATH)/ssl/statem/statem.c +# $(OPENSSL_PATH)/ssl/statem/statem_clnt.c +# $(OPENSSL_PATH)/ssl/statem/statem_dtls.c +# $(OPENSSL_PATH)/ssl/statem/statem_lib.c +# $(OPENSSL_PATH)/ssl/statem/statem_srvr.c +# $(OPENSSL_PATH)/ssl/t1_enc.c +# $(OPENSSL_PATH)/ssl/t1_lib.c +# $(OPENSSL_PATH)/ssl/t1_trce.c +# $(OPENSSL_PATH)/ssl/tls13_enc.c +# $(OPENSSL_PATH)/ssl/tls_srp.c +# $(OPENSSL_PATH)/ssl/packet_local.h +# $(OPENSSL_PATH)/ssl/ssl_cert_table.h +# $(OPENSSL_PATH)/ssl/ssl_local.h +# $(OPENSSL_PATH)/ssl/record/record.h +# $(OPENSSL_PATH)/ssl/record/record_local.h +# $(OPENSSL_PATH)/ssl/statem/statem.h +# $(OPENSSL_PATH)/ssl/statem/statem_local.h # Autogenerated files list ends here buildinf.h ossl_store.c @@ -587,15 +643,13 @@ [LibraryClasses.ARM] ArmSoftFloatLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES - [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, # so we do not break the build with /WX option: # C4090: 'function' : different 'const' qualifiers # C4132: 'object' : const object should be initialized (tls13_enc.c) + # C4210: nonstandard extension used: function given file scope # C4244: conversion from type1 to type2, possible loss of data # C4245: conversion from type1 to type2, signed/unsigned mismatch # C4267: conversion from size_t to type, possible loss of data @@ -607,11 +661,19 @@ # C4706: assignment within conditional expression # C4819: The file contains a character that cannot be represented in the current code page # - MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) /wd4090 /wd4132 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 - MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) /wd4090 /wd4132 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 + MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + + # + # Disable following Visual Studio 2015 compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4718: recursive call has no side effects, deleting + # + MSFT:*_VS2015x86_IA32_CC_FLAGS = /wd4718 + MSFT:*_VS2015x86_X64_CC_FLAGS = /wd4718 - INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) /w - INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) /w + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w + INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w # # Suppress the following build warnings in openssl so we don't break the build with -Werror @@ -620,10 +682,10 @@ # types appropriate to the format string specified. # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). # - GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable - GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS GCC:*_*_ARM_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable - GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable -Wno-error=format GCC:*_*_RISCV64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_*_LOONGARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized @@ -649,8 +711,8 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized - XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized # # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.uni b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.uni index d3f12e178c..462ccf4355 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.uni +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.uni @@ -1,7 +1,6 @@ // /** @file -// This module provides openSSL Library implementation (libcrypto only, no libssl). -// -// This module provides OpenSSL Library implementation (libcrypto only, no libssl). +// This module provides OpenSSL Library implementation (libcrypto only, no +// libssl or ecc). // // Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
// @@ -9,8 +8,6 @@ // // **/ +#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation (libcrypto only, no libssl or ecc)" -#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation (libcrypto only, no libssl)" - -#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation (libcrypto only, no libssl)." - +#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation (libcrypto only, no libssl or ecc)." diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf similarity index 79% rename from CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf rename to CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index b6ee718ede..c3b78a448a 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibIa32.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -1,5 +1,11 @@ ## @file -# This module provides OpenSSL Library implementation. +# This module provides OpenSSL Library implementation with ECC and TLS +# features. +# +# This library should be used if a module module needs ECC in TLS, or +# asymmetric cryptography services such as X509 certificate or PEM format +# data processing. This library increases the size overhead up to ~115 KB +# compared to OpensslLib.inf library instance. # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
@@ -9,33 +15,27 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = OpensslLibIa32 - MODULE_UNI_FILE = OpensslLib.uni - FILE_GUID = 5805D1D4-F8EE-4FBA-BDD8-74465F16A534 + BASE_NAME = OpensslLibFull + MODULE_UNI_FILE = OpensslLibFull.uni + FILE_GUID = AB9E2231-D8FC-433F-9F27-FA293B64FB2C MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = OpensslLib - DEFINE OPENSSL_PATH = openssl - DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE - DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM CONSTRUCTOR = OpensslLibConstructor + DEFINE OPENSSL_PATH = openssl + DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DOPENSSL_NO_ASM + DEFINE OPENSSL_FLAGS_CONFIG = + # -# VALID_ARCHITECTURES = IA32 +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 # -[Sources.IA32] +[Sources] OpensslLibConstructor.c $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here - IA32/crypto/aes/aesni-x86.nasm - IA32/crypto/aes/vpaes-x86.nasm - IA32/crypto/modes/ghash-x86.nasm - IA32/crypto/sha/sha1-586.nasm - IA32/crypto/sha/sha256-586.nasm - IA32/crypto/sha/sha512-586.nasm - IA32/crypto/x86cpuid.nasm $(OPENSSL_PATH)/crypto/aes/aes_cbc.c $(OPENSSL_PATH)/crypto/aes/aes_cfb.c $(OPENSSL_PATH)/crypto/aes/aes_core.c @@ -209,43 +209,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve25519.c + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c + $(OPENSSL_PATH)/crypto/ec/ec_check.c + $(OPENSSL_PATH)/crypto/ec/ec_curve.c + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c + $(OPENSSL_PATH)/crypto/ec/ec_err.c + $(OPENSSL_PATH)/crypto/ec/ec_key.c + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_lib.c + $(OPENSSL_PATH)/crypto/ec/ec_mult.c + $(OPENSSL_PATH)/crypto/ec/ec_oct.c + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_print.c + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c + $(OPENSSL_PATH)/crypto/ec/eck_prn.c + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -324,6 +324,7 @@ $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c $(OPENSSL_PATH)/crypto/mem.c + $(OPENSSL_PATH)/crypto/mem_clr.c $(OPENSSL_PATH)/crypto/mem_dbg.c $(OPENSSL_PATH)/crypto/mem_sec.c $(OPENSSL_PATH)/crypto/modes/cbc128.c @@ -430,10 +431,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -546,15 +547,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h + $(OPENSSL_PATH)/crypto/ec/curve448/field.h + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h + $(OPENSSL_PATH)/crypto/ec/curve448/word.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -643,8 +644,8 @@ RngLib PrintLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES +[LibraryClasses.ARM] + ArmSoftFloatLib [BuildOptions] # @@ -665,8 +666,18 @@ # C4819: The file contains a character that cannot be represented in the current code page # MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 + MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + + # + # Disable following Visual Studio 2015 compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4718: recursive call has no side effects, deleting + # + MSFT:*_VS2015x86_IA32_CC_FLAGS = /wd4718 + MSFT:*_VS2015x86_X64_CC_FLAGS = /wd4718 INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w + INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w # # Suppress the following build warnings in openssl so we don't break the build with -Werror @@ -675,7 +686,15 @@ # types appropriate to the format string specified. # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). # - GCC:*_*_IA32_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_*_ARM_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable -Wno-error=format + GCC:*_*_RISCV64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_*_LOONGARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable + GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types @@ -697,3 +716,15 @@ # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized + XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized + + # + # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute + # with the MMU off. This involves SEC, PEI_CORE and PEIM modules as well as BASE + # libraries, given that they may be included into such modules. + # This library, even though of the BASE type, is never used in such cases, and + # avoiding the SIMD register file (which is shared with the FPU) prevents the + # compiler from successfully building some of the OpenSSL source files that + # use floating point types, so clear the flags here. + # + GCC:*_*_AARCH64_CC_XIPFLAGS == diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.uni b/CryptoPkg/Library/OpensslLib/OpensslLibFull.uni new file mode 100644 index 0000000000..ec50adba9f --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.uni @@ -0,0 +1,12 @@ +// /** @file +// This module provides OpenSSL Library implementation with TLS and ECC features. +// +// Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation with TLS and ECC features" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation with TLS and ECC features." diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf similarity index 78% rename from CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf rename to CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 0f1b4b16f8..ec53a5911b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibX64Gcc.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -1,5 +1,12 @@ ## @file -# This module provides OpenSSL Library implementation. +# This module provides OpenSSL Library implementation with ECC and TLS +# features along with performance optimized implementations of SHA1, +# SHA256, SHA512 AESNI, VPAED, and GHASH for IA32 and X64. +# +# This library should be used if a module module needs ECC in TLS, or +# asymmetric cryptography services such as X509 certificate or PEM format +# data processing. This library increases the size overhead up to ~115 KB +# compared to OpensslLibAccel.inf library instance. # # Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
@@ -9,39 +16,27 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = OpensslLibX64Gcc - MODULE_UNI_FILE = OpensslLib.uni - FILE_GUID = DD90DB9D-6A3F-4F2B-87BF-A8F2BBEF982F + BASE_NAME = OpensslLibFullAccel + MODULE_UNI_FILE = OpensslLibFullAccel.uni + FILE_GUID = AC649FB2-ADCF-450A-9C61-ED3CAFF12864 MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = OpensslLib + CONSTRUCTOR = OpensslLibConstructor + DEFINE OPENSSL_PATH = openssl DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM - CONSTRUCTOR = OpensslLibConstructor # -# VALID_ARCHITECTURES = X64 +# VALID_ARCHITECTURES = IA32 X64 # -[Sources.X64] +[Sources] OpensslLibConstructor.c $(OPENSSL_PATH)/e_os.h $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here - X64Gcc/crypto/aes/aesni-mb-x86_64.S - X64Gcc/crypto/aes/aesni-sha1-x86_64.S - X64Gcc/crypto/aes/aesni-sha256-x86_64.S - X64Gcc/crypto/aes/aesni-x86_64.S - X64Gcc/crypto/aes/vpaes-x86_64.S - X64Gcc/crypto/modes/aesni-gcm-x86_64.S - X64Gcc/crypto/modes/ghash-x86_64.S - X64Gcc/crypto/sha/sha1-mb-x86_64.S - X64Gcc/crypto/sha/sha1-x86_64.S - X64Gcc/crypto/sha/sha256-mb-x86_64.S - X64Gcc/crypto/sha/sha256-x86_64.S - X64Gcc/crypto/sha/sha512-x86_64.S - X64Gcc/crypto/x86_64cpuid.S $(OPENSSL_PATH)/crypto/aes/aes_cbc.c $(OPENSSL_PATH)/crypto/aes/aes_cfb.c $(OPENSSL_PATH)/crypto/aes/aes_core.c @@ -215,43 +210,43 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/curve25519.c + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c + $(OPENSSL_PATH)/crypto/ec/ec_check.c + $(OPENSSL_PATH)/crypto/ec/ec_curve.c + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c + $(OPENSSL_PATH)/crypto/ec/ec_err.c + $(OPENSSL_PATH)/crypto/ec/ec_key.c + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_lib.c + $(OPENSSL_PATH)/crypto/ec/ec_mult.c + $(OPENSSL_PATH)/crypto/ec/ec_oct.c + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_print.c + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c + $(OPENSSL_PATH)/crypto/ec/eck_prn.c + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -330,6 +325,7 @@ $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c $(OPENSSL_PATH)/crypto/mem.c +# $(OPENSSL_PATH)/crypto/mem_clr.c # Replaced by assembly optimized NASM/S files $(OPENSSL_PATH)/crypto/mem_dbg.c $(OPENSSL_PATH)/crypto/mem_sec.c $(OPENSSL_PATH)/crypto/modes/cbc128.c @@ -436,10 +432,10 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -552,15 +548,15 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + $(OPENSSL_PATH)/crypto/ec/ec_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h + $(OPENSSL_PATH)/crypto/ec/curve448/field.h + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h + $(OPENSSL_PATH)/crypto/ec/curve448/word.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -638,7 +634,53 @@ buildinf.h ossl_store.c rand_pool.c + +[Sources.IA32] + IA32/crypto/aes/aesni-x86.nasm | MSFT + IA32/crypto/aes/vpaes-x86.nasm | MSFT + IA32/crypto/modes/ghash-x86.nasm | MSFT + IA32/crypto/sha/sha1-586.nasm | MSFT + IA32/crypto/sha/sha256-586.nasm | MSFT + IA32/crypto/sha/sha512-586.nasm | MSFT + IA32/crypto/x86cpuid.nasm | MSFT + + IA32Gcc/crypto/aes/aesni-x86.S | GCC + IA32Gcc/crypto/aes/vpaes-x86.S | GCC + IA32Gcc/crypto/modes/ghash-x86.S | GCC + IA32Gcc/crypto/sha/sha1-586.S | GCC + IA32Gcc/crypto/sha/sha256-586.S | GCC + IA32Gcc/crypto/sha/sha512-586.S | GCC + IA32Gcc/crypto/x86cpuid.S | GCC + +[Sources.X64] X64/ApiHooks.c + X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT + X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT + X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT + X64/crypto/aes/aesni-x86_64.nasm | MSFT + X64/crypto/aes/vpaes-x86_64.nasm | MSFT + X64/crypto/modes/aesni-gcm-x86_64.nasm | MSFT + X64/crypto/modes/ghash-x86_64.nasm | MSFT + X64/crypto/sha/sha1-mb-x86_64.nasm | MSFT + X64/crypto/sha/sha1-x86_64.nasm | MSFT + X64/crypto/sha/sha256-mb-x86_64.nasm | MSFT + X64/crypto/sha/sha256-x86_64.nasm | MSFT + X64/crypto/sha/sha512-x86_64.nasm | MSFT + X64/crypto/x86_64cpuid.nasm | MSFT + + X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC + X64Gcc/crypto/aes/aesni-x86_64.S | GCC + X64Gcc/crypto/aes/vpaes-x86_64.S | GCC + X64Gcc/crypto/modes/aesni-gcm-x86_64.S | GCC + X64Gcc/crypto/modes/ghash-x86_64.S | GCC + X64Gcc/crypto/sha/sha1-mb-x86_64.S | GCC + X64Gcc/crypto/sha/sha1-x86_64.S | GCC + X64Gcc/crypto/sha/sha256-mb-x86_64.S | GCC + X64Gcc/crypto/sha/sha256-x86_64.S | GCC + X64Gcc/crypto/sha/sha512-x86_64.S | GCC + X64Gcc/crypto/x86_64cpuid.S | GCC [Packages] MdePkg/MdePkg.dec @@ -650,9 +692,6 @@ RngLib PrintLib -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES - [BuildOptions] # # Disables the following Visual Studio compiler warnings brought by openssl source, @@ -671,8 +710,18 @@ # C4706: assignment within conditional expression # C4819: The file contains a character that cannot be represented in the current code page # + MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 MSFT:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4306 /wd4310 /wd4700 /wd4389 /wd4702 /wd4706 /wd4819 + # + # Disable following Visual Studio 2015 compiler warnings brought by openssl source, + # so we do not break the build with /WX option: + # C4718: recursive call has no side effects, deleting + # + MSFT:*_VS2015x86_IA32_CC_FLAGS = /wd4718 + MSFT:*_VS2015x86_X64_CC_FLAGS = /wd4718 + + INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w INTEL:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w # @@ -682,7 +731,11 @@ # types appropriate to the format string specified. # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). # - GCC:*_*_X64_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable + GCC:*_*_X64_CC_FLAGS = -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=format -Wno-format -Wno-error=unused-but-set-variable -DNO_MSABI_VA_FUNCS + GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types @@ -703,4 +756,5 @@ # 1: ignore "#1-D: last line of file ends without a newline" # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) + XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized XCODE:*_*_X64_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.uni b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.uni new file mode 100644 index 0000000000..b8453b6c90 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.uni @@ -0,0 +1,14 @@ +// /** @file +// This module provides openSSL Library implementation with ECC and TLS +// features along with performance optimized implementations of SHA1, +// SHA256, SHA512 AESNI, VPAED, and GHASH for IA32 and X64. +// +// Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "OpenSSL Library implementation with TLS and ECC features and performance optimizations" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides OpenSSL Library implementation with TLS and ECC features and performance optimizations." diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf b/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf deleted file mode 100644 index 150a82ec7a..0000000000 --- a/CryptoPkg/Library/OpensslLib/OpensslLibIa32Gcc.inf +++ /dev/null @@ -1,699 +0,0 @@ -## @file -# This module provides OpenSSL Library implementation. -# -# Copyright (c) 2010 - 2020, Intel Corporation. All rights reserved.
-# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = OpensslLibIa32Gcc - MODULE_UNI_FILE = OpensslLib.uni - FILE_GUID = B1B32F26-A4E1-4D38-9E34-53A148B8EB11 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = OpensslLib - DEFINE OPENSSL_PATH = openssl - DEFINE OPENSSL_FLAGS = -DL_ENDIAN -DOPENSSL_SMALL_FOOTPRINT -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE - DEFINE OPENSSL_FLAGS_CONFIG = -DOPENSSL_CPUID_OBJ -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM - CONSTRUCTOR = OpensslLibConstructor - -# -# VALID_ARCHITECTURES = IA32 -# - -[Sources.IA32] - OpensslLibConstructor.c - $(OPENSSL_PATH)/e_os.h - $(OPENSSL_PATH)/ms/uplink.h -# Autogenerated files list starts here - IA32Gcc/crypto/aes/aesni-x86.S - IA32Gcc/crypto/aes/vpaes-x86.S - IA32Gcc/crypto/modes/ghash-x86.S - IA32Gcc/crypto/sha/sha1-586.S - IA32Gcc/crypto/sha/sha256-586.S - IA32Gcc/crypto/sha/sha512-586.S - IA32Gcc/crypto/x86cpuid.S - $(OPENSSL_PATH)/crypto/aes/aes_cbc.c - $(OPENSSL_PATH)/crypto/aes/aes_cfb.c - $(OPENSSL_PATH)/crypto/aes/aes_core.c - $(OPENSSL_PATH)/crypto/aes/aes_ige.c - $(OPENSSL_PATH)/crypto/aes/aes_misc.c - $(OPENSSL_PATH)/crypto/aes/aes_ofb.c - $(OPENSSL_PATH)/crypto/aes/aes_wrap.c - $(OPENSSL_PATH)/crypto/aria/aria.c - $(OPENSSL_PATH)/crypto/asn1/a_bitstr.c - $(OPENSSL_PATH)/crypto/asn1/a_d2i_fp.c - $(OPENSSL_PATH)/crypto/asn1/a_digest.c - $(OPENSSL_PATH)/crypto/asn1/a_dup.c - $(OPENSSL_PATH)/crypto/asn1/a_gentm.c - $(OPENSSL_PATH)/crypto/asn1/a_i2d_fp.c - $(OPENSSL_PATH)/crypto/asn1/a_int.c - $(OPENSSL_PATH)/crypto/asn1/a_mbstr.c - $(OPENSSL_PATH)/crypto/asn1/a_object.c - $(OPENSSL_PATH)/crypto/asn1/a_octet.c - $(OPENSSL_PATH)/crypto/asn1/a_print.c - $(OPENSSL_PATH)/crypto/asn1/a_sign.c - $(OPENSSL_PATH)/crypto/asn1/a_strex.c - $(OPENSSL_PATH)/crypto/asn1/a_strnid.c - $(OPENSSL_PATH)/crypto/asn1/a_time.c - $(OPENSSL_PATH)/crypto/asn1/a_type.c - $(OPENSSL_PATH)/crypto/asn1/a_utctm.c - $(OPENSSL_PATH)/crypto/asn1/a_utf8.c - $(OPENSSL_PATH)/crypto/asn1/a_verify.c - $(OPENSSL_PATH)/crypto/asn1/ameth_lib.c - $(OPENSSL_PATH)/crypto/asn1/asn1_err.c - $(OPENSSL_PATH)/crypto/asn1/asn1_gen.c - $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.c - $(OPENSSL_PATH)/crypto/asn1/asn1_lib.c - $(OPENSSL_PATH)/crypto/asn1/asn1_par.c - $(OPENSSL_PATH)/crypto/asn1/asn_mime.c - $(OPENSSL_PATH)/crypto/asn1/asn_moid.c - $(OPENSSL_PATH)/crypto/asn1/asn_mstbl.c - $(OPENSSL_PATH)/crypto/asn1/asn_pack.c - $(OPENSSL_PATH)/crypto/asn1/bio_asn1.c - $(OPENSSL_PATH)/crypto/asn1/bio_ndef.c - $(OPENSSL_PATH)/crypto/asn1/d2i_pr.c - $(OPENSSL_PATH)/crypto/asn1/d2i_pu.c - $(OPENSSL_PATH)/crypto/asn1/evp_asn1.c - $(OPENSSL_PATH)/crypto/asn1/f_int.c - $(OPENSSL_PATH)/crypto/asn1/f_string.c - $(OPENSSL_PATH)/crypto/asn1/i2d_pr.c - $(OPENSSL_PATH)/crypto/asn1/i2d_pu.c - $(OPENSSL_PATH)/crypto/asn1/n_pkey.c - $(OPENSSL_PATH)/crypto/asn1/nsseq.c - $(OPENSSL_PATH)/crypto/asn1/p5_pbe.c - $(OPENSSL_PATH)/crypto/asn1/p5_pbev2.c - $(OPENSSL_PATH)/crypto/asn1/p5_scrypt.c - $(OPENSSL_PATH)/crypto/asn1/p8_pkey.c - $(OPENSSL_PATH)/crypto/asn1/t_bitst.c - $(OPENSSL_PATH)/crypto/asn1/t_pkey.c - $(OPENSSL_PATH)/crypto/asn1/t_spki.c - $(OPENSSL_PATH)/crypto/asn1/tasn_dec.c - $(OPENSSL_PATH)/crypto/asn1/tasn_enc.c - $(OPENSSL_PATH)/crypto/asn1/tasn_fre.c - $(OPENSSL_PATH)/crypto/asn1/tasn_new.c - $(OPENSSL_PATH)/crypto/asn1/tasn_prn.c - $(OPENSSL_PATH)/crypto/asn1/tasn_scn.c - $(OPENSSL_PATH)/crypto/asn1/tasn_typ.c - $(OPENSSL_PATH)/crypto/asn1/tasn_utl.c - $(OPENSSL_PATH)/crypto/asn1/x_algor.c - $(OPENSSL_PATH)/crypto/asn1/x_bignum.c - $(OPENSSL_PATH)/crypto/asn1/x_info.c - $(OPENSSL_PATH)/crypto/asn1/x_int64.c - $(OPENSSL_PATH)/crypto/asn1/x_long.c - $(OPENSSL_PATH)/crypto/asn1/x_pkey.c - $(OPENSSL_PATH)/crypto/asn1/x_sig.c - $(OPENSSL_PATH)/crypto/asn1/x_spki.c - $(OPENSSL_PATH)/crypto/asn1/x_val.c - $(OPENSSL_PATH)/crypto/async/arch/async_null.c - $(OPENSSL_PATH)/crypto/async/arch/async_posix.c - $(OPENSSL_PATH)/crypto/async/arch/async_win.c - $(OPENSSL_PATH)/crypto/async/async.c - $(OPENSSL_PATH)/crypto/async/async_err.c - $(OPENSSL_PATH)/crypto/async/async_wait.c - $(OPENSSL_PATH)/crypto/bio/b_addr.c - $(OPENSSL_PATH)/crypto/bio/b_dump.c - $(OPENSSL_PATH)/crypto/bio/b_sock.c - $(OPENSSL_PATH)/crypto/bio/b_sock2.c - $(OPENSSL_PATH)/crypto/bio/bf_buff.c - $(OPENSSL_PATH)/crypto/bio/bf_lbuf.c - $(OPENSSL_PATH)/crypto/bio/bf_nbio.c - $(OPENSSL_PATH)/crypto/bio/bf_null.c - $(OPENSSL_PATH)/crypto/bio/bio_cb.c - $(OPENSSL_PATH)/crypto/bio/bio_err.c - $(OPENSSL_PATH)/crypto/bio/bio_lib.c - $(OPENSSL_PATH)/crypto/bio/bio_meth.c - $(OPENSSL_PATH)/crypto/bio/bss_acpt.c - $(OPENSSL_PATH)/crypto/bio/bss_bio.c - $(OPENSSL_PATH)/crypto/bio/bss_conn.c - $(OPENSSL_PATH)/crypto/bio/bss_dgram.c - $(OPENSSL_PATH)/crypto/bio/bss_fd.c - $(OPENSSL_PATH)/crypto/bio/bss_file.c - $(OPENSSL_PATH)/crypto/bio/bss_log.c - $(OPENSSL_PATH)/crypto/bio/bss_mem.c - $(OPENSSL_PATH)/crypto/bio/bss_null.c - $(OPENSSL_PATH)/crypto/bio/bss_sock.c - $(OPENSSL_PATH)/crypto/bn/bn_add.c - $(OPENSSL_PATH)/crypto/bn/bn_asm.c - $(OPENSSL_PATH)/crypto/bn/bn_blind.c - $(OPENSSL_PATH)/crypto/bn/bn_const.c - $(OPENSSL_PATH)/crypto/bn/bn_ctx.c - $(OPENSSL_PATH)/crypto/bn/bn_depr.c - $(OPENSSL_PATH)/crypto/bn/bn_dh.c - $(OPENSSL_PATH)/crypto/bn/bn_div.c - $(OPENSSL_PATH)/crypto/bn/bn_err.c - $(OPENSSL_PATH)/crypto/bn/bn_exp.c - $(OPENSSL_PATH)/crypto/bn/bn_exp2.c - $(OPENSSL_PATH)/crypto/bn/bn_gcd.c - $(OPENSSL_PATH)/crypto/bn/bn_gf2m.c - $(OPENSSL_PATH)/crypto/bn/bn_intern.c - $(OPENSSL_PATH)/crypto/bn/bn_kron.c - $(OPENSSL_PATH)/crypto/bn/bn_lib.c - $(OPENSSL_PATH)/crypto/bn/bn_mod.c - $(OPENSSL_PATH)/crypto/bn/bn_mont.c - $(OPENSSL_PATH)/crypto/bn/bn_mpi.c - $(OPENSSL_PATH)/crypto/bn/bn_mul.c - $(OPENSSL_PATH)/crypto/bn/bn_nist.c - $(OPENSSL_PATH)/crypto/bn/bn_prime.c - $(OPENSSL_PATH)/crypto/bn/bn_print.c - $(OPENSSL_PATH)/crypto/bn/bn_rand.c - $(OPENSSL_PATH)/crypto/bn/bn_recp.c - $(OPENSSL_PATH)/crypto/bn/bn_shift.c - $(OPENSSL_PATH)/crypto/bn/bn_sqr.c - $(OPENSSL_PATH)/crypto/bn/bn_sqrt.c - $(OPENSSL_PATH)/crypto/bn/bn_srp.c - $(OPENSSL_PATH)/crypto/bn/bn_word.c - $(OPENSSL_PATH)/crypto/bn/bn_x931p.c - $(OPENSSL_PATH)/crypto/buffer/buf_err.c - $(OPENSSL_PATH)/crypto/buffer/buffer.c - $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c - $(OPENSSL_PATH)/crypto/cmac/cm_pmeth.c - $(OPENSSL_PATH)/crypto/cmac/cmac.c - $(OPENSSL_PATH)/crypto/comp/c_zlib.c - $(OPENSSL_PATH)/crypto/comp/comp_err.c - $(OPENSSL_PATH)/crypto/comp/comp_lib.c - $(OPENSSL_PATH)/crypto/conf/conf_api.c - $(OPENSSL_PATH)/crypto/conf/conf_def.c - $(OPENSSL_PATH)/crypto/conf/conf_err.c - $(OPENSSL_PATH)/crypto/conf/conf_lib.c - $(OPENSSL_PATH)/crypto/conf/conf_mall.c - $(OPENSSL_PATH)/crypto/conf/conf_mod.c - $(OPENSSL_PATH)/crypto/conf/conf_sap.c - $(OPENSSL_PATH)/crypto/conf/conf_ssl.c - $(OPENSSL_PATH)/crypto/cpt_err.c - $(OPENSSL_PATH)/crypto/cryptlib.c - $(OPENSSL_PATH)/crypto/ctype.c - $(OPENSSL_PATH)/crypto/cversion.c - $(OPENSSL_PATH)/crypto/dh/dh_ameth.c - $(OPENSSL_PATH)/crypto/dh/dh_asn1.c - $(OPENSSL_PATH)/crypto/dh/dh_check.c - $(OPENSSL_PATH)/crypto/dh/dh_depr.c - $(OPENSSL_PATH)/crypto/dh/dh_err.c - $(OPENSSL_PATH)/crypto/dh/dh_gen.c - $(OPENSSL_PATH)/crypto/dh/dh_kdf.c - $(OPENSSL_PATH)/crypto/dh/dh_key.c - $(OPENSSL_PATH)/crypto/dh/dh_lib.c - $(OPENSSL_PATH)/crypto/dh/dh_meth.c - $(OPENSSL_PATH)/crypto/dh/dh_pmeth.c - $(OPENSSL_PATH)/crypto/dh/dh_prn.c - $(OPENSSL_PATH)/crypto/dh/dh_rfc5114.c - $(OPENSSL_PATH)/crypto/dh/dh_rfc7919.c - $(OPENSSL_PATH)/crypto/dso/dso_dl.c - $(OPENSSL_PATH)/crypto/dso/dso_dlfcn.c - $(OPENSSL_PATH)/crypto/dso/dso_err.c - $(OPENSSL_PATH)/crypto/dso/dso_lib.c - $(OPENSSL_PATH)/crypto/dso/dso_openssl.c - $(OPENSSL_PATH)/crypto/dso/dso_vms.c - $(OPENSSL_PATH)/crypto/dso/dso_win32.c - $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_check.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_curve.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_key.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_lib.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_mult.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ec_print.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/eck_prn.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/err/err.c - $(OPENSSL_PATH)/crypto/err/err_prn.c - $(OPENSSL_PATH)/crypto/evp/bio_b64.c - $(OPENSSL_PATH)/crypto/evp/bio_enc.c - $(OPENSSL_PATH)/crypto/evp/bio_md.c - $(OPENSSL_PATH)/crypto/evp/bio_ok.c - $(OPENSSL_PATH)/crypto/evp/c_allc.c - $(OPENSSL_PATH)/crypto/evp/c_alld.c - $(OPENSSL_PATH)/crypto/evp/cmeth_lib.c - $(OPENSSL_PATH)/crypto/evp/digest.c - $(OPENSSL_PATH)/crypto/evp/e_aes.c - $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha1.c - $(OPENSSL_PATH)/crypto/evp/e_aes_cbc_hmac_sha256.c - $(OPENSSL_PATH)/crypto/evp/e_aria.c - $(OPENSSL_PATH)/crypto/evp/e_bf.c - $(OPENSSL_PATH)/crypto/evp/e_camellia.c - $(OPENSSL_PATH)/crypto/evp/e_cast.c - $(OPENSSL_PATH)/crypto/evp/e_chacha20_poly1305.c - $(OPENSSL_PATH)/crypto/evp/e_des.c - $(OPENSSL_PATH)/crypto/evp/e_des3.c - $(OPENSSL_PATH)/crypto/evp/e_idea.c - $(OPENSSL_PATH)/crypto/evp/e_null.c - $(OPENSSL_PATH)/crypto/evp/e_old.c - $(OPENSSL_PATH)/crypto/evp/e_rc2.c - $(OPENSSL_PATH)/crypto/evp/e_rc4.c - $(OPENSSL_PATH)/crypto/evp/e_rc4_hmac_md5.c - $(OPENSSL_PATH)/crypto/evp/e_rc5.c - $(OPENSSL_PATH)/crypto/evp/e_seed.c - $(OPENSSL_PATH)/crypto/evp/e_sm4.c - $(OPENSSL_PATH)/crypto/evp/e_xcbc_d.c - $(OPENSSL_PATH)/crypto/evp/encode.c - $(OPENSSL_PATH)/crypto/evp/evp_cnf.c - $(OPENSSL_PATH)/crypto/evp/evp_enc.c - $(OPENSSL_PATH)/crypto/evp/evp_err.c - $(OPENSSL_PATH)/crypto/evp/evp_key.c - $(OPENSSL_PATH)/crypto/evp/evp_lib.c - $(OPENSSL_PATH)/crypto/evp/evp_pbe.c - $(OPENSSL_PATH)/crypto/evp/evp_pkey.c - $(OPENSSL_PATH)/crypto/evp/m_md2.c - $(OPENSSL_PATH)/crypto/evp/m_md4.c - $(OPENSSL_PATH)/crypto/evp/m_md5.c - $(OPENSSL_PATH)/crypto/evp/m_md5_sha1.c - $(OPENSSL_PATH)/crypto/evp/m_mdc2.c - $(OPENSSL_PATH)/crypto/evp/m_null.c - $(OPENSSL_PATH)/crypto/evp/m_ripemd.c - $(OPENSSL_PATH)/crypto/evp/m_sha1.c - $(OPENSSL_PATH)/crypto/evp/m_sha3.c - $(OPENSSL_PATH)/crypto/evp/m_sigver.c - $(OPENSSL_PATH)/crypto/evp/m_wp.c - $(OPENSSL_PATH)/crypto/evp/names.c - $(OPENSSL_PATH)/crypto/evp/p5_crpt.c - $(OPENSSL_PATH)/crypto/evp/p5_crpt2.c - $(OPENSSL_PATH)/crypto/evp/p_dec.c - $(OPENSSL_PATH)/crypto/evp/p_enc.c - $(OPENSSL_PATH)/crypto/evp/p_lib.c - $(OPENSSL_PATH)/crypto/evp/p_open.c - $(OPENSSL_PATH)/crypto/evp/p_seal.c - $(OPENSSL_PATH)/crypto/evp/p_sign.c - $(OPENSSL_PATH)/crypto/evp/p_verify.c - $(OPENSSL_PATH)/crypto/evp/pbe_scrypt.c - $(OPENSSL_PATH)/crypto/evp/pmeth_fn.c - $(OPENSSL_PATH)/crypto/evp/pmeth_gn.c - $(OPENSSL_PATH)/crypto/evp/pmeth_lib.c - $(OPENSSL_PATH)/crypto/ex_data.c - $(OPENSSL_PATH)/crypto/getenv.c - $(OPENSSL_PATH)/crypto/hmac/hm_ameth.c - $(OPENSSL_PATH)/crypto/hmac/hm_pmeth.c - $(OPENSSL_PATH)/crypto/hmac/hmac.c - $(OPENSSL_PATH)/crypto/init.c - $(OPENSSL_PATH)/crypto/kdf/hkdf.c - $(OPENSSL_PATH)/crypto/kdf/kdf_err.c - $(OPENSSL_PATH)/crypto/kdf/scrypt.c - $(OPENSSL_PATH)/crypto/kdf/tls1_prf.c - $(OPENSSL_PATH)/crypto/lhash/lh_stats.c - $(OPENSSL_PATH)/crypto/lhash/lhash.c - $(OPENSSL_PATH)/crypto/md5/md5_dgst.c - $(OPENSSL_PATH)/crypto/md5/md5_one.c - $(OPENSSL_PATH)/crypto/mem.c - $(OPENSSL_PATH)/crypto/mem_dbg.c - $(OPENSSL_PATH)/crypto/mem_sec.c - $(OPENSSL_PATH)/crypto/modes/cbc128.c - $(OPENSSL_PATH)/crypto/modes/ccm128.c - $(OPENSSL_PATH)/crypto/modes/cfb128.c - $(OPENSSL_PATH)/crypto/modes/ctr128.c - $(OPENSSL_PATH)/crypto/modes/cts128.c - $(OPENSSL_PATH)/crypto/modes/gcm128.c - $(OPENSSL_PATH)/crypto/modes/ocb128.c - $(OPENSSL_PATH)/crypto/modes/ofb128.c - $(OPENSSL_PATH)/crypto/modes/wrap128.c - $(OPENSSL_PATH)/crypto/modes/xts128.c - $(OPENSSL_PATH)/crypto/o_dir.c - $(OPENSSL_PATH)/crypto/o_fips.c - $(OPENSSL_PATH)/crypto/o_fopen.c - $(OPENSSL_PATH)/crypto/o_init.c - $(OPENSSL_PATH)/crypto/o_str.c - $(OPENSSL_PATH)/crypto/o_time.c - $(OPENSSL_PATH)/crypto/objects/o_names.c - $(OPENSSL_PATH)/crypto/objects/obj_dat.c - $(OPENSSL_PATH)/crypto/objects/obj_err.c - $(OPENSSL_PATH)/crypto/objects/obj_lib.c - $(OPENSSL_PATH)/crypto/objects/obj_xref.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_asn.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_cl.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_err.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_ext.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_ht.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_lib.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_prn.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_srv.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_vfy.c - $(OPENSSL_PATH)/crypto/ocsp/v3_ocsp.c - $(OPENSSL_PATH)/crypto/pem/pem_all.c - $(OPENSSL_PATH)/crypto/pem/pem_err.c - $(OPENSSL_PATH)/crypto/pem/pem_info.c - $(OPENSSL_PATH)/crypto/pem/pem_lib.c - $(OPENSSL_PATH)/crypto/pem/pem_oth.c - $(OPENSSL_PATH)/crypto/pem/pem_pk8.c - $(OPENSSL_PATH)/crypto/pem/pem_pkey.c - $(OPENSSL_PATH)/crypto/pem/pem_sign.c - $(OPENSSL_PATH)/crypto/pem/pem_x509.c - $(OPENSSL_PATH)/crypto/pem/pem_xaux.c - $(OPENSSL_PATH)/crypto/pem/pvkfmt.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_add.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_asn.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_attr.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_crpt.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_crt.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_decr.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_init.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_key.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_kiss.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_mutl.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_npas.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_p8d.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_p8e.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_sbag.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_utl.c - $(OPENSSL_PATH)/crypto/pkcs12/pk12err.c - $(OPENSSL_PATH)/crypto/pkcs7/bio_pk7.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_asn1.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_attr.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_doit.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_lib.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_mime.c - $(OPENSSL_PATH)/crypto/pkcs7/pk7_smime.c - $(OPENSSL_PATH)/crypto/pkcs7/pkcs7err.c - $(OPENSSL_PATH)/crypto/rand/drbg_ctr.c - $(OPENSSL_PATH)/crypto/rand/drbg_lib.c - $(OPENSSL_PATH)/crypto/rand/rand_egd.c - $(OPENSSL_PATH)/crypto/rand/rand_err.c - $(OPENSSL_PATH)/crypto/rand/rand_lib.c - $(OPENSSL_PATH)/crypto/rand/rand_unix.c - $(OPENSSL_PATH)/crypto/rand/rand_vms.c - $(OPENSSL_PATH)/crypto/rand/rand_win.c - $(OPENSSL_PATH)/crypto/rsa/rsa_ameth.c - $(OPENSSL_PATH)/crypto/rsa/rsa_asn1.c - $(OPENSSL_PATH)/crypto/rsa/rsa_chk.c - $(OPENSSL_PATH)/crypto/rsa/rsa_crpt.c - $(OPENSSL_PATH)/crypto/rsa/rsa_depr.c - $(OPENSSL_PATH)/crypto/rsa/rsa_err.c - $(OPENSSL_PATH)/crypto/rsa/rsa_gen.c - $(OPENSSL_PATH)/crypto/rsa/rsa_lib.c - $(OPENSSL_PATH)/crypto/rsa/rsa_meth.c - $(OPENSSL_PATH)/crypto/rsa/rsa_mp.c - $(OPENSSL_PATH)/crypto/rsa/rsa_none.c - $(OPENSSL_PATH)/crypto/rsa/rsa_oaep.c - $(OPENSSL_PATH)/crypto/rsa/rsa_ossl.c - $(OPENSSL_PATH)/crypto/rsa/rsa_pk1.c - $(OPENSSL_PATH)/crypto/rsa/rsa_pmeth.c - $(OPENSSL_PATH)/crypto/rsa/rsa_prn.c - $(OPENSSL_PATH)/crypto/rsa/rsa_pss.c - $(OPENSSL_PATH)/crypto/rsa/rsa_saos.c - $(OPENSSL_PATH)/crypto/rsa/rsa_sign.c - $(OPENSSL_PATH)/crypto/rsa/rsa_ssl.c - $(OPENSSL_PATH)/crypto/rsa/rsa_x931.c - $(OPENSSL_PATH)/crypto/rsa/rsa_x931g.c - $(OPENSSL_PATH)/crypto/sha/keccak1600.c - $(OPENSSL_PATH)/crypto/sha/sha1_one.c - $(OPENSSL_PATH)/crypto/sha/sha1dgst.c - $(OPENSSL_PATH)/crypto/sha/sha256.c - $(OPENSSL_PATH)/crypto/sha/sha512.c - $(OPENSSL_PATH)/crypto/siphash/siphash.c - $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c - $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/sm3/m_sm3.c - $(OPENSSL_PATH)/crypto/sm3/sm3.c - $(OPENSSL_PATH)/crypto/sm4/sm4.c - $(OPENSSL_PATH)/crypto/stack/stack.c - $(OPENSSL_PATH)/crypto/threads_none.c - $(OPENSSL_PATH)/crypto/threads_pthread.c - $(OPENSSL_PATH)/crypto/threads_win.c - $(OPENSSL_PATH)/crypto/txt_db/txt_db.c - $(OPENSSL_PATH)/crypto/ui/ui_err.c - $(OPENSSL_PATH)/crypto/ui/ui_lib.c - $(OPENSSL_PATH)/crypto/ui/ui_null.c - $(OPENSSL_PATH)/crypto/ui/ui_openssl.c - $(OPENSSL_PATH)/crypto/ui/ui_util.c - $(OPENSSL_PATH)/crypto/uid.c - $(OPENSSL_PATH)/crypto/x509/by_dir.c - $(OPENSSL_PATH)/crypto/x509/by_file.c - $(OPENSSL_PATH)/crypto/x509/t_crl.c - $(OPENSSL_PATH)/crypto/x509/t_req.c - $(OPENSSL_PATH)/crypto/x509/t_x509.c - $(OPENSSL_PATH)/crypto/x509/x509_att.c - $(OPENSSL_PATH)/crypto/x509/x509_cmp.c - $(OPENSSL_PATH)/crypto/x509/x509_d2.c - $(OPENSSL_PATH)/crypto/x509/x509_def.c - $(OPENSSL_PATH)/crypto/x509/x509_err.c - $(OPENSSL_PATH)/crypto/x509/x509_ext.c - $(OPENSSL_PATH)/crypto/x509/x509_lu.c - $(OPENSSL_PATH)/crypto/x509/x509_meth.c - $(OPENSSL_PATH)/crypto/x509/x509_obj.c - $(OPENSSL_PATH)/crypto/x509/x509_r2x.c - $(OPENSSL_PATH)/crypto/x509/x509_req.c - $(OPENSSL_PATH)/crypto/x509/x509_set.c - $(OPENSSL_PATH)/crypto/x509/x509_trs.c - $(OPENSSL_PATH)/crypto/x509/x509_txt.c - $(OPENSSL_PATH)/crypto/x509/x509_v3.c - $(OPENSSL_PATH)/crypto/x509/x509_vfy.c - $(OPENSSL_PATH)/crypto/x509/x509_vpm.c - $(OPENSSL_PATH)/crypto/x509/x509cset.c - $(OPENSSL_PATH)/crypto/x509/x509name.c - $(OPENSSL_PATH)/crypto/x509/x509rset.c - $(OPENSSL_PATH)/crypto/x509/x509spki.c - $(OPENSSL_PATH)/crypto/x509/x509type.c - $(OPENSSL_PATH)/crypto/x509/x_all.c - $(OPENSSL_PATH)/crypto/x509/x_attrib.c - $(OPENSSL_PATH)/crypto/x509/x_crl.c - $(OPENSSL_PATH)/crypto/x509/x_exten.c - $(OPENSSL_PATH)/crypto/x509/x_name.c - $(OPENSSL_PATH)/crypto/x509/x_pubkey.c - $(OPENSSL_PATH)/crypto/x509/x_req.c - $(OPENSSL_PATH)/crypto/x509/x_x509.c - $(OPENSSL_PATH)/crypto/x509/x_x509a.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_cache.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_data.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_lib.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_map.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_node.c - $(OPENSSL_PATH)/crypto/x509v3/pcy_tree.c - $(OPENSSL_PATH)/crypto/x509v3/v3_addr.c - $(OPENSSL_PATH)/crypto/x509v3/v3_admis.c - $(OPENSSL_PATH)/crypto/x509v3/v3_akey.c - $(OPENSSL_PATH)/crypto/x509v3/v3_akeya.c - $(OPENSSL_PATH)/crypto/x509v3/v3_alt.c - $(OPENSSL_PATH)/crypto/x509v3/v3_asid.c - $(OPENSSL_PATH)/crypto/x509v3/v3_bcons.c - $(OPENSSL_PATH)/crypto/x509v3/v3_bitst.c - $(OPENSSL_PATH)/crypto/x509v3/v3_conf.c - $(OPENSSL_PATH)/crypto/x509v3/v3_cpols.c - $(OPENSSL_PATH)/crypto/x509v3/v3_crld.c - $(OPENSSL_PATH)/crypto/x509v3/v3_enum.c - $(OPENSSL_PATH)/crypto/x509v3/v3_extku.c - $(OPENSSL_PATH)/crypto/x509v3/v3_genn.c - $(OPENSSL_PATH)/crypto/x509v3/v3_ia5.c - $(OPENSSL_PATH)/crypto/x509v3/v3_info.c - $(OPENSSL_PATH)/crypto/x509v3/v3_int.c - $(OPENSSL_PATH)/crypto/x509v3/v3_lib.c - $(OPENSSL_PATH)/crypto/x509v3/v3_ncons.c - $(OPENSSL_PATH)/crypto/x509v3/v3_pci.c - $(OPENSSL_PATH)/crypto/x509v3/v3_pcia.c - $(OPENSSL_PATH)/crypto/x509v3/v3_pcons.c - $(OPENSSL_PATH)/crypto/x509v3/v3_pku.c - $(OPENSSL_PATH)/crypto/x509v3/v3_pmaps.c - $(OPENSSL_PATH)/crypto/x509v3/v3_prn.c - $(OPENSSL_PATH)/crypto/x509v3/v3_purp.c - $(OPENSSL_PATH)/crypto/x509v3/v3_skey.c - $(OPENSSL_PATH)/crypto/x509v3/v3_sxnet.c - $(OPENSSL_PATH)/crypto/x509v3/v3_tlsf.c - $(OPENSSL_PATH)/crypto/x509v3/v3_utl.c - $(OPENSSL_PATH)/crypto/x509v3/v3err.c - $(OPENSSL_PATH)/crypto/arm_arch.h - $(OPENSSL_PATH)/crypto/mips_arch.h - $(OPENSSL_PATH)/crypto/ppc_arch.h - $(OPENSSL_PATH)/crypto/s390x_arch.h - $(OPENSSL_PATH)/crypto/sparc_arch.h - $(OPENSSL_PATH)/crypto/vms_rms.h - $(OPENSSL_PATH)/crypto/aes/aes_local.h - $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h - $(OPENSSL_PATH)/crypto/asn1/asn1_local.h - $(OPENSSL_PATH)/crypto/asn1/charmap.h - $(OPENSSL_PATH)/crypto/asn1/standard_methods.h - $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h - $(OPENSSL_PATH)/crypto/async/async_local.h - $(OPENSSL_PATH)/crypto/async/arch/async_null.h - $(OPENSSL_PATH)/crypto/async/arch/async_posix.h - $(OPENSSL_PATH)/crypto/async/arch/async_win.h - $(OPENSSL_PATH)/crypto/bio/bio_local.h - $(OPENSSL_PATH)/crypto/bn/bn_local.h - $(OPENSSL_PATH)/crypto/bn/bn_prime.h - $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h - $(OPENSSL_PATH)/crypto/comp/comp_local.h - $(OPENSSL_PATH)/crypto/conf/conf_def.h - $(OPENSSL_PATH)/crypto/conf/conf_local.h - $(OPENSSL_PATH)/crypto/dh/dh_local.h - $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/field.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/word.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - $(OPENSSL_PATH)/crypto/evp/evp_local.h - $(OPENSSL_PATH)/crypto/hmac/hmac_local.h - $(OPENSSL_PATH)/crypto/lhash/lhash_local.h - $(OPENSSL_PATH)/crypto/md5/md5_local.h - $(OPENSSL_PATH)/crypto/modes/modes_local.h - $(OPENSSL_PATH)/crypto/objects/obj_dat.h - $(OPENSSL_PATH)/crypto/objects/obj_local.h - $(OPENSSL_PATH)/crypto/objects/obj_xref.h - $(OPENSSL_PATH)/crypto/ocsp/ocsp_local.h - $(OPENSSL_PATH)/crypto/pkcs12/p12_local.h - $(OPENSSL_PATH)/crypto/rand/rand_local.h - $(OPENSSL_PATH)/crypto/rsa/rsa_local.h - $(OPENSSL_PATH)/crypto/sha/sha_local.h - $(OPENSSL_PATH)/crypto/siphash/siphash_local.h - $(OPENSSL_PATH)/crypto/sm3/sm3_local.h - $(OPENSSL_PATH)/crypto/store/store_local.h - $(OPENSSL_PATH)/crypto/ui/ui_local.h - $(OPENSSL_PATH)/crypto/x509/x509_local.h - $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h - $(OPENSSL_PATH)/crypto/x509v3/pcy_local.h - $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h - $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h - $(OPENSSL_PATH)/ssl/bio_ssl.c - $(OPENSSL_PATH)/ssl/d1_lib.c - $(OPENSSL_PATH)/ssl/d1_msg.c - $(OPENSSL_PATH)/ssl/d1_srtp.c - $(OPENSSL_PATH)/ssl/methods.c - $(OPENSSL_PATH)/ssl/packet.c - $(OPENSSL_PATH)/ssl/pqueue.c - $(OPENSSL_PATH)/ssl/record/dtls1_bitmap.c - $(OPENSSL_PATH)/ssl/record/rec_layer_d1.c - $(OPENSSL_PATH)/ssl/record/rec_layer_s3.c - $(OPENSSL_PATH)/ssl/record/ssl3_buffer.c - $(OPENSSL_PATH)/ssl/record/ssl3_record.c - $(OPENSSL_PATH)/ssl/record/ssl3_record_tls13.c - $(OPENSSL_PATH)/ssl/s3_cbc.c - $(OPENSSL_PATH)/ssl/s3_enc.c - $(OPENSSL_PATH)/ssl/s3_lib.c - $(OPENSSL_PATH)/ssl/s3_msg.c - $(OPENSSL_PATH)/ssl/ssl_asn1.c - $(OPENSSL_PATH)/ssl/ssl_cert.c - $(OPENSSL_PATH)/ssl/ssl_ciph.c - $(OPENSSL_PATH)/ssl/ssl_conf.c - $(OPENSSL_PATH)/ssl/ssl_err.c - $(OPENSSL_PATH)/ssl/ssl_init.c - $(OPENSSL_PATH)/ssl/ssl_lib.c - $(OPENSSL_PATH)/ssl/ssl_mcnf.c - $(OPENSSL_PATH)/ssl/ssl_rsa.c - $(OPENSSL_PATH)/ssl/ssl_sess.c - $(OPENSSL_PATH)/ssl/ssl_stat.c - $(OPENSSL_PATH)/ssl/ssl_txt.c - $(OPENSSL_PATH)/ssl/ssl_utst.c - $(OPENSSL_PATH)/ssl/statem/extensions.c - $(OPENSSL_PATH)/ssl/statem/extensions_clnt.c - $(OPENSSL_PATH)/ssl/statem/extensions_cust.c - $(OPENSSL_PATH)/ssl/statem/extensions_srvr.c - $(OPENSSL_PATH)/ssl/statem/statem.c - $(OPENSSL_PATH)/ssl/statem/statem_clnt.c - $(OPENSSL_PATH)/ssl/statem/statem_dtls.c - $(OPENSSL_PATH)/ssl/statem/statem_lib.c - $(OPENSSL_PATH)/ssl/statem/statem_srvr.c - $(OPENSSL_PATH)/ssl/t1_enc.c - $(OPENSSL_PATH)/ssl/t1_lib.c - $(OPENSSL_PATH)/ssl/t1_trce.c - $(OPENSSL_PATH)/ssl/tls13_enc.c - $(OPENSSL_PATH)/ssl/tls_srp.c - $(OPENSSL_PATH)/ssl/packet_local.h - $(OPENSSL_PATH)/ssl/ssl_cert_table.h - $(OPENSSL_PATH)/ssl/ssl_local.h - $(OPENSSL_PATH)/ssl/record/record.h - $(OPENSSL_PATH)/ssl/record/record_local.h - $(OPENSSL_PATH)/ssl/statem/statem.h - $(OPENSSL_PATH)/ssl/statem/statem_local.h -# Autogenerated files list ends here - buildinf.h - ossl_store.c - rand_pool.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - RngLib - PrintLib - -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled ## CONSUMES - -[BuildOptions] - # - # Disables the following Visual Studio compiler warnings brought by openssl source, - # so we do not break the build with /WX option: - # C4090: 'function' : different 'const' qualifiers - # C4132: 'object' : const object should be initialized (tls13_enc.c) - # C4210: nonstandard extension used: function given file scope - # C4244: conversion from type1 to type2, possible loss of data - # C4245: conversion from type1 to type2, signed/unsigned mismatch - # C4267: conversion from size_t to type, possible loss of data - # C4306: 'identifier' : conversion from 'type1' to 'type2' of greater size - # C4310: cast truncates constant value - # C4389: 'operator' : signed/unsigned mismatch (xxxx) - # C4700: uninitialized local variable 'name' used. (conf_sap.c(71)) - # C4702: unreachable code - # C4706: assignment within conditional expression - # C4819: The file contains a character that cannot be represented in the current code page - # - MSFT:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /wd4090 /wd4132 /wd4210 /wd4244 /wd4245 /wd4267 /wd4310 /wd4389 /wd4700 /wd4702 /wd4706 /wd4819 - - INTEL:*_*_IA32_CC_FLAGS = -U_WIN32 -U_WIN64 -U_MSC_VER -U__ICC $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) /w - - # - # Suppress the following build warnings in openssl so we don't break the build with -Werror - # -Werror=maybe-uninitialized: there exist some other paths for which the variable is not initialized. - # -Werror=format: Check calls to printf and scanf, etc., to make sure that the arguments supplied have - # types appropriate to the format string specified. - # -Werror=unused-but-set-variable: Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). - # - GCC:*_*_IA32_CC_FLAGS = -UWIN32 -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -Wno-error=maybe-uninitialized -Wno-error=unused-but-set-variable - - # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: - # 1295: Deprecated declaration - give arg types - # 550: was set but never used - # 1293: assignment in condition - # 111: statement is unreachable (invariably "break;" after "return X;" in case statement) - # 68: integer conversion resulted in a change of sign ("if (Status == -1)") - # 177: was declared but never referenced - # 223: function declared implicitly - # 144: a value of type cannot be used to initialize an entity of type - # 513: a value of type cannot be assigned to an entity of type - # 188: enumerated type mixed with another type (i.e. passing an integer as an enum without a cast) - # 1296: Extended constant initialiser used - # 128: loop is not reachable - may be emitted inappropriately if code follows a conditional return - # from the function that evaluates to true at compile time - # 546: transfer of control bypasses initialization - may be emitted inappropriately if the uninitialized - # variable is never referenced after the jump - # 1: ignore "#1-D: last line of file ends without a newline" - # 3017: may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with - # commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.) - XCODE:*_*_IA32_CC_FLAGS = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) $(OPENSSL_FLAGS_CONFIG) -w -std=c99 -Wno-error=uninitialized From 46f56ef631d580fdf8aebdced4523b98cfcdd835 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 30 Sep 2022 14:05:21 -0700 Subject: [PATCH 0197/1529] CryptoPkg/Library/OpensslLib: Produce consistent set of APIs Update all OpensslLib instances so they produce all the APIs used by the BaseCryptLib instances. Not producing the same set of APIs for a library class does not follow the EDK II library class rules and breaks the assumptions that consumers of the OpensslLib may make about which services are present. * Add missing declaration of the private library class OpensslLib to CryptoPkg.dec. * Add SslNull.c with NULL implementations of SSL functions * Add EcSm2Null.c with NULL implementations of EC/SM2 functions. * Update OpensslLibCrypto.inf to include both SslNull.c and EcSm2Null.c so this library instance produces all the opensll APIs used by the BaseCryptLib instances. * Update OpensslLib.inf and OpensslLibAccel.inf to include EcSm2Null.c so these library instances produce all the opensll APIs used by the BaseCryptLib instances. * Add missing declaration of the private library class IntrinsicLib to CryptoPkg.dec Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dec | 9 + CryptoPkg/Library/OpensslLib/EcSm2Null.c | 383 +++++++++++++++++ CryptoPkg/Library/OpensslLib/OpensslLib.inf | 2 + .../Library/OpensslLib/OpensslLibAccel.inf | 2 + .../Library/OpensslLib/OpensslLibCrypto.inf | 2 + .../Library/OpensslLib/OpensslLibFull.inf | 2 + .../OpensslLib/OpensslLibFullAccel.inf | 2 + CryptoPkg/Library/OpensslLib/SslNull.c | 405 ++++++++++++++++++ CryptoPkg/Private/Library/IntrinsicLib.h | 16 + CryptoPkg/Private/Library/OpensslLib.h | 14 + 10 files changed, 837 insertions(+) create mode 100644 CryptoPkg/Library/OpensslLib/EcSm2Null.c create mode 100644 CryptoPkg/Library/OpensslLib/SslNull.c create mode 100644 CryptoPkg/Private/Library/IntrinsicLib.h create mode 100644 CryptoPkg/Private/Library/OpensslLib.h diff --git a/CryptoPkg/CryptoPkg.dec b/CryptoPkg/CryptoPkg.dec index 217e73c3bc..f326c63240 100644 --- a/CryptoPkg/CryptoPkg.dec +++ b/CryptoPkg/CryptoPkg.dec @@ -37,6 +37,15 @@ # HashApiLib|Include/Library/HashApiLib.h +[LibraryClasses.common.Private] + ## @libraryclass Provides library functions from the openssl project. + # + OpensslLib|Private/Library/OpensslLib.h + + ## @libraryclass Provides compiler intrinsic functions required to link openssl project. + # + InstrinsicLib|Private/Library/IntrinsicLib.h + [Protocols] ## EDK II Crypto DXE protocol # 2C2275C9-3A7B-426F-BE54-2D22BD9D1092 diff --git a/CryptoPkg/Library/OpensslLib/EcSm2Null.c b/CryptoPkg/Library/OpensslLib/EcSm2Null.c new file mode 100644 index 0000000000..6d5ab2d4cc --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/EcSm2Null.c @@ -0,0 +1,383 @@ +/** @file + Null implementation of EC and SM2 functions called by BaseCryptLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +#undef OPENSSL_NO_EC + +#include +#include +#include +#include + +void +EC_GROUP_free ( + EC_GROUP *group + ) +{ + ASSERT (FALSE); +} + +int +EC_GROUP_get_order ( + const EC_GROUP *group, + BIGNUM *order, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_GROUP_get_curve_name ( + const EC_GROUP *group + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_GROUP_get_curve ( + const EC_GROUP *group, + BIGNUM *p, + BIGNUM *a, + BIGNUM *b, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_GROUP_get_degree ( + const EC_GROUP *group + ) +{ + ASSERT (FALSE); + return 0; +} + +EC_GROUP * +EC_GROUP_new_by_curve_name ( + int nid + ) +{ + ASSERT (FALSE); + return NULL; +} + +EC_POINT * +EC_POINT_new ( + const EC_GROUP *group + ) +{ + ASSERT (FALSE); + return NULL; +} + +void +EC_POINT_free ( + EC_POINT *point + ) +{ + ASSERT (FALSE); +} + +void +EC_POINT_clear_free ( + EC_POINT *point + ) +{ + ASSERT (FALSE); +} + +int +EC_POINT_set_affine_coordinates ( + const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + const BIGNUM *y, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_get_affine_coordinates ( + const EC_GROUP *group, + const EC_POINT *p, + BIGNUM *x, + BIGNUM *y, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_set_compressed_coordinates ( + const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + int y_bit, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_add ( + const EC_GROUP *group, + EC_POINT *r, + const EC_POINT *a, + const EC_POINT *b, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_invert ( + const EC_GROUP *group, + EC_POINT *a, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_is_at_infinity ( + const EC_GROUP *group, + const EC_POINT *p + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_POINT_is_on_curve ( + const EC_GROUP *group, + const EC_POINT *point, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return -1; +} + +int +EC_POINT_cmp ( + const EC_GROUP *group, + const EC_POINT *a, + const EC_POINT *b, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return -1; +} + +int +EC_POINT_mul ( + const EC_GROUP *group, + EC_POINT *r, + const BIGNUM *n, + const EC_POINT *q, + const BIGNUM *m, + BN_CTX *ctx + ) +{ + ASSERT (FALSE); + return -0; +} + +EC_KEY * +EC_KEY_new_by_curve_name ( + int nid + ) +{ + ASSERT (FALSE); + return NULL; +} + +void +EC_KEY_free ( + EC_KEY *key + ) +{ + ASSERT (FALSE); +} + +EC_KEY * +EC_KEY_dup ( + const EC_KEY *src + ) +{ + ASSERT (FALSE); + return NULL; +} + +const EC_GROUP * +EC_KEY_get0_group ( + const EC_KEY *key + ) +{ + ASSERT (FALSE); + return NULL; +} + +const EC_POINT * +EC_KEY_get0_public_key ( + const EC_KEY *key + ) +{ + ASSERT (FALSE); + return NULL; +} + +int +EC_KEY_set_public_key ( + EC_KEY *key, + const EC_POINT *pub + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_KEY_generate_key ( + EC_KEY *key + ) +{ + ASSERT (FALSE); + return 0; +} + +int +EC_KEY_check_key ( + const EC_KEY *key + ) +{ + ASSERT (FALSE); + return 0; +} + +int +ECDH_compute_key ( + void *out, + size_t outlen, + const EC_POINT *pub_key, + const EC_KEY *ecdh, + void *(*KDF)( + const void *in, + size_t inlen, + void *out, + size_t *outlen + ) + ) +{ + ASSERT (FALSE); + return 0; +} + +struct ec_key_st * +EVP_PKEY_get0_EC_KEY ( + EVP_PKEY *pkey + ) +{ + ASSERT (FALSE); + return NULL; +} + +EC_KEY * +PEM_read_bio_ECPrivateKey ( + BIO *bp, + EC_KEY **key, + pem_password_cb *cb, + void *u + ) +{ + ASSERT (FALSE); + return NULL; +} + +ECDSA_SIG * +ECDSA_SIG_new ( + void + ) +{ + ASSERT (FALSE); + return NULL; +} + +void +ECDSA_SIG_free ( + ECDSA_SIG *sig + ) +{ + ASSERT (FALSE); +} + +void +ECDSA_SIG_get0 ( + const ECDSA_SIG *sig, + const BIGNUM **pr, + const BIGNUM **ps + ) +{ + ASSERT (FALSE); +} + +int +ECDSA_SIG_set0 ( + ECDSA_SIG *sig, + BIGNUM *r, + BIGNUM *s + ) +{ + return 0; + ASSERT (FALSE); +} + +ECDSA_SIG * +ECDSA_do_sign ( + const unsigned char *dgst, + int dgst_len, + EC_KEY *eckey + ) +{ + ASSERT (FALSE); + return NULL; +} + +int +ECDSA_do_verify ( + const unsigned char *dgst, + int dgst_len, + const ECDSA_SIG *sig, + EC_KEY *eckey + ) +{ + ASSERT (FALSE); + return -1; +} diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 25f4f1635e..615cd37573 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -628,6 +628,8 @@ buildinf.h ossl_store.c rand_pool.c +# SslNull.c + EcSm2Null.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 6d43556a40..de3974885b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -629,6 +629,8 @@ buildinf.h ossl_store.c rand_pool.c +# SslNull.c + EcSm2Null.c [Sources.IA32] IA32/crypto/aes/aesni-x86.nasm | MSFT diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index 3e344f8515..dbb216437c 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -629,6 +629,8 @@ buildinf.h ossl_store.c rand_pool.c + SslNull.c + EcSm2Null.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index c3b78a448a..46794e4796 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -633,6 +633,8 @@ buildinf.h ossl_store.c rand_pool.c +# SslNull.c +# EcSm2Null.c [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index ec53a5911b..2a7aff30d7 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -634,6 +634,8 @@ buildinf.h ossl_store.c rand_pool.c +# SslNull.c +# EcSm2Null.c [Sources.IA32] IA32/crypto/aes/aesni-x86.nasm | MSFT diff --git a/CryptoPkg/Library/OpensslLib/SslNull.c b/CryptoPkg/Library/OpensslLib/SslNull.c new file mode 100644 index 0000000000..49f1405bc0 --- /dev/null +++ b/CryptoPkg/Library/OpensslLib/SslNull.c @@ -0,0 +1,405 @@ +/** @file + Null implementation of SSL functions called by BaseCryptLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +int +OPENSSL_init_ssl ( + uint64_t opts, + const OPENSSL_INIT_SETTINGS *settings + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur uint32_t +SSL_CIPHER_get_id ( + const SSL_CIPHER *c + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_COMP_add_compression_method ( + int id, + COMP_METHOD *cm + ) +{ + ASSERT (FALSE); + return 0; +} + +long +SSL_CTX_ctrl ( + SSL_CTX *ctx, + int cmd, + long larg, + void *parg + ) +{ + ASSERT (FALSE); + return 0; +} + +void +SSL_CTX_free ( + SSL_CTX *x + ) +{ + ASSERT (FALSE); + return; +} + +__owur X509_STORE * +SSL_CTX_get_cert_store ( + const SSL_CTX *x + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur SSL_CTX * +SSL_CTX_new ( + const SSL_METHOD *meth + ) +{ + ASSERT (FALSE); + return NULL; +} + +unsigned long +SSL_CTX_set_options ( + SSL_CTX *ctx, + unsigned long op + ) +{ + ASSERT (FALSE); + return 0; +} + +const unsigned char * +SSL_SESSION_get_id ( + const SSL_SESSION *s, + unsigned int *len + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur size_t +SSL_SESSION_get_master_key ( + const SSL_SESSION *sess, + unsigned char *out, + size_t outlen + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_SESSION_set1_id ( + SSL_SESSION *s, + const unsigned char *sid, + unsigned int sid_len + ) +{ + ASSERT (FALSE); + return 0; +} + +long +SSL_ctrl ( + SSL *ssl, + int cmd, + long larg, + void *parg + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_do_handshake ( + SSL *s + ) +{ + ASSERT (FALSE); + return 0; +} + +void +SSL_free ( + SSL *ssl + ) +{ + ASSERT (FALSE); + return; +} + +__owur X509 * +SSL_get_certificate ( + const SSL *ssl + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur size_t +SSL_get_client_random ( + const SSL *ssl, + unsigned char *out, + size_t outlen + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur const SSL_CIPHER * +SSL_get_current_cipher ( + const SSL *s + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur int +SSL_get_error ( + const SSL *s, + int ret_code + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur size_t +SSL_get_server_random ( + const SSL *ssl, + unsigned char *out, + size_t outlen + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur SSL_SESSION * +SSL_get_session ( + const SSL *ssl + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur SSL_CTX * +SSL_get_SSL_CTX ( + const SSL *ssl + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur OSSL_HANDSHAKE_STATE +SSL_get_state ( + const SSL *ssl + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_get_verify_mode ( + const SSL *s + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur X509_VERIFY_PARAM * +SSL_get0_param ( + SSL *ssl + ) +{ + ASSERT (FALSE); + return NULL; +} + +int +SSL_is_init_finished ( + const SSL *s + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_is_server ( + const SSL *s + ) +{ + ASSERT (FALSE); + return 0; +} + +SSL * +SSL_new ( + SSL_CTX *ctx + ) +{ + ASSERT (FALSE); + return NULL; +} + +__owur int +SSL_read ( + SSL *ssl, + void *buf, + int num + ) +{ + ASSERT (FALSE); + return 0; +} + +void +SSL_set_bio ( + SSL *s, + BIO *rbio, + BIO *wbio + ) +{ + ASSERT (FALSE); + return; +} + +__owur int +SSL_set_cipher_list ( + SSL *s, + const char *str + ) +{ + ASSERT (FALSE); + return 0; +} + +void +SSL_set_connect_state ( + SSL *s + ) +{ + ASSERT (FALSE); + return; +} + +void +SSL_set_hostflags ( + SSL *s, + unsigned int flags + ) +{ + ASSERT (FALSE); + return; +} + +void +SSL_set_info_callback ( + SSL *ssl, + void ( *cb )(const SSL *ssl, int type, int val) + ) +{ + ASSERT (FALSE); + return; +} + +void +SSL_set_security_level ( + SSL *s, + int level + ) +{ + ASSERT (FALSE); + return; +} + +void +SSL_set_verify ( + SSL *s, + int mode, + SSL_verify_cb callback + ) +{ + ASSERT (FALSE); + return; +} + +int +SSL_shutdown ( + SSL *s + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_use_certificate ( + SSL *ssl, + X509 *x + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_version ( + const SSL *ssl + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur int +SSL_write ( + SSL *ssl, + const void *buf, + int num + ) +{ + ASSERT (FALSE); + return 0; +} + +__owur const SSL_METHOD * +TLS_client_method ( + void + ) +{ + ASSERT (FALSE); + return NULL; +} diff --git a/CryptoPkg/Private/Library/IntrinsicLib.h b/CryptoPkg/Private/Library/IntrinsicLib.h new file mode 100644 index 0000000000..69172a0419 --- /dev/null +++ b/CryptoPkg/Private/Library/IntrinsicLib.h @@ -0,0 +1,16 @@ +/** @file + InstrinsicLib class with intrinsic APIs generated by compilers. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef INTRINSTIC_LIB_H_ +#define INTRINSTIC_LIB_H_ + +// +// Compiler dependent intrinsic APIs. +// + +#endif diff --git a/CryptoPkg/Private/Library/OpensslLib.h b/CryptoPkg/Private/Library/OpensslLib.h new file mode 100644 index 0000000000..005eb84872 --- /dev/null +++ b/CryptoPkg/Private/Library/OpensslLib.h @@ -0,0 +1,14 @@ +/** @file + OpensslLib class with APIs from the openssl project + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef OPENSSL_LIB_H_ +#define OPENSSL_LIB_H_ + +#include + +#endif From 5aeff52ecb36aeb336b4e536dd8eae6cc82f1db6 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 4 Oct 2022 16:48:24 -0700 Subject: [PATCH 0198/1529] CryptoPkg/Library/OpensslLib: Remove PrintLib from INF files The OpensslLib instances do not directly use any PrintLib services. Remove PrintLib from [LibraryClasses] sections of all OpensslLib INF files. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 1 - CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf | 1 - CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf | 1 - CryptoPkg/Library/OpensslLib/OpensslLibFull.inf | 1 - CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf | 1 - 5 files changed, 5 deletions(-) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 615cd37573..82ffe4ec2f 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -639,7 +639,6 @@ BaseLib DebugLib RngLib - PrintLib [LibraryClasses.ARM] ArmSoftFloatLib diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index de3974885b..32eae4a792 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -687,7 +687,6 @@ BaseLib DebugLib RngLib - PrintLib [BuildOptions] # diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index dbb216437c..d02769428b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -640,7 +640,6 @@ BaseLib DebugLib RngLib - PrintLib [LibraryClasses.ARM] ArmSoftFloatLib diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index 46794e4796..aa73265931 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -644,7 +644,6 @@ BaseLib DebugLib RngLib - PrintLib [LibraryClasses.ARM] ArmSoftFloatLib diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 2a7aff30d7..6345b54bca 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -692,7 +692,6 @@ BaseLib DebugLib RngLib - PrintLib [BuildOptions] # From 4e943750f9136044a05c843eccbd4ff31e3ef2fe Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 4 Oct 2022 17:57:18 -0700 Subject: [PATCH 0199/1529] CryptoPkg: Remove PcdOpensslEcEnabled from CryptoPkg.dec Remove the PcdOpensslEcEnabled PCD that is no longer used. The EC feature is selected by using one of the OpensslLib instances that includes the EC features which are either OpensslLibFull.inf or OpensslLibFullAccel.inf. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dec | 33 --------------------------------- 1 file changed, 33 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dec b/CryptoPkg/CryptoPkg.dec index f326c63240..e20a5e9c38 100644 --- a/CryptoPkg/CryptoPkg.dec +++ b/CryptoPkg/CryptoPkg.dec @@ -90,38 +90,5 @@ # @ValidList 0x80000001 | 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010 gEfiCryptoPkgTokenSpaceGuid.PcdHashApiLibPolicy|0x00000002|UINT32|0x00000001 - ## Enable/Disable the ECC feature in openssl library. The default is disabled. - # If ECC feature is disabled, all related source files will not be compiled. - # @Prompt Enable/Disable ECC feature in openssl library - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled|FALSE|BOOLEAN|0x0000003 - # Set it to TRUE if: - # 1) Platform needs ECC in TLS, or asymmetric cryptography services such as - # X509 certificate or PEM format data processing. - # 2) Platform needs to enable PcdCryptoServiceFamilyEnable.Ec service. - # Please note: - # ECC feature will cause a significant memory increase, approximate memory impact - # in below table for reference by platform developers with FW size limitations. - # Uncompressed LZMA Compressed - # CPU CRYPTO_SERVICES Module EC=FALSE EC=TRUE EC=FALSE EC=TRUE Increase - # ==== =============== ======== ======== ======= ======== ======= ======== - # IA32 NONE CryptoPei 21536 21568 0 KB - # IA32 NONE CryptoDxe 21632 21696 0 KB - # IA32 NONE CryptoSmm 22976 23072 0 KB - # IA32 MIN_PEI CryptoPei 248992 249120 0 KB - # IA32 MIN_DXE_MIN_SMM CryptoDxe 636672 829568 288520 401034 113 KB - # IA32 MIN_DXE_MIN_SMM CryptoSmm 426048 601472 191517 296022 105 KB - # IA32 ALL CryptoPei 423840 598976 189047 293759 104 KB - # IA32 ALL CryptoDxe 645280 838144 292955 405277 113 KB - # IA32 ALL CryptoSmm 441888 617184 198779 303628 105 KB - # X64 NONE CryptoPei 29632 29664 0 KB - # X64 NONE CryptoDxe 29792 29792 0 KB - # X64 NONE CryptoSmm 31296 31296 0 KB - # X64 MIN_PEI CryptoPei 310784 310848 0 KB - # X64 MIN_DXE_MIN_SMM CryptoDxe 804288 1016256 311436 426596 115 KB - # X64 MIN_DXE_MIN_SMM CryptoSmm 543776 733920 204483 310775 106 KB - # X64 ALL CryptoPei 540384 730240 202494 308467 106 KB - # X64 ALL CryptoDxe 815392 1027296 316228 431321 115 KB - # X64 ALL CryptoSmm 563648 753696 213488 319644 106 KB - [UserExtensions.TianoCore."ExtraFiles"] CryptoPkgExtra.uni From 76ae40ba9d6168385beadabedf6bc2ec131c1596 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 4 Oct 2022 17:36:41 -0700 Subject: [PATCH 0200/1529] CryptoPkg: Update DSC to improve CI test coverage With the addition of EC services and performance optimized versions of the OpensslLib for IA32/X64, the CryptoPkg.dsc file is updated to make sure all combinations are covered in CI builds. * Use different output directory for each CRYPTO_SERVICES profile. * Add FILE_GUID define names for CryptoPei, CryptoDxe, and CryptoSmm when they are linked with different OpensslLib instances. * Update CryptoPei, CryptoDxe, CryptoSmm builds to include all combinations of OpensslLib library instances supported by each CPU architecture. * Add TARGET_UINT_TESTS profile to CryptoPkg.dsc to build only the target-based unit tests. This reduces the size of CryptoPkg components not related to unit testing by removing unit test specific assert handlers. Build target-based unit tests using OpensslLibFull.inf and OpensslLibFullAccel.inf. * Remove the PACKAGE profile and instead make the ALL profile the default for CI testing that enables all services for all modules. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 428 ++++++++++++++++++++++++++++++++-------- 1 file changed, 345 insertions(+), 83 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 032b9e6377..3b245979c3 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -19,17 +19,14 @@ PLATFORM_GUID = E1063286-6C8C-4c25-AEF0-67A9A5B6E6B6 PLATFORM_VERSION = 0.98 DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/CryptoPkg SUPPORTED_ARCHITECTURES = IA32|X64|ARM|AARCH64|RISCV64|LOONGARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT # # Flavor of PEI, DXE, SMM modules to build. - # Must be one of ALL, NONE, MIN_PEI, MIN_DXE_MIN_SMM. + # Must be one of ALL, NONE, MIN_PEI, MIN_DXE_MIN_SMM, TARGET_UINT_TESTS. # Default is ALL that is used for package build verification. - # PACKAGE - Package verification build of all components. Null - # versions of libraries are used to minimize build times. # ALL - Build PEIM, DXE, and SMM drivers. Protocols and PPIs # publish all services. # NONE - Build PEIM, DXE, and SMM drivers. Protocols and PPIs @@ -39,14 +36,56 @@ # services. # MIN_DXE_MIN_SMM - Build DXE and SMM drivers with Protocols that publish # minimum required services. + # TARGET_UNIT_TESTS - Build target-based unit tests # - DEFINE CRYPTO_SERVICES = PACKAGE -!if $(CRYPTO_SERVICES) IN "PACKAGE ALL NONE MIN_PEI MIN_DXE_MIN_SMM" + DEFINE CRYPTO_SERVICES = ALL +!if $(CRYPTO_SERVICES) IN "ALL NONE MIN_PEI MIN_DXE_MIN_SMM TARGET_UNIT_TESTS" !else - !error CRYPTO_SERVICES must be set to one of PACKAGE ALL NONE MIN_PEI MIN_DXE_MIN_SMM. + !error CRYPTO_SERVICES must be set to one of ALL NONE MIN_PEI MIN_DXE_MIN_SMM TARGET_UNIT_TESTS. !endif +# +# Define different OUTPUT_DIRECTORY for each CRYPTO_SERVICES profile +# +!if $(CRYPTO_SERVICES) == ALL + OUTPUT_DIRECTORY = Build/CryptoPkg/All +!endif +!if $(CRYPTO_SERVICES) == NONE + OUTPUT_DIRECTORY = Build/CryptoPkg/None +!endif +!if $(CRYPTO_SERVICES) == MIN_PEI + OUTPUT_DIRECTORY = Build/CryptoPkg/MinPei +!endif +!if $(CRYPTO_SERVICES) == MIN_DXE_MIN_SMM + OUTPUT_DIRECTORY = Build/CryptoPkg/MinDxeMinSmm +!endif +!if $(CRYPTO_SERVICES) == TARGET_UNIT_TESTS + OUTPUT_DIRECTORY = Build/CryptoPkg/TagetUnitTests +!endif + +# +# Define FILE_GUID names/values for CryptoPei, CryptopDxe, and CryptoSmm +# drivers that are linked with different OpensslLib instances +# + DEFINE PEI_CRYPTO_GUID = C693A250-6B36-49B9-B7F3-7283F8136A72 + DEFINE PEI_STD_GUID = EBD49F5C-6D8B-40D1-A56D-9AFA485A8661 + DEFINE PEI_FULL_GUID = D51FCE59-6860-49C0-9B35-984470735D17 + DEFINE PEI_STD_ACCEL_GUID = DCC9CB49-7BE2-47C6-864E-6DCC932360F9 + DEFINE PEI_FULL_ACCEL_GUID = A10827AD-7598-4955-B661-52EE2B62B057 + DEFINE DXE_CRYPTO_GUID = 31C17C54-325D-47D5-8622-888098F10E44 + DEFINE DXE_STD_GUID = ADD6D05A-52A2-437B-98E7-DBFDA89352CD + DEFINE DXE_FULL_GUID = AA83B296-F6EA-447F-B013-E80E98629CF8 + DEFINE DXE_STD_ACCEL_GUID = 9FBDAD27-910C-4229-9EFF-A93BB5FE18C6 + DEFINE DXE_FULL_ACCEL_GUID = 41A491D1-A972-468B-A299-DABF415A43B7 + DEFINE SMM_CRYPTO_GUID = 1A1C9E13-5722-4636-AB73-31328EDE8BAF + DEFINE SMM_STD_GUID = E4D7D1E3-E886-4412-A442-EFD6F2502DD3 + DEFINE SMM_FULL_GUID = 1930CE7E-6598-48ED-8AB1-EBE7E85EC254 + DEFINE SMM_STD_ACCEL_GUID = 828959D3-CEA6-4B79-B1FC-5AFA0D7F2144 + DEFINE SMM_FULL_ACCEL_GUID = C1760694-AB3A-4532-8C6D-52D8F86EB1AA + +!if $(CRYPTO_SERVICES) == TARGET_UNIT_TESTS !include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc +!endif ################################################################################ # @@ -59,17 +98,24 @@ [LibraryClasses] BaseLib|MdePkg/Library/BaseLib/BaseLib.inf BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf - UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf - UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf - BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf - TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf - HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf - RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf + TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf + RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + +[LibraryClasses.IA32, LibraryClasses.X64, LibraryClasses.AARCH64] + RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf [LibraryClasses.ARM, LibraryClasses.AARCH64] + ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf # # It is not possible to prevent the ARM compiler for generic intrinsic functions. # This library provides the instrinsic functions generate by a given compiler. @@ -81,41 +127,19 @@ # Add support for stack protector NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf -[LibraryClasses.common.PEIM] - PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf - MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf - PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf - PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf - HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf - -[LibraryClasses.common.DXE_SMM_DRIVER] - SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf - MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf - MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf - -!if $(CRYPTO_SERVICES) IN "ALL NONE MIN_PEI MIN_DXE_MIN_SMM" -[LibraryClasses] - MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf - DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf - DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf - OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf - TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf - UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf #??? - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf #??? - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf - IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf - SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - [LibraryClasses.ARM] ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf [LibraryClasses.common.SEC] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf [LibraryClasses.common.PEIM] + PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf + PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -124,19 +148,34 @@ [LibraryClasses.IA32.PEIM, LibraryClasses.X64.PEIM] PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf -[LibraryClasses.ARM.PEIM, LibraryClasses.AARCH64.PEIM] - PeiServicesTablePointerLib|ArmPkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf - [LibraryClasses.common.DXE_DRIVER] + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf [LibraryClasses.common.DXE_SMM_DRIVER] + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf + MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf + MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf + PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf -!endif + +[LibraryClasses.common.UEFI_APPLICATION] + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf ################################################################################ # @@ -148,7 +187,12 @@ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000 gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x06 -!if $(CRYPTO_SERVICES) IN "PACKAGE ALL" +# +# For ALL and TARGET_UINT_TESTS profiles, enable all non-deprecated families +# and services in PcdCryptoServiceFamilyEnable. +# +!if $(CRYPTO_SERVICES) IN "ALL TARGET_UINT_TESTS" +[PcdsFixedAtBuild] gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -177,7 +221,12 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Ec.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif +# +# Enable minimum set of families/services in PcdCryptoServiceFamilyEnable +# required by typical PEI phase. +# !if $(CRYPTO_SERVICES) == MIN_PEI +[PcdsFixedAtBuild] gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY @@ -192,7 +241,12 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE !endif +# +# Enable minimum set of families/services in PcdCryptoServiceFamilyEnable +# required by typical DXE and SMM phases. +# !if $(CRYPTO_SERVICES) == MIN_DXE_MIN_SMM +[PcdsFixedAtBuild] gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs1v2Encrypt | TRUE @@ -244,12 +298,61 @@ # generated for it, but the binary will not be put into any firmware volume. # ################################################################################################### -[Components] - CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf -!if $(CRYPTO_SERVICES) == PACKAGE +# +# If profile is TARGET_UNIT_TESTS, then build target-based unit tests +# using the OpensslLib, BaseCryptLib, and TlsLib with the largest set of +# available services. +# +!if $(CRYPTO_SERVICES) == TARGET_UNIT_TESTS +[Components.IA32, Components.X64, Components.ARM, Components.AARCH64] + # + # Target based unit tests + # + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf { + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + + MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE + MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + MSFT:NOOPT_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + } + +[Components.IA32, Components.X64] + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf { + + FILE_GUID = B91B9A95-4D52-4501-A98F-A1711C14ED93 + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + + MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE + MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + MSFT:NOOPT_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + } + +[Components.RISCV64] + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf { + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + } +!endif + +# +# If profile is ALL, then do verification build of all library instances. +# +!if $(CRYPTO_SERVICES) == ALL [Components] + # + # Build verification of all library instances + # CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -259,59 +362,218 @@ CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf CryptoPkg/Library/TlsLib/TlsLib.inf CryptoPkg/Library/TlsLibNull/TlsLibNull.inf - CryptoPkg/Library/OpensslLib/OpensslLib.inf CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf + CryptoPkg/Library/OpensslLib/OpensslLib.inf + CryptoPkg/Library/OpensslLib/OpensslLibFull.inf CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf - CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + # + # Build verification of target-based unit tests + # + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibShell.inf { + + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + } + +[Components.IA32, Components.X64] + # + # Build verification of IA32/X64 specific libraries + # + CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf + CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf !endif -!if $(CRYPTO_SERVICES) IN "PACKAGE ALL NONE MIN_PEI" +# +# If profile is ALL or NONE or MIN_PEI, then build CryptoPei with all supported +# OpensslLib instances. +# +!if $(CRYPTO_SERVICES) in "ALL NONE MIN_PEI" +[Components] + # + # CryptoPei with OpensslLib instance without SSL or EC services + # + CryptoPkg/Driver/CryptoPei.inf { + + FILE_GUID = $(PEI_CRYPTO_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf + } + # + # CryptoPei with OpensslLib instance without EC services + # + CryptoPkg/Driver/CryptoPei.inf { + + FILE_GUID = $(PEI_STD_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + } [Components.IA32, Components.X64, Components.ARM, Components.AARCH64] + # + # CryptoPei with OpensslLib instance with all services + # + CryptoPkg/Driver/CryptoPei.inf { + + FILE_GUID = $(PEI_FULL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + } + +[Components.IA32, Components.X64] + # + # CryptoPei with IA32/X64 performance optimized OpensslLib instance without EC services + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoPei.inf { + + FILE_GUID = $(PEI_STD_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 + } + + # + # CryptoPei with IA32/X64 performance optimized OpensslLib instance all services + # IA32/X64 assembly optimizations required larger alignments + # CryptoPkg/Driver/CryptoPei.inf { - !if $(CRYPTO_SERVICES) == ALL - FILE_GUID = 8DF53C2E-3380-495F-A8B7-370CFE28E1C6 - !elseif $(CRYPTO_SERVICES) == NONE - FILE_GUID = E5A97EE3-71CC-407F-9DA9-6BE0C8A6C7DF - !elseif $(CRYPTO_SERVICES) == MIN_PEI - FILE_GUID = 0F5827A9-35FD-4F41-8D38-9BAFCE594D31 - !endif + FILE_GUID = $(PEI_FULL_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 } !endif -!if $(CRYPTO_SERVICES) IN "PACKAGE ALL NONE MIN_DXE_MIN_SMM" -[Components.IA32, Components.X64, Components.AARCH64] +# +# If profile is ALL or NONE or MIN_DXE_MIN_SMM, then build CryptoDxe and +# CryptoSmm using all supported OpensslLib instances. +# +!if $(CRYPTO_SERVICES) in "ALL NONE MIN_DXE_MIN_SMM" +[Components] + # + # CryptoDxe with OpensslLib instance with no SSL or EC services + # + CryptoPkg/Driver/CryptoDxe.inf { + + FILE_GUID = $(DXE_CRYPTO_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + } + # + # CryptoDxe with OpensslLib instance with no EC services + # + CryptoPkg/Driver/CryptoDxe.inf { + + FILE_GUID = $(DXE_STD_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + } +[Components.IA32, Components.X64, Components.ARM, Components.AARCH64] + # + # CryptoDxe with OpensslLib instance with all services + # CryptoPkg/Driver/CryptoDxe.inf { - !if $(CRYPTO_SERVICES) == ALL - FILE_GUID = D9444B06-060D-42C5-9344-F04707BE0169 - !elseif $(CRYPTO_SERVICES) == NONE - FILE_GUID = C7A340F4-A6CC-4F95-A2DA-42BEA4C3944A - !elseif $(CRYPTO_SERVICES) == MIN_DXE_MIN_SMM - FILE_GUID = DDF5BE9E-159A-4B77-B6D7-82B84B5763A2 - !endif + FILE_GUID = $(DXE_FULL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf } [Components.IA32, Components.X64] + # + # CryptoDxe with IA32/X64 performance optimized OpensslLib instance with no EC services + # with TLS feature enabled. + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoDxe.inf { + + FILE_GUID = $(DXE_STD_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 + } + # + # CryptoDxe with IA32/X64 performance optimized OpensslLib instance with all services. + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoDxe.inf { + + FILE_GUID = $(DXE_FULL_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 + } + # + # CryptoSmm with OpensslLib instance with no SSL or EC services + # + CryptoPkg/Driver/CryptoSmm.inf { + + FILE_GUID = $(SMM_CRYPTO_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf + } + # + # CryptoSmm with OpensslLib instance with no SSL services + # + CryptoPkg/Driver/CryptoSmm.inf { + + FILE_GUID = $(SMM_STD_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + } + # + # CryptoSmm with OpensslLib instance with no all services + # + CryptoPkg/Driver/CryptoSmm.inf { + + FILE_GUID = $(SMM_FULL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + } + # + # CryptoSmm with IA32/X64 performance optimized OpensslLib instance with no EC services + # IA32/X64 assembly optimizations required larger alignments + # CryptoPkg/Driver/CryptoSmm.inf { - !if $(CRYPTO_SERVICES) == ALL - FILE_GUID = A3542CE8-77F7-49DC-A834-45D37D2EC1FA - !elseif $(CRYPTO_SERVICES) == NONE - FILE_GUID = 6DCB3127-01E7-4131-A487-DC77A965A541 - !elseif $(CRYPTO_SERVICES) == MIN_DXE_MIN_SMM - FILE_GUID = 85F7EA15-3A2B-474A-8875-180542CD6BF3 - !endif + FILE_GUID = $(SMM_STD_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 + } + # + # CryptoSmm with IA32/X64 performance optimized OpensslLib instance with all services + # IA32/X64 assembly optimizations required larger alignments + # + CryptoPkg/Driver/CryptoSmm.inf { + + FILE_GUID = $(SMM_FULL_ACCEL_GUID) + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + + MSFT:*_*_IA32_DLINK_FLAGS = /ALIGN:64 + MSFT:*_*_X64_DLINK_FLAGS = /ALIGN:256 } !endif [BuildOptions] + RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES -!if $(CRYPTO_SERVICES) IN "PACKAGE ALL" - MSFT:*_*_*_CC_FLAGS = /D ENABLE_MD5_DEPRECATED_INTERFACES - INTEL:*_*_*_CC_FLAGS = /D ENABLE_MD5_DEPRECATED_INTERFACES - GCC:*_*_*_CC_FLAGS = -D ENABLE_MD5_DEPRECATED_INTERFACES -!endif From 74d44326472451853ae37680e8a90952c92a270f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 3 Oct 2022 16:27:26 -0700 Subject: [PATCH 0201/1529] CryptoPkg: Fixed host-based unit tests * Build host-based tests using OpensslLib instance with all services enabled. * Build host-based tests using performance optimized OpensslLib instance with all services enabled. * Remove unused PCD gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled * Remove redundant and unnecessary [BuildOptions] * Limit host-based unit tests to only IA32/X64 Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- .../BaseCryptLib/UnitTestHostBaseCryptLib.inf | 22 ++------ CryptoPkg/Test/CryptoPkgHostUnitTest.dsc | 17 ++---- .../TestBaseCryptLibHostAccel.inf | 56 +++++++++++++++++++ 3 files changed, 68 insertions(+), 27 deletions(-) create mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf diff --git a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf index 168e24e4c0..8026179447 100644 --- a/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf @@ -18,7 +18,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] @@ -28,6 +28,7 @@ Hash/CryptSha256.c Hash/CryptSha512.c Hash/CryptSm3.c + Hash/CryptParallelHashNull.c Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c @@ -48,8 +49,7 @@ Pk/CryptRsaPss.c Pk/CryptRsaPssSign.c Bn/CryptBn.c - Pk/CryptEcNull.c |*|*|*|!gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled - Pk/CryptEc.c |*|*|*|gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + Pk/CryptEc.c SysCall/UnitTestHostCrtWrapper.c @@ -59,12 +59,6 @@ [Sources.X64] Rand/CryptRandTsc.c -[Sources.ARM] - Rand/CryptRand.c - -[Sources.AARCH64] - Rand/CryptRand.c - [Packages] MdePkg/MdePkg.dec CryptoPkg/CryptoPkg.dec @@ -75,9 +69,7 @@ MemoryAllocationLib DebugLib OpensslLib - -[FixedPcd] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled + PrintLib # # Remove these [BuildOptions] after this library is cleaned up @@ -85,11 +77,9 @@ [BuildOptions] # # suppress the following warnings so we do not break the build with warnings-as-errors: - # C4090: 'function' : different 'const' qualifiers - # C4018: '>': signed/unsigned mismatch - MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4018 - + # GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc index b6e1a66198..369a1cb699 100644 --- a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc +++ b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc @@ -19,19 +19,13 @@ !include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc -[PcdsFixedAtBuild] - gEfiCryptoPkgTokenSpaceGuid.PcdOpensslEcEnabled|TRUE - [LibraryClasses] - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf -[LibraryClasses.AARCH64, LibraryClasses.ARM] - RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf - [LibraryClasses.X64, LibraryClasses.IA32] RngLib|MdePkg/Library/BaseRngLib/BaseRngLib.inf @@ -40,9 +34,10 @@ # Build HOST_APPLICATION that tests the SampleUnitTest # CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf { + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf + } [BuildOptions] - *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES - MSFT:*_*_*_CC_FLAGS = /D ENABLE_MD5_DEPRECATED_INTERFACES - INTEL:*_*_*_CC_FLAGS = /D ENABLE_MD5_DEPRECATED_INTERFACES - GCC:*_*_*_CC_FLAGS = -D ENABLE_MD5_DEPRECATED_INTERFACES + *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf new file mode 100644 index 0000000000..9d0fcfd357 --- /dev/null +++ b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf @@ -0,0 +1,56 @@ +## @file +# Host-based UnitTest for BaseCryptLib +# +# Copyright (c) Microsoft Corporation.
+# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseCryptLibUnitTestHostAccel + FILE_GUID = B1AED64E-B53A-4D69-B0BA-60EEDAC47A6B + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + UnitTestMain.c + BaseCryptLibUnitTests.c + TestBaseCryptLib.h + HashTests.c + HmacTests.c + BlockCipherTests.c + RsaTests.c + RsaPkcs7Tests.c + Pkcs5Pbkdf2Tests.c + AuthenticodeTests.c + TSTests.c + DhTests.c + RandTests.c + Pkcs7EkuTests.c + OaepEncryptTests.c + RsaPssTests.c + ParallelhashTests.c + HkdfTests.c + AeadAesGcmTests.c + BnTests.c + EcTests.c + X509Tests.c + +[Packages] + MdePkg/MdePkg.dec + CryptoPkg/CryptoPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + BaseCryptLib + UnitTestLib + MmServicesTableLib + SynchronizationLib From d438e0222b08f47320d2a3b744ce7659ef25c3f4 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 10 Oct 2022 23:50:33 -0700 Subject: [PATCH 0202/1529] CryptoPkg: Add Readme.md Add Readme.md that provides an overview of the CryptoPkg and how to configure the use of cryptographic services in a platform. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Readme.md | 498 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 498 insertions(+) create mode 100644 CryptoPkg/Readme.md diff --git a/CryptoPkg/Readme.md b/CryptoPkg/Readme.md new file mode 100644 index 0000000000..946aa1e99e --- /dev/null +++ b/CryptoPkg/Readme.md @@ -0,0 +1,498 @@ +# Crypto Package + +This package provides cryptographic services that are used to implement firmware +features such as UEFI Secure Boot, Measured Boot, firmware image authentication, +and network boot. The cryptographic service implementation in this package uses +services from the [OpenSSL](https://www.openssl.org/) project. + +EDK II firmware modules/libraries that requires the use of cryptographic +services can either statically link all the required services, or the EDK II +firmware module/library can use a dynamic Protocol/PPI service to call +cryptographic services. The dynamic Protocol/PPI services are only available to +PEIMs, DXE Drivers, UEFI Drivers, and SMM Drivers, and only if the cryptographic +modules are included in the platform firmware image. + +There may be firmware image size differences between the static and dynamic +options. Some experimentation may be required to find the solution that +provides the smallest overall firmware overhead. + +# Public Library Classes + +* **BaseCryptLib** - Provides library functions for cryptographic primitives. +* **TlsLib** - Provides TLS library functions for EFI TLS protocol. +* **HashApiLib** - Provides Unified API for different hash implementations. + +# Private Library Classes + +* **OpensslLib** - Provides library functions from the openssl project. +* **IntrinsicLib** - Provides C runtime library (CRT) required by openssl. + +# Private Protocols and PPIs + +* **EDK II Crypto PPI** - PPI that provides all the services from + the BaseCryptLib and TlsLib library classes. +* **EDK II Crypto Protocol** - Protocol that provides all the services from + the BaseCryptLib and TlsLib library classes. +* **EDK II SMM Crypto Protocol** - SMM Protocol that provides all the services + from the BaseCryptLib and TlsLib library + classes. + +## Statically Linking Cryptographic Services + +The figure below shows an example of a firmware modules that requires the use of +cryptographic services. The cryptographic services are provided by three library +classes called BaseCryptLib, TlsLib, and HashApiLib. These library classes are +implemented using APIs from the OpenSSL project that are abstracted by the +private library class called OpensslLib. The OpenSSL project implementation +depends on C runtime library services. The EDK II project does not provide a +full C runtime library for firmware components. Instead, the CryptoPkg includes +the smallest subset of services required to build the OpenSSL project in the +private library class called IntrinsicLib. + +The CryptoPkg provides several instances if the BaseCryptLib and OpensslLib with +different cryptographic service features and performance optimizations. The +platform developer must select the correct instances based on cryptographic +service requirements in each UEFI/PI firmware phase (SEC, PEI, DXE, UEFI, +UEFI RT, and SMM), firmware image size requirements, and firmware boot +performance requirements. + +``` ++================================+ +| EDK II Firmware Module/Library | ++================================+ + ^ ^ ^ + | | | + | | v + | | +============+ + | | | HashApiLib | + | | +============+ + | | ^ + | | | + v v v ++========+ +====================+ +| TlsLib | | BaseCryptLib | ++========+ +====================+ + ^ ^ + | | + v v ++================================+ +| OpensslLib (Private) | ++================================+ + ^ + | + v ++================================+ +| IntrinsicLib (Private) | ++================================+ +``` + +## Dynamically Linking Cryptographic Services + +The figure below shows the entire stack when dynamic linking is used with +cryptographic services produced by the CryptoPei, CryptoDxe, or CryptoSmm module +through a PPI/Protocol. This solution requires the CryptoPei, CryptoDxe, and +CryptoSmm modules to be configured with the set of cryptographic services +required by all the PEIMs, DXE Drivers, UEFI Drivers, and SMM Drivers. Dynamic +linking is not available for SEC or UEFI RT modules. + +The EDK II modules/libraries that require cryptographic services use the same +BaseCryptLib/TlsLib/HashApiLib APIs. This means no source changes are required +to use static linking or dynamic linking. It is a platform configuration options +to select static linking or dynamic linking. This choice can be make globally, +per firmware module type, or individual modules. + +``` ++===================+ +===================+ +===================+ +| EDK II PEI | | EDK II DXE/UEFI | | EDK II SMM | +| Module/Library | | Module/Library | | Module/Library | ++===================+ +===================+ +===================+ + ^ ^ ^ ^ ^ ^ ^ ^ ^ + | | | | | | | | | + | | v | | v | | v + | | +==========+ | | +==========+ | | +==========+ + | | |HashApiLib| | | |HashApiLib| | | |HashApiLib| + | | +==========+ | | +==========+ | | +==========+ + | | ^ | | ^ | | ^ + | | | | | | | | | + v v v v v v v v v ++===================+ +===================+ +===================+ +|TlsLib|BaseCryptLib| |TlsLib|BaseCryptLib| |TlsLib|BaseCryptLib| ++-------------------+ +-------------------+ +-------------------+ +| BaseCryptLib | | BaseCryptLib | | BaseCryptLib | +| OnPpiProtocol/ | | OnPpiProtocol/ | | OnPpiProtocol/ | +| PeiCryptLib.inf | | DxeCryptLib.inf | | SmmCryptLib.inf | ++===================+ +===================+ +===================+ + ^ ^ ^ + ||| (Dynamic) ||| (Dynamic) ||| (Dynamic) + v v v ++===================+ +===================+ +=====================+ +| Crypto PPI | | Crypto Protocol | | Crypto SMM Protocol | ++-------------------| |-------------------| |---------------------| +| CryptoPei | | CryptoDxe | | CryptoSmm | ++===================+ +===================+ +=====================+ + ^ ^ ^ ^ ^ ^ + | | | | | | + v | v | v | ++========+ | +========+ | +========+ | +| TlsLib | | | TlsLib | | | TlsLib | | ++========+ v +========+ v +========+ v + ^ +==============+ ^ +==============+ ^ +==============+ + | | BaseCryptLib | | | BaseCryptLib | | | BaseCryptLib | + | +==============+ | +==============+ | +==============+ + | ^ | ^ | ^ + | | | | | | + v v v v v v ++===================+ +===================+ +===================+ +| OpensslLib | | OpensslLib | | OpensslLib | ++===================+ +===================+ +===================+ + ^ ^ ^ + | | | + v v v ++===================+ +===================+ +===================+ +| IntrinsicLib | | IntrinsicLib | | IntrinsicLib | ++===================+ +===================+ +===================+ +``` + +## Supported Cryptographic Families and Services + +The table below provides a summary of the supported cryptographic services. It +indicates if the family or service is deprecated or recommended to not be used. +It also shows which *CryptLib library instances support the family or service. +If a cell is blank then the service or family is always disabled and the +`PcdCryptoServiceFamilyEnable` settings for that family or service is ignored. +If the cell is not blank, then the service or family is configurable using +`PcdCryptoServiceFamilyEnable` as long as the correct OpensslLib or TlsLib is +also configured. + +|Key | Description | +|---------|--------------------------------------------------------------------------------| +| | Family or service is always disabled. | +| C | Configurable using PcdCryptoServiceFamilyEnable. | +| C-Tls | Configurable using PcdCryptoServiceFamilyEnable. Requires TlsLib.inf. | +| C-Full | Configurable using PcdCryptoServiceFamilyEnable. Requires OpensslLibFull*.inf. | + +|Family/Service | Deprecated | Don't Use | SecCryptLib | PeiCryptLib | BaseCryptLib | SmmCryptLib | RuntimeCryptLib | +|:--------------------------------|:----------:|:---------:|:-----------:|:-----------:|:------------:|:-----------:|:---------------:| +| HmacMd5 | Y | Y | | | | | | +| HmacSha1 | Y | Y | | | | | | +| HmacSha256 | N | N | | C | C | C | C | +| HmacSha384 | N | N | | C | C | C | C | +| Md4 | Y | Y | | | | | | +| Md5 | Y | Y | | C | C | C | C | +| Pkcs.Pkcs1v2Encrypt | N | N | | | C | C | | +| Pkcs.Pkcs5HashPassword | N | N | | | C | C | | +| Pkcs.Pkcs7Verify | N | N | | C | C | C | C | +| Pkcs.VerifyEKUsInPkcs7Signature | N | N | | C | C | C | | +| Pkcs.Pkcs7GetSigners | N | N | | C | C | C | C | +| Pkcs.Pkcs7FreeSigners | N | N | | C | C | C | C | +| Pkcs.Pkcs7Sign | N | N | | | C | | | +| Pkcs.Pkcs7GetAttachedContent | N | N | | C | C | C | | +| Pkcs.Pkcs7GetCertificatesList | N | N | | C | C | C | C | +| Pkcs.AuthenticodeVerify | N | N | | | C | | | +| Pkcs.ImageTimestampVerify | N | N | | | C | | | +| Dh | N | N | | | C | | | +| Random | N | N | | | C | C | C | +| Rsa.VerifyPkcs1 | Y | Y | | | | | | +| Rsa.New | N | N | | C | C | C | C | +| Rsa.Free | N | N | | C | C | C | C | +| Rsa.SetKey | N | N | | C | C | C | C | +| Rsa.GetKey | N | N | | | C | | | +| Rsa.GenerateKey | N | N | | | C | | | +| Rsa.CheckKey | N | N | | | C | | | +| Rsa.Pkcs1Sign | N | N | | | C | | | +| Rsa.Pkcs1Verify | N | N | | C | C | C | C | +| Sha1 | N | Y | | C | C | C | C | +| Sha256 | N | N | | C | C | C | C | +| Sha384 | N | N | C | C | C | C | C | +| Sha512 | N | N | C | C | C | C | C | +| X509 | N | N | | | C | C | C | +| Tdes | Y | Y | | | | | | +| Aes.GetContextSize | N | N | | | C | C | C | +| Aes.Init | N | N | | | C | C | C | +| Aes.EcbEncrypt | Y | Y | | | | | | +| Aes.EcbDecrypt | Y | Y | | | | | | +| Aes.CbcEncrypt | N | N | | | C | C | C | +| Aes.CbcDecrypt | N | N | | | C | C | C | +| Arc4 | Y | Y | | | | | | +| Sm3 | N | N | | C | C | C | C | +| Hkdf | N | N | | C | C | | C | +| Tls | N | N | | | C-Tls | | | +| TlsSet | N | N | | | C-Tls | | | +| TlsGet | N | N | | | C-Tls | | | +| RsaPss.Sign | N | N | | | C | | | +| RsaPss.Verify | N | N | | C | C | C | | +| ParallelHash | N | N | | | | C | | +| AeadAesGcm | N | N | | | C | | | +| Bn | N | N | | | C | | | +| Ec | N | N | | | C-Full | | | + +## Platform Configuration of Cryptographic Services + +Configuring the cryptographic services requires library mappings and PCD +settings in a platform DSC file. This must be done for each of the firmware +phases (SEC, PEI, DXE, UEFI, SMM, UEFI RT). + +The following table can be used to help select the best OpensslLib instance for +each phase. The Size column only shows the estimated size increase for a +compressed IA32/X64 modules that uses the cryptographic services with +`OpensslLib.inf` as the baseline size. The actual size increase depends on the +specific set of enabled cryptographic services. If ECC services are not +required, then size can be reduced by using OpensslLib.inf instead of +`OpensslLibFull.inf`. Performance optimization requires a size increase. + +| OpensslLib Instance | SSL | ECC | Perf Opt | CPU Arch | Size | +|:------------------------|:---:|:---:|:--------:|:--------:|:-----:| +| OpensslLibCrypto.inf | N | N | N | All | +0K | +| OpensslLib.inf | Y | N | N | All | +0K | +| OpensslLibAccel.inf | Y | N | Y | IA32/X64 | +20K | +| OpensslLibFull.inf | Y | Y | N | All | +115K | +| OpensslLibFullAccel.inf | Y | Y | Y | IA32/X64 | +135K | + +### SEC Phase Library Mappings + +The SEC Phase only supports static linking of cryptographic services. The +following library mappings are recommended for the SEC Phase. It uses the SEC +specific version of the BaseCryptLib and the null version of the TlsLib because +TLS services are not typically used in SEC. + +``` +[LibraryClasses.common.SEC] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +``` + +### PEI Phase Library Mappings + +The PEI Phase supports either static or dynamic linking of cryptographic +services. The following library mappings are recommended for the PEI Phase. It +uses the PEI specific version of the BaseCryptLib and the null version of the +TlsLib because TLS services are not typically used in PEI. + +``` +[LibraryClasses.common.PEIM] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +``` + +If dynamic linking is used, then all PEIMs except CryptoPei use the following +library mappings. The CryptoPei module uses the static linking settings. + +``` +[LibraryClasses.common.PEIM] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/PeiCryptLib.inf + +[Components] + CryptoPkg/Driver/CryptoPei.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + } +``` + +### DXE Phase, UEFI Driver, UEFI Application Library Mappings + +The DXE/UEFI Phase supports either static or dynamic linking of cryptographic +services. The following library mappings are recommended for the DXE/UEFI Phase. +It uses the DXE specific version of the BaseCryptLib and the full version of the +OpensslLib and TlsLib. If ECC services are not required then a smaller +OpensslLib instance can be used. + +``` +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +``` + +If dynamic linking is used, then all DXE Drivers except CryptoDxe use the +following library mappings. The CryptoDxe module uses the static linking +settings. + +``` +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf + +[Components] + CryptoPkg/Driver/CryptoDxe.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + } +``` + +### SMM Phase Library Mappings + +The SMM Phase supports either static or dynamic linking of cryptographic +services. The following library mappings are recommended for the SMM Phase. It +uses the SMM specific version of the BaseCryptLib and the null version of the +TlsLib. + +``` +[LibraryClasses.common.DXE_SMM_DRIVER] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +``` + +If dynamic linking is used, then all SMM Drivers except CryptoSmm use the +following library mappings. The CryptoDxe module uses the static linking +settings. + +``` +[LibraryClasses.common.DXE_SMM_DRIVER] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLibOnProtocolPpi/SmmCryptLib.inf + +[Components] + CryptoPkg/Driver/CryptoSmm.inf { + + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + } +``` + +### UEFI Runtime Driver Library Mappings + +UEFI Runtime Drivers only supports static linking of cryptographic services. +The following library mappings are recommended for UEFI Runtime Drivers. It uses +the runtime specific version of the BaseCryptLib and the null version of the +TlsLib because TLS services are not typically used in runtime. + +``` +[LibraryClasses.common.DXE_RUNTIME_DRIVER] + HashApiLib|CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +``` + +### PCD Configuration Settings + +There are 2 PCD settings that are used to configure cryptographic services. +`PcdHashApiLibPolicy` is used to configure the hash algorithm provided by the +BaseHashApiLib library instance. `PcdCryptoServiceFamilyEnable` is used to +configure the cryptographic services supported by the CryptoPei, CryptoDxe, +and CryptoSmm modules. + +* `gEfiCryptoPkgTokenSpaceGuid.PcdHashApiLibPolicy` - This PCD indicates the + HASH algorithm to to use in the BaseHashApiLib to calculate hash of data. The + default hashing algorithm for BaseHashApiLib is set to HASH_ALG_SHA256. + | Setting | Algorithm | + |------------|------------------| + | 0x00000001 | HASH_ALG_SHA1 | + | 0x00000002 | HASH_ALG_SHA256 | + | 0x00000004 | HASH_ALG_SHA384 | + | 0x00000008 | HASH_ALG_SHA512 | + | 0x00000010 | HASH_ALG_SM3_256 | + +* `gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable` - Enable/Disable + the families and individual services produced by the EDK II Crypto + Protocols/PPIs. The default is all services disabled. This Structured PCD is + associated with `PCD_CRYPTO_SERVICE_FAMILY_ENABLE` structure that defined in + `Include/Pcd/PcdCryptoServiceFamilyEnable.h`. + + There are three layers of priority that determine if a specific family or + individual cryptographic service is actually enabled in the CryptoPei, + CryptoDxe, and CryptoSmm modules. + + 1) OpensslLib instance selection. When the CryptoPei, CryptoDxe, or CryptoSmm + drivers are built, they are statically linked to an OpensslLib library + instance. If the required cryptographic service is not enabled in the + OpensslLib instance linked, then the service is always disabled. + 2) BaseCryptLib instance selection. + * CryptoPei is always linked with the PeiCryptLib instance of the + BaseCryptLib library class. The table above have a column for the + PeiCryptLib. If the family or service is blank, then that family or + service is always disabled. + * CryptoDxe is always linked with the BaseCryptLib instance of the + BaseCryptLib library class. The table above have a column for the + BaseCryptLib. If the family or service is blank, then that family or + service is always disabled. + * CryptoSmm is always linked with the SmmCryptLib instance of the + BaseCryptLib library class. The table above have a column for the + SmmCryptLib. If the family or service is blank, then that family or + service is always disabled. + 3) If a family or service is enabled in the OpensslLib instance and it is + enabled in the BaseCryptLib instance, then it can be enabled/disabled + using `PcdCryptoServiceFamilyEnable`. This structured PCD is associated + with the `PCD_CRYPTO_SERVICE_FAMILY_ENABLE` data structure that contains + bit fields for each family of services. All of the families are disabled + by default. An entire family of services can be enabled by setting the + family field to the value `PCD_CRYPTO_SERVICE_ENABLE_FAMILY`. Individual + services can be enabled by setting a single service name to `TRUE`. + Settings listed later in the DSC file have priority over settings earlier + in the DSC file, so it is legal for an entire family to be enabled first + and then a few individual services disabled by setting the service name to + `FALSE`. + +#### Common PEI PcdCryptoServiceFamilyEnable Settings + +``` + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Pkcs1Verify | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.New | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE +``` + +#### Common DXE and SMM PcdCryptoServiceFamilyEnable Settings + +``` + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs1v2Encrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs7Verify | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.VerifyEKUsInPkcs7Signature | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs7GetSigners | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs7FreeSigners | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.AuthenticodeVerify | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Random.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Pkcs1Verify | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.New | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.GetPublicKeyFromX509 | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Services.HashAll | FALSE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Services.GetSubjectName | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Services.GetCommonName | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Services.GetOrganizationName | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.X509.Services.GetTBSCert | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Tls.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsSet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.TlsGet.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Encrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Decrypt | TRUE +``` From 18cfaefb075e902b1e557086b4078136837df7a4 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Mon, 17 Oct 2022 15:53:12 +0800 Subject: [PATCH 0203/1529] Revert "CryptoPkg: Update process_files.pl to auto add PCD config option" This reverts commit 499b0d5fa57dafe47b260aaf0cea6c6b0286e656. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Cc: Michael D Kinney Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/process_files.pl | 77 +------------------ 1 file changed, 3 insertions(+), 74 deletions(-) diff --git a/CryptoPkg/Library/OpensslLib/process_files.pl b/CryptoPkg/Library/OpensslLib/process_files.pl index 82e5176b39..7e18c9f52d 100755 --- a/CryptoPkg/Library/OpensslLib/process_files.pl +++ b/CryptoPkg/Library/OpensslLib/process_files.pl @@ -81,19 +81,6 @@ sub copy_license_header my $extension; my $arch; my @inf; -# -# Use PCD to conditionally enable certain openssl features. -# $conditional_feature contains pcd_name:fetures_names pairs -# of conditional features. -# @conditional_feature_dir contains relative_path:pcd_name pairs -# of conditional features in openssl, MUST correspond to the content -# in $conditional_feature. -# -# Configure list [openssl_configuration : new_define_list : new_file_list : pcd] -# 1. no-ec : {NO_EC, NO_ECDH, NO_ECDSA, NO_TLS1_3, NO_SM2} : {/ec/, /sm2/} : PcdOpensslEcEnabled -# -my %conditional_feature = ("PcdOpensslEcEnabled"=>["EC", "ECDH", "ECDSA", "TLS1_3", "SM2"]); -my %conditional_feature_dir = ("/ec/"=>"PcdOpensslEcEnabled", "/sm2/"=>"PcdOpensslEcEnabled"); BEGIN { $inf_file = "OpensslLib.inf"; @@ -307,13 +294,7 @@ BEGIN push @sslfilelist, ' $(OPENSSL_PATH)/' . $s . "\r\n"; next; } - push @cryptofilelist, ' $(OPENSSL_PATH)/' . $s; - foreach (keys(%conditional_feature_dir)) { - if ($s =~ $_) { - push @cryptofilelist, ' |*|*|*|gEfiCryptoPkgTokenSpaceGuid.' . $conditional_feature_dir{$_}; - } - } - push @cryptofilelist, "\r\n"; + push @cryptofilelist, ' $(OPENSSL_PATH)/' . $s . "\r\n"; } } } @@ -342,13 +323,7 @@ BEGIN push @sslfilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; next; } - push @cryptofilelist, ' $(OPENSSL_PATH)/' . $_; - foreach my $conditional_key (keys(%conditional_feature_dir)) { - if ($_ =~ $conditional_key) { - push @cryptofilelist, ' |*|*|*|gEfiCryptoPkgTokenSpaceGuid.' . $conditional_feature_dir{$conditional_key}; - } - } - push @cryptofilelist, "\r\n"; + push @cryptofilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; } @@ -453,7 +428,7 @@ BEGIN system( "perl -pe 's/\\n/\\r\\n/' " . "< " . $OPENSSL_PATH . "/include/openssl/opensslconf.h " . - "> " . $OPENSSL_PATH . "/../../Include/openssl/opensslconf_generated.h" + "> " . $OPENSSL_PATH . "/../../Include/openssl/opensslconf.h" ) == 0 || die "Cannot copy opensslconf.h!"; print "Done!"; @@ -465,52 +440,6 @@ BEGIN "> " . $OPENSSL_PATH . "/../../Include/crypto/dso_conf.h" ) == 0 || die "Cannot copy dso_conf.h!"; -print "Done!"; - -# -# Add conditional feature to opensslconf.h -# -my $conf_file = "../Include/openssl/opensslconf.h"; -my @conf_raw = (); -my @conditional_define = (); -print "\n--> Updating conditional feature in $conf_file ... "; - -foreach my $pcd_name (keys(%conditional_feature)) { - push @conditional_define, "#if !FixedPcdGetBool ($pcd_name)\r\n"; - foreach (@{$conditional_feature{$pcd_name}}) { - push @conditional_define, "# ifndef OPENSSL_NO_$_\r\n"; - push @conditional_define, "# define OPENSSL_NO_$_\r\n"; - push @conditional_define, "# endif\r\n"; - } - push @conditional_define, "#endif\r\n"; -} - -open( FD, "<" . $conf_file ) || - die $conf_file; -foreach () { - # Insert conditional define to the begin of opensslconf.h - if ($_ =~ "Autogenerated conditional openssl feature list starts here") { - push @conf_raw, $_, @conditional_define; - $subbing = 1; - next; - } - if ($_ =~ "Autogenerated conditional openssl feature list ends here") { - push @conf_raw, $_; - $subbing = 0; - next; - } - push @conf_raw, $_ - unless ($subbing); -} -close(FD) || - die $conf_file; - -open( FD, ">" . $conf_file ) || - die $conf_file; -print( FD @conf_raw ) || - die $conf_file; -close(FD) || - die $conf_file; print "Done!\n"; print "\nProcessing Files Done!\n"; From 4b45e295cb8d2efe21e550f006becd76c5129c77 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Tue, 18 Oct 2022 13:10:55 +0800 Subject: [PATCH 0204/1529] CryptoPkg/Library/OpensslLib: Update process_files.pl INF generation Update process_files.pl to generate all OpensslLib INF files. * OpensslLib.inf * OpensslLibAccel.inf * OpensslLibCrypto.inf * OpensslLibFull.inf * OpensslLibFullAccel.inf Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Cc: Michael D Kinney Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/process_files.pl | 93 +++++++++++++++++-- 1 file changed, 87 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Library/OpensslLib/process_files.pl b/CryptoPkg/Library/OpensslLib/process_files.pl index 7e18c9f52d..fba97e7c39 100755 --- a/CryptoPkg/Library/OpensslLib/process_files.pl +++ b/CryptoPkg/Library/OpensslLib/process_files.pl @@ -15,6 +15,15 @@ # ./process_files.pl # ./process_files.pl X64 # ./process_files.pl [Arch] +# +# Follow the command below to update the INF file: +# 1. OpensslLib.inf ,OpensslLibCrypto.inf and OpensslLibFull.inf +# ./process_files.pl +# 2. OpensslLibAccel.inf and OpensslLibFullAccel.inf +# ./process_files.pl X64 +# ./process_files.pl X64Gcc +# ./process_files.pl IA32 +# ./process_files.pl IA32Gcc use strict; use Cwd; @@ -79,6 +88,7 @@ sub copy_license_header my $OPENSSL_PATH; my $uefi_config; my $extension; +my $compile; my $arch; my @inf; @@ -90,31 +100,32 @@ BEGIN if (defined $arch) { if (uc ($arch) eq "X64") { $arch = "X64"; - $inf_file = "OpensslLibX64.inf"; $uefi_config = "UEFI-x86_64"; $extension = "nasm"; + $compile = "MSFT"; $comment_character = ";"; } elsif (uc ($arch) eq "X64GCC") { $arch = "X64Gcc"; - $inf_file = "OpensslLibX64Gcc.inf"; $uefi_config = "UEFI-x86_64-GCC"; $extension = "S"; + $compile = "GCC"; $comment_character = "#"; } elsif (uc ($arch) eq "IA32") { $arch = "IA32"; - $inf_file = "OpensslLibIa32.inf"; $uefi_config = "UEFI-x86"; $extension = "nasm"; + $compile = "MSFT"; $comment_character = ";"; } elsif (uc ($arch) eq "IA32GCC") { $arch = "IA32Gcc"; - $inf_file = "OpensslLibIa32Gcc.inf"; $uefi_config = "UEFI-x86-GCC"; $extension = "S"; + $compile = "GCC"; $comment_character = "#"; } else { die "Unsupported architecture \"" . $arch . "\"!"; } + $inf_file = "OpensslLibAccel.inf"; if ($extension eq "nasm") { if (`nasm -v 2>&1`) { #Presence of nasm executable will trigger inclusion of AVX instructions @@ -256,6 +267,7 @@ BEGIN my @cryptofilelist = (); my @sslfilelist = (); +my @ecfilelist = (); my @asmfilelist = (); my @asmbuild = (); foreach my $product ((@{$unified_info{libraries}}, @@ -286,10 +298,14 @@ BEGIN $buildstring .= " ./$arch/$path$s.$extension"; make_path ("./$arch/$path"); push @asmbuild, "$buildstring\n"; - push @asmfilelist, " $arch/$path$s.$extension\r\n"; + push @asmfilelist, " $arch/$path$s.$extension |$compile\r\n"; } next; } + if ($s =~ "/ec/" || $s =~ "/sm2/") { + push @ecfilelist, ' $(OPENSSL_PATH)/' . $s . "\r\n"; + next; + } if ($product =~ "libssl") { push @sslfilelist, ' $(OPENSSL_PATH)/' . $s . "\r\n"; next; @@ -323,6 +339,10 @@ BEGIN push @sslfilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; next; } + if ($_ =~ "/ec/" || $_ =~ "/sm2/") { + push @ecfilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; + next; + } push @cryptofilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; } @@ -351,10 +371,18 @@ BEGIN next; } if ( $_ =~ "# Autogenerated files list starts here" ) { - push @new_inf, $_, @asmfilelist, @cryptofilelist, @sslfilelist; + push @new_inf, $_, @cryptofilelist, @sslfilelist; $subbing = 1; next; } + if (defined $arch) { + my $arch_asmfile_flag = "# Autogenerated " . $arch . " files list starts here"; + if ($_ =~ $arch_asmfile_flag) { + push @new_inf, $_, @asmfilelist; + $subbing = 1; + next; + } + } if ( $_ =~ "# Autogenerated files list ends here" ) { push @new_inf, $_; $subbing = 0; @@ -421,6 +449,59 @@ BEGIN print "Done!"; } +# +# Update OpensslLibFull.inf with autogenerated file list +# +if (!defined $arch) { + $inf_file = "OpensslLibFull.inf"; +} else { + $inf_file = "OpensslLibFullAccel.inf"; +} +# Read the contents of the inf file +@inf = (); +@new_inf = (); +open( FD, "<" . $inf_file ) || + die "Cannot open \"" . $inf_file . "\"!"; +@inf = (); +close(FD) || + die "Cannot close \"" . $inf_file . "\"!"; +$subbing = 0; +print "\n--> Updating $inf_file ... "; +foreach (@inf) { + if ( $_ =~ "# Autogenerated files list starts here" ) { + push @new_inf, $_, @cryptofilelist, @sslfilelist, @ecfilelist; + $subbing = 1; + next; + } + if (defined $arch) { + my $arch_asmfile_flag = "# Autogenerated " . $arch . " files list starts here"; + if ($_ =~ $arch_asmfile_flag) { + push @new_inf, $_, @asmfilelist; + $subbing = 1; + next; + } + } + if ( $_ =~ "# Autogenerated files list ends here" ) { + push @new_inf, $_; + $subbing = 0; + next; + } + + push @new_inf, $_ + unless ($subbing); +} + +$new_inf_file = $inf_file . ".new"; +open( FD, ">" . $new_inf_file ) || + die $new_inf_file; +print( FD @new_inf ) || + die $new_inf_file; +close(FD) || + die $new_inf_file; +rename( $new_inf_file, $inf_file ) || + die "rename $inf_file"; +print "Done!"; + # # Copy opensslconf.h and dso_conf.h generated from OpenSSL Configuration # From b1399482736b7cc9d2aa2e13135f45be68d93865 Mon Sep 17 00:00:00 2001 From: Yi Li Date: Thu, 20 Oct 2022 14:46:56 +0800 Subject: [PATCH 0205/1529] CryptoPkg/Library/OpensslLib: Add generated flag to Accel INF Update OpensslLibAccel.inf and OpensslLibFullAccel.inf to include flags used by process_files.pl to generate OpensslLib INF files. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Cc: Michael D Kinney Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf | 8 ++++++++ CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 32eae4a792..98b07fd2ea 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -633,6 +633,7 @@ EcSm2Null.c [Sources.IA32] +# Autogenerated IA32 files list starts here IA32/crypto/aes/aesni-x86.nasm | MSFT IA32/crypto/aes/vpaes-x86.nasm | MSFT IA32/crypto/modes/ghash-x86.nasm | MSFT @@ -640,7 +641,9 @@ IA32/crypto/sha/sha256-586.nasm | MSFT IA32/crypto/sha/sha512-586.nasm | MSFT IA32/crypto/x86cpuid.nasm | MSFT +# Autogenerated files list ends here +# Autogenerated IA32Gcc files list starts here IA32Gcc/crypto/aes/aesni-x86.S | GCC IA32Gcc/crypto/aes/vpaes-x86.S | GCC IA32Gcc/crypto/modes/ghash-x86.S | GCC @@ -648,9 +651,11 @@ IA32Gcc/crypto/sha/sha256-586.S | GCC IA32Gcc/crypto/sha/sha512-586.S | GCC IA32Gcc/crypto/x86cpuid.S | GCC +# Autogenerated files list ends here [Sources.X64] X64/ApiHooks.c +# Autogenerated X64 files list starts here X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT @@ -664,7 +669,9 @@ X64/crypto/sha/sha256-x86_64.nasm | MSFT X64/crypto/sha/sha512-x86_64.nasm | MSFT X64/crypto/x86_64cpuid.nasm | MSFT +# Autogenerated files list ends here +# Autogenerated X64Gcc files list starts here X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC @@ -678,6 +685,7 @@ X64Gcc/crypto/sha/sha256-x86_64.S | GCC X64Gcc/crypto/sha/sha512-x86_64.S | GCC X64Gcc/crypto/x86_64cpuid.S | GCC +# Autogenerated files list ends here [Packages] MdePkg/MdePkg.dec diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 6345b54bca..6525b73a9e 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -638,6 +638,7 @@ # EcSm2Null.c [Sources.IA32] +# Autogenerated IA32 files list starts here IA32/crypto/aes/aesni-x86.nasm | MSFT IA32/crypto/aes/vpaes-x86.nasm | MSFT IA32/crypto/modes/ghash-x86.nasm | MSFT @@ -645,7 +646,9 @@ IA32/crypto/sha/sha256-586.nasm | MSFT IA32/crypto/sha/sha512-586.nasm | MSFT IA32/crypto/x86cpuid.nasm | MSFT +# Autogenerated files list ends here +# Autogenerated IA32Gcc files list starts here IA32Gcc/crypto/aes/aesni-x86.S | GCC IA32Gcc/crypto/aes/vpaes-x86.S | GCC IA32Gcc/crypto/modes/ghash-x86.S | GCC @@ -653,9 +656,11 @@ IA32Gcc/crypto/sha/sha256-586.S | GCC IA32Gcc/crypto/sha/sha512-586.S | GCC IA32Gcc/crypto/x86cpuid.S | GCC +# Autogenerated files list ends here [Sources.X64] X64/ApiHooks.c +# Autogenerated X64 files list starts here X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT @@ -669,7 +674,9 @@ X64/crypto/sha/sha256-x86_64.nasm | MSFT X64/crypto/sha/sha512-x86_64.nasm | MSFT X64/crypto/x86_64cpuid.nasm | MSFT +# Autogenerated files list ends here +# Autogenerated X64Gcc files list starts here X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC @@ -683,6 +690,7 @@ X64Gcc/crypto/sha/sha256-x86_64.S | GCC X64Gcc/crypto/sha/sha512-x86_64.S | GCC X64Gcc/crypto/x86_64cpuid.S | GCC +# Autogenerated files list ends here [Packages] MdePkg/MdePkg.dec From 9093b0a11606ccca62c00a360945915ad135899e Mon Sep 17 00:00:00 2001 From: Yi Li Date: Thu, 20 Oct 2022 15:44:42 +0800 Subject: [PATCH 0206/1529] CryptoPkg/Library/OpensslLib: update auto-generated files Update OpensslLib INF files to match results from running process_files.pl to auto-generate the INF files. * OpensslLib.inf * OpensslLibAccel.inf * OpensslLibCrypto.inf * OpensslLibFull.inf * OpensslLibFullAccel.inf These INF files are generated by running the following perl scripts: * process_files.pl * process_files.pl X64 * process_files.pl X64Gcc * process_files.pl IA32 * process_files.pl IA32Gcc Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Christopher Zurcher Cc: Michael D Kinney Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- .../Library/Include/openssl/opensslconf.h | 10 +- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 50 ----- .../Library/OpensslLib/OpensslLibAccel.inf | 131 ++++--------- .../Library/OpensslLib/OpensslLibCrypto.inf | 101 ---------- .../Library/OpensslLib/OpensslLibFull.inf | 100 +++++----- .../OpensslLib/OpensslLibFullAccel.inf | 181 +++++++++--------- 6 files changed, 185 insertions(+), 388 deletions(-) diff --git a/CryptoPkg/Library/Include/openssl/opensslconf.h b/CryptoPkg/Library/Include/openssl/opensslconf.h index b98b068b3d..09a6641ffc 100644 --- a/CryptoPkg/Library/Include/openssl/opensslconf.h +++ b/CryptoPkg/Library/Include/openssl/opensslconf.h @@ -250,11 +250,11 @@ extern "C" { # undef DECLARE_DEPRECATED # define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); # endif -#elif defined(__SUNPRO_C) -#if (__SUNPRO_C >= 0x5130) -#undef DECLARE_DEPRECATED -#define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); -#endif +# elif defined(__SUNPRO_C) +# if (__SUNPRO_C >= 0x5130) +# undef DECLARE_DEPRECATED +# define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); +# endif # endif #endif diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 82ffe4ec2f..60c6c24b0a 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -204,43 +204,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c -# $(OPENSSL_PATH)/crypto/ec/curve25519.c -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c -# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c -# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c -# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c -# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c -# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c -# $(OPENSSL_PATH)/crypto/ec/ec_check.c -# $(OPENSSL_PATH)/crypto/ec/ec_curve.c -# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c -# $(OPENSSL_PATH)/crypto/ec/ec_err.c -# $(OPENSSL_PATH)/crypto/ec/ec_key.c -# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_lib.c -# $(OPENSSL_PATH)/crypto/ec/ec_mult.c -# $(OPENSSL_PATH)/crypto/ec/ec_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_print.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c -# $(OPENSSL_PATH)/crypto/ec/eck_prn.c -# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c -# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c -# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -426,10 +389,6 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -542,15 +501,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h -# $(OPENSSL_PATH)/crypto/ec/ec_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h -# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/field.h -# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/word.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 98b07fd2ea..103ef7bda2 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -205,43 +205,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c -# $(OPENSSL_PATH)/crypto/ec/curve25519.c -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c -# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c -# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c -# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c -# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c -# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c -# $(OPENSSL_PATH)/crypto/ec/ec_check.c -# $(OPENSSL_PATH)/crypto/ec/ec_curve.c -# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c -# $(OPENSSL_PATH)/crypto/ec/ec_err.c -# $(OPENSSL_PATH)/crypto/ec/ec_key.c -# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_lib.c -# $(OPENSSL_PATH)/crypto/ec/ec_mult.c -# $(OPENSSL_PATH)/crypto/ec/ec_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_print.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c -# $(OPENSSL_PATH)/crypto/ec/eck_prn.c -# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c -# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c -# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -320,7 +283,6 @@ $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c $(OPENSSL_PATH)/crypto/mem.c -# $(OPENSSL_PATH)/crypto/mem_clr.c # Replaced by assembly optimized NASM/S files $(OPENSSL_PATH)/crypto/mem_dbg.c $(OPENSSL_PATH)/crypto/mem_sec.c $(OPENSSL_PATH)/crypto/modes/cbc128.c @@ -427,10 +389,6 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -543,15 +501,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h -# $(OPENSSL_PATH)/crypto/ec/ec_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h -# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/field.h -# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/word.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -634,57 +583,57 @@ [Sources.IA32] # Autogenerated IA32 files list starts here - IA32/crypto/aes/aesni-x86.nasm | MSFT - IA32/crypto/aes/vpaes-x86.nasm | MSFT - IA32/crypto/modes/ghash-x86.nasm | MSFT - IA32/crypto/sha/sha1-586.nasm | MSFT - IA32/crypto/sha/sha256-586.nasm | MSFT - IA32/crypto/sha/sha512-586.nasm | MSFT - IA32/crypto/x86cpuid.nasm | MSFT + IA32/crypto/aes/aesni-x86.nasm |MSFT + IA32/crypto/aes/vpaes-x86.nasm |MSFT + IA32/crypto/modes/ghash-x86.nasm |MSFT + IA32/crypto/sha/sha1-586.nasm |MSFT + IA32/crypto/sha/sha256-586.nasm |MSFT + IA32/crypto/sha/sha512-586.nasm |MSFT + IA32/crypto/x86cpuid.nasm |MSFT # Autogenerated files list ends here # Autogenerated IA32Gcc files list starts here - IA32Gcc/crypto/aes/aesni-x86.S | GCC - IA32Gcc/crypto/aes/vpaes-x86.S | GCC - IA32Gcc/crypto/modes/ghash-x86.S | GCC - IA32Gcc/crypto/sha/sha1-586.S | GCC - IA32Gcc/crypto/sha/sha256-586.S | GCC - IA32Gcc/crypto/sha/sha512-586.S | GCC - IA32Gcc/crypto/x86cpuid.S | GCC + IA32Gcc/crypto/aes/aesni-x86.S |GCC + IA32Gcc/crypto/aes/vpaes-x86.S |GCC + IA32Gcc/crypto/modes/ghash-x86.S |GCC + IA32Gcc/crypto/sha/sha1-586.S |GCC + IA32Gcc/crypto/sha/sha256-586.S |GCC + IA32Gcc/crypto/sha/sha512-586.S |GCC + IA32Gcc/crypto/x86cpuid.S |GCC # Autogenerated files list ends here [Sources.X64] X64/ApiHooks.c # Autogenerated X64 files list starts here - X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT - X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT - X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT - X64/crypto/aes/aesni-x86_64.nasm | MSFT - X64/crypto/aes/vpaes-x86_64.nasm | MSFT - X64/crypto/modes/aesni-gcm-x86_64.nasm | MSFT - X64/crypto/modes/ghash-x86_64.nasm | MSFT - X64/crypto/sha/sha1-mb-x86_64.nasm | MSFT - X64/crypto/sha/sha1-x86_64.nasm | MSFT - X64/crypto/sha/sha256-mb-x86_64.nasm | MSFT - X64/crypto/sha/sha256-x86_64.nasm | MSFT - X64/crypto/sha/sha512-x86_64.nasm | MSFT - X64/crypto/x86_64cpuid.nasm | MSFT + X64/crypto/aes/aesni-mb-x86_64.nasm |MSFT + X64/crypto/aes/aesni-sha1-x86_64.nasm |MSFT + X64/crypto/aes/aesni-sha256-x86_64.nasm |MSFT + X64/crypto/aes/aesni-x86_64.nasm |MSFT + X64/crypto/aes/vpaes-x86_64.nasm |MSFT + X64/crypto/modes/aesni-gcm-x86_64.nasm |MSFT + X64/crypto/modes/ghash-x86_64.nasm |MSFT + X64/crypto/sha/sha1-mb-x86_64.nasm |MSFT + X64/crypto/sha/sha1-x86_64.nasm |MSFT + X64/crypto/sha/sha256-mb-x86_64.nasm |MSFT + X64/crypto/sha/sha256-x86_64.nasm |MSFT + X64/crypto/sha/sha512-x86_64.nasm |MSFT + X64/crypto/x86_64cpuid.nasm |MSFT # Autogenerated files list ends here # Autogenerated X64Gcc files list starts here - X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-x86_64.S | GCC - X64Gcc/crypto/aes/vpaes-x86_64.S | GCC - X64Gcc/crypto/modes/aesni-gcm-x86_64.S | GCC - X64Gcc/crypto/modes/ghash-x86_64.S | GCC - X64Gcc/crypto/sha/sha1-mb-x86_64.S | GCC - X64Gcc/crypto/sha/sha1-x86_64.S | GCC - X64Gcc/crypto/sha/sha256-mb-x86_64.S | GCC - X64Gcc/crypto/sha/sha256-x86_64.S | GCC - X64Gcc/crypto/sha/sha512-x86_64.S | GCC - X64Gcc/crypto/x86_64cpuid.S | GCC + X64Gcc/crypto/aes/aesni-mb-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-sha1-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-sha256-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-x86_64.S |GCC + X64Gcc/crypto/aes/vpaes-x86_64.S |GCC + X64Gcc/crypto/modes/aesni-gcm-x86_64.S |GCC + X64Gcc/crypto/modes/ghash-x86_64.S |GCC + X64Gcc/crypto/sha/sha1-mb-x86_64.S |GCC + X64Gcc/crypto/sha/sha1-x86_64.S |GCC + X64Gcc/crypto/sha/sha256-mb-x86_64.S |GCC + X64Gcc/crypto/sha/sha256-x86_64.S |GCC + X64Gcc/crypto/sha/sha512-x86_64.S |GCC + X64Gcc/crypto/x86_64cpuid.S |GCC # Autogenerated files list ends here [Packages] diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index d02769428b..c4eaea888c 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -205,43 +205,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c -# $(OPENSSL_PATH)/crypto/ec/curve25519.c -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c -# $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c -# $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c -# $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c -# $(OPENSSL_PATH)/crypto/ec/ec2_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ec_ameth.c -# $(OPENSSL_PATH)/crypto/ec/ec_asn1.c -# $(OPENSSL_PATH)/crypto/ec/ec_check.c -# $(OPENSSL_PATH)/crypto/ec/ec_curve.c -# $(OPENSSL_PATH)/crypto/ec/ec_cvt.c -# $(OPENSSL_PATH)/crypto/ec/ec_err.c -# $(OPENSSL_PATH)/crypto/ec/ec_key.c -# $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_lib.c -# $(OPENSSL_PATH)/crypto/ec/ec_mult.c -# $(OPENSSL_PATH)/crypto/ec/ec_oct.c -# $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c -# $(OPENSSL_PATH)/crypto/ec/ec_print.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c -# $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c -# $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c -# $(OPENSSL_PATH)/crypto/ec/eck_prn.c -# $(OPENSSL_PATH)/crypto/ec/ecp_mont.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nist.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c -# $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c -# $(OPENSSL_PATH)/crypto/ec/ecp_oct.c -# $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c -# $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -427,10 +390,6 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_err.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c -# $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -543,15 +502,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h -# $(OPENSSL_PATH)/crypto/ec/ec_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h -# $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h -# $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/field.h -# $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h -# $(OPENSSL_PATH)/crypto/ec/curve448/word.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h -# $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -574,57 +524,6 @@ $(OPENSSL_PATH)/crypto/x509v3/pcy_local.h $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h -# $(OPENSSL_PATH)/ssl/bio_ssl.c -# $(OPENSSL_PATH)/ssl/d1_lib.c -# $(OPENSSL_PATH)/ssl/d1_msg.c -# $(OPENSSL_PATH)/ssl/d1_srtp.c -# $(OPENSSL_PATH)/ssl/methods.c -# $(OPENSSL_PATH)/ssl/packet.c -# $(OPENSSL_PATH)/ssl/pqueue.c -# $(OPENSSL_PATH)/ssl/record/dtls1_bitmap.c -# $(OPENSSL_PATH)/ssl/record/rec_layer_d1.c -# $(OPENSSL_PATH)/ssl/record/rec_layer_s3.c -# $(OPENSSL_PATH)/ssl/record/ssl3_buffer.c -# $(OPENSSL_PATH)/ssl/record/ssl3_record.c -# $(OPENSSL_PATH)/ssl/record/ssl3_record_tls13.c -# $(OPENSSL_PATH)/ssl/s3_cbc.c -# $(OPENSSL_PATH)/ssl/s3_enc.c -# $(OPENSSL_PATH)/ssl/s3_lib.c -# $(OPENSSL_PATH)/ssl/s3_msg.c -# $(OPENSSL_PATH)/ssl/ssl_asn1.c -# $(OPENSSL_PATH)/ssl/ssl_cert.c -# $(OPENSSL_PATH)/ssl/ssl_ciph.c -# $(OPENSSL_PATH)/ssl/ssl_conf.c -# $(OPENSSL_PATH)/ssl/ssl_err.c -# $(OPENSSL_PATH)/ssl/ssl_init.c -# $(OPENSSL_PATH)/ssl/ssl_lib.c -# $(OPENSSL_PATH)/ssl/ssl_mcnf.c -# $(OPENSSL_PATH)/ssl/ssl_rsa.c -# $(OPENSSL_PATH)/ssl/ssl_sess.c -# $(OPENSSL_PATH)/ssl/ssl_stat.c -# $(OPENSSL_PATH)/ssl/ssl_txt.c -# $(OPENSSL_PATH)/ssl/ssl_utst.c -# $(OPENSSL_PATH)/ssl/statem/extensions.c -# $(OPENSSL_PATH)/ssl/statem/extensions_clnt.c -# $(OPENSSL_PATH)/ssl/statem/extensions_cust.c -# $(OPENSSL_PATH)/ssl/statem/extensions_srvr.c -# $(OPENSSL_PATH)/ssl/statem/statem.c -# $(OPENSSL_PATH)/ssl/statem/statem_clnt.c -# $(OPENSSL_PATH)/ssl/statem/statem_dtls.c -# $(OPENSSL_PATH)/ssl/statem/statem_lib.c -# $(OPENSSL_PATH)/ssl/statem/statem_srvr.c -# $(OPENSSL_PATH)/ssl/t1_enc.c -# $(OPENSSL_PATH)/ssl/t1_lib.c -# $(OPENSSL_PATH)/ssl/t1_trce.c -# $(OPENSSL_PATH)/ssl/tls13_enc.c -# $(OPENSSL_PATH)/ssl/tls_srp.c -# $(OPENSSL_PATH)/ssl/packet_local.h -# $(OPENSSL_PATH)/ssl/ssl_cert_table.h -# $(OPENSSL_PATH)/ssl/ssl_local.h -# $(OPENSSL_PATH)/ssl/record/record.h -# $(OPENSSL_PATH)/ssl/record/record_local.h -# $(OPENSSL_PATH)/ssl/statem/statem.h -# $(OPENSSL_PATH)/ssl/statem/statem_local.h # Autogenerated files list ends here buildinf.h ossl_store.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index aa73265931..309e43055c 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -209,43 +209,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c - $(OPENSSL_PATH)/crypto/ec/ec_check.c - $(OPENSSL_PATH)/crypto/ec/ec_curve.c - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c - $(OPENSSL_PATH)/crypto/ec/ec_err.c - $(OPENSSL_PATH)/crypto/ec/ec_key.c - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c - $(OPENSSL_PATH)/crypto/ec/ec_lib.c - $(OPENSSL_PATH)/crypto/ec/ec_mult.c - $(OPENSSL_PATH)/crypto/ec/ec_oct.c - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c - $(OPENSSL_PATH)/crypto/ec/ec_print.c - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c - $(OPENSSL_PATH)/crypto/ec/eck_prn.c - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -431,10 +394,6 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -547,15 +506,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h - $(OPENSSL_PATH)/crypto/ec/curve448/field.h - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h - $(OPENSSL_PATH)/crypto/ec/curve448/word.h - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -629,6 +579,56 @@ $(OPENSSL_PATH)/ssl/record/record_local.h $(OPENSSL_PATH)/ssl/statem/statem.h $(OPENSSL_PATH)/ssl/statem/statem_local.h + $(OPENSSL_PATH)/crypto/ec/curve25519.c + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c + $(OPENSSL_PATH)/crypto/ec/ec_check.c + $(OPENSSL_PATH)/crypto/ec/ec_curve.c + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c + $(OPENSSL_PATH)/crypto/ec/ec_err.c + $(OPENSSL_PATH)/crypto/ec/ec_key.c + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_lib.c + $(OPENSSL_PATH)/crypto/ec/ec_mult.c + $(OPENSSL_PATH)/crypto/ec/ec_oct.c + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_print.c + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c + $(OPENSSL_PATH)/crypto/ec/eck_prn.c + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c + $(OPENSSL_PATH)/crypto/ec/ec_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h + $(OPENSSL_PATH)/crypto/ec/curve448/field.h + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h + $(OPENSSL_PATH)/crypto/ec/curve448/word.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h # Autogenerated files list ends here buildinf.h ossl_store.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 6525b73a9e..4eeeeb79bd 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -210,43 +210,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c $(OPENSSL_PATH)/crypto/ebcdic.c - $(OPENSSL_PATH)/crypto/ec/curve25519.c - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c - $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c - $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c - $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c - $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c - $(OPENSSL_PATH)/crypto/ec/ec2_oct.c - $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c - $(OPENSSL_PATH)/crypto/ec/ec_ameth.c - $(OPENSSL_PATH)/crypto/ec/ec_asn1.c - $(OPENSSL_PATH)/crypto/ec/ec_check.c - $(OPENSSL_PATH)/crypto/ec/ec_curve.c - $(OPENSSL_PATH)/crypto/ec/ec_cvt.c - $(OPENSSL_PATH)/crypto/ec/ec_err.c - $(OPENSSL_PATH)/crypto/ec/ec_key.c - $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c - $(OPENSSL_PATH)/crypto/ec/ec_lib.c - $(OPENSSL_PATH)/crypto/ec/ec_mult.c - $(OPENSSL_PATH)/crypto/ec/ec_oct.c - $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c - $(OPENSSL_PATH)/crypto/ec/ec_print.c - $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c - $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c - $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c - $(OPENSSL_PATH)/crypto/ec/eck_prn.c - $(OPENSSL_PATH)/crypto/ec/ecp_mont.c - $(OPENSSL_PATH)/crypto/ec/ecp_nist.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c - $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c - $(OPENSSL_PATH)/crypto/ec/ecp_oct.c - $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c - $(OPENSSL_PATH)/crypto/ec/ecx_meth.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c $(OPENSSL_PATH)/crypto/evp/bio_b64.c @@ -325,7 +288,6 @@ $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c $(OPENSSL_PATH)/crypto/mem.c -# $(OPENSSL_PATH)/crypto/mem_clr.c # Replaced by assembly optimized NASM/S files $(OPENSSL_PATH)/crypto/mem_dbg.c $(OPENSSL_PATH)/crypto/mem_sec.c $(OPENSSL_PATH)/crypto/modes/cbc128.c @@ -432,10 +394,6 @@ $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c - $(OPENSSL_PATH)/crypto/sm2/sm2_err.c - $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c - $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c $(OPENSSL_PATH)/crypto/sm4/sm4.c @@ -548,15 +506,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_local.h $(OPENSSL_PATH)/crypto/dh/dh_local.h $(OPENSSL_PATH)/crypto/dso/dso_local.h - $(OPENSSL_PATH)/crypto/ec/ec_local.h - $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h - $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h - $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h - $(OPENSSL_PATH)/crypto/ec/curve448/field.h - $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h - $(OPENSSL_PATH)/crypto/ec/curve448/word.h - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h - $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h $(OPENSSL_PATH)/crypto/evp/evp_local.h $(OPENSSL_PATH)/crypto/hmac/hmac_local.h $(OPENSSL_PATH)/crypto/lhash/lhash_local.h @@ -630,6 +579,56 @@ $(OPENSSL_PATH)/ssl/record/record_local.h $(OPENSSL_PATH)/ssl/statem/statem.h $(OPENSSL_PATH)/ssl/statem/statem_local.h + $(OPENSSL_PATH)/crypto/ec/curve25519.c + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448.c + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_tables.c + $(OPENSSL_PATH)/crypto/ec/curve448/eddsa.c + $(OPENSSL_PATH)/crypto/ec/curve448/f_generic.c + $(OPENSSL_PATH)/crypto/ec/curve448/scalar.c + $(OPENSSL_PATH)/crypto/ec/ec2_oct.c + $(OPENSSL_PATH)/crypto/ec/ec2_smpl.c + $(OPENSSL_PATH)/crypto/ec/ec_ameth.c + $(OPENSSL_PATH)/crypto/ec/ec_asn1.c + $(OPENSSL_PATH)/crypto/ec/ec_check.c + $(OPENSSL_PATH)/crypto/ec/ec_curve.c + $(OPENSSL_PATH)/crypto/ec/ec_cvt.c + $(OPENSSL_PATH)/crypto/ec/ec_err.c + $(OPENSSL_PATH)/crypto/ec/ec_key.c + $(OPENSSL_PATH)/crypto/ec/ec_kmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_lib.c + $(OPENSSL_PATH)/crypto/ec/ec_mult.c + $(OPENSSL_PATH)/crypto/ec/ec_oct.c + $(OPENSSL_PATH)/crypto/ec/ec_pmeth.c + $(OPENSSL_PATH)/crypto/ec/ec_print.c + $(OPENSSL_PATH)/crypto/ec/ecdh_kdf.c + $(OPENSSL_PATH)/crypto/ec/ecdh_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_ossl.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_sign.c + $(OPENSSL_PATH)/crypto/ec/ecdsa_vrf.c + $(OPENSSL_PATH)/crypto/ec/eck_prn.c + $(OPENSSL_PATH)/crypto/ec/ecp_mont.c + $(OPENSSL_PATH)/crypto/ec/ecp_nist.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp224.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp256.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistp521.c + $(OPENSSL_PATH)/crypto/ec/ecp_nistputil.c + $(OPENSSL_PATH)/crypto/ec/ecp_oct.c + $(OPENSSL_PATH)/crypto/ec/ecp_smpl.c + $(OPENSSL_PATH)/crypto/ec/ecx_meth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_crypt.c + $(OPENSSL_PATH)/crypto/sm2/sm2_err.c + $(OPENSSL_PATH)/crypto/sm2/sm2_pmeth.c + $(OPENSSL_PATH)/crypto/sm2/sm2_sign.c + $(OPENSSL_PATH)/crypto/ec/ec_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448_local.h + $(OPENSSL_PATH)/crypto/ec/curve448/curve448utils.h + $(OPENSSL_PATH)/crypto/ec/curve448/ed448.h + $(OPENSSL_PATH)/crypto/ec/curve448/field.h + $(OPENSSL_PATH)/crypto/ec/curve448/point_448.h + $(OPENSSL_PATH)/crypto/ec/curve448/word.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/arch_intrinsics.h + $(OPENSSL_PATH)/crypto/ec/curve448/arch_32/f_impl.h # Autogenerated files list ends here buildinf.h ossl_store.c @@ -639,57 +638,57 @@ [Sources.IA32] # Autogenerated IA32 files list starts here - IA32/crypto/aes/aesni-x86.nasm | MSFT - IA32/crypto/aes/vpaes-x86.nasm | MSFT - IA32/crypto/modes/ghash-x86.nasm | MSFT - IA32/crypto/sha/sha1-586.nasm | MSFT - IA32/crypto/sha/sha256-586.nasm | MSFT - IA32/crypto/sha/sha512-586.nasm | MSFT - IA32/crypto/x86cpuid.nasm | MSFT + IA32/crypto/aes/aesni-x86.nasm |MSFT + IA32/crypto/aes/vpaes-x86.nasm |MSFT + IA32/crypto/modes/ghash-x86.nasm |MSFT + IA32/crypto/sha/sha1-586.nasm |MSFT + IA32/crypto/sha/sha256-586.nasm |MSFT + IA32/crypto/sha/sha512-586.nasm |MSFT + IA32/crypto/x86cpuid.nasm |MSFT # Autogenerated files list ends here # Autogenerated IA32Gcc files list starts here - IA32Gcc/crypto/aes/aesni-x86.S | GCC - IA32Gcc/crypto/aes/vpaes-x86.S | GCC - IA32Gcc/crypto/modes/ghash-x86.S | GCC - IA32Gcc/crypto/sha/sha1-586.S | GCC - IA32Gcc/crypto/sha/sha256-586.S | GCC - IA32Gcc/crypto/sha/sha512-586.S | GCC - IA32Gcc/crypto/x86cpuid.S | GCC + IA32Gcc/crypto/aes/aesni-x86.S |GCC + IA32Gcc/crypto/aes/vpaes-x86.S |GCC + IA32Gcc/crypto/modes/ghash-x86.S |GCC + IA32Gcc/crypto/sha/sha1-586.S |GCC + IA32Gcc/crypto/sha/sha256-586.S |GCC + IA32Gcc/crypto/sha/sha512-586.S |GCC + IA32Gcc/crypto/x86cpuid.S |GCC # Autogenerated files list ends here [Sources.X64] X64/ApiHooks.c # Autogenerated X64 files list starts here - X64/crypto/aes/aesni-mb-x86_64.nasm | MSFT - X64/crypto/aes/aesni-sha1-x86_64.nasm | MSFT - X64/crypto/aes/aesni-sha256-x86_64.nasm | MSFT - X64/crypto/aes/aesni-x86_64.nasm | MSFT - X64/crypto/aes/vpaes-x86_64.nasm | MSFT - X64/crypto/modes/aesni-gcm-x86_64.nasm | MSFT - X64/crypto/modes/ghash-x86_64.nasm | MSFT - X64/crypto/sha/sha1-mb-x86_64.nasm | MSFT - X64/crypto/sha/sha1-x86_64.nasm | MSFT - X64/crypto/sha/sha256-mb-x86_64.nasm | MSFT - X64/crypto/sha/sha256-x86_64.nasm | MSFT - X64/crypto/sha/sha512-x86_64.nasm | MSFT - X64/crypto/x86_64cpuid.nasm | MSFT + X64/crypto/aes/aesni-mb-x86_64.nasm |MSFT + X64/crypto/aes/aesni-sha1-x86_64.nasm |MSFT + X64/crypto/aes/aesni-sha256-x86_64.nasm |MSFT + X64/crypto/aes/aesni-x86_64.nasm |MSFT + X64/crypto/aes/vpaes-x86_64.nasm |MSFT + X64/crypto/modes/aesni-gcm-x86_64.nasm |MSFT + X64/crypto/modes/ghash-x86_64.nasm |MSFT + X64/crypto/sha/sha1-mb-x86_64.nasm |MSFT + X64/crypto/sha/sha1-x86_64.nasm |MSFT + X64/crypto/sha/sha256-mb-x86_64.nasm |MSFT + X64/crypto/sha/sha256-x86_64.nasm |MSFT + X64/crypto/sha/sha512-x86_64.nasm |MSFT + X64/crypto/x86_64cpuid.nasm |MSFT # Autogenerated files list ends here # Autogenerated X64Gcc files list starts here - X64Gcc/crypto/aes/aesni-mb-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-sha1-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-sha256-x86_64.S | GCC - X64Gcc/crypto/aes/aesni-x86_64.S | GCC - X64Gcc/crypto/aes/vpaes-x86_64.S | GCC - X64Gcc/crypto/modes/aesni-gcm-x86_64.S | GCC - X64Gcc/crypto/modes/ghash-x86_64.S | GCC - X64Gcc/crypto/sha/sha1-mb-x86_64.S | GCC - X64Gcc/crypto/sha/sha1-x86_64.S | GCC - X64Gcc/crypto/sha/sha256-mb-x86_64.S | GCC - X64Gcc/crypto/sha/sha256-x86_64.S | GCC - X64Gcc/crypto/sha/sha512-x86_64.S | GCC - X64Gcc/crypto/x86_64cpuid.S | GCC + X64Gcc/crypto/aes/aesni-mb-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-sha1-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-sha256-x86_64.S |GCC + X64Gcc/crypto/aes/aesni-x86_64.S |GCC + X64Gcc/crypto/aes/vpaes-x86_64.S |GCC + X64Gcc/crypto/modes/aesni-gcm-x86_64.S |GCC + X64Gcc/crypto/modes/ghash-x86_64.S |GCC + X64Gcc/crypto/sha/sha1-mb-x86_64.S |GCC + X64Gcc/crypto/sha/sha1-x86_64.S |GCC + X64Gcc/crypto/sha/sha256-mb-x86_64.S |GCC + X64Gcc/crypto/sha/sha256-x86_64.S |GCC + X64Gcc/crypto/sha/sha512-x86_64.S |GCC + X64Gcc/crypto/x86_64cpuid.S |GCC # Autogenerated files list ends here [Packages] From 50a50ee52f0c63ad0914a4ff6181726b94ff74f7 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 08:11:22 +0200 Subject: [PATCH 0207/1529] BaseTools/Tests: Use quotes around PYTHON_COMMAND Commit ("2355f0c09c52 BaseTools: Fix check for ${PYTHON_COMMAND} in Tests/GNUmakefile") fixed a latent issue in the BaseTools/Tests Makefile, but inadvertently broke the BaseTools build for cases where PYTHON_COMMAND is not set. As it turns out, running 'command' without a command argument makes the invocation succeed, causing the empty variable to be evaluated and called later. Let's put double quotes around PYTHON_COMMAND in the invocation of 'command' and force it to fail when PYTHON_COMMAND is not set. Signed-off-by: Ard Biesheuvel Reviewed-by: Bob Feng --- BaseTools/Tests/GNUmakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Tests/GNUmakefile b/BaseTools/Tests/GNUmakefile index caa4d26c9b..20b387864f 100644 --- a/BaseTools/Tests/GNUmakefile +++ b/BaseTools/Tests/GNUmakefile @@ -8,7 +8,7 @@ all: test test: - @if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then ${PYTHON_COMMAND} RunTests.py; else python RunTests.py; fi + @if command -v "${PYTHON_COMMAND}" >/dev/null 2>&1; then ${PYTHON_COMMAND} RunTests.py; else python RunTests.py; fi clean: find . -name '*.pyc' -exec rm '{}' ';' From 66d82c5fd8bed53634763ab3968d517690a5c3b5 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 25 Sep 2022 18:05:02 +0200 Subject: [PATCH 0208/1529] ArmVirtPkg: remove EbcDxe from all platforms The EBC interpreter is rarely, if ever, used on ARM, and is especially pointless on virtual machines. So let's drop it from the builds. Signed-off-by: Ard Biesheuvel Acked-by: Leif Lindholm --- ArmVirtPkg/ArmVirt.dsc.inc | 5 ----- ArmVirtPkg/ArmVirtCloudHv.fdf | 5 ----- ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc | 5 ----- ArmVirtPkg/ArmVirtXen.fdf | 5 ----- 4 files changed, 20 deletions(-) diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc index c39e2506a3..34575585ad 100644 --- a/ArmVirtPkg/ArmVirt.dsc.inc +++ b/ArmVirtPkg/ArmVirt.dsc.inc @@ -422,8 +422,3 @@ NULL|EmbeddedPkg/Library/PlatformHasAcpiLib/PlatformHasAcpiLib.inf } - - # - # EBC support - # - MdeModulePkg/Universal/EbcDxe/EbcDxe.inf diff --git a/ArmVirtPkg/ArmVirtCloudHv.fdf b/ArmVirtPkg/ArmVirtCloudHv.fdf index 81c539590a..a5f172d79b 100644 --- a/ArmVirtPkg/ArmVirtCloudHv.fdf +++ b/ArmVirtPkg/ArmVirtCloudHv.fdf @@ -195,11 +195,6 @@ READ_LOCK_STATUS = TRUE INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf INF ArmVirtPkg/CloudHvAcpiPlatformDxe/CloudHvAcpiPlatformDxe.inf - - # - # EBC support - # - INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf !endif # diff --git a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc index d4df6dede0..7872861330 100644 --- a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc +++ b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc @@ -146,11 +146,6 @@ READ_LOCK_STATUS = TRUE INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf INF OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf - - # - # EBC support - # - INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf !endif # diff --git a/ArmVirtPkg/ArmVirtXen.fdf b/ArmVirtPkg/ArmVirtXen.fdf index 132480f030..770fbf7289 100644 --- a/ArmVirtPkg/ArmVirtXen.fdf +++ b/ArmVirtPkg/ArmVirtXen.fdf @@ -201,11 +201,6 @@ READ_LOCK_STATUS = TRUE !if $(ARCH) == AARCH64 INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF ArmVirtPkg/XenAcpiPlatformDxe/XenAcpiPlatformDxe.inf - - # - # EBC support - # - INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf !endif # From 9c442f5d418e514b11dae6679edb3d5c9f066981 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 28 Jun 2022 12:58:43 +0200 Subject: [PATCH 0209/1529] ArmVirtPkg: do not enable iSCSI driver by default The iSCSI driver slows down the boot on a pristine variable store flash image, as it creates a couple of large EFI non-volatile variables to preserve state between boots. Since iSCSI boot for VMs is kind of niche anyway, let's default to disabled. If someone needs it in their build, they can use the -D build command option to re-enable it on the fly. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmVirtPkg/ArmVirtQemu.dsc | 2 +- ArmVirtPkg/ArmVirtQemuKernel.dsc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 9369a88858..25abf5eb27 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -40,7 +40,7 @@ DEFINE NETWORK_SNP_ENABLE = FALSE DEFINE NETWORK_TLS_ENABLE = FALSE DEFINE NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE - DEFINE NETWORK_ISCSI_ENABLE = TRUE + DEFINE NETWORK_ISCSI_ENABLE = FALSE !if $(NETWORK_SNP_ENABLE) == TRUE !error "NETWORK_SNP_ENABLE is IA32/X64/EBC only" diff --git a/ArmVirtPkg/ArmVirtQemuKernel.dsc b/ArmVirtPkg/ArmVirtQemuKernel.dsc index 7f7d15d6ee..a80ae92faa 100644 --- a/ArmVirtPkg/ArmVirtQemuKernel.dsc +++ b/ArmVirtPkg/ArmVirtQemuKernel.dsc @@ -38,7 +38,7 @@ DEFINE NETWORK_SNP_ENABLE = FALSE DEFINE NETWORK_TLS_ENABLE = FALSE DEFINE NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE - DEFINE NETWORK_ISCSI_ENABLE = TRUE + DEFINE NETWORK_ISCSI_ENABLE = FALSE !if $(NETWORK_SNP_ENABLE) == TRUE !error "NETWORK_SNP_ENABLE is IA32/X64/EBC only" From deed548dc087c503ce4c85132b8e4c6c96ad4332 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 1 Jul 2022 20:24:26 +0200 Subject: [PATCH 0210/1529] ArmPlatformPkg/PrePeiCore: permit entry with the MMU enabled Some platforms may set up a preliminary ID map in flash and enter EFI with the MMU and caches enabled, as this removes a lot of the complexity around cache coherency. Let's take this into account, and avoid touching the MMU controls or perform cache invalidation when the MMU is enabled at entry. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPlatformPkg/PrePeiCore/PrePeiCore.c | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c index 9c4b25df95..8b86c6e69a 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c @@ -58,17 +58,19 @@ CEntryPoint ( IN EFI_PEI_CORE_ENTRY_POINT PeiCoreEntryPoint ) { - // Data Cache enabled on Primary core when MMU is enabled. - ArmDisableDataCache (); - // Invalidate instruction cache - ArmInvalidateInstructionCache (); - // Enable Instruction Caches on all cores. - ArmEnableInstructionCache (); - - InvalidateDataCacheRange ( - (VOID *)(UINTN)PcdGet64 (PcdCPUCoresStackBase), - PcdGet32 (PcdCPUCorePrimaryStackSize) - ); + if (!ArmMmuEnabled ()) { + // Data Cache enabled on Primary core when MMU is enabled. + ArmDisableDataCache (); + // Invalidate instruction cache + ArmInvalidateInstructionCache (); + // Enable Instruction Caches on all cores. + ArmEnableInstructionCache (); + + InvalidateDataCacheRange ( + (VOID *)(UINTN)PcdGet64 (PcdCPUCoresStackBase), + PcdGet32 (PcdCPUCorePrimaryStackSize) + ); + } // // Note: Doesn't have to Enable CPU interface in non-secure world, From 98a575dac1715ac49604279a1316d01f3b56eaea Mon Sep 17 00:00:00 2001 From: Matt DeVillier Date: Wed, 26 May 2021 17:33:29 -0500 Subject: [PATCH 0211/1529] Ps2KbdCtrller: Make wait for SUCCESS after BAT non-fatal Recent model Chromebooks only return ACK, but not BAT_SUCCESS, which causes hanging and failed ps2k init. To mitigate this, make the absence of BAT_SUCCESS reply non-fatal, and reduce the no-reply timeout from 4s to 1s. Tested on google/dracia and purism/librem_14 Acked-by: Hao A Wu Reviewed-by: Ray Ni Signed-off-by: Sean Rhodes Signed-off-by: Matt DeVillier --- MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c index 77dc226222..981309f8b0 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c @@ -1731,13 +1731,7 @@ InitKeyboard ( // // wait for BAT completion code // - mWaitForValueTimeOut = KEYBOARD_BAT_TIMEOUT; - - Status = KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_BAT_SUCCESS); - if (EFI_ERROR (Status)) { - KeyboardError (ConsoleIn, L"Keyboard self test failed!\n\r"); - goto Done; - } + KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_BAT_SUCCESS); mWaitForValueTimeOut = KEYBOARD_WAITFORVALUE_TIMEOUT; From cf6f9e5d78d546139a0a4ef71812e9c2a5eb9a56 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 11 Oct 2022 14:59:52 -0600 Subject: [PATCH 0212/1529] ArmPlatformPkg/PrePeiCore: Print the firmware version early in boot Copy code from PrePi to PrePeiCore that prints the firmware version and build date early in the boot process. Signed-off-by: Rebecca Cran Reviewed-by: Sami Mujawar Tested-by: Oliver Steffen Reviewed-by: Leif Lindholm --- ArmPlatformPkg/PrePeiCore/PrePeiCore.c | 29 +++++++++++++++++++ .../PrePeiCore/PrePeiCoreMPCore.inf | 3 ++ .../PrePeiCore/PrePeiCoreUniCore.inf | 3 ++ 3 files changed, 35 insertions(+) diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c index 8b86c6e69a..42a7ccc9c6 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include "PrePeiCore.h" @@ -52,6 +54,31 @@ CreatePpiList ( *PpiListSize = sizeof (gCommonPpiTable) + PlatformPpiListSize; } +/** + + Prints firmware version and build time to serial console. + +**/ +STATIC +VOID +PrintFirmwareVersion ( + VOID + ) +{ + CHAR8 Buffer[100]; + UINTN CharCount; + + CharCount = AsciiSPrint ( + Buffer, + sizeof (Buffer), + "UEFI firmware (version %s built at %a on %a)\n\r", + (CHAR16 *)PcdGetPtr (PcdFirmwareVersionString), + __TIME__, + __DATE__ + ); + SerialPortWrite ((UINT8 *)Buffer, CharCount); +} + VOID CEntryPoint ( IN UINTN MpId, @@ -96,6 +123,8 @@ CEntryPoint ( // called. ProcessLibraryConstructorList (); + PrintFirmwareVersion (); + // Initialize the Debug Agent for Source Level Debugging InitializeDebugAgent (DEBUG_AGENT_INIT_POSTMEM_SEC, NULL, NULL); SaveAndSetDebugTimerInterrupt (TRUE); diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf b/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf index a5b4722459..4a3112b58d 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf @@ -54,6 +54,9 @@ gEfiTemporaryRamSupportPpiGuid gArmMpCoreInfoPpiGuid +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString + [FeaturePcd] gArmPlatformTokenSpaceGuid.PcdSendSgiToBringUpSecondaryCores diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf b/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf index 466a2b01c3..ab5bf1dac2 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf @@ -52,6 +52,9 @@ [Ppis] gEfiTemporaryRamSupportPpiGuid +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString + [FeaturePcd] gArmPlatformTokenSpaceGuid.PcdSendSgiToBringUpSecondaryCores From b8c8f67ea12a516571220ca1a8db9bf2ab0ce9e5 Mon Sep 17 00:00:00 2001 From: Nate DeSimone Date: Tue, 25 Oct 2022 14:38:29 -0700 Subject: [PATCH 0213/1529] MdeModulePkg: Fix spelling error in PciSioSerialDxe gSerialDevTempate should be gSerialDevTemplate Cc: Ray Ni Cc: Zhichao Gao Cc: Jian J Wang Cc: Liming Gao Cc: Michael D Kinney Signed-off-by: Nate DeSimone Reviewed-by: Michael D Kinney --- MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c index 2b5ff0a37a..8b1ce70118 100644 --- a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c +++ b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c @@ -138,7 +138,7 @@ InitializePciSioSerial ( ASSERT_EFI_ERROR (Status); // - // Initialize UART default setting in gSerialDevTempate + // Initialize UART default setting in gSerialDevTemplate // gSerialDevTemplate.SerialMode.BaudRate = PcdGet64 (PcdUartDefaultBaudRate); gSerialDevTemplate.SerialMode.DataBits = PcdGet8 (PcdUartDefaultDataBits); From d80247eb6de62a98312b5319ee584b3c36dde3b2 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Tue, 25 Oct 2022 11:43:49 -0700 Subject: [PATCH 0214/1529] IntelFsp2WrapperPkg: Check header revision for MultiPhase support. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4119 Earlier version of FSP header may not have MultiPhase fields present in the FspInfoHeader so the handler should verify header revision before accessing the MultiPhase fields from the header. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- .../PeiFspWrapperMultiPhaseProcessLib.c | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c b/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c index 1248accf87..834dca07a9 100644 --- a/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c +++ b/IntelFsp2WrapperPkg/Library/FspWrapperMultiPhaseProcessLib/PeiFspWrapperMultiPhaseProcessLib.c @@ -73,15 +73,27 @@ CallFspMultiPhaseEntry ( // // FSP_MULTI_PHASE_INIT and FSP_MULTI_PHASE_SI_INIT API functions having same prototype. // - UINTN FspMultiPhaseApiEntry; - UINTN FspMultiPhaseApiOffset; - EFI_STATUS Status; - BOOLEAN InterruptState; + UINTN FspMultiPhaseApiEntry; + UINTN FspMultiPhaseApiOffset; + EFI_STATUS Status; + BOOLEAN InterruptState; + BOOLEAN IsVariableServiceRequest; + FSP_MULTI_PHASE_PARAMS *FspMultiPhaseParamsPtr; + + FspMultiPhaseParamsPtr = (FSP_MULTI_PHASE_PARAMS *)FspMultiPhaseParams; + IsVariableServiceRequest = FALSE; + if ((FspMultiPhaseParamsPtr->MultiPhaseAction == EnumMultiPhaseGetVariableRequestInfo) || + (FspMultiPhaseParamsPtr->MultiPhaseAction == EnumMultiPhaseCompleteVariableRequest)) + { + IsVariableServiceRequest = TRUE; + } if (ComponentIndex == FspMultiPhaseMemInitApiIndex) { FspHeader = (FSP_INFO_HEADER *)FspFindFspHeader (PcdGet32 (PcdFspmBaseAddress)); if (FspHeader == NULL) { return EFI_DEVICE_ERROR; + } else if (FspHeader->SpecVersion < 0x24) { + return EFI_UNSUPPORTED; } FspMultiPhaseApiOffset = FspHeader->FspMultiPhaseMemInitEntryOffset; @@ -89,6 +101,10 @@ CallFspMultiPhaseEntry ( FspHeader = (FSP_INFO_HEADER *)FspFindFspHeader (PcdGet32 (PcdFspsBaseAddress)); if (FspHeader == NULL) { return EFI_DEVICE_ERROR; + } else if (FspHeader->SpecVersion < 0x22) { + return EFI_UNSUPPORTED; + } else if ((FspHeader->SpecVersion < 0x24) && (IsVariableServiceRequest == TRUE)) { + return EFI_UNSUPPORTED; } FspMultiPhaseApiOffset = FspHeader->FspMultiPhaseSiInitEntryOffset; @@ -117,10 +133,11 @@ CallFspMultiPhaseEntry ( /** FSP Wrapper Variable Request Handler - @param[in] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) - @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. + @param[in, out] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) + @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. - @retval EFI_UNSUPPORTED FSP Wrapper cannot support the specific variable request + @retval EFI_UNSUPPORTED FSP Wrapper cannot support the specific variable request, + or FSP does not support VariableService @retval EFI_STATUS Return FSP returned status **/ @@ -284,10 +301,11 @@ FspWrapperVariableRequestHandler ( /** FSP Wrapper MultiPhase Handler - @param[in] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) - @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. + @param[in, out] FspHobListPtr - Pointer to FSP HobList (valid after FSP-M completed) + @param[in] ComponentIndex - FSP Component which executing MultiPhase initialization. - @retval EFI_STATUS Always return EFI_SUCCESS + @retval EFI_UNSUPPORTED Specific MultiPhase action was not supported. + @retval EFI_SUCCESS MultiPhase action were completed successfully. **/ EFI_STATUS From 9bd90ae4985d2b9670fd60451c7ee51a398e89a8 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Wed, 26 Oct 2022 00:13:08 +0800 Subject: [PATCH 0215/1529] Maintainers.txt: Update maintainers list Update maintainers.txt to add Igor from AMI as the reviewer of RedfishPkg. Signed-off-by: Abner Chang Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Cc: Nickle Wang Cc: Igor Kulchytskyy --- Maintainers.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Maintainers.txt b/Maintainers.txt index c641414109..1391b079b7 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -544,6 +544,7 @@ RedfishPkg: Redfish related modules F: RedfishPkg/ M: Abner Chang [changab] M: Nickle Wang [nicklela] +R: Igor Kulchytskyy [igorkulchytskyy] SecurityPkg F: SecurityPkg/ From 132a6fd602a2f53f9085e160777f742cf7e9a9c3 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Thu, 20 Oct 2022 22:43:14 +0800 Subject: [PATCH 0216/1529] Maintainers.txt: Update maintainers and reviewers for LoongArch64 Cc: Michael D Kinney Cc: Liming Gao Cc: Baoqi Zhang Cc: Dongyan Qian Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- Maintainers.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Maintainers.txt b/Maintainers.txt index 1391b079b7..8e81ccfdec 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -102,6 +102,12 @@ F: */RiscV64/ M: Sunil V L [vlsunil] R: Daniel Schaefer [JohnAZoidberg] +LOONGARCH64 +F: */LoongArch64/ +M: Chao Li [kilaterlee] +M: Baoqi Zhang [zhangbaoqi-ls] +R: Dongyan Qian [MarsDoge] + EDK II Continuous Integration: ------------------------------ .azurepipelines/ From e7c7c0849fb3728636bef24dc61c09d9f6b2bec0 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 2 Aug 2022 11:48:04 +0200 Subject: [PATCH 0217/1529] ArmVirtPkg: make EFI_LOADER_DATA non-executable When the memory protections were implemented and enabled on ArmVirtQemu 5+ years ago, we had to work around the fact that GRUB at the time expected EFI_LOADER_DATA to be executable, as that is the memory type it allocates when loading its modules. This has been fixed in GRUB in August 2017, so by now, we should be able to tighten this, and remove execute permissions from EFI_LOADER_DATA allocations. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirt.dsc.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc index 34575585ad..462073517a 100644 --- a/ArmVirtPkg/ArmVirt.dsc.inc +++ b/ArmVirtPkg/ArmVirt.dsc.inc @@ -368,7 +368,7 @@ # reserved ones, with the exception of LoaderData regions, of which OS loaders # (i.e., GRUB) may assume that its contents are executable. # - gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD1 + gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5 [Components.common] # From 64a490bea6721c08eface948120ae2941cda2365 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 2 Aug 2022 18:53:51 +0200 Subject: [PATCH 0218/1529] ArmVirtPkg/ArmVirtQemu: wire up timeout PCD to Timeout variable Use the appropriate PCD definition in the ArmVirtQemu DSC so that the boot timeout is taken from the Timeout variable automatically, which is what Linux tools such as efibootmgr expect. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 25abf5eb27..a40234bf78 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -293,6 +293,8 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS !endif + gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|L"Timeout"|gEfiGlobalVariableGuid|0x0|5 + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform From 9f846c4b285a4f0688fd32c72da0f9b902f751ad Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 2 Jul 2022 19:19:05 +0200 Subject: [PATCH 0219/1529] ArmVirtPkg/ArmVirtQemu: implement ArmPlatformLib with static ID map To substantially reduce the amount of processing that takes place with the MMU and caches off, implement a version of ArmPlatformLib specific for QEMU/mach-virt in AArch64 mode that carries a statically allocated and populated ID map that covers the NOR flash and device region, and 128 MiB of DRAM at the base of memory (0x4000_0000). Note that 128 MiB has always been the minimum amount of DRAM we support for this configuration, and the existing code already ASSERT()s in DEBUG mode when booting with less. Signed-off-by: Ard Biesheuvel --- .../AArch64/ArmPlatformHelper.S | 115 ++++++++++++++++++ .../ArmPlatformLibQemu/ArmPlatformLibQemu.c | 64 ++++++++++ .../ArmPlatformLibQemu/ArmPlatformLibQemu.inf | 40 ++++++ ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S | 57 +++++++++ 4 files changed, 276 insertions(+) create mode 100644 ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S create mode 100644 ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.c create mode 100644 ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.inf create mode 100644 ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S new file mode 100644 index 0000000000..05ccc7f9f0 --- /dev/null +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S @@ -0,0 +1,115 @@ +// +// Copyright (c) 2022, Google LLC. All rights reserved. +// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// + +#include + + .macro mov_i, reg:req, imm:req + movz \reg, :abs_g3:\imm + movk \reg, :abs_g2_nc:\imm + movk \reg, :abs_g1_nc:\imm + movk \reg, :abs_g0_nc:\imm + .endm + + .set MAIR_DEV_nGnRnE, 0x00 + .set MAIR_MEM_NC, 0x44 + .set MAIR_MEM_WT, 0xbb + .set MAIR_MEM_WBWA, 0xff + .set mairval, MAIR_DEV_nGnRnE | (MAIR_MEM_NC << 8) | (MAIR_MEM_WT << 16) | (MAIR_MEM_WBWA << 24) + + .set TCR_TG0_4KB, 0x0 << 14 + .set TCR_TG1_4KB, 0x2 << 30 + .set TCR_IPS_SHIFT, 32 + .set TCR_EPD1, 0x1 << 23 + .set TCR_SH_INNER, 0x3 << 12 + .set TCR_RGN_OWB, 0x1 << 10 + .set TCR_RGN_IWB, 0x1 << 8 + .set tcrval, TCR_TG0_4KB | TCR_TG1_4KB | TCR_EPD1 | TCR_RGN_OWB + .set tcrval, tcrval | TCR_RGN_IWB | TCR_SH_INNER + + .set SCTLR_ELx_I, 0x1 << 12 + .set SCTLR_ELx_SA, 0x1 << 3 + .set SCTLR_ELx_C, 0x1 << 2 + .set SCTLR_ELx_M, 0x1 << 0 + .set SCTLR_EL1_SPAN, 0x1 << 23 + .set SCTLR_EL1_WXN, 0x1 << 19 + .set SCTLR_EL1_SED, 0x1 << 8 + .set SCTLR_EL1_ITD, 0x1 << 7 + .set SCTLR_EL1_RES1, (0x1 << 11) | (0x1 << 20) | (0x1 << 22) | (0x1 << 28) | (0x1 << 29) + .set sctlrval, SCTLR_ELx_M | SCTLR_ELx_C | SCTLR_ELx_SA | SCTLR_EL1_ITD | SCTLR_EL1_SED + .set sctlrval, sctlrval | SCTLR_ELx_I | SCTLR_EL1_SPAN | SCTLR_EL1_RES1 + + +ASM_FUNC(ArmPlatformPeiBootAction) + mrs x0, CurrentEL // check current exception level + tbz x0, #3, 0f // bail if above EL1 + ret + +0:mov_i x0, mairval + mov_i x1, tcrval + adrp x2, idmap + orr x2, x2, #0xff << 48 // set non-zero ASID + mov_i x3, sctlrval + + mrs x6, id_aa64mmfr0_el1 // get the supported PA range + and x6, x6, #0xf // isolate PArange bits + cmp x6, #6 // 0b0110 == 52 bits + sub x6, x6, #1 // subtract 1 + cinc x6, x6, ne // add back 1 unless PArange == 52 bits + bfi x1, x6, #32, #3 // copy updated PArange into TCR_EL1.IPS + + cmp x6, #3 // 0b0011 == 42 bits + sub x6, x6, #1 // subtract 1 + cinc x6, x6, lt // add back 1 unless VA range >= 42 + + mov x7, #32 + sub x6, x7, x6, lsl #2 // T0SZ for PArange != 42 + mov x7, #64 - 42 // T0SZ for PArange == 42 + csel x6, x6, x7, ne + orr x1, x1, x6 // set T0SZ field in TCR + + cmp x6, #64 - 40 // VA size < 40 bits? + add x4, x2, #0x1000 // advance to level 1 descriptor + csel x2, x4, x2, gt + + msr mair_el1, x0 // set up the 1:1 mapping + msr tcr_el1, x1 + msr ttbr0_el1, x2 + isb + + tlbi vmalle1 // invalidate any cached translations + ic iallu // invalidate the I-cache + dsb nsh + isb + + msr sctlr_el1, x3 // enable MMU and caches + isb + ret + +//UINTN +//ArmPlatformGetCorePosition ( +// IN UINTN MpId +// ); +// With this function: CorePos = (ClusterId * 4) + CoreId +ASM_FUNC(ArmPlatformGetCorePosition) + mov x0, xzr + ret + +//UINTN +//ArmPlatformGetPrimaryCoreMpId ( +// VOID +// ); +ASM_FUNC(ArmPlatformGetPrimaryCoreMpId) + MOV32 (w0, FixedPcdGet32 (PcdArmPrimaryCore)) + ret + +//UINTN +//ArmPlatformIsPrimaryCore ( +// IN UINTN MpId +// ); +ASM_FUNC(ArmPlatformIsPrimaryCore) + mov x0, #1 + ret diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.c b/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.c new file mode 100644 index 0000000000..1de80422ee --- /dev/null +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.c @@ -0,0 +1,64 @@ +/** @file + + Copyright (c) 2011-2012, ARM Limited. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Return the current Boot Mode. + + This function returns the boot reason on the platform + + @return Return the current Boot Mode of the platform + +**/ +EFI_BOOT_MODE +ArmPlatformGetBootMode ( + VOID + ) +{ + return BOOT_WITH_FULL_CONFIGURATION; +} + +/** + Initialize controllers that must setup in the normal world. + + This function is called by the ArmPlatformPkg/PrePi or + ArmPlatformPkg/PlatformPei in the PEI phase. + + @param[in] MpId ID of the calling CPU + + @return RETURN_SUCCESS unless the operation failed +**/ +RETURN_STATUS +ArmPlatformInitialize ( + IN UINTN MpId + ) +{ + return RETURN_SUCCESS; +} + +/** + Return the Platform specific PPIs. + + This function exposes the Platform Specific PPIs. They can be used by any + PrePi modules or passed to the PeiCore by PrePeiCore. + + @param[out] PpiListSize Size in Bytes of the Platform PPI List + @param[out] PpiList Platform PPI List + +**/ +VOID +ArmPlatformGetPlatformPpiList ( + OUT UINTN *PpiListSize, + OUT EFI_PEI_PPI_DESCRIPTOR **PpiList + ) +{ + *PpiListSize = 0; + *PpiList = NULL; +} diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.inf b/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.inf new file mode 100644 index 0000000000..b2ecdfa061 --- /dev/null +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.inf @@ -0,0 +1,40 @@ +## @file +# ArmPlatformLib implementation for QEMU/mach-virt on AArch64 that contains a +# statically allocated 1:1 mapping of the first 128 MiB of DRAM, as well as +# the NOR flash and the device region +# +# Copyright (c) 2011-2012, ARM Limited. All rights reserved. +# Copyright (c) 2022, Google LLC. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = ArmPlatformLibQemu + FILE_GUID = 40af3a25-f02c-4aef-94ef-7ac0282d21d4 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ArmPlatformLib + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + ArmPkg/ArmPkg.dec + ArmPlatformPkg/ArmPlatformPkg.dec + +[LibraryClasses] + ArmLib + DebugLib + +[Sources.common] + ArmPlatformLibQemu.c + IdMap.S + +[Sources.AArch64] + AArch64/ArmPlatformHelper.S + +[FixedPcd] + gArmTokenSpaceGuid.PcdArmPrimaryCoreMask + gArmTokenSpaceGuid.PcdArmPrimaryCore diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S new file mode 100644 index 0000000000..4a4b7b77ed --- /dev/null +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: BSD-2-Clause-Patent +// Copyright 2022 Google LLC +// Author: Ard Biesheuvel + + .set TT_TYPE_BLOCK, 0x1 + .set TT_TYPE_PAGE, 0x3 + .set TT_TYPE_TABLE, 0x3 + + .set TT_AF, 0x1 << 10 + .set TT_NG, 0x1 << 11 + .set TT_RO, 0x2 << 6 + .set TT_XN, 0x3 << 53 + + .set TT_MT_DEV, 0x0 << 2 // MAIR #0 + .set TT_MT_MEM, (0x3 << 2) | (0x3 << 8) // MAIR #3 + + .set PAGE_XIP, TT_TYPE_PAGE | TT_MT_MEM | TT_AF | TT_RO | TT_NG + .set BLOCK_DEV, TT_TYPE_BLOCK | TT_MT_DEV | TT_AF | TT_XN | TT_NG + .set BLOCK_MEM, TT_TYPE_BLOCK | TT_MT_MEM | TT_AF | TT_XN | TT_NG + + .globl idmap + .section ".rodata.idmap", "a", %progbits + .align 12 + +idmap: /* level 0 */ + .quad 1f + TT_TYPE_TABLE + .fill 511, 8, 0x0 + +1: /* level 1 */ + .quad 20f + TT_TYPE_TABLE // 1 GB of flash and device mappings + .quad 21f + TT_TYPE_TABLE // up to 1 GB of DRAM + .fill 510, 8, 0x0 // 510 GB of remaining VA space + +20: /* level 2 */ + .quad 3f + TT_TYPE_TABLE // up to 2 MB of flash + .fill 63, 8, 0x0 // 126 MB of unused flash + .set idx, 64 + .rept 448 + .quad BLOCK_DEV | (idx << 21) // 896 MB of RW- device mappings + .set idx, idx + 1 + .endr + +21: /* level 2 */ + .set idx, 0x40000000 >> 21 + .rept 64 + .quad BLOCK_MEM | (idx << 21) // 128 MB of RW- memory mappings + .set idx, idx + 1 + .endr + .fill 448, 8, 0x0 + +3: /* level 3 */ + .quad 0x0 // omit first 4k page + .set idx, 1 + .rept 511 + .quad PAGE_XIP | (idx << 12) // 2044 KiB of R-X flash mappings + .set idx, idx + 1 + .endr From f0fddf074ce4d5b4ac721ae3eb17367721a09030 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 2 Jul 2022 19:24:13 +0200 Subject: [PATCH 0220/1529] ArmVirtPkg/ArmVirtQemu: use first 128 MiB as permanent PEI memory In order to allow booting with the MMU and caches enabled really early, we need to ensure that the code that populates the page tables can access those page tables with the statically defined ID map active. So let's put the permanent PEI RAM in the first 128 MiB of memory, which we will cover with this initial ID map (as it is the minimum supported DRAM size for ArmVirtQemu). Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c | 104 ++++++++++++++++++++ ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf | 59 +++++++++++ 2 files changed, 163 insertions(+) create mode 100644 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c create mode 100644 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf diff --git a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c new file mode 100644 index 0000000000..ef88a9df1d --- /dev/null +++ b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c @@ -0,0 +1,104 @@ +/** @file + + Copyright (c) 2011, ARM Limited. All rights reserved. + Copyright (c) 2022, Google LLC. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include + +EFI_STATUS +EFIAPI +MemoryPeim ( + IN EFI_PHYSICAL_ADDRESS UefiMemoryBase, + IN UINT64 UefiMemorySize + ); + +/** + Build the memory type information HOB that describes how many pages of each + type to preallocate when initializing the GCD memory map. +**/ +VOID +EFIAPI +BuildMemoryTypeInformationHob ( + VOID + ) +{ + EFI_MEMORY_TYPE_INFORMATION Info[10]; + + Info[0].Type = EfiACPIReclaimMemory; + Info[0].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiACPIReclaimMemory); + Info[1].Type = EfiACPIMemoryNVS; + Info[1].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiACPIMemoryNVS); + Info[2].Type = EfiReservedMemoryType; + Info[2].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiReservedMemoryType); + Info[3].Type = EfiRuntimeServicesData; + Info[3].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiRuntimeServicesData); + Info[4].Type = EfiRuntimeServicesCode; + Info[4].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiRuntimeServicesCode); + Info[5].Type = EfiBootServicesCode; + Info[5].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiBootServicesCode); + Info[6].Type = EfiBootServicesData; + Info[6].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiBootServicesData); + Info[7].Type = EfiLoaderCode; + Info[7].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiLoaderCode); + Info[8].Type = EfiLoaderData; + Info[8].NumberOfPages = FixedPcdGet32 (PcdMemoryTypeEfiLoaderData); + + // Terminator for the list + Info[9].Type = EfiMaxMemoryType; + Info[9].NumberOfPages = 0; + + BuildGuidDataHob (&gEfiMemoryTypeInformationGuid, &Info, sizeof (Info)); +} + +/** + Module entry point. + + @param[in] FileHandle Handle of the file being invoked. + @param[in] PeiServices Describes the list of possible PEI Services. + + @return EFI_SUCCESS unless the operation failed. +**/ +EFI_STATUS +EFIAPI +InitializeMemory ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + UINTN UefiMemoryBase; + EFI_STATUS Status; + + ASSERT (FixedPcdGet64 (PcdSystemMemoryBase) < (UINT64)MAX_ALLOC_ADDRESS); + + // + // Put the permanent PEI memory in the first 128 MiB of DRAM so that + // it is covered by the statically configured ID map. + // + UefiMemoryBase = (UINTN)FixedPcdGet64 (PcdSystemMemoryBase) + SIZE_128MB + - FixedPcdGet32 (PcdSystemMemoryUefiRegionSize); + + Status = PeiServicesInstallPeiMemory ( + UefiMemoryBase, + FixedPcdGet32 (PcdSystemMemoryUefiRegionSize) + ); + ASSERT_EFI_ERROR (Status); + + Status = MemoryPeim ( + UefiMemoryBase, + FixedPcdGet32 (PcdSystemMemoryUefiRegionSize) + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} diff --git a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf new file mode 100644 index 0000000000..2039f71a0e --- /dev/null +++ b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf @@ -0,0 +1,59 @@ +## @file +# Implementation of MemoryInitPeim that uses the first 128 MiB at the base of +# DRAM as permanent PEI memory +# +# Copyright (c) 2011-2014, ARM Ltd. All rights reserved.
+# Copyright (c) 2022, Google LLC. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = MemoryInit + FILE_GUID = 0fbffd44-f98f-4e1c-9922-e9b21f13c3f8 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = InitializeMemory + +[Sources] + MemoryInitPeim.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + EmbeddedPkg/EmbeddedPkg.dec + ArmPkg/ArmPkg.dec + ArmPlatformPkg/ArmPlatformPkg.dec + +[LibraryClasses] + PeimEntryPoint + DebugLib + HobLib + ArmLib + ArmPlatformLib + MemoryInitPeiLib + +[Guids] + gEfiMemoryTypeInformationGuid + +[FeaturePcd] + gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob + +[FixedPcd] + gArmTokenSpaceGuid.PcdSystemMemoryBase + gArmPlatformTokenSpaceGuid.PcdSystemMemoryUefiRegionSize + + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData + +[Depex] + TRUE From cf3caf6b1619bedeaa496a05d0c830cd7c85055a Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 2 Jul 2022 19:27:37 +0200 Subject: [PATCH 0221/1529] ArmVirtPkg/ArmVirtQemu: enable initial ID map at early boot Now that we have all the pieces in place, switch the AArch64 version of ArmVirtQemu to a mode where the first thing it does out of reset is enable a preliminary ID map that covers the NOR flash and sufficient DRAM to create the UEFI page tables as usual. The advantage of this is that no manipulation of memory occurs any longer before the MMU is enabled, which removes the need for explicit coherency management, which is cumbersome and bad for performance. It also means we no longer need to build all components that may execute with the MMU off (including BASE libraries) with strict alignment. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 17 ++++++++++++++--- ArmVirtPkg/ArmVirtQemu.fdf | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index a40234bf78..be8c697b0b 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -64,8 +64,6 @@ QemuFwCfgSimpleParserLib|OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParserLib.inf QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf - ArmPlatformLib|ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf - TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf NorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf @@ -93,6 +91,12 @@ TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLibNull/PeiDxeTpmPlatformHierarchyLib.inf !endif +[LibraryClasses.AARCH64] + ArmPlatformLib|ArmVirtPkg/Library/ArmPlatformLibQemu/ArmPlatformLibQemu.inf + +[LibraryClasses.ARM] + ArmPlatformLib|ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf + [LibraryClasses.common.PEIM] ArmVirtMemInfoLib|ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf @@ -113,6 +117,8 @@ UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf [BuildOptions] + GCC:*_*_AARCH64_CC_XIPFLAGS = -mno-strict-align + !include NetworkPkg/NetworkBuildOptions.dsc.inc ################################################################################ @@ -311,7 +317,12 @@ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } ArmPlatformPkg/PlatformPei/PlatformPeim.inf - ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf + ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf { + +!if $(ARCH) == AARCH64 + ArmMmuLib|ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf +!endif + } ArmPkg/Drivers/CpuPei/CpuPei.inf MdeModulePkg/Universal/Variable/Pei/VariablePei.inf diff --git a/ArmVirtPkg/ArmVirtQemu.fdf b/ArmVirtPkg/ArmVirtQemu.fdf index b5e2253295..7f17aeb3ad 100644 --- a/ArmVirtPkg/ArmVirtQemu.fdf +++ b/ArmVirtPkg/ArmVirtQemu.fdf @@ -107,7 +107,7 @@ READ_LOCK_STATUS = TRUE INF ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf INF MdeModulePkg/Core/Pei/PeiMain.inf INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf - INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf + INF ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf INF ArmPkg/Drivers/CpuPei/CpuPei.inf INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf From 2a75c09c280b004dadea3fa1f365a5afe5f98fc5 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 25 Sep 2022 16:02:36 +0200 Subject: [PATCH 0222/1529] ArmVirtPkg/ArmVirtQemu: Drop unused variable PEIM The variable PEIM is included in the build but its runtime prerequisites are absent so it is never dispatched. Just drop it. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 2 -- ArmVirtPkg/ArmVirtQemu.fdf | 1 - 2 files changed, 3 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index be8c697b0b..3baa1be7a7 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -325,8 +325,6 @@ } ArmPkg/Drivers/CpuPei/CpuPei.inf - MdeModulePkg/Universal/Variable/Pei/VariablePei.inf - !if $(TPM2_ENABLE) == TRUE MdeModulePkg/Universal/ResetSystemPei/ResetSystemPei.inf { diff --git a/ArmVirtPkg/ArmVirtQemu.fdf b/ArmVirtPkg/ArmVirtQemu.fdf index 7f17aeb3ad..c85e36b185 100644 --- a/ArmVirtPkg/ArmVirtQemu.fdf +++ b/ArmVirtPkg/ArmVirtQemu.fdf @@ -110,7 +110,6 @@ READ_LOCK_STATUS = TRUE INF ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf INF ArmPkg/Drivers/CpuPei/CpuPei.inf INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf - INF MdeModulePkg/Universal/Variable/Pei/VariablePei.inf INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf !if $(TPM2_ENABLE) == TRUE From 7d326dcf3baa43c91552a0e06dfc90a5ceeb50fc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 25 Sep 2022 17:24:41 +0200 Subject: [PATCH 0223/1529] ArmVirtPkg/ArmVirtQemu: avoid shadowing PEIMs unless necessary Some PEIMs register for shadow execution explicitly, but others exist that don't care and can happily execute in place. Since the emulated NOR flash is just RAM, shadowing has no performance benefits so let's only do this if needed. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 3baa1be7a7..d9c43e294c 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -218,6 +218,9 @@ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|3 gEfiShellPkgTokenSpaceGuid.PcdShellFileOperationSize|0x20000 + # Shadowing PEI modules is absolutely pointless when the NOR flash is emulated + gEfiMdeModulePkgTokenSpaceGuid.PcdShadowPeimOnBoot|FALSE + [PcdsFixedAtBuild.AARCH64] # Clearing BIT0 in this PCD prevents installing a 32-bit SMBIOS entry point, # if the entry point version is >= 3.0. AARCH64 OSes cannot assume the From 72829717b8b4c723cda2de657e56968b7a866a9d Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 25 Sep 2022 16:53:27 +0200 Subject: [PATCH 0224/1529] ArmVirtPkg/QemuVirtMemInfoLib: use HOB not PCD to record the memory size Due to the way we inherited the formerly fixed PCDs to describe the system memory base and size from ArmPlatformPkg, we ended up with a MemoryInit PEIM that relies on dynamic PCDs to communicate the size of system memory between the constructor of one of its library dependencies and the core module. This is unnecessary, and forces us to incorporate the PCD PEIM as well, for no good reason. So instead, let's use a HOB. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtPkg.dec | 1 + ArmVirtPkg/ArmVirtQemu.dsc | 6 ++-- .../ArmVirtMemoryInitPeiLib.c | 14 ++++++-- .../ArmVirtMemoryInitPeiLib.inf | 1 + .../QemuVirtMemInfoLib/QemuVirtMemInfoLib.c | 35 +++++++++++++++++-- .../QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf | 5 ++- .../QemuVirtMemInfoPeiLib.inf | 8 ++--- .../QemuVirtMemInfoPeiLibConstructor.c | 30 +++++++++------- 8 files changed, 75 insertions(+), 25 deletions(-) diff --git a/ArmVirtPkg/ArmVirtPkg.dec b/ArmVirtPkg/ArmVirtPkg.dec index 4e165f6cd8..89d21ec3a3 100644 --- a/ArmVirtPkg/ArmVirtPkg.dec +++ b/ArmVirtPkg/ArmVirtPkg.dec @@ -32,6 +32,7 @@ gArmVirtTokenSpaceGuid = { 0x0B6F5CA7, 0x4F53, 0x445A, { 0xB7, 0x6E, 0x2E, 0x36, 0x5B, 0x80, 0x63, 0x66 } } gEarlyPL011BaseAddressGuid = { 0xB199DEA9, 0xFD5C, 0x4A84, { 0x80, 0x82, 0x2F, 0x41, 0x70, 0x78, 0x03, 0x05 } } gEarly16550UartBaseAddressGuid = { 0xea67ca3e, 0x1f54, 0x436b, { 0x97, 0x88, 0xd4, 0xeb, 0x29, 0xc3, 0x42, 0x67 } } + gArmVirtSystemMemorySizeGuid = { 0x504eccb9, 0x1bf0, 0x4420, { 0x86, 0x5d, 0xdc, 0x66, 0x06, 0xd4, 0x13, 0xbf } } gArmVirtVariableGuid = { 0x50bea1e5, 0xa2c5, 0x46e9, { 0x9b, 0x3a, 0x59, 0x59, 0x65, 0x16, 0xb0, 0x0a } } diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index d9c43e294c..e3686c7ee3 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -221,6 +221,9 @@ # Shadowing PEI modules is absolutely pointless when the NOR flash is emulated gEfiMdeModulePkgTokenSpaceGuid.PcdShadowPeimOnBoot|FALSE + # System Memory Size -- 128 MB initially, actual size will be fetched from DT + gArmTokenSpaceGuid.PcdSystemMemorySize|0x8000000 + [PcdsFixedAtBuild.AARCH64] # Clearing BIT0 in this PCD prevents installing a 32-bit SMBIOS entry point, # if the entry point version is >= 3.0. AARCH64 OSes cannot assume the @@ -237,9 +240,6 @@ # enumeration to complete before installing ACPI tables. gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE - # System Memory Size -- 1 MB initially, actual size will be fetched from DT - gArmTokenSpaceGuid.PcdSystemMemorySize|0x00100000 - gArmTokenSpaceGuid.PcdArmArchTimerSecIntrNum|0x0 gArmTokenSpaceGuid.PcdArmArchTimerIntrNum|0x0 gArmTokenSpaceGuid.PcdArmArchTimerVirtIntrNum|0x0 diff --git a/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.c b/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.c index 98d90ad420..72e5c65af7 100644 --- a/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.c +++ b/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.c @@ -52,10 +52,19 @@ MemoryPeim ( { EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttributes; UINT64 SystemMemoryTop; + UINT64 SystemMemorySize; + VOID *Hob; // Ensure PcdSystemMemorySize has been set ASSERT (PcdGet64 (PcdSystemMemorySize) != 0); + SystemMemorySize = PcdGet64 (PcdSystemMemorySize); + + Hob = GetFirstGuidHob (&gArmVirtSystemMemorySizeGuid); + if (Hob != NULL) { + SystemMemorySize = *(UINT64 *)GET_GUID_HOB_DATA (Hob); + } + // // Now, the permanent memory has been installed, we can call AllocatePages() // @@ -66,8 +75,7 @@ MemoryPeim ( EFI_RESOURCE_ATTRIBUTE_TESTED ); - SystemMemoryTop = PcdGet64 (PcdSystemMemoryBase) + - PcdGet64 (PcdSystemMemorySize); + SystemMemoryTop = PcdGet64 (PcdSystemMemoryBase) + SystemMemorySize; if (SystemMemoryTop - 1 > MAX_ALLOC_ADDRESS) { BuildResourceDescriptorHob ( @@ -87,7 +95,7 @@ MemoryPeim ( EFI_RESOURCE_SYSTEM_MEMORY, ResourceAttributes, PcdGet64 (PcdSystemMemoryBase), - PcdGet64 (PcdSystemMemorySize) + SystemMemorySize ); } diff --git a/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.inf b/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.inf index 21327f79f4..48d9c66b22 100644 --- a/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.inf +++ b/ArmVirtPkg/Library/ArmVirtMemoryInitPeiLib/ArmVirtMemoryInitPeiLib.inf @@ -34,6 +34,7 @@ CacheMaintenanceLib [Guids] + gArmVirtSystemMemorySizeGuid gEfiMemoryTypeInformationGuid [FeaturePcd] diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c index cf569bed99..9cf43f06c0 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c @@ -6,10 +6,12 @@ **/ -#include +#include +#include #include #include #include +#include #include // Number of Virtual Memory Map Descriptors @@ -24,6 +26,28 @@ #define MACH_VIRT_PERIPH_BASE 0x08000000 #define MACH_VIRT_PERIPH_SIZE SIZE_128MB +/** + Default library constructur that obtains the memory size from a PCD. + + @return Always returns RETURN_SUCCESS + +**/ +RETURN_STATUS +EFIAPI +QemuVirtMemInfoLibConstructor ( + VOID + ) +{ + UINT64 Size; + VOID *Hob; + + Size = PcdGet64 (PcdSystemMemorySize); + Hob = BuildGuidDataHob (&gArmVirtSystemMemorySizeGuid, &Size, sizeof Size); + ASSERT (Hob != NULL); + + return RETURN_SUCCESS; +} + /** Return the Virtual Memory Map of your platform @@ -43,9 +67,16 @@ ArmVirtGetMemoryMap ( ) { ARM_MEMORY_REGION_DESCRIPTOR *VirtualMemoryTable; + VOID *MemorySizeHob; ASSERT (VirtualMemoryMap != NULL); + MemorySizeHob = GetFirstGuidHob (&gArmVirtSystemMemorySizeGuid); + ASSERT (MemorySizeHob != NULL); + if (MemorySizeHob == NULL) { + return; + } + VirtualMemoryTable = AllocatePool ( sizeof (ARM_MEMORY_REGION_DESCRIPTOR) * MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS @@ -59,7 +90,7 @@ ArmVirtGetMemoryMap ( // System DRAM VirtualMemoryTable[0].PhysicalBase = PcdGet64 (PcdSystemMemoryBase); VirtualMemoryTable[0].VirtualBase = VirtualMemoryTable[0].PhysicalBase; - VirtualMemoryTable[0].Length = PcdGet64 (PcdSystemMemorySize); + VirtualMemoryTable[0].Length = *(UINT64 *)GET_GUID_HOB_DATA (MemorySizeHob); VirtualMemoryTable[0].Attributes = ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK; DEBUG (( diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf index 7150de6c10..6acad8bbd7 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf @@ -14,6 +14,7 @@ MODULE_TYPE = BASE VERSION_STRING = 1.0 LIBRARY_CLASS = ArmVirtMemInfoLib + CONSTRUCTOR = QemuVirtMemInfoLibConstructor [Sources] QemuVirtMemInfoLib.c @@ -30,7 +31,9 @@ BaseMemoryLib DebugLib MemoryAllocationLib - PcdLib + +[Guids] + gArmVirtSystemMemorySizeGuid [Pcd] gArmTokenSpaceGuid.PcdFvBaseAddress diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf index 7ecf6dfbb7..f045e39a41 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLib.inf @@ -32,16 +32,16 @@ BaseMemoryLib DebugLib FdtLib - PcdLib MemoryAllocationLib -[Pcd] +[Guids] + gArmVirtSystemMemorySizeGuid + +[FixedPcd] gArmTokenSpaceGuid.PcdFdBaseAddress gArmTokenSpaceGuid.PcdFvBaseAddress gArmTokenSpaceGuid.PcdSystemMemoryBase gArmTokenSpaceGuid.PcdSystemMemorySize - -[FixedPcd] gArmTokenSpaceGuid.PcdFdSize gArmTokenSpaceGuid.PcdFvSize gArmVirtTokenSpaceGuid.PcdDeviceTreeInitialBaseAddress diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c index 33d3597d57..c47ab82966 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c @@ -6,9 +6,10 @@ **/ -#include +#include +#include #include -#include +#include #include RETURN_STATUS @@ -17,14 +18,14 @@ QemuVirtMemInfoPeiLibConstructor ( VOID ) { - VOID *DeviceTreeBase; - INT32 Node, Prev; - UINT64 NewBase, CurBase; - UINT64 NewSize, CurSize; - CONST CHAR8 *Type; - INT32 Len; - CONST UINT64 *RegProp; - RETURN_STATUS PcdStatus; + VOID *DeviceTreeBase; + INT32 Node, Prev; + UINT64 NewBase, CurBase; + UINT64 NewSize, CurSize; + CONST CHAR8 *Type; + INT32 Len; + CONST UINT64 *RegProp; + VOID *Hob; NewBase = 0; NewSize = 0; @@ -86,8 +87,13 @@ QemuVirtMemInfoPeiLibConstructor ( // Make sure the start of DRAM matches our expectation // ASSERT (FixedPcdGet64 (PcdSystemMemoryBase) == NewBase); - PcdStatus = PcdSet64S (PcdSystemMemorySize, NewSize); - ASSERT_RETURN_ERROR (PcdStatus); + + Hob = BuildGuidDataHob ( + &gArmVirtSystemMemorySizeGuid, + &NewSize, + sizeof NewSize + ); + ASSERT (Hob != NULL); // // We need to make sure that the machine we are running on has at least From 81441cfcdbce7669369c8accdbe2b0ed4a3a8d8c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 25 Sep 2022 17:22:04 +0200 Subject: [PATCH 0225/1529] ArmVirtPkg/ArmVirtQemu: omit PCD PEIM unless TPM support is enabled The TPM discovery code relies on a dynamic PCD to communicate the TPM base address to other components. But no other code relies on dynamic PCDs in the PEI phase so let's drop the PCD PEIM when TPM support is not enabled. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 22 +++++++++++++++++----- ArmVirtPkg/ArmVirtQemu.fdf | 2 +- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index e3686c7ee3..fbd9270db5 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -288,10 +288,15 @@ # # TPM2 support # - gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 !if $(TPM2_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} gEfiSecurityPkgTokenSpaceGuid.PcdTpm2HashMask|0 +!else +[PcdsPatchableInModule] + # make this PCD patchable instead of dynamic when TPM support is not enabled + # this permits setting the PCD in unreachable code without pulling in dynamic PCD support + gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 !endif [PcdsDynamicHii] @@ -304,6 +309,13 @@ gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|L"Timeout"|gEfiGlobalVariableGuid|0x0|5 +[LibraryClasses.common.PEI_CORE, LibraryClasses.common.PEIM] +!if $(TPM2_ENABLE) == TRUE + PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf +!else + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf +!endif + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform @@ -315,10 +327,6 @@ # ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf MdeModulePkg/Core/Pei/PeiMain.inf - MdeModulePkg/Universal/PCD/Pei/Pcd.inf { - - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - } ArmPlatformPkg/PlatformPei/PlatformPeim.inf ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf { @@ -329,6 +337,10 @@ ArmPkg/Drivers/CpuPei/CpuPei.inf !if $(TPM2_ENABLE) == TRUE + MdeModulePkg/Universal/PCD/Pei/Pcd.inf { + + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + } MdeModulePkg/Universal/ResetSystemPei/ResetSystemPei.inf { ResetSystemLib|ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.inf diff --git a/ArmVirtPkg/ArmVirtQemu.fdf b/ArmVirtPkg/ArmVirtQemu.fdf index c85e36b185..764f652afd 100644 --- a/ArmVirtPkg/ArmVirtQemu.fdf +++ b/ArmVirtPkg/ArmVirtQemu.fdf @@ -109,10 +109,10 @@ READ_LOCK_STATUS = TRUE INF ArmPlatformPkg/PlatformPei/PlatformPeim.inf INF ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf INF ArmPkg/Drivers/CpuPei/CpuPei.inf - INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf !if $(TPM2_ENABLE) == TRUE + INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf INF MdeModulePkg/Universal/ResetSystemPei/ResetSystemPei.inf INF OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf INF SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf From 4bc7821deb3cd4054bbbcaeaea6a6798196beddf Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 26 Oct 2022 21:51:38 +0200 Subject: [PATCH 0226/1529] ArmVirtPkg/ArmVirtQemu: Clear XIP flags instead of overriding them Clang does not support undoing the effects of -mstrict-align by passing the -mno-strict-align counterpart, so appending the latter to the compiler's XIPFLAGS does not work. Instead, clear the flags entirely. This also removes -mgeneral-regs-only, but this is fine - we can tolerate SIMD codegen in PEIMs or BASE libraries as they run with the MMU and caches enabled. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtQemu.dsc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index fbd9270db5..28a4453068 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -117,7 +117,7 @@ UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf [BuildOptions] - GCC:*_*_AARCH64_CC_XIPFLAGS = -mno-strict-align + GCC:*_*_AARCH64_CC_XIPFLAGS == !include NetworkPkg/NetworkBuildOptions.dsc.inc From c89975ed8228e07d95c74306688ebf6e6ae2cfbb Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 18:35:10 +0200 Subject: [PATCH 0227/1529] OvmfPkg: clone NorFlashPlatformLib into VirtNorFlashPlatformLib Create a new library class in Ovmf that duplicates the existing NorFlashPlatformLib, but which will be tied to the VirtNorFlashDxe driver that will be introduced in a subsequent patch. This allows us to retire the original from ArmPlatformPkg. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- .../Include/Library/VirtNorFlashPlatformLib.h | 30 +++++++++++++++++++ OvmfPkg/OvmfPkg.dec | 4 +++ 2 files changed, 34 insertions(+) create mode 100644 OvmfPkg/Include/Library/VirtNorFlashPlatformLib.h diff --git a/OvmfPkg/Include/Library/VirtNorFlashPlatformLib.h b/OvmfPkg/Include/Library/VirtNorFlashPlatformLib.h new file mode 100644 index 0000000000..8f5b5e972d --- /dev/null +++ b/OvmfPkg/Include/Library/VirtNorFlashPlatformLib.h @@ -0,0 +1,30 @@ +/** @file + + Copyright (c) 2011-2012, ARM Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + **/ + +#ifndef __VIRT_NOR_FLASH_PLATFORM_LIB__ +#define __VIRT_NOR_FLASH_PLATFORM_LIB__ + +typedef struct { + UINTN DeviceBaseAddress; // Start address of the Device Base Address (DBA) + UINTN RegionBaseAddress; // Start address of one single region + UINTN Size; + UINTN BlockSize; +} VIRT_NOR_FLASH_DESCRIPTION; + +EFI_STATUS +VirtNorFlashPlatformInitialization ( + VOID + ); + +EFI_STATUS +VirtNorFlashPlatformGetDevices ( + OUT VIRT_NOR_FLASH_DESCRIPTION **NorFlashDescriptions, + OUT UINT32 *Count + ); + +#endif /* __VIRT_NOR_FLASH_PLATFORM_LIB__ */ diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index f13dd4a61f..5f5556c67c 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -101,6 +101,10 @@ # transports. VirtioMmioDeviceLib|Include/Library/VirtioMmioDeviceLib.h + ## @libraryclass Provides a Nor flash interface. + # + VirtNorFlashPlatformLib|Include/Library/VirtNorFlashPlatformLib.h + ## @libraryclass Invoke Xen hypercalls # XenHypercallLib|Include/Library/XenHypercallLib.h From 95cb43785825d4f60f8977efbeabed8e21c22240 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 16:41:43 +0200 Subject: [PATCH 0228/1529] OvmfPkg/VirtNorFlashDxe: clone ArmPlatformPkg's NOR flash driver QEMU's mach-virt is loosely based on ARM Versatile Express, and inherits its NOR flash driver, which is now being used on other QEMU emulated architectures as well. In order to permit ourselves the freedom to optimize this driver for use under KVM emulation, let's clone it into OvmfPkg, so we have a version we can hack without the risk of regressing bare metal platforms. The cloned version is mostly identical to the original, but it depends on the newly added VirtNorFlashPlatformLib library class instead of the original one from ArmPlatformPkg. Beyond that, only cosmetic changes related to #include order etc were made. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 991 ++++++++++++++++++ OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h | 422 ++++++++ .../VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c | 123 +++ OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 506 +++++++++ OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf | 72 ++ OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c | 777 ++++++++++++++ 6 files changed, 2891 insertions(+) create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf create mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c new file mode 100644 index 0000000000..12fa720dad --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -0,0 +1,991 @@ +/** @file NorFlash.c + + Copyright (c) 2011 - 2020, Arm Limited. All rights reserved.
+ Copyright (c) 2020, Linaro, Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +#include "VirtNorFlash.h" + +// +// Global variable declarations +// +extern NOR_FLASH_INSTANCE **mNorFlashInstances; +extern UINT32 mNorFlashDeviceCount; + +UINT32 +NorFlashReadStatusRegister ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN SR_Address + ) +{ + // Prepare to read the status register + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER); + return MmioRead32 (Instance->DeviceBaseAddress); +} + +STATIC +BOOLEAN +NorFlashBlockIsLocked ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ) +{ + UINT32 LockStatus; + + // Send command for reading device id + SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID); + + // Read block lock status + LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2)); + + // Decode block lock status + LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus); + + if ((LockStatus & 0x2) != 0) { + DEBUG ((DEBUG_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n")); + } + + return ((LockStatus & 0x1) != 0); +} + +STATIC +EFI_STATUS +NorFlashUnlockSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ) +{ + UINT32 LockStatus; + + // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations + // and to protect shared data structures. + + if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) { + do { + // Request a lock setup + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); + + // Request an unlock + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); + + // Send command for reading device id + SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID); + + // Read block lock status + LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2)); + + // Decode block lock status + LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus); + } while ((LockStatus & 0x1) == 1); + } else { + // Request a lock setup + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); + + // Request an unlock + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); + + // Wait until the status register gives us the all clear + do { + LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress); + } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); + } + + // Put device back into Read Array mode + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY); + + DEBUG ((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress)); + + return EFI_SUCCESS; +} + +EFI_STATUS +NorFlashUnlockSingleBlockIfNecessary ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ) +{ + EFI_STATUS Status; + + Status = EFI_SUCCESS; + + if (NorFlashBlockIsLocked (Instance, BlockAddress)) { + Status = NorFlashUnlockSingleBlock (Instance, BlockAddress); + } + + return Status; +} + +/** + * The following function presumes that the block has already been unlocked. + **/ +EFI_STATUS +NorFlashEraseSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ) +{ + EFI_STATUS Status; + UINT32 StatusRegister; + + Status = EFI_SUCCESS; + + // Request a block erase and then confirm it + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP); + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM); + + // Wait until the status register gives us the all clear + do { + StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress); + } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); + + if (StatusRegister & P30_SR_BIT_VPP) { + DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress)); + Status = EFI_DEVICE_ERROR; + } + + if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) { + DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_ERASE) { + DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { + // The debug level message has been reduced because a device lock might happen. In this case we just retry it ... + DEBUG ((DEBUG_INFO, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress)); + Status = EFI_WRITE_PROTECTED; + } + + if (EFI_ERROR (Status)) { + // Clear the Status Register + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); + } + + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + return Status; +} + +EFI_STATUS +NorFlashWriteSingleWord ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN WordAddress, + IN UINT32 WriteData + ) +{ + EFI_STATUS Status; + UINT32 StatusRegister; + + Status = EFI_SUCCESS; + + // Request a write single word command + SEND_NOR_COMMAND (WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP); + + // Store the word into NOR Flash; + MmioWrite32 (WordAddress, WriteData); + + // Wait for the write to complete and then check for any errors; i.e. check the Status Register + do { + // Prepare to read the status register + StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress); + // The chip is busy while the WRITE bit is not asserted + } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); + + // Perform a full status check: + // Mask the relevant bits of Status Register. + // Everything should be zero, if not, we have a problem + + if (StatusRegister & P30_SR_BIT_VPP) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n", WordAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_PROGRAM) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n", WordAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n", WordAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (!EFI_ERROR (Status)) { + // Clear the Status Register + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); + } + + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + return Status; +} + +/* + * Writes data to the NOR Flash using the Buffered Programming method. + * + * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions. + * Therefore this function will only handle buffers up to 32 words or 128 bytes. + * To deal with larger buffers, call this function again. + * + * This function presumes that both the TargetAddress and the TargetAddress+BufferSize + * exist entirely within the NOR Flash. Therefore these conditions will not be checked here. + * + * In buffered programming, if the target address not at the beginning of a 32-bit word boundary, + * then programming time is doubled and power consumption is increased. + * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries. + * i.e. the last 4 bits of the target start address must be zero: 0x......00 + */ +EFI_STATUS +NorFlashWriteBuffer ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN TargetAddress, + IN UINTN BufferSizeInBytes, + IN UINT32 *Buffer + ) +{ + EFI_STATUS Status; + UINTN BufferSizeInWords; + UINTN Count; + volatile UINT32 *Data; + UINTN WaitForBuffer; + BOOLEAN BufferAvailable; + UINT32 StatusRegister; + + WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS; + BufferAvailable = FALSE; + + // Check that the target address does not cross a 32-word boundary. + if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) { + return EFI_INVALID_PARAMETER; + } + + // Check there are some data to program + if (BufferSizeInBytes == 0) { + return EFI_BUFFER_TOO_SMALL; + } + + // Check that the buffer size does not exceed the maximum hardware buffer size on chip. + if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) { + return EFI_BAD_BUFFER_SIZE; + } + + // Check that the buffer size is a multiple of 32-bit words + if ((BufferSizeInBytes % 4) != 0) { + return EFI_BAD_BUFFER_SIZE; + } + + // Pre-programming conditions checked, now start the algorithm. + + // Prepare the data destination address + Data = (UINT32 *)TargetAddress; + + // Check the availability of the buffer + do { + // Issue the Buffered Program Setup command + SEND_NOR_COMMAND (TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP); + + // Read back the status register bit#7 from the same address + if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) { + BufferAvailable = TRUE; + } + + // Update the loop counter + WaitForBuffer--; + } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE)); + + // The buffer was not available for writing + if (WaitForBuffer == 0) { + Status = EFI_DEVICE_ERROR; + goto EXIT; + } + + // From now on we work in 32-bit words + BufferSizeInWords = BufferSizeInBytes / (UINTN)4; + + // Write the word count, which is (buffer_size_in_words - 1), + // because word count 0 means one word. + SEND_NOR_COMMAND (TargetAddress, 0, (BufferSizeInWords - 1)); + + // Write the data to the NOR Flash, advancing each address by 4 bytes + for (Count = 0; Count < BufferSizeInWords; Count++, Data++, Buffer++) { + MmioWrite32 ((UINTN)Data, *Buffer); + } + + // Issue the Buffered Program Confirm command, to start the programming operation + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM); + + // Wait for the write to complete and then check for any errors; i.e. check the Status Register + do { + StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress); + // The chip is busy while the WRITE bit is not asserted + } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); + + // Perform a full status check: + // Mask the relevant bits of Status Register. + // Everything should be zero, if not, we have a problem + + Status = EFI_SUCCESS; + + if (StatusRegister & P30_SR_BIT_VPP) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_PROGRAM) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n", TargetAddress)); + Status = EFI_DEVICE_ERROR; + } + + if (!EFI_ERROR (Status)) { + // Clear the Status Register + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); + } + +EXIT: + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + return Status; +} + +EFI_STATUS +NorFlashWriteBlocks ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + IN VOID *Buffer + ) +{ + UINT32 *pWriteBuffer; + EFI_STATUS Status; + EFI_LBA CurrentBlock; + UINT32 BlockSizeInWords; + UINT32 NumBlocks; + UINT32 BlockCount; + + Status = EFI_SUCCESS; + + // The buffer must be valid + if (Buffer == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (Instance->Media.ReadOnly == TRUE) { + return EFI_WRITE_PROTECTED; + } + + // We must have some bytes to read + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes)); + if (BufferSizeInBytes == 0) { + return EFI_BAD_BUFFER_SIZE; + } + + // The size of the buffer must be a multiple of the block size + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize)); + if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { + return EFI_BAD_BUFFER_SIZE; + } + + // All blocks must be within the device + NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; + + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba)); + + if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n")); + return EFI_INVALID_PARAMETER; + } + + BlockSizeInWords = Instance->Media.BlockSize / 4; + + // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer + // to a proper data type, so use *ReadBuffer + pWriteBuffer = (UINT32 *)Buffer; + + CurrentBlock = Lba; + for (BlockCount = 0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) { + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock)); + + Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords); + + if (EFI_ERROR (Status)) { + break; + } + } + + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status)); + return Status; +} + +#define BOTH_ALIGNED(a, b, align) ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0) + +/** + Copy Length bytes from Source to Destination, using aligned accesses only. + Note that this implementation uses memcpy() semantics rather then memmove() + semantics, i.e., SourceBuffer and DestinationBuffer should not overlap. + + @param DestinationBuffer The target of the copy request. + @param SourceBuffer The place to copy from. + @param Length The number of bytes to copy. + + @return Destination + +**/ +STATIC +VOID * +AlignedCopyMem ( + OUT VOID *DestinationBuffer, + IN CONST VOID *SourceBuffer, + IN UINTN Length + ) +{ + UINT8 *Destination8; + CONST UINT8 *Source8; + UINT32 *Destination32; + CONST UINT32 *Source32; + UINT64 *Destination64; + CONST UINT64 *Source64; + + if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 8) && (Length >= 8)) { + Destination64 = DestinationBuffer; + Source64 = SourceBuffer; + while (Length >= 8) { + *Destination64++ = *Source64++; + Length -= 8; + } + + Destination8 = (UINT8 *)Destination64; + Source8 = (CONST UINT8 *)Source64; + } else if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 4) && (Length >= 4)) { + Destination32 = DestinationBuffer; + Source32 = SourceBuffer; + while (Length >= 4) { + *Destination32++ = *Source32++; + Length -= 4; + } + + Destination8 = (UINT8 *)Destination32; + Source8 = (CONST UINT8 *)Source32; + } else { + Destination8 = DestinationBuffer; + Source8 = SourceBuffer; + } + + while (Length-- != 0) { + *Destination8++ = *Source8++; + } + + return DestinationBuffer; +} + +EFI_STATUS +NorFlashReadBlocks ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ) +{ + UINT32 NumBlocks; + UINTN StartAddress; + + DEBUG (( + DEBUG_BLKIO, + "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n", + BufferSizeInBytes, + Instance->Media.BlockSize, + Instance->Media.LastBlock, + Lba + )); + + // The buffer must be valid + if (Buffer == NULL) { + return EFI_INVALID_PARAMETER; + } + + // Return if we have not any byte to read + if (BufferSizeInBytes == 0) { + return EFI_SUCCESS; + } + + // The size of the buffer must be a multiple of the block size + if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { + return EFI_BAD_BUFFER_SIZE; + } + + // All blocks must be within the device + NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; + + if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { + DEBUG ((DEBUG_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n")); + return EFI_INVALID_PARAMETER; + } + + // Get the address to start reading from + StartAddress = GET_NOR_BLOCK_ADDRESS ( + Instance->RegionBaseAddress, + Lba, + Instance->Media.BlockSize + ); + + // Put the device into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + // Readout the data + AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes); + + return EFI_SUCCESS; +} + +EFI_STATUS +NorFlashRead ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN Offset, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ) +{ + UINTN StartAddress; + + // The buffer must be valid + if (Buffer == NULL) { + return EFI_INVALID_PARAMETER; + } + + // Return if we have not any byte to read + if (BufferSizeInBytes == 0) { + return EFI_SUCCESS; + } + + if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) { + DEBUG ((DEBUG_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n")); + return EFI_INVALID_PARAMETER; + } + + // Get the address to start reading from + StartAddress = GET_NOR_BLOCK_ADDRESS ( + Instance->RegionBaseAddress, + Lba, + Instance->Media.BlockSize + ); + + // Put the device into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + // Readout the data + AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes); + + return EFI_SUCCESS; +} + +/* + Write a full or portion of a block. It must not span block boundaries; that is, + Offset + *NumBytes <= Instance->Media.BlockSize. +*/ +EFI_STATUS +NorFlashWriteSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ) +{ + EFI_STATUS TempStatus; + UINT32 Tmp; + UINT32 TmpBuf; + UINT32 WordToWrite; + UINT32 Mask; + BOOLEAN DoErase; + UINTN BytesToWrite; + UINTN CurOffset; + UINTN WordAddr; + UINTN BlockSize; + UINTN BlockAddress; + UINTN PrevBlockAddress; + + PrevBlockAddress = 0; + + DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer)); + + // Detect WriteDisabled state + if (Instance->Media.ReadOnly == TRUE) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n")); + // It is in WriteDisabled state, return an error right away + return EFI_ACCESS_DENIED; + } + + // Cache the block size to avoid de-referencing pointers all the time + BlockSize = Instance->Media.BlockSize; + + // The write must not span block boundaries. + // We need to check each variable individually because adding two large values together overflows. + if ((Offset >= BlockSize) || + (*NumBytes > BlockSize) || + ((Offset + *NumBytes) > BlockSize)) + { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); + return EFI_BAD_BUFFER_SIZE; + } + + // We must have some bytes to write + if (*NumBytes == 0) { + DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); + return EFI_BAD_BUFFER_SIZE; + } + + // Pick 128bytes as a good start for word operations as opposed to erasing the + // block and writing the data regardless if an erase is really needed. + // It looks like most individual NV variable writes are smaller than 128bytes. + if (*NumBytes <= 128) { + // Check to see if we need to erase before programming the data into NOR. + // If the destination bits are only changing from 1s to 0s we can just write. + // After a block is erased all bits in the block is set to 1. + // If any byte requires us to erase we just give up and rewrite all of it. + DoErase = FALSE; + BytesToWrite = *NumBytes; + CurOffset = Offset; + + while (BytesToWrite > 0) { + // Read full word from NOR, splice as required. A word is the smallest + // unit we can write. + TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof (Tmp), &Tmp); + if (EFI_ERROR (TempStatus)) { + return EFI_DEVICE_ERROR; + } + + // Physical address of word in NOR to write. + WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS ( + Instance->RegionBaseAddress, + Lba, + BlockSize + ); + // The word of data that is to be written. + TmpBuf = *((UINT32 *)(Buffer + (*NumBytes - BytesToWrite))); + + // First do word aligned chunks. + if ((CurOffset & 0x3) == 0) { + if (BytesToWrite >= 4) { + // Is the destination still in 'erased' state? + if (~Tmp != 0) { + // Check to see if we are only changing bits to zero. + if ((Tmp ^ TmpBuf) & TmpBuf) { + DoErase = TRUE; + break; + } + } + + // Write this word to NOR + WordToWrite = TmpBuf; + CurOffset += sizeof (TmpBuf); + BytesToWrite -= sizeof (TmpBuf); + } else { + // BytesToWrite < 4. Do small writes and left-overs + Mask = ~((~0) << (BytesToWrite * 8)); + // Mask out the bytes we want. + TmpBuf &= Mask; + // Is the destination still in 'erased' state? + if ((Tmp & Mask) != Mask) { + // Check to see if we are only changing bits to zero. + if ((Tmp ^ TmpBuf) & TmpBuf) { + DoErase = TRUE; + break; + } + } + + // Merge old and new data. Write merged word to NOR + WordToWrite = (Tmp & ~Mask) | TmpBuf; + CurOffset += BytesToWrite; + BytesToWrite = 0; + } + } else { + // Do multiple words, but starting unaligned. + if (BytesToWrite > (4 - (CurOffset & 0x3))) { + Mask = ((~0) << ((CurOffset & 0x3) * 8)); + // Mask out the bytes we want. + TmpBuf &= Mask; + // Is the destination still in 'erased' state? + if ((Tmp & Mask) != Mask) { + // Check to see if we are only changing bits to zero. + if ((Tmp ^ TmpBuf) & TmpBuf) { + DoErase = TRUE; + break; + } + } + + // Merge old and new data. Write merged word to NOR + WordToWrite = (Tmp & ~Mask) | TmpBuf; + BytesToWrite -= (4 - (CurOffset & 0x3)); + CurOffset += (4 - (CurOffset & 0x3)); + } else { + // Unaligned and fits in one word. + Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8); + // Mask out the bytes we want. + TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask; + // Is the destination still in 'erased' state? + if ((Tmp & Mask) != Mask) { + // Check to see if we are only changing bits to zero. + if ((Tmp ^ TmpBuf) & TmpBuf) { + DoErase = TRUE; + break; + } + } + + // Merge old and new data. Write merged word to NOR + WordToWrite = (Tmp & ~Mask) | TmpBuf; + CurOffset += BytesToWrite; + BytesToWrite = 0; + } + } + + // + // Write the word to NOR. + // + + BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize); + if (BlockAddress != PrevBlockAddress) { + TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); + if (EFI_ERROR (TempStatus)) { + return EFI_DEVICE_ERROR; + } + + PrevBlockAddress = BlockAddress; + } + + TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite); + if (EFI_ERROR (TempStatus)) { + return EFI_DEVICE_ERROR; + } + } + + // Exit if we got here and could write all the data. Otherwise do the + // Erase-Write cycle. + if (!DoErase) { + return EFI_SUCCESS; + } + } + + // Check we did get some memory. Buffer is BlockSize. + if (Instance->ShadowBuffer == NULL) { + DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n")); + return EFI_DEVICE_ERROR; + } + + // Read NOR Flash data into shadow buffer + TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); + if (EFI_ERROR (TempStatus)) { + // Return one of the pre-approved error statuses + return EFI_DEVICE_ERROR; + } + + // Put the data at the appropriate location inside the buffer area + CopyMem ((VOID *)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes); + + // Write the modified buffer back to the NorFlash + TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); + if (EFI_ERROR (TempStatus)) { + // Return one of the pre-approved error statuses + return EFI_DEVICE_ERROR; + } + + return EFI_SUCCESS; +} + +/* + Although DiskIoDxe will automatically install the DiskIO protocol whenever + we install the BlockIO protocol, its implementation is sub-optimal as it reads + and writes entire blocks using the BlockIO protocol. In fact we can access + NOR flash with a finer granularity than that, so we can improve performance + by directly producing the DiskIO protocol. +*/ + +/** + Read BufferSize bytes from Offset into Buffer. + + @param This Protocol instance pointer. + @param MediaId Id of the media, changes every time the media is replaced. + @param Offset The starting byte offset to read from + @param BufferSize Size of Buffer + @param Buffer Buffer containing read data + + @retval EFI_SUCCESS The data was read correctly from the device. + @retval EFI_DEVICE_ERROR The device reported an error while performing the read. + @retval EFI_NO_MEDIA There is no media in the device. + @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. + @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not + valid for the device. + +**/ +EFI_STATUS +EFIAPI +NorFlashDiskIoReadDisk ( + IN EFI_DISK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 DiskOffset, + IN UINTN BufferSize, + OUT VOID *Buffer + ) +{ + NOR_FLASH_INSTANCE *Instance; + UINT32 BlockSize; + UINT32 BlockOffset; + EFI_LBA Lba; + + Instance = INSTANCE_FROM_DISKIO_THIS (This); + + if (MediaId != Instance->Media.MediaId) { + return EFI_MEDIA_CHANGED; + } + + BlockSize = Instance->Media.BlockSize; + Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); + + return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer); +} + +/** + Writes a specified number of bytes to a device. + + @param This Indicates a pointer to the calling context. + @param MediaId ID of the medium to be written. + @param Offset The starting byte offset on the logical block I/O device to write. + @param BufferSize The size in bytes of Buffer. The number of bytes to write to the device. + @param Buffer A pointer to the buffer containing the data to be written. + + @retval EFI_SUCCESS The data was written correctly to the device. + @retval EFI_WRITE_PROTECTED The device can not be written to. + @retval EFI_DEVICE_ERROR The device reported an error while performing the write. + @retval EFI_NO_MEDIA There is no media in the device. + @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. + @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not + valid for the device. + +**/ +EFI_STATUS +EFIAPI +NorFlashDiskIoWriteDisk ( + IN EFI_DISK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 DiskOffset, + IN UINTN BufferSize, + IN VOID *Buffer + ) +{ + NOR_FLASH_INSTANCE *Instance; + UINT32 BlockSize; + UINT32 BlockOffset; + EFI_LBA Lba; + UINTN RemainingBytes; + UINTN WriteSize; + EFI_STATUS Status; + + Instance = INSTANCE_FROM_DISKIO_THIS (This); + + if (MediaId != Instance->Media.MediaId) { + return EFI_MEDIA_CHANGED; + } + + BlockSize = Instance->Media.BlockSize; + Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); + + RemainingBytes = BufferSize; + + // Write either all the remaining bytes, or the number of bytes that bring + // us up to a block boundary, whichever is less. + // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next + // block boundary (even if it is already on one). + WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset); + + do { + if (WriteSize == BlockSize) { + // Write a full block + Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32)); + } else { + // Write a partial block + Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer); + } + + if (EFI_ERROR (Status)) { + return Status; + } + + // Now continue writing either all the remaining bytes or single blocks. + RemainingBytes -= WriteSize; + Buffer = (UINT8 *)Buffer + WriteSize; + Lba++; + BlockOffset = 0; + WriteSize = MIN (RemainingBytes, BlockSize); + } while (RemainingBytes); + + return Status; +} + +EFI_STATUS +NorFlashReset ( + IN NOR_FLASH_INSTANCE *Instance + ) +{ + // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + return EFI_SUCCESS; +} + +/** + 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 +NorFlashVirtualNotifyEvent ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + UINTN Index; + + for (Index = 0; Index < mNorFlashDeviceCount; Index++) { + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress); + + // Convert BlockIo protocol + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.Reset); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks); + + // Convert Fvb + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Read); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes); + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Write); + + if (mNorFlashInstances[Index]->ShadowBuffer != NULL) { + EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->ShadowBuffer); + } + } + + return; +} diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h new file mode 100644 index 0000000000..e46522a198 --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h @@ -0,0 +1,422 @@ +/** @file NorFlash.h + + Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __VIRT_NOR_FLASH__ +#define __VIRT_NOR_FLASH__ + +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#define NOR_FLASH_ERASE_RETRY 10 + +// Device access macros +// These are necessary because we use 2 x 16bit parts to make up 32bit data + +#define HIGH_16_BITS 0xFFFF0000 +#define LOW_16_BITS 0x0000FFFF +#define LOW_8_BITS 0x000000FF + +#define FOLD_32BIT_INTO_16BIT(value) ( ( value >> 16 ) | ( value & LOW_16_BITS ) ) + +#define GET_LOW_BYTE(value) ( value & LOW_8_BITS ) +#define GET_HIGH_BYTE(value) ( GET_LOW_BYTE( value >> 16 ) ) + +// Each command must be sent simultaneously to both chips, +// i.e. at the lower 16 bits AND at the higher 16 bits +#define CREATE_NOR_ADDRESS(BaseAddr, OffsetAddr) ((BaseAddr) + ((OffsetAddr) << 2)) +#define CREATE_DUAL_CMD(Cmd) ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) ) +#define SEND_NOR_COMMAND(BaseAddr, Offset, Cmd) MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd)) +#define GET_NOR_BLOCK_ADDRESS(BaseAddr, Lba, LbaSize) ( BaseAddr + (UINTN)((Lba) * LbaSize) ) + +// Status Register Bits +#define P30_SR_BIT_WRITE (BIT7 << 16 | BIT7) +#define P30_SR_BIT_ERASE_SUSPEND (BIT6 << 16 | BIT6) +#define P30_SR_BIT_ERASE (BIT5 << 16 | BIT5) +#define P30_SR_BIT_PROGRAM (BIT4 << 16 | BIT4) +#define P30_SR_BIT_VPP (BIT3 << 16 | BIT3) +#define P30_SR_BIT_PROGRAM_SUSPEND (BIT2 << 16 | BIT2) +#define P30_SR_BIT_BLOCK_LOCKED (BIT1 << 16 | BIT1) +#define P30_SR_BIT_BEFP (BIT0 << 16 | BIT0) + +// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family + +// On chip buffer size for buffered programming operations +// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes. +// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes +#define P30_MAX_BUFFER_SIZE_IN_BYTES ((UINTN)128) +#define P30_MAX_BUFFER_SIZE_IN_WORDS (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4)) +#define MAX_BUFFERED_PROG_ITERATIONS 10000000 +#define BOUNDARY_OF_32_WORDS 0x7F + +// CFI Addresses +#define P30_CFI_ADDR_QUERY_UNIQUE_QRY 0x10 +#define P30_CFI_ADDR_VENDOR_ID 0x13 + +// CFI Data +#define CFI_QRY 0x00595251 + +// READ Commands +#define P30_CMD_READ_DEVICE_ID 0x0090 +#define P30_CMD_READ_STATUS_REGISTER 0x0070 +#define P30_CMD_CLEAR_STATUS_REGISTER 0x0050 +#define P30_CMD_READ_ARRAY 0x00FF +#define P30_CMD_READ_CFI_QUERY 0x0098 + +// WRITE Commands +#define P30_CMD_WORD_PROGRAM_SETUP 0x0040 +#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP 0x0010 +#define P30_CMD_BUFFERED_PROGRAM_SETUP 0x00E8 +#define P30_CMD_BUFFERED_PROGRAM_CONFIRM 0x00D0 +#define P30_CMD_BEFP_SETUP 0x0080 +#define P30_CMD_BEFP_CONFIRM 0x00D0 + +// ERASE Commands +#define P30_CMD_BLOCK_ERASE_SETUP 0x0020 +#define P30_CMD_BLOCK_ERASE_CONFIRM 0x00D0 + +// SUSPEND Commands +#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND 0x00B0 +#define P30_CMD_SUSPEND_RESUME 0x00D0 + +// BLOCK LOCKING / UNLOCKING Commands +#define P30_CMD_LOCK_BLOCK_SETUP 0x0060 +#define P30_CMD_LOCK_BLOCK 0x0001 +#define P30_CMD_UNLOCK_BLOCK 0x00D0 +#define P30_CMD_LOCK_DOWN_BLOCK 0x002F + +// PROTECTION Commands +#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP 0x00C0 + +// CONFIGURATION Commands +#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP 0x0060 +#define P30_CMD_READ_CONFIGURATION_REGISTER 0x0003 + +#define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0') +#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE) +#define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE) +#define INSTANCE_FROM_DISKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, DiskIoProtocol, NOR_FLASH_SIGNATURE) + +typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE; + +#pragma pack (1) +typedef struct { + VENDOR_DEVICE_PATH Vendor; + UINT8 Index; + EFI_DEVICE_PATH_PROTOCOL End; +} NOR_FLASH_DEVICE_PATH; +#pragma pack () + +struct _NOR_FLASH_INSTANCE { + UINT32 Signature; + EFI_HANDLE Handle; + + UINTN DeviceBaseAddress; + UINTN RegionBaseAddress; + UINTN Size; + EFI_LBA StartLba; + + EFI_BLOCK_IO_PROTOCOL BlockIoProtocol; + EFI_BLOCK_IO_MEDIA Media; + EFI_DISK_IO_PROTOCOL DiskIoProtocol; + + EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol; + VOID *ShadowBuffer; + + NOR_FLASH_DEVICE_PATH DevicePath; +}; + +EFI_STATUS +NorFlashReadCfiData ( + IN UINTN DeviceBaseAddress, + IN UINTN CFI_Offset, + IN UINT32 NumberOfBytes, + OUT UINT32 *Data + ); + +EFI_STATUS +NorFlashWriteBuffer ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN TargetAddress, + IN UINTN BufferSizeInBytes, + IN UINT32 *Buffer + ); + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset +// +EFI_STATUS +EFIAPI +NorFlashBlockIoReset ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification + ); + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoReadBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ); + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoWriteBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + IN VOID *Buffer + ); + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoFlushBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This + ); + +// +// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.ReadDisk +// +EFI_STATUS +EFIAPI +NorFlashDiskIoReadDisk ( + IN EFI_DISK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Offset, + IN UINTN BufferSize, + OUT VOID *Buffer + ); + +// +// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.WriteDisk +// +EFI_STATUS +EFIAPI +NorFlashDiskIoWriteDisk ( + IN EFI_DISK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Offset, + IN UINTN BufferSize, + IN VOID *Buffer + ); + +// +// NorFlashFvbDxe.c +// + +EFI_STATUS +EFIAPI +FvbGetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ); + +EFI_STATUS +EFIAPI +FvbSetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ); + +EFI_STATUS +EFIAPI +FvbGetPhysicalAddress ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + OUT EFI_PHYSICAL_ADDRESS *Address + ); + +EFI_STATUS +EFIAPI +FvbGetBlockSize ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + OUT UINTN *BlockSize, + OUT UINTN *NumberOfBlocks + ); + +EFI_STATUS +EFIAPI +FvbRead ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN OUT UINT8 *Buffer + ); + +EFI_STATUS +EFIAPI +FvbWrite ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ); + +EFI_STATUS +EFIAPI +FvbEraseBlocks ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + ... + ); + +EFI_STATUS +ValidateFvHeader ( + IN NOR_FLASH_INSTANCE *Instance + ); + +EFI_STATUS +InitializeFvAndVariableStoreHeaders ( + IN NOR_FLASH_INSTANCE *Instance + ); + +VOID +EFIAPI +FvbVirtualNotifyEvent ( + IN EFI_EVENT Event, + IN VOID *Context + ); + +// +// NorFlashDxe.c +// + +EFI_STATUS +NorFlashWriteFullBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINT32 *DataBuffer, + IN UINT32 BlockSizeInWords + ); + +EFI_STATUS +NorFlashUnlockAndEraseSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ); + +EFI_STATUS +NorFlashCreateInstance ( + IN UINTN NorFlashDeviceBase, + IN UINTN NorFlashRegionBase, + IN UINTN NorFlashSize, + IN UINT32 Index, + IN UINT32 BlockSize, + IN BOOLEAN SupportFvb, + OUT NOR_FLASH_INSTANCE **NorFlashInstance + ); + +EFI_STATUS +EFIAPI +NorFlashFvbInitialize ( + IN NOR_FLASH_INSTANCE *Instance + ); + +// +// NorFlash.c +// +EFI_STATUS +NorFlashWriteSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ); + +EFI_STATUS +NorFlashWriteBlocks ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + IN VOID *Buffer + ); + +EFI_STATUS +NorFlashReadBlocks ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ); + +EFI_STATUS +NorFlashRead ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN Offset, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ); + +EFI_STATUS +NorFlashWrite ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ); + +EFI_STATUS +NorFlashReset ( + IN NOR_FLASH_INSTANCE *Instance + ); + +EFI_STATUS +NorFlashEraseSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ); + +EFI_STATUS +NorFlashUnlockSingleBlockIfNecessary ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ); + +EFI_STATUS +NorFlashWriteSingleWord ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN WordAddress, + IN UINT32 WriteData + ); + +VOID +EFIAPI +NorFlashVirtualNotifyEvent ( + IN EFI_EVENT Event, + IN VOID *Context + ); + +#endif /* __VIRT_NOR_FLASH__ */ diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c new file mode 100644 index 0000000000..ecf152e355 --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c @@ -0,0 +1,123 @@ +/** @file NorFlashBlockIoDxe.c + + Copyright (c) 2011-2013, ARM Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +#include "VirtNorFlash.h" + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset +// +EFI_STATUS +EFIAPI +NorFlashBlockIoReset ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification + ) +{ + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_BLKIO_THIS (This); + + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReset(MediaId=0x%x)\n", This->Media->MediaId)); + + return NorFlashReset (Instance); +} + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoReadBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + OUT VOID *Buffer + ) +{ + NOR_FLASH_INSTANCE *Instance; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + + if (This == NULL) { + return EFI_INVALID_PARAMETER; + } + + Instance = INSTANCE_FROM_BLKIO_THIS (This); + Media = This->Media; + + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, BufferSizeInBytes, Buffer)); + + if (!Media) { + Status = EFI_INVALID_PARAMETER; + } else if (!Media->MediaPresent) { + Status = EFI_NO_MEDIA; + } else if (Media->MediaId != MediaId) { + Status = EFI_MEDIA_CHANGED; + } else if ((Media->IoAlign > 2) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { + Status = EFI_INVALID_PARAMETER; + } else { + Status = NorFlashReadBlocks (Instance, Lba, BufferSizeInBytes, Buffer); + } + + return Status; +} + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoWriteBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSizeInBytes, + IN VOID *Buffer + ) +{ + NOR_FLASH_INSTANCE *Instance; + EFI_STATUS Status; + + Instance = INSTANCE_FROM_BLKIO_THIS (This); + + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes, BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); + + if ( !This->Media->MediaPresent ) { + Status = EFI_NO_MEDIA; + } else if ( This->Media->MediaId != MediaId ) { + Status = EFI_MEDIA_CHANGED; + } else if ( This->Media->ReadOnly ) { + Status = EFI_WRITE_PROTECTED; + } else { + Status = NorFlashWriteBlocks (Instance, Lba, BufferSizeInBytes, Buffer); + } + + return Status; +} + +// +// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks +// +EFI_STATUS +EFIAPI +NorFlashBlockIoFlushBlocks ( + IN EFI_BLOCK_IO_PROTOCOL *This + ) +{ + // No Flush required for the NOR Flash driver + // because cache operations are not permitted. + + DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoFlushBlocks: Function NOT IMPLEMENTED (not required).\n")); + + // Nothing to do so just return without error + return EFI_SUCCESS; +} diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c new file mode 100644 index 0000000000..819425545e --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -0,0 +1,506 @@ +/** @file NorFlashDxe.c + + Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include + +#include "VirtNorFlash.h" + +STATIC EFI_EVENT mNorFlashVirtualAddrChangeEvent; + +// +// Global variable declarations +// +NOR_FLASH_INSTANCE **mNorFlashInstances; +UINT32 mNorFlashDeviceCount; +UINTN mFlashNvStorageVariableBase; +EFI_EVENT mFvbVirtualAddrChangeEvent; + +NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = { + NOR_FLASH_SIGNATURE, // Signature + NULL, // Handle ... NEED TO BE FILLED + + 0, // DeviceBaseAddress ... NEED TO BE FILLED + 0, // RegionBaseAddress ... NEED TO BE FILLED + 0, // Size ... NEED TO BE FILLED + 0, // StartLba + + { + EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision + NULL, // Media ... NEED TO BE FILLED + NorFlashBlockIoReset, // Reset; + NorFlashBlockIoReadBlocks, // ReadBlocks + NorFlashBlockIoWriteBlocks, // WriteBlocks + NorFlashBlockIoFlushBlocks // FlushBlocks + }, // BlockIoProtocol + + { + 0, // MediaId ... NEED TO BE FILLED + FALSE, // RemovableMedia + TRUE, // MediaPresent + FALSE, // LogicalPartition + FALSE, // ReadOnly + FALSE, // WriteCaching; + 0, // BlockSize ... NEED TO BE FILLED + 4, // IoAlign + 0, // LastBlock ... NEED TO BE FILLED + 0, // LowestAlignedLba + 1, // LogicalBlocksPerPhysicalBlock + }, // Media; + + { + EFI_DISK_IO_PROTOCOL_REVISION, // Revision + NorFlashDiskIoReadDisk, // ReadDisk + NorFlashDiskIoWriteDisk // WriteDisk + }, + + { + FvbGetAttributes, // GetAttributes + FvbSetAttributes, // SetAttributes + FvbGetPhysicalAddress, // GetPhysicalAddress + FvbGetBlockSize, // GetBlockSize + FvbRead, // Read + FvbWrite, // Write + FvbEraseBlocks, // EraseBlocks + NULL, // ParentHandle + }, // FvbProtoccol; + NULL, // ShadowBuffer + { + { + { + HARDWARE_DEVICE_PATH, + HW_VENDOR_DP, + { + (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End)), + (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End) >> 8) + } + }, + { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } + }, // GUID ... NEED TO BE FILLED + }, + 0, // Index + { + END_DEVICE_PATH_TYPE, + END_ENTIRE_DEVICE_PATH_SUBTYPE, + { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 } + } + } // DevicePath +}; + +EFI_STATUS +NorFlashCreateInstance ( + IN UINTN NorFlashDeviceBase, + IN UINTN NorFlashRegionBase, + IN UINTN NorFlashSize, + IN UINT32 Index, + IN UINT32 BlockSize, + IN BOOLEAN SupportFvb, + OUT NOR_FLASH_INSTANCE **NorFlashInstance + ) +{ + EFI_STATUS Status; + NOR_FLASH_INSTANCE *Instance; + + ASSERT (NorFlashInstance != NULL); + + Instance = AllocateRuntimeCopyPool (sizeof (NOR_FLASH_INSTANCE), &mNorFlashInstanceTemplate); + if (Instance == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + Instance->DeviceBaseAddress = NorFlashDeviceBase; + Instance->RegionBaseAddress = NorFlashRegionBase; + Instance->Size = NorFlashSize; + + Instance->BlockIoProtocol.Media = &Instance->Media; + Instance->Media.MediaId = Index; + Instance->Media.BlockSize = BlockSize; + Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1; + + CopyGuid (&Instance->DevicePath.Vendor.Guid, &gEfiCallerIdGuid); + Instance->DevicePath.Index = (UINT8)Index; + + Instance->ShadowBuffer = AllocateRuntimePool (BlockSize); + if (Instance->ShadowBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + if (SupportFvb) { + NorFlashFvbInitialize (Instance); + + Status = gBS->InstallMultipleProtocolInterfaces ( + &Instance->Handle, + &gEfiDevicePathProtocolGuid, + &Instance->DevicePath, + &gEfiBlockIoProtocolGuid, + &Instance->BlockIoProtocol, + &gEfiFirmwareVolumeBlockProtocolGuid, + &Instance->FvbProtocol, + NULL + ); + if (EFI_ERROR (Status)) { + FreePool (Instance); + return Status; + } + } else { + Status = gBS->InstallMultipleProtocolInterfaces ( + &Instance->Handle, + &gEfiDevicePathProtocolGuid, + &Instance->DevicePath, + &gEfiBlockIoProtocolGuid, + &Instance->BlockIoProtocol, + &gEfiDiskIoProtocolGuid, + &Instance->DiskIoProtocol, + NULL + ); + if (EFI_ERROR (Status)) { + FreePool (Instance); + return Status; + } + } + + *NorFlashInstance = Instance; + return Status; +} + +/** + * This function unlock and erase an entire NOR Flash block. + **/ +EFI_STATUS +NorFlashUnlockAndEraseSingleBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN UINTN BlockAddress + ) +{ + EFI_STATUS Status; + UINTN Index; + EFI_TPL OriginalTPL; + + if (!EfiAtRuntime ()) { + // Raise TPL to TPL_HIGH to stop anyone from interrupting us. + OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + } else { + // This initialization is only to prevent the compiler to complain about the + // use of uninitialized variables + OriginalTPL = TPL_HIGH_LEVEL; + } + + Index = 0; + // The block erase might fail a first time (SW bug ?). Retry it ... + do { + // Unlock the block if we have to + Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); + if (EFI_ERROR (Status)) { + break; + } + + Status = NorFlashEraseSingleBlock (Instance, BlockAddress); + Index++; + } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED)); + + if (Index == NOR_FLASH_ERASE_RETRY) { + DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index)); + } + + if (!EfiAtRuntime ()) { + // Interruptions can resume. + gBS->RestoreTPL (OriginalTPL); + } + + return Status; +} + +EFI_STATUS +NorFlashWriteFullBlock ( + IN NOR_FLASH_INSTANCE *Instance, + IN EFI_LBA Lba, + IN UINT32 *DataBuffer, + IN UINT32 BlockSizeInWords + ) +{ + EFI_STATUS Status; + UINTN WordAddress; + UINT32 WordIndex; + UINTN BufferIndex; + UINTN BlockAddress; + UINTN BuffersInBlock; + UINTN RemainingWords; + EFI_TPL OriginalTPL; + UINTN Cnt; + + Status = EFI_SUCCESS; + + // Get the physical address of the block + BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4); + + // Start writing from the first address at the start of the block + WordAddress = BlockAddress; + + if (!EfiAtRuntime ()) { + // Raise TPL to TPL_HIGH to stop anyone from interrupting us. + OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + } else { + // This initialization is only to prevent the compiler to complain about the + // use of uninitialized variables + OriginalTPL = TPL_HIGH_LEVEL; + } + + Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress)); + goto EXIT; + } + + // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method. + + // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero + if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) { + // First, break the entire block into buffer-sized chunks. + BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES; + + // Then feed each buffer chunk to the NOR Flash + // If a buffer does not contain any data, don't write it. + for (BufferIndex = 0; + BufferIndex < BuffersInBlock; + BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS + ) + { + // Check the buffer to see if it contains any data (not set all 1s). + for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) { + if (~DataBuffer[Cnt] != 0 ) { + // Some data found, write the buffer. + Status = NorFlashWriteBuffer ( + Instance, + WordAddress, + P30_MAX_BUFFER_SIZE_IN_BYTES, + DataBuffer + ); + if (EFI_ERROR (Status)) { + goto EXIT; + } + + break; + } + } + } + + // Finally, finish off any remaining words that are less than the maximum size of the buffer + RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS; + + if (RemainingWords != 0) { + Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer); + if (EFI_ERROR (Status)) { + goto EXIT; + } + } + } else { + // For now, use the single word programming algorithm + // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range, + // i.e. which ends in the range 0x......01 - 0x......7F. + for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) { + Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer); + if (EFI_ERROR (Status)) { + goto EXIT; + } + } + } + +EXIT: + if (!EfiAtRuntime ()) { + // Interruptions can resume. + gBS->RestoreTPL (OriginalTPL); + } + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status)); + } + + return Status; +} + +EFI_STATUS +EFIAPI +NorFlashInitialise ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UINT32 Index; + VIRT_NOR_FLASH_DESCRIPTION *NorFlashDevices; + BOOLEAN ContainVariableStorage; + + Status = VirtNorFlashPlatformInitialization (); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to initialize Nor Flash devices\n")); + return Status; + } + + Status = VirtNorFlashPlatformGetDevices (&NorFlashDevices, &mNorFlashDeviceCount); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to get Nor Flash devices\n")); + return Status; + } + + mNorFlashInstances = AllocateRuntimePool (sizeof (NOR_FLASH_INSTANCE *) * mNorFlashDeviceCount); + + for (Index = 0; Index < mNorFlashDeviceCount; Index++) { + // Check if this NOR Flash device contain the variable storage region + + if (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) { + ContainVariableStorage = + (NorFlashDevices[Index].RegionBaseAddress <= PcdGet64 (PcdFlashNvStorageVariableBase64)) && + (PcdGet64 (PcdFlashNvStorageVariableBase64) + PcdGet32 (PcdFlashNvStorageVariableSize) <= + NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); + } else { + ContainVariableStorage = + (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) && + (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= + NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); + } + + Status = NorFlashCreateInstance ( + NorFlashDevices[Index].DeviceBaseAddress, + NorFlashDevices[Index].RegionBaseAddress, + NorFlashDevices[Index].Size, + Index, + NorFlashDevices[Index].BlockSize, + ContainVariableStorage, + &mNorFlashInstances[Index] + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to create instance for NorFlash[%d]\n", Index)); + } + } + + // + // Register for the virtual address change event + // + Status = gBS->CreateEventEx ( + EVT_NOTIFY_SIGNAL, + TPL_NOTIFY, + NorFlashVirtualNotifyEvent, + NULL, + &gEfiEventVirtualAddressChangeGuid, + &mNorFlashVirtualAddrChangeEvent + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} + +EFI_STATUS +EFIAPI +NorFlashFvbInitialize ( + IN NOR_FLASH_INSTANCE *Instance + ) +{ + EFI_STATUS Status; + UINT32 FvbNumLba; + EFI_BOOT_MODE BootMode; + UINTN RuntimeMmioRegionSize; + + DEBUG ((DEBUG_BLKIO, "NorFlashFvbInitialize\n")); + ASSERT ((Instance != NULL)); + + // + // Declare the Non-Volatile storage as EFI_MEMORY_RUNTIME + // + + // Note: all the NOR Flash region needs to be reserved into the UEFI Runtime memory; + // even if we only use the small block region at the top of the NOR Flash. + // The reason is when the NOR Flash memory is set into program mode, the command + // is written as the base of the flash region (ie: Instance->DeviceBaseAddress) + RuntimeMmioRegionSize = (Instance->RegionBaseAddress - Instance->DeviceBaseAddress) + Instance->Size; + + Status = gDS->AddMemorySpace ( + EfiGcdMemoryTypeMemoryMappedIo, + Instance->DeviceBaseAddress, + RuntimeMmioRegionSize, + EFI_MEMORY_UC | EFI_MEMORY_RUNTIME + ); + ASSERT_EFI_ERROR (Status); + + Status = gDS->SetMemorySpaceAttributes ( + Instance->DeviceBaseAddress, + RuntimeMmioRegionSize, + EFI_MEMORY_UC | EFI_MEMORY_RUNTIME + ); + ASSERT_EFI_ERROR (Status); + + mFlashNvStorageVariableBase = (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) ? + PcdGet64 (PcdFlashNvStorageVariableBase64) : PcdGet32 (PcdFlashNvStorageVariableBase); + + // Set the index of the first LBA for the FVB + Instance->StartLba = (mFlashNvStorageVariableBase - Instance->RegionBaseAddress) / Instance->Media.BlockSize; + + BootMode = GetBootModeHob (); + if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) { + Status = EFI_INVALID_PARAMETER; + } else { + // Determine if there is a valid header at the beginning of the NorFlash + Status = ValidateFvHeader (Instance); + } + + // Install the Default FVB header if required + if (EFI_ERROR (Status)) { + // There is no valid header, so time to install one. + DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__)); + DEBUG (( + DEBUG_INFO, + "%a: Installing a correct one for this volume.\n", + __FUNCTION__ + )); + + // Erase all the NorFlash that is reserved for variable storage + FvbNumLba = (PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize; + + Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR); + if (EFI_ERROR (Status)) { + return Status; + } + + // Install all appropriate headers + Status = InitializeFvAndVariableStoreHeaders (Instance); + if (EFI_ERROR (Status)) { + return Status; + } + } + + // + // The driver implementing the variable read service can now be dispatched; + // the varstore headers are in place. + // + Status = gBS->InstallProtocolInterface ( + &gImageHandle, + &gEdkiiNvVarStoreFormattedGuid, + EFI_NATIVE_INTERFACE, + NULL + ); + ASSERT_EFI_ERROR (Status); + + // + // Register for the virtual address change event + // + Status = gBS->CreateEventEx ( + EVT_NOTIFY_SIGNAL, + TPL_NOTIFY, + FvbVirtualNotifyEvent, + NULL, + &gEfiEventVirtualAddressChangeGuid, + &mFvbVirtualAddrChangeEvent + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf new file mode 100644 index 0000000000..1bf50e4823 --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf @@ -0,0 +1,72 @@ +#/** @file +# +# Component description file for NorFlashDxe module +# +# Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#**/ + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = VirtNorFlashDxe + FILE_GUID = e452cabd-5fe1-4d97-8161-e80ed6a409a8 + MODULE_TYPE = DXE_RUNTIME_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = NorFlashInitialise + +[Sources.common] + VirtNorFlash.c + VirtNorFlash.h + VirtNorFlashBlockIoDxe.c + VirtNorFlashDxe.c + VirtNorFlashFvb.c + +[Packages] + ArmPlatformPkg/ArmPlatformPkg.dec + EmbeddedPkg/EmbeddedPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + DxeServicesTableLib + HobLib + IoLib + UefiBootServicesTableLib + UefiDriverEntryPoint + UefiLib + UefiRuntimeLib + VirtNorFlashPlatformLib + +[Guids] + gEdkiiNvVarStoreFormattedGuid ## PRODUCES ## PROTOCOL + gEfiAuthenticatedVariableGuid + gEfiEventVirtualAddressChangeGuid + gEfiSystemNvDataFvGuid + gEfiVariableGuid + +[Protocols] + gEfiBlockIoProtocolGuid + gEfiDevicePathProtocolGuid + gEfiDiskIoProtocolGuid + gEfiFirmwareVolumeBlockProtocolGuid + +[Pcd.common] + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize + + gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked + +[Depex] + gEfiCpuArchProtocolGuid diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c new file mode 100644 index 0000000000..c824e0a0fb --- /dev/null +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c @@ -0,0 +1,777 @@ +/*++ @file NorFlashFvbDxe.c + + Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + --*/ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "VirtNorFlash.h" + +extern UINTN mFlashNvStorageVariableBase; +/// +/// The Firmware Volume Block Protocol is the low-level interface +/// to a firmware volume. File-level access to a firmware volume +/// should not be done using the Firmware Volume Block Protocol. +/// Normal access to a firmware volume must use the Firmware +/// Volume Protocol. Typically, only the file system driver that +/// produces the Firmware Volume Protocol will bind to the +/// Firmware Volume Block Protocol. +/// + +/** + Initialises the FV Header and Variable Store Header + to support variable operations. + + @param[in] Ptr - Location to initialise the headers + +**/ +EFI_STATUS +InitializeFvAndVariableStoreHeaders ( + IN NOR_FLASH_INSTANCE *Instance + ) +{ + EFI_STATUS Status; + VOID *Headers; + UINTN HeadersLength; + EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader; + VARIABLE_STORE_HEADER *VariableStoreHeader; + UINT32 NvStorageFtwSpareSize; + UINT32 NvStorageFtwWorkingSize; + UINT32 NvStorageVariableSize; + UINT64 NvStorageFtwSpareBase; + UINT64 NvStorageFtwWorkingBase; + UINT64 NvStorageVariableBase; + + HeadersLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY) + sizeof (VARIABLE_STORE_HEADER); + Headers = AllocateZeroPool (HeadersLength); + + NvStorageFtwWorkingSize = PcdGet32 (PcdFlashNvStorageFtwWorkingSize); + NvStorageFtwSpareSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize); + NvStorageVariableSize = PcdGet32 (PcdFlashNvStorageVariableSize); + + NvStorageFtwSpareBase = (PcdGet64 (PcdFlashNvStorageFtwSpareBase64) != 0) ? + PcdGet64 (PcdFlashNvStorageFtwSpareBase64) : PcdGet32 (PcdFlashNvStorageFtwSpareBase); + NvStorageFtwWorkingBase = (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) != 0) ? + PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) : PcdGet32 (PcdFlashNvStorageFtwWorkingBase); + NvStorageVariableBase = (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) ? + PcdGet64 (PcdFlashNvStorageVariableBase64) : PcdGet32 (PcdFlashNvStorageVariableBase); + + // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous. + if ((NvStorageVariableBase + NvStorageVariableSize) != NvStorageFtwWorkingBase) { + DEBUG (( + DEBUG_ERROR, + "%a: NvStorageFtwWorkingBase is not contiguous with NvStorageVariableBase region\n", + __FUNCTION__ + )); + return EFI_INVALID_PARAMETER; + } + + if ((NvStorageFtwWorkingBase + NvStorageFtwWorkingSize) != NvStorageFtwSpareBase) { + DEBUG (( + DEBUG_ERROR, + "%a: NvStorageFtwSpareBase is not contiguous with NvStorageFtwWorkingBase region\n", + __FUNCTION__ + )); + return EFI_INVALID_PARAMETER; + } + + // Check if the size of the area is at least one block size + if ((NvStorageVariableSize <= 0) || (NvStorageVariableSize / Instance->Media.BlockSize <= 0)) { + DEBUG (( + DEBUG_ERROR, + "%a: NvStorageVariableSize is 0x%x, should be atleast one block size\n", + __FUNCTION__, + NvStorageVariableSize + )); + return EFI_INVALID_PARAMETER; + } + + if ((NvStorageFtwWorkingSize <= 0) || (NvStorageFtwWorkingSize / Instance->Media.BlockSize <= 0)) { + DEBUG (( + DEBUG_ERROR, + "%a: NvStorageFtwWorkingSize is 0x%x, should be atleast one block size\n", + __FUNCTION__, + NvStorageFtwWorkingSize + )); + return EFI_INVALID_PARAMETER; + } + + if ((NvStorageFtwSpareSize <= 0) || (NvStorageFtwSpareSize / Instance->Media.BlockSize <= 0)) { + DEBUG (( + DEBUG_ERROR, + "%a: NvStorageFtwSpareSize is 0x%x, should be atleast one block size\n", + __FUNCTION__, + NvStorageFtwSpareSize + )); + return EFI_INVALID_PARAMETER; + } + + // Ensure the Variable area Base Addresses are aligned on a block size boundaries + if ((NvStorageVariableBase % Instance->Media.BlockSize != 0) || + (NvStorageFtwWorkingBase % Instance->Media.BlockSize != 0) || + (NvStorageFtwSpareBase % Instance->Media.BlockSize != 0)) + { + DEBUG ((DEBUG_ERROR, "%a: NvStorage Base addresses must be aligned to block size boundaries", __FUNCTION__)); + return EFI_INVALID_PARAMETER; + } + + // + // EFI_FIRMWARE_VOLUME_HEADER + // + FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Headers; + CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid); + FirmwareVolumeHeader->FvLength = + PcdGet32 (PcdFlashNvStorageVariableSize) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + + PcdGet32 (PcdFlashNvStorageFtwSpareSize); + FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE; + FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2)( + EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled + EFI_FVB2_READ_STATUS | // Reads are currently enabled + EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY + EFI_FVB2_MEMORY_MAPPED | // It is memory mapped + EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1') + EFI_FVB2_WRITE_STATUS | // Writes are currently enabled + EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled + ); + FirmwareVolumeHeader->HeaderLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY); + FirmwareVolumeHeader->Revision = EFI_FVH_REVISION; + FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1; + FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize; + FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0; + FirmwareVolumeHeader->BlockMap[1].Length = 0; + FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FirmwareVolumeHeader, FirmwareVolumeHeader->HeaderLength); + + // + // VARIABLE_STORE_HEADER + // + VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)Headers + FirmwareVolumeHeader->HeaderLength); + CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid); + VariableStoreHeader->Size = PcdGet32 (PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength; + VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED; + VariableStoreHeader->State = VARIABLE_STORE_HEALTHY; + + // Install the combined super-header in the NorFlash + Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers); + + FreePool (Headers); + return Status; +} + +/** + Check the integrity of firmware volume header. + + @param[in] FwVolHeader - A pointer to a firmware volume header + + @retval EFI_SUCCESS - The firmware volume is consistent + @retval EFI_NOT_FOUND - The firmware volume has been corrupted. + +**/ +EFI_STATUS +ValidateFvHeader ( + IN NOR_FLASH_INSTANCE *Instance + ) +{ + UINT16 Checksum; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + VARIABLE_STORE_HEADER *VariableStoreHeader; + UINTN VariableStoreLength; + UINTN FvLength; + + FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Instance->RegionBaseAddress; + + FvLength = PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + + PcdGet32 (PcdFlashNvStorageFtwSpareSize); + + // + // Verify the header revision, header signature, length + // Length of FvBlock cannot be 2**64-1 + // HeaderLength cannot be an odd number + // + if ( (FwVolHeader->Revision != EFI_FVH_REVISION) + || (FwVolHeader->Signature != EFI_FVH_SIGNATURE) + || (FwVolHeader->FvLength != FvLength) + ) + { + DEBUG (( + DEBUG_INFO, + "%a: No Firmware Volume header present\n", + __FUNCTION__ + )); + return EFI_NOT_FOUND; + } + + // Check the Firmware Volume Guid + if ( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) { + DEBUG (( + DEBUG_INFO, + "%a: Firmware Volume Guid non-compatible\n", + __FUNCTION__ + )); + return EFI_NOT_FOUND; + } + + // Verify the header checksum + Checksum = CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength); + if (Checksum != 0) { + DEBUG (( + DEBUG_INFO, + "%a: FV checksum is invalid (Checksum:0x%X)\n", + __FUNCTION__, + Checksum + )); + return EFI_NOT_FOUND; + } + + VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)FwVolHeader + FwVolHeader->HeaderLength); + + // Check the Variable Store Guid + if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) && + !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid)) + { + DEBUG (( + DEBUG_INFO, + "%a: Variable Store Guid non-compatible\n", + __FUNCTION__ + )); + return EFI_NOT_FOUND; + } + + VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength; + if (VariableStoreHeader->Size != VariableStoreLength) { + DEBUG (( + DEBUG_INFO, + "%a: Variable Store Length does not match\n", + __FUNCTION__ + )); + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; +} + +/** + The GetAttributes() function retrieves the attributes and + current settings of the block. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and + current settings are returned. + Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER. + + @retval EFI_SUCCESS The firmware volume attributes were returned. + + **/ +EFI_STATUS +EFIAPI +FvbGetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ) +{ + EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes; + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2)( + + EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled + EFI_FVB2_READ_STATUS | // Reads are currently enabled + EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY + EFI_FVB2_MEMORY_MAPPED | // It is memory mapped + EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1') + + ); + + // Check if it is write protected + if (Instance->Media.ReadOnly != TRUE) { + FlashFvbAttributes = FlashFvbAttributes | + EFI_FVB2_WRITE_STATUS | // Writes are currently enabled + EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled + } + + *Attributes = FlashFvbAttributes; + + DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes)); + + return EFI_SUCCESS; +} + +/** + The SetAttributes() function sets configurable firmware volume attributes + and returns the new settings of the firmware volume. + + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2 + that contains the desired firmware volume settings. + On successful return, it contains the new settings of + the firmware volume. + Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER. + + @retval EFI_SUCCESS The firmware volume attributes were returned. + + @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities + as declared in the firmware volume header. + + **/ +EFI_STATUS +EFIAPI +FvbSetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ) +{ + DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n", *Attributes)); + return EFI_UNSUPPORTED; +} + +/** + The GetPhysicalAddress() function retrieves the base address of + a memory-mapped firmware volume. This function should be called + only for memory-mapped firmware volumes. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Address Pointer to a caller-allocated + EFI_PHYSICAL_ADDRESS that, on successful + return from GetPhysicalAddress(), contains the + base address of the firmware volume. + + @retval EFI_SUCCESS The firmware volume base address was returned. + + @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped. + + **/ +EFI_STATUS +EFIAPI +FvbGetPhysicalAddress ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + OUT EFI_PHYSICAL_ADDRESS *Address + ) +{ + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress)); + + ASSERT (Address != NULL); + + *Address = mFlashNvStorageVariableBase; + return EFI_SUCCESS; +} + +/** + The GetBlockSize() function retrieves the size of the requested + block. It also returns the number of additional blocks with + the identical size. The GetBlockSize() function is used to + retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER). + + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Lba Indicates the block for which to return the size. + + @param BlockSize Pointer to a caller-allocated UINTN in which + the size of the block is returned. + + @param NumberOfBlocks Pointer to a caller-allocated UINTN in + which the number of consecutive blocks, + starting with Lba, is returned. All + blocks in this range have a size of + BlockSize. + + + @retval EFI_SUCCESS The firmware volume base address was returned. + + @retval EFI_INVALID_PARAMETER The requested LBA is out of range. + + **/ +EFI_STATUS +EFIAPI +FvbGetBlockSize ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + OUT UINTN *BlockSize, + OUT UINTN *NumberOfBlocks + ) +{ + EFI_STATUS Status; + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock)); + + if (Lba > Instance->Media.LastBlock) { + DEBUG ((DEBUG_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock)); + Status = EFI_INVALID_PARAMETER; + } else { + // This is easy because in this platform each NorFlash device has equal sized blocks. + *BlockSize = (UINTN)Instance->Media.BlockSize; + *NumberOfBlocks = (UINTN)(Instance->Media.LastBlock - Lba + 1); + + DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks)); + + Status = EFI_SUCCESS; + } + + return Status; +} + +/** + Reads the specified number of bytes into a buffer from the specified block. + + The Read() function reads the requested number of bytes from the + requested block and stores them in the provided buffer. + Implementations should be mindful that the firmware volume + might be in the ReadDisabled state. If it is in this state, + the Read() function must return the status code + EFI_ACCESS_DENIED without modifying the contents of the + buffer. The Read() function must also prevent spanning block + boundaries. If a read is requested that would span a block + boundary, the read must read up to the boundary but not + beyond. The output parameter NumBytes must be set to correctly + indicate the number of bytes actually read. The caller must be + aware that a read may be partially completed. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Lba The starting logical block index from which to read. + + @param Offset Offset into the block at which to begin reading. + + @param NumBytes Pointer to a UINTN. + At entry, *NumBytes contains the total size of the buffer. + At exit, *NumBytes contains the total number of bytes read. + + @param Buffer Pointer to a caller-allocated buffer that will be used + to hold the data that is read. + + @retval EFI_SUCCESS The firmware volume was read successfully, and contents are + in Buffer. + + @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary. + On output, NumBytes contains the total number of bytes + returned in Buffer. + + @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state. + + @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read. + + **/ +EFI_STATUS +EFIAPI +FvbRead ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN OUT UINT8 *Buffer + ) +{ + EFI_STATUS TempStatus; + UINTN BlockSize; + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer)); + + TempStatus = EFI_SUCCESS; + + // Cache the block size to avoid de-referencing pointers all the time + BlockSize = Instance->Media.BlockSize; + + DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); + + // The read must not span block boundaries. + // We need to check each variable individually because adding two large values together overflows. + if ((Offset >= BlockSize) || + (*NumBytes > BlockSize) || + ((Offset + *NumBytes) > BlockSize)) + { + DEBUG ((DEBUG_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); + return EFI_BAD_BUFFER_SIZE; + } + + // We must have some bytes to read + if (*NumBytes == 0) { + return EFI_BAD_BUFFER_SIZE; + } + + // Decide if we are doing full block reads or not. + if (*NumBytes % BlockSize != 0) { + TempStatus = NorFlashRead (Instance, Instance->StartLba + Lba, Offset, *NumBytes, Buffer); + if (EFI_ERROR (TempStatus)) { + return EFI_DEVICE_ERROR; + } + } else { + // Read NOR Flash data into shadow buffer + TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, Buffer); + if (EFI_ERROR (TempStatus)) { + // Return one of the pre-approved error statuses + return EFI_DEVICE_ERROR; + } + } + + return EFI_SUCCESS; +} + +/** + Writes the specified number of bytes from the input buffer to the block. + + The Write() function writes the specified number of bytes from + the provided buffer to the specified block and offset. If the + firmware volume is sticky write, the caller must ensure that + all the bits of the specified range to write are in the + EFI_FVB_ERASE_POLARITY state before calling the Write() + function, or else the result will be unpredictable. This + unpredictability arises because, for a sticky-write firmware + volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY + state but cannot flip it back again. Before calling the + Write() function, it is recommended for the caller to first call + the EraseBlocks() function to erase the specified block to + write. A block erase cycle will transition bits from the + (NOT)EFI_FVB_ERASE_POLARITY state back to the + EFI_FVB_ERASE_POLARITY state. Implementations should be + mindful that the firmware volume might be in the WriteDisabled + state. If it is in this state, the Write() function must + return the status code EFI_ACCESS_DENIED without modifying the + contents of the firmware volume. The Write() function must + also prevent spanning block boundaries. If a write is + requested that spans a block boundary, the write must store up + to the boundary but not beyond. The output parameter NumBytes + must be set to correctly indicate the number of bytes actually + written. The caller must be aware that a write may be + partially completed. All writes, partial or otherwise, must be + fully flushed to the hardware before the Write() service + returns. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. + + @param Lba The starting logical block index to write to. + + @param Offset Offset into the block at which to begin writing. + + @param NumBytes The pointer to a UINTN. + At entry, *NumBytes contains the total size of the buffer. + At exit, *NumBytes contains the total number of bytes actually written. + + @param Buffer The pointer to a caller-allocated buffer that contains the source for the write. + + @retval EFI_SUCCESS The firmware volume was written successfully. + + @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary. + On output, NumBytes contains the total number of bytes + actually written. + + @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state. + + @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written. + + + **/ +EFI_STATUS +EFIAPI +FvbWrite ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ) +{ + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + return NorFlashWriteSingleBlock (Instance, Instance->StartLba + Lba, Offset, NumBytes, Buffer); +} + +/** + Erases and initialises a firmware volume block. + + The EraseBlocks() function erases one or more blocks as denoted + by the variable argument list. The entire parameter list of + blocks must be verified before erasing any blocks. If a block is + requested that does not exist within the associated firmware + volume (it has a larger index than the last block of the + firmware volume), the EraseBlocks() function must return the + status code EFI_INVALID_PARAMETER without modifying the contents + of the firmware volume. Implementations should be mindful that + the firmware volume might be in the WriteDisabled state. If it + is in this state, the EraseBlocks() function must return the + status code EFI_ACCESS_DENIED without modifying the contents of + the firmware volume. All calls to EraseBlocks() must be fully + flushed to the hardware before the EraseBlocks() service + returns. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL + instance. + + @param ... The variable argument list is a list of tuples. + Each tuple describes a range of LBAs to erase + and consists of the following: + - An EFI_LBA that indicates the starting LBA + - A UINTN that indicates the number of blocks to erase. + + The list is terminated with an EFI_LBA_LIST_TERMINATOR. + For example, the following indicates that two ranges of blocks + (5-7 and 10-11) are to be erased: + EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR); + + @retval EFI_SUCCESS The erase request successfully completed. + + @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state. + + @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written. + The firmware device may have been partially erased. + + @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do + not exist in the firmware volume. + + **/ +EFI_STATUS +EFIAPI +FvbEraseBlocks ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, + ... + ) +{ + EFI_STATUS Status; + VA_LIST Args; + UINTN BlockAddress; // Physical address of Lba to erase + EFI_LBA StartingLba; // Lba from which we start erasing + UINTN NumOfLba; // Number of Lba blocks to erase + NOR_FLASH_INSTANCE *Instance; + + Instance = INSTANCE_FROM_FVB_THIS (This); + + DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n")); + + Status = EFI_SUCCESS; + + // Detect WriteDisabled state + if (Instance->Media.ReadOnly == TRUE) { + // Firmware volume is in WriteDisabled state + DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n")); + return EFI_ACCESS_DENIED; + } + + // Before erasing, check the entire list of parameters to ensure all specified blocks are valid + + VA_START (Args, This); + do { + // Get the Lba from which we start erasing + StartingLba = VA_ARG (Args, EFI_LBA); + + // Have we reached the end of the list? + if (StartingLba == EFI_LBA_LIST_TERMINATOR) { + // Exit the while loop + break; + } + + // How many Lba blocks are we requested to erase? + NumOfLba = VA_ARG (Args, UINTN); + + // All blocks must be within range + DEBUG (( + DEBUG_BLKIO, + "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%Lu - 1 ) > LastBlock=%ld.\n", + Instance->StartLba + StartingLba, + (UINT64)NumOfLba, + Instance->Media.LastBlock + )); + if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) { + VA_END (Args); + DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n")); + Status = EFI_INVALID_PARAMETER; + goto EXIT; + } + } while (TRUE); + + VA_END (Args); + + // + // To get here, all must be ok, so start erasing + // + VA_START (Args, This); + do { + // Get the Lba from which we start erasing + StartingLba = VA_ARG (Args, EFI_LBA); + + // Have we reached the end of the list? + if (StartingLba == EFI_LBA_LIST_TERMINATOR) { + // Exit the while loop + break; + } + + // How many Lba blocks are we requested to erase? + NumOfLba = VA_ARG (Args, UINTN); + + // Go through each one and erase it + while (NumOfLba > 0) { + // Get the physical address of Lba to erase + BlockAddress = GET_NOR_BLOCK_ADDRESS ( + Instance->RegionBaseAddress, + Instance->StartLba + StartingLba, + Instance->Media.BlockSize + ); + + // Erase it + DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress)); + Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress); + if (EFI_ERROR (Status)) { + VA_END (Args); + Status = EFI_DEVICE_ERROR; + goto EXIT; + } + + // Move to the next Lba + StartingLba++; + NumOfLba--; + } + } while (TRUE); + + VA_END (Args); + +EXIT: + return Status; +} + +/** + 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 +FvbVirtualNotifyEvent ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + EfiConvertPointer (0x0, (VOID **)&mFlashNvStorageVariableBase); + return; +} From 2167a0f79cbb42d311b49485bb58a435b0a90a4a Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 16:45:02 +0200 Subject: [PATCH 0229/1529] OvmfPkg/VirtNorFlashDxe: remove CheckBlockLocked feature We inherited a feature from the ArmPlatformPkg version of this driver that never gets enabled. Let's remove it. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 35 +++++---------------- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf | 3 -- 2 files changed, 8 insertions(+), 30 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index 12fa720dad..59a562efdf 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -65,35 +65,16 @@ NorFlashUnlockSingleBlock ( // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations // and to protect shared data structures. - if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) { - do { - // Request a lock setup - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); + // Request a lock setup + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); - // Request an unlock - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); + // Request an unlock + SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); - // Send command for reading device id - SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID); - - // Read block lock status - LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2)); - - // Decode block lock status - LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus); - } while ((LockStatus & 0x1) == 1); - } else { - // Request a lock setup - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); - - // Request an unlock - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); - - // Wait until the status register gives us the all clear - do { - LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress); - } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); - } + // Wait until the status register gives us the all clear + do { + LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress); + } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); // Put device back into Read Array mode SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY); diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf index 1bf50e4823..53e9d58204 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf @@ -24,7 +24,6 @@ VirtNorFlashFvb.c [Packages] - ArmPlatformPkg/ArmPlatformPkg.dec EmbeddedPkg/EmbeddedPkg.dec MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec @@ -66,7 +65,5 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize - gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked - [Depex] gEfiCpuArchProtocolGuid From 43047863275fb7e4d955ad7d607193e7a3d86900 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 16:50:05 +0200 Subject: [PATCH 0230/1529] OvmfPkg/VirtNorFlashDxe: remove disk I/O protocol implementation We only use NOR flash for firmware volumes, either for executable images or for the variable store. So we have no need for exposing disk I/O on top of the NOR flash partitions so let's remove it. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 129 ------------------ OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h | 29 ---- .../VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c | 123 ----------------- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 8 -- 4 files changed, 289 deletions(-) delete mode 100644 OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index 59a562efdf..1094d48f7d 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -788,135 +788,6 @@ NorFlashWriteSingleBlock ( return EFI_SUCCESS; } -/* - Although DiskIoDxe will automatically install the DiskIO protocol whenever - we install the BlockIO protocol, its implementation is sub-optimal as it reads - and writes entire blocks using the BlockIO protocol. In fact we can access - NOR flash with a finer granularity than that, so we can improve performance - by directly producing the DiskIO protocol. -*/ - -/** - Read BufferSize bytes from Offset into Buffer. - - @param This Protocol instance pointer. - @param MediaId Id of the media, changes every time the media is replaced. - @param Offset The starting byte offset to read from - @param BufferSize Size of Buffer - @param Buffer Buffer containing read data - - @retval EFI_SUCCESS The data was read correctly from the device. - @retval EFI_DEVICE_ERROR The device reported an error while performing the read. - @retval EFI_NO_MEDIA There is no media in the device. - @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. - @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not - valid for the device. - -**/ -EFI_STATUS -EFIAPI -NorFlashDiskIoReadDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 DiskOffset, - IN UINTN BufferSize, - OUT VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - UINT32 BlockSize; - UINT32 BlockOffset; - EFI_LBA Lba; - - Instance = INSTANCE_FROM_DISKIO_THIS (This); - - if (MediaId != Instance->Media.MediaId) { - return EFI_MEDIA_CHANGED; - } - - BlockSize = Instance->Media.BlockSize; - Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); - - return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer); -} - -/** - Writes a specified number of bytes to a device. - - @param This Indicates a pointer to the calling context. - @param MediaId ID of the medium to be written. - @param Offset The starting byte offset on the logical block I/O device to write. - @param BufferSize The size in bytes of Buffer. The number of bytes to write to the device. - @param Buffer A pointer to the buffer containing the data to be written. - - @retval EFI_SUCCESS The data was written correctly to the device. - @retval EFI_WRITE_PROTECTED The device can not be written to. - @retval EFI_DEVICE_ERROR The device reported an error while performing the write. - @retval EFI_NO_MEDIA There is no media in the device. - @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. - @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not - valid for the device. - -**/ -EFI_STATUS -EFIAPI -NorFlashDiskIoWriteDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 DiskOffset, - IN UINTN BufferSize, - IN VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - UINT32 BlockSize; - UINT32 BlockOffset; - EFI_LBA Lba; - UINTN RemainingBytes; - UINTN WriteSize; - EFI_STATUS Status; - - Instance = INSTANCE_FROM_DISKIO_THIS (This); - - if (MediaId != Instance->Media.MediaId) { - return EFI_MEDIA_CHANGED; - } - - BlockSize = Instance->Media.BlockSize; - Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); - - RemainingBytes = BufferSize; - - // Write either all the remaining bytes, or the number of bytes that bring - // us up to a block boundary, whichever is less. - // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next - // block boundary (even if it is already on one). - WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset); - - do { - if (WriteSize == BlockSize) { - // Write a full block - Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32)); - } else { - // Write a partial block - Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer); - } - - if (EFI_ERROR (Status)) { - return Status; - } - - // Now continue writing either all the remaining bytes or single blocks. - RemainingBytes -= WriteSize; - Buffer = (UINT8 *)Buffer + WriteSize; - Lba++; - BlockOffset = 0; - WriteSize = MIN (RemainingBytes, BlockSize); - } while (RemainingBytes); - - return Status; -} - EFI_STATUS NorFlashReset ( IN NOR_FLASH_INSTANCE *Instance diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h index e46522a198..7733ee02ee 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h @@ -15,7 +15,6 @@ #include #include -#include #include #include @@ -111,7 +110,6 @@ #define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0') #define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE) #define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE) -#define INSTANCE_FROM_DISKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, DiskIoProtocol, NOR_FLASH_SIGNATURE) typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE; @@ -134,7 +132,6 @@ struct _NOR_FLASH_INSTANCE { EFI_BLOCK_IO_PROTOCOL BlockIoProtocol; EFI_BLOCK_IO_MEDIA Media; - EFI_DISK_IO_PROTOCOL DiskIoProtocol; EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol; VOID *ShadowBuffer; @@ -203,32 +200,6 @@ NorFlashBlockIoFlushBlocks ( IN EFI_BLOCK_IO_PROTOCOL *This ); -// -// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.ReadDisk -// -EFI_STATUS -EFIAPI -NorFlashDiskIoReadDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Offset, - IN UINTN BufferSize, - OUT VOID *Buffer - ); - -// -// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.WriteDisk -// -EFI_STATUS -EFIAPI -NorFlashDiskIoWriteDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Offset, - IN UINTN BufferSize, - IN VOID *Buffer - ); - // // NorFlashFvbDxe.c // diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c deleted file mode 100644 index ecf152e355..0000000000 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashBlockIoDxe.c +++ /dev/null @@ -1,123 +0,0 @@ -/** @file NorFlashBlockIoDxe.c - - Copyright (c) 2011-2013, ARM Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -#include "VirtNorFlash.h" - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification - ) -{ - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReset(MediaId=0x%x)\n", This->Media->MediaId)); - - return NorFlashReset (Instance); -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - - if (This == NULL) { - return EFI_INVALID_PARAMETER; - } - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - Media = This->Media; - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, BufferSizeInBytes, Buffer)); - - if (!Media) { - Status = EFI_INVALID_PARAMETER; - } else if (!Media->MediaPresent) { - Status = EFI_NO_MEDIA; - } else if (Media->MediaId != MediaId) { - Status = EFI_MEDIA_CHANGED; - } else if ((Media->IoAlign > 2) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { - Status = EFI_INVALID_PARAMETER; - } else { - Status = NorFlashReadBlocks (Instance, Lba, BufferSizeInBytes, Buffer); - } - - return Status; -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - EFI_STATUS Status; - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes, BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); - - if ( !This->Media->MediaPresent ) { - Status = EFI_NO_MEDIA; - } else if ( This->Media->MediaId != MediaId ) { - Status = EFI_MEDIA_CHANGED; - } else if ( This->Media->ReadOnly ) { - Status = EFI_WRITE_PROTECTED; - } else { - Status = NorFlashWriteBlocks (Instance, Lba, BufferSizeInBytes, Buffer); - } - - return Status; -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This - ) -{ - // No Flush required for the NOR Flash driver - // because cache operations are not permitted. - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoFlushBlocks: Function NOT IMPLEMENTED (not required).\n")); - - // Nothing to do so just return without error - return EFI_SUCCESS; -} diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index 819425545e..4875b057d5 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -58,12 +58,6 @@ NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = { 1, // LogicalBlocksPerPhysicalBlock }, // Media; - { - EFI_DISK_IO_PROTOCOL_REVISION, // Revision - NorFlashDiskIoReadDisk, // ReadDisk - NorFlashDiskIoWriteDisk // WriteDisk - }, - { FvbGetAttributes, // GetAttributes FvbSetAttributes, // SetAttributes @@ -159,8 +153,6 @@ NorFlashCreateInstance ( &Instance->DevicePath, &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol, - &gEfiDiskIoProtocolGuid, - &Instance->DiskIoProtocol, NULL ); if (EFI_ERROR (Status)) { From 7f7d7286a2a2a4fb930511f4c914200fec2c1a84 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 17:12:08 +0200 Subject: [PATCH 0231/1529] OvmfPkg/VirtNorFlashDxe: drop block I/O protocol implementation We never boot from NOR flash, and generally rely on the firmware volume PI protocols to expose the contents. So drop the block I/O protocol implementation from VirtNorFlashDxe. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 49 ++++++------------ OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h | 54 ++------------------ OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 40 +++------------ OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf | 1 - OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c | 55 ++++++++------------- 5 files changed, 45 insertions(+), 154 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index 1094d48f7d..f41d9d372f 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -366,10 +366,6 @@ NorFlashWriteBlocks ( return EFI_INVALID_PARAMETER; } - if (Instance->Media.ReadOnly == TRUE) { - return EFI_WRITE_PROTECTED; - } - // We must have some bytes to read DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes)); if (BufferSizeInBytes == 0) { @@ -377,22 +373,22 @@ NorFlashWriteBlocks ( } // The size of the buffer must be a multiple of the block size - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize)); - if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->BlockSize)); + if ((BufferSizeInBytes % Instance->BlockSize) != 0) { return EFI_BAD_BUFFER_SIZE; } // All blocks must be within the device - NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; + NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->BlockSize; - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba)); + DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->LastBlock, Lba)); - if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { + if ((Lba + NumBlocks) > (Instance->LastBlock + 1)) { DEBUG ((DEBUG_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n")); return EFI_INVALID_PARAMETER; } - BlockSizeInWords = Instance->Media.BlockSize / 4; + BlockSizeInWords = Instance->BlockSize / 4; // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer // to a proper data type, so use *ReadBuffer @@ -489,8 +485,8 @@ NorFlashReadBlocks ( DEBUG_BLKIO, "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n", BufferSizeInBytes, - Instance->Media.BlockSize, - Instance->Media.LastBlock, + Instance->BlockSize, + Instance->LastBlock, Lba )); @@ -505,14 +501,14 @@ NorFlashReadBlocks ( } // The size of the buffer must be a multiple of the block size - if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { + if ((BufferSizeInBytes % Instance->BlockSize) != 0) { return EFI_BAD_BUFFER_SIZE; } // All blocks must be within the device - NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; + NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->BlockSize; - if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { + if ((Lba + NumBlocks) > (Instance->LastBlock + 1)) { DEBUG ((DEBUG_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n")); return EFI_INVALID_PARAMETER; } @@ -521,7 +517,7 @@ NorFlashReadBlocks ( StartAddress = GET_NOR_BLOCK_ADDRESS ( Instance->RegionBaseAddress, Lba, - Instance->Media.BlockSize + Instance->BlockSize ); // Put the device into Read Array mode @@ -554,7 +550,7 @@ NorFlashRead ( return EFI_SUCCESS; } - if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) { + if (((Lba * Instance->BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) { DEBUG ((DEBUG_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n")); return EFI_INVALID_PARAMETER; } @@ -563,7 +559,7 @@ NorFlashRead ( StartAddress = GET_NOR_BLOCK_ADDRESS ( Instance->RegionBaseAddress, Lba, - Instance->Media.BlockSize + Instance->BlockSize ); // Put the device into Read Array mode @@ -577,7 +573,7 @@ NorFlashRead ( /* Write a full or portion of a block. It must not span block boundaries; that is, - Offset + *NumBytes <= Instance->Media.BlockSize. + Offset + *NumBytes <= Instance->BlockSize. */ EFI_STATUS NorFlashWriteSingleBlock ( @@ -605,15 +601,8 @@ NorFlashWriteSingleBlock ( DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer)); - // Detect WriteDisabled state - if (Instance->Media.ReadOnly == TRUE) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n")); - // It is in WriteDisabled state, return an error right away - return EFI_ACCESS_DENIED; - } - // Cache the block size to avoid de-referencing pointers all the time - BlockSize = Instance->Media.BlockSize; + BlockSize = Instance->BlockSize; // The write must not span block boundaries. // We need to check each variable individually because adding two large values together overflows. @@ -819,12 +808,6 @@ NorFlashVirtualNotifyEvent ( EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress); EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress); - // Convert BlockIo protocol - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.Reset); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks); - // Convert Fvb EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks); EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes); diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h index 7733ee02ee..b7f5d208b2 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.h @@ -14,7 +14,6 @@ #include -#include #include #include @@ -108,8 +107,7 @@ #define P30_CMD_READ_CONFIGURATION_REGISTER 0x0003 #define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0') -#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE) -#define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE) +#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE) typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE; @@ -129,9 +127,8 @@ struct _NOR_FLASH_INSTANCE { UINTN RegionBaseAddress; UINTN Size; EFI_LBA StartLba; - - EFI_BLOCK_IO_PROTOCOL BlockIoProtocol; - EFI_BLOCK_IO_MEDIA Media; + EFI_LBA LastBlock; + UINT32 BlockSize; EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol; VOID *ShadowBuffer; @@ -155,51 +152,6 @@ NorFlashWriteBuffer ( IN UINT32 *Buffer ); -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This - ); - // // NorFlashFvbDxe.c // diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index 4875b057d5..2ceda22635 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -34,29 +34,8 @@ NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = { 0, // RegionBaseAddress ... NEED TO BE FILLED 0, // Size ... NEED TO BE FILLED 0, // StartLba - - { - EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision - NULL, // Media ... NEED TO BE FILLED - NorFlashBlockIoReset, // Reset; - NorFlashBlockIoReadBlocks, // ReadBlocks - NorFlashBlockIoWriteBlocks, // WriteBlocks - NorFlashBlockIoFlushBlocks // FlushBlocks - }, // BlockIoProtocol - - { - 0, // MediaId ... NEED TO BE FILLED - FALSE, // RemovableMedia - TRUE, // MediaPresent - FALSE, // LogicalPartition - FALSE, // ReadOnly - FALSE, // WriteCaching; - 0, // BlockSize ... NEED TO BE FILLED - 4, // IoAlign - 0, // LastBlock ... NEED TO BE FILLED - 0, // LowestAlignedLba - 1, // LogicalBlocksPerPhysicalBlock - }, // Media; + 0, // LastBlock + 0, // BlockSize { FvbGetAttributes, // GetAttributes @@ -115,11 +94,8 @@ NorFlashCreateInstance ( Instance->DeviceBaseAddress = NorFlashDeviceBase; Instance->RegionBaseAddress = NorFlashRegionBase; Instance->Size = NorFlashSize; - - Instance->BlockIoProtocol.Media = &Instance->Media; - Instance->Media.MediaId = Index; - Instance->Media.BlockSize = BlockSize; - Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1; + Instance->BlockSize = BlockSize; + Instance->LastBlock = (NorFlashSize / BlockSize) - 1; CopyGuid (&Instance->DevicePath.Vendor.Guid, &gEfiCallerIdGuid); Instance->DevicePath.Index = (UINT8)Index; @@ -136,8 +112,6 @@ NorFlashCreateInstance ( &Instance->Handle, &gEfiDevicePathProtocolGuid, &Instance->DevicePath, - &gEfiBlockIoProtocolGuid, - &Instance->BlockIoProtocol, &gEfiFirmwareVolumeBlockProtocolGuid, &Instance->FvbProtocol, NULL @@ -151,8 +125,6 @@ NorFlashCreateInstance ( &Instance->Handle, &gEfiDevicePathProtocolGuid, &Instance->DevicePath, - &gEfiBlockIoProtocolGuid, - &Instance->BlockIoProtocol, NULL ); if (EFI_ERROR (Status)) { @@ -434,7 +406,7 @@ NorFlashFvbInitialize ( PcdGet64 (PcdFlashNvStorageVariableBase64) : PcdGet32 (PcdFlashNvStorageVariableBase); // Set the index of the first LBA for the FVB - Instance->StartLba = (mFlashNvStorageVariableBase - Instance->RegionBaseAddress) / Instance->Media.BlockSize; + Instance->StartLba = (mFlashNvStorageVariableBase - Instance->RegionBaseAddress) / Instance->BlockSize; BootMode = GetBootModeHob (); if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) { @@ -455,7 +427,7 @@ NorFlashFvbInitialize ( )); // Erase all the NorFlash that is reserved for variable storage - FvbNumLba = (PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize; + FvbNumLba = (PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / Instance->BlockSize; Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR); if (EFI_ERROR (Status)) { diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf index 53e9d58204..2a3d4a218e 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf @@ -19,7 +19,6 @@ [Sources.common] VirtNorFlash.c VirtNorFlash.h - VirtNorFlashBlockIoDxe.c VirtNorFlashDxe.c VirtNorFlashFvb.c diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c index c824e0a0fb..cc5eefaaf3 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c @@ -89,7 +89,7 @@ InitializeFvAndVariableStoreHeaders ( } // Check if the size of the area is at least one block size - if ((NvStorageVariableSize <= 0) || (NvStorageVariableSize / Instance->Media.BlockSize <= 0)) { + if ((NvStorageVariableSize <= 0) || (NvStorageVariableSize / Instance->BlockSize <= 0)) { DEBUG (( DEBUG_ERROR, "%a: NvStorageVariableSize is 0x%x, should be atleast one block size\n", @@ -99,7 +99,7 @@ InitializeFvAndVariableStoreHeaders ( return EFI_INVALID_PARAMETER; } - if ((NvStorageFtwWorkingSize <= 0) || (NvStorageFtwWorkingSize / Instance->Media.BlockSize <= 0)) { + if ((NvStorageFtwWorkingSize <= 0) || (NvStorageFtwWorkingSize / Instance->BlockSize <= 0)) { DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwWorkingSize is 0x%x, should be atleast one block size\n", @@ -109,7 +109,7 @@ InitializeFvAndVariableStoreHeaders ( return EFI_INVALID_PARAMETER; } - if ((NvStorageFtwSpareSize <= 0) || (NvStorageFtwSpareSize / Instance->Media.BlockSize <= 0)) { + if ((NvStorageFtwSpareSize <= 0) || (NvStorageFtwSpareSize / Instance->BlockSize <= 0)) { DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwSpareSize is 0x%x, should be atleast one block size\n", @@ -120,9 +120,9 @@ InitializeFvAndVariableStoreHeaders ( } // Ensure the Variable area Base Addresses are aligned on a block size boundaries - if ((NvStorageVariableBase % Instance->Media.BlockSize != 0) || - (NvStorageFtwWorkingBase % Instance->Media.BlockSize != 0) || - (NvStorageFtwSpareBase % Instance->Media.BlockSize != 0)) + if ((NvStorageVariableBase % Instance->BlockSize != 0) || + (NvStorageFtwWorkingBase % Instance->BlockSize != 0) || + (NvStorageFtwSpareBase % Instance->BlockSize != 0)) { DEBUG ((DEBUG_ERROR, "%a: NvStorage Base addresses must be aligned to block size boundaries", __FUNCTION__)); return EFI_INVALID_PARAMETER; @@ -149,8 +149,8 @@ InitializeFvAndVariableStoreHeaders ( ); FirmwareVolumeHeader->HeaderLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY); FirmwareVolumeHeader->Revision = EFI_FVH_REVISION; - FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1; - FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize; + FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->LastBlock + 1; + FirmwareVolumeHeader->BlockMap[0].Length = Instance->BlockSize; FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0; FirmwareVolumeHeader->BlockMap[1].Length = 0; FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FirmwareVolumeHeader, FirmwareVolumeHeader->HeaderLength); @@ -284,9 +284,6 @@ FvbGetAttributes ( ) { EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes; - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2)( @@ -294,17 +291,12 @@ FvbGetAttributes ( EFI_FVB2_READ_STATUS | // Reads are currently enabled EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY EFI_FVB2_MEMORY_MAPPED | // It is memory mapped - EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1') + EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1') + EFI_FVB2_WRITE_STATUS | // Writes are currently enabled + EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled ); - // Check if it is write protected - if (Instance->Media.ReadOnly != TRUE) { - FlashFvbAttributes = FlashFvbAttributes | - EFI_FVB2_WRITE_STATUS | // Writes are currently enabled - EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled - } - *Attributes = FlashFvbAttributes; DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes)); @@ -418,15 +410,15 @@ FvbGetBlockSize ( Instance = INSTANCE_FROM_FVB_THIS (This); - DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock)); + DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->BlockSize, Instance->LastBlock)); - if (Lba > Instance->Media.LastBlock) { - DEBUG ((DEBUG_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock)); + if (Lba > Instance->LastBlock) { + DEBUG ((DEBUG_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->LastBlock)); Status = EFI_INVALID_PARAMETER; } else { // This is easy because in this platform each NorFlash device has equal sized blocks. - *BlockSize = (UINTN)Instance->Media.BlockSize; - *NumberOfBlocks = (UINTN)(Instance->Media.LastBlock - Lba + 1); + *BlockSize = (UINTN)Instance->BlockSize; + *NumberOfBlocks = (UINTN)(Instance->LastBlock - Lba + 1); DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks)); @@ -498,7 +490,7 @@ FvbRead ( TempStatus = EFI_SUCCESS; // Cache the block size to avoid de-referencing pointers all the time - BlockSize = Instance->Media.BlockSize; + BlockSize = Instance->BlockSize; DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); @@ -669,13 +661,6 @@ FvbEraseBlocks ( Status = EFI_SUCCESS; - // Detect WriteDisabled state - if (Instance->Media.ReadOnly == TRUE) { - // Firmware volume is in WriteDisabled state - DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n")); - return EFI_ACCESS_DENIED; - } - // Before erasing, check the entire list of parameters to ensure all specified blocks are valid VA_START (Args, This); @@ -698,9 +683,9 @@ FvbEraseBlocks ( "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%Lu - 1 ) > LastBlock=%ld.\n", Instance->StartLba + StartingLba, (UINT64)NumOfLba, - Instance->Media.LastBlock + Instance->LastBlock )); - if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) { + if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->LastBlock)) { VA_END (Args); DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n")); Status = EFI_INVALID_PARAMETER; @@ -733,7 +718,7 @@ FvbEraseBlocks ( BlockAddress = GET_NOR_BLOCK_ADDRESS ( Instance->RegionBaseAddress, Instance->StartLba + StartingLba, - Instance->Media.BlockSize + Instance->BlockSize ); // Erase it From 43595844596f75c84bd4d8b7b3a0175fe835940f Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 17:34:09 +0200 Subject: [PATCH 0232/1529] OvmfPkg/VirtNorFlashDxe: avoid array mode switch after each word write NorFlashWriteSingleWord() switches into programming mode and back into array mode for every single word that it writes. Under KVM, this involves tearing down the read-only memslot, and setting it up again, which is costly and unnecessary. Instead, move the array mode switch into the callers, and only make the switch when the writing is done. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 12 +++--------- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 3 +++ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index f41d9d372f..0a5c5d48c7 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -205,9 +205,6 @@ NorFlashWriteSingleWord ( SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); } - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - return Status; } @@ -286,8 +283,7 @@ NorFlashWriteBuffer ( // The buffer was not available for writing if (WaitForBuffer == 0) { - Status = EFI_DEVICE_ERROR; - goto EXIT; + return EFI_DEVICE_ERROR; } // From now on we work in 32-bit words @@ -337,10 +333,6 @@ NorFlashWriteBuffer ( SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); } -EXIT: - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - return Status; } @@ -739,6 +731,8 @@ NorFlashWriteSingleBlock ( } TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite); + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); if (EFI_ERROR (TempStatus)) { return EFI_DEVICE_ERROR; } diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index 2ceda22635..f9a41f6aab 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -280,6 +280,9 @@ NorFlashWriteFullBlock ( } EXIT: + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + if (!EfiAtRuntime ()) { // Interruptions can resume. gBS->RestoreTPL (OriginalTPL); From b5eb81d5e2e08ad770395ace715c33947b204d00 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 17:58:07 +0200 Subject: [PATCH 0233/1529] OvmfPkg/VirtNorFlashDxe: avoid switching between modes in a tight loop Currently, when dealing with small updates that can be written out directly (i.e., if they only involve clearing bits and not setting bits, as the latter requires a block level erase), we iterate over the data one word at a time, read the old value, compare it, write the new value, and repeat, unless we encountered a value that we cannot write (0->1 transition), in which case we fall back to a block level operation. This is inefficient for two reasons: - reading and writing a word at a time involves switching between array and programming mode for every word of data, which is disproportionately costly when running under KVM; - we end up writing some data twice, as we may not notice that a block erase is needed until after some data has been written to flash. So replace this sequence with a single read of up to twice the buffered write maximum size, followed by one or two buffered writes if the data can be written directly. Otherwise, fall back to the existing block level sequence, but without writing out part of the data twice. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 214 +++++++++---------------- 1 file changed, 76 insertions(+), 138 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index 0a5c5d48c7..0343131a54 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -576,23 +576,20 @@ NorFlashWriteSingleBlock ( IN UINT8 *Buffer ) { - EFI_STATUS TempStatus; - UINT32 Tmp; - UINT32 TmpBuf; - UINT32 WordToWrite; - UINT32 Mask; - BOOLEAN DoErase; - UINTN BytesToWrite; + EFI_STATUS Status; UINTN CurOffset; - UINTN WordAddr; UINTN BlockSize; UINTN BlockAddress; - UINTN PrevBlockAddress; - - PrevBlockAddress = 0; + UINT8 *OrigData; DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer)); + // Check we did get some memory. Buffer is BlockSize. + if (Instance->ShadowBuffer == NULL) { + DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n")); + return EFI_DEVICE_ERROR; + } + // Cache the block size to avoid de-referencing pointers all the time BlockSize = Instance->BlockSize; @@ -612,148 +609,89 @@ NorFlashWriteSingleBlock ( return EFI_BAD_BUFFER_SIZE; } - // Pick 128bytes as a good start for word operations as opposed to erasing the - // block and writing the data regardless if an erase is really needed. - // It looks like most individual NV variable writes are smaller than 128bytes. - if (*NumBytes <= 128) { + // Pick P30_MAX_BUFFER_SIZE_IN_BYTES (== 128 bytes) as a good start for word + // operations as opposed to erasing the block and writing the data regardless + // if an erase is really needed. It looks like most individual NV variable + // writes are smaller than 128 bytes. + // To avoid pathological cases were a 2 byte write is disregarded because it + // occurs right at a 128 byte buffered write alignment boundary, permit up to + // twice the max buffer size, and perform two writes if needed. + if ((*NumBytes + (Offset & BOUNDARY_OF_32_WORDS)) <= (2 * P30_MAX_BUFFER_SIZE_IN_BYTES)) { // Check to see if we need to erase before programming the data into NOR. // If the destination bits are only changing from 1s to 0s we can just write. // After a block is erased all bits in the block is set to 1. // If any byte requires us to erase we just give up and rewrite all of it. - DoErase = FALSE; - BytesToWrite = *NumBytes; - CurOffset = Offset; - - while (BytesToWrite > 0) { - // Read full word from NOR, splice as required. A word is the smallest - // unit we can write. - TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof (Tmp), &Tmp); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } - // Physical address of word in NOR to write. - WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS ( - Instance->RegionBaseAddress, - Lba, - BlockSize - ); - // The word of data that is to be written. - TmpBuf = *((UINT32 *)(Buffer + (*NumBytes - BytesToWrite))); - - // First do word aligned chunks. - if ((CurOffset & 0x3) == 0) { - if (BytesToWrite >= 4) { - // Is the destination still in 'erased' state? - if (~Tmp != 0) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Write this word to NOR - WordToWrite = TmpBuf; - CurOffset += sizeof (TmpBuf); - BytesToWrite -= sizeof (TmpBuf); - } else { - // BytesToWrite < 4. Do small writes and left-overs - Mask = ~((~0) << (BytesToWrite * 8)); - // Mask out the bytes we want. - TmpBuf &= Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - CurOffset += BytesToWrite; - BytesToWrite = 0; - } - } else { - // Do multiple words, but starting unaligned. - if (BytesToWrite > (4 - (CurOffset & 0x3))) { - Mask = ((~0) << ((CurOffset & 0x3) * 8)); - // Mask out the bytes we want. - TmpBuf &= Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - BytesToWrite -= (4 - (CurOffset & 0x3)); - CurOffset += (4 - (CurOffset & 0x3)); - } else { - // Unaligned and fits in one word. - Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8); - // Mask out the bytes we want. - TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - CurOffset += BytesToWrite; - BytesToWrite = 0; - } + // Read the old version of the data into the shadow buffer + Status = NorFlashRead ( + Instance, + Lba, + Offset & ~BOUNDARY_OF_32_WORDS, + (*NumBytes | BOUNDARY_OF_32_WORDS) + 1, + Instance->ShadowBuffer + ); + if (EFI_ERROR (Status)) { + return EFI_DEVICE_ERROR; + } + + // Make OrigData point to the start of the old version of the data inside + // the word aligned buffer + OrigData = Instance->ShadowBuffer + (Offset & BOUNDARY_OF_32_WORDS); + + // Update the buffer containing the old version of the data with the new + // contents, while checking whether the old version had any bits cleared + // that we want to set. In that case, we will need to erase the block first. + for (CurOffset = 0; CurOffset < *NumBytes; CurOffset++) { + if (~OrigData[CurOffset] & Buffer[CurOffset]) { + goto DoErase; } - // - // Write the word to NOR. - // + OrigData[CurOffset] = Buffer[CurOffset]; + } - BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize); - if (BlockAddress != PrevBlockAddress) { - TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } + // + // Write the updated buffer to NOR. + // + BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize); - PrevBlockAddress = BlockAddress; - } + // Unlock the block if we have to + Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); + if (EFI_ERROR (Status)) { + goto Exit; + } - TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite); - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } + Status = NorFlashWriteBuffer ( + Instance, + BlockAddress + (Offset & ~BOUNDARY_OF_32_WORDS), + P30_MAX_BUFFER_SIZE_IN_BYTES, + Instance->ShadowBuffer + ); + if (EFI_ERROR (Status)) { + goto Exit; } - // Exit if we got here and could write all the data. Otherwise do the - // Erase-Write cycle. - if (!DoErase) { - return EFI_SUCCESS; + if ((*NumBytes + (Offset & BOUNDARY_OF_32_WORDS)) > P30_MAX_BUFFER_SIZE_IN_BYTES) { + BlockAddress += P30_MAX_BUFFER_SIZE_IN_BYTES; + + Status = NorFlashWriteBuffer ( + Instance, + BlockAddress + (Offset & ~BOUNDARY_OF_32_WORDS), + P30_MAX_BUFFER_SIZE_IN_BYTES, + Instance->ShadowBuffer + P30_MAX_BUFFER_SIZE_IN_BYTES + ); } - } - // Check we did get some memory. Buffer is BlockSize. - if (Instance->ShadowBuffer == NULL) { - DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n")); - return EFI_DEVICE_ERROR; +Exit: + // Put device back into Read Array mode + SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); + + return Status; } +DoErase: // Read NOR Flash data into shadow buffer - TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); - if (EFI_ERROR (TempStatus)) { + Status = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); + if (EFI_ERROR (Status)) { // Return one of the pre-approved error statuses return EFI_DEVICE_ERROR; } @@ -762,8 +700,8 @@ NorFlashWriteSingleBlock ( CopyMem ((VOID *)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes); // Write the modified buffer back to the NorFlash - TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); - if (EFI_ERROR (TempStatus)) { + Status = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); + if (EFI_ERROR (Status)) { // Return one of the pre-approved error statuses return EFI_DEVICE_ERROR; } From 60d51030f59f2b653cacca2ad971dc9c9e0ab504 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 18:16:18 +0200 Subject: [PATCH 0234/1529] OvmfPkg/VirtNorFlashDxe: use EFI_MEMORY_WC and drop AlignedCopyMem() NOR flash emulation under KVM involves switching between two modes, where array mode is backed by a read-only memslot, and programming mode is fully emulated, i.e., the memory region is not backed by anything, and the faulting accesses are forwarded to the VMM by the hypervisor, which translates them into NOR flash programming commands. Normally, we are limited to the use of device attributes when mapping such regions, given that the programming mode has MMIO semantics. However, when running under KVM, the chosen memory attributes only take effect when in array mode, since no memory mapping exists otherwise. This means we can tune the memory mapping so it behaves a bit more like a ROM, by switching to EFI_MEMORY_WC attributes. This means we no longer need a special CopyMem() implementation that avoids unaligned accesses at all cost. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c | 65 +---------------------- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 4 +- 2 files changed, 4 insertions(+), 65 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c index 0343131a54..1afd60ce66 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlash.c @@ -401,67 +401,6 @@ NorFlashWriteBlocks ( return Status; } -#define BOTH_ALIGNED(a, b, align) ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0) - -/** - Copy Length bytes from Source to Destination, using aligned accesses only. - Note that this implementation uses memcpy() semantics rather then memmove() - semantics, i.e., SourceBuffer and DestinationBuffer should not overlap. - - @param DestinationBuffer The target of the copy request. - @param SourceBuffer The place to copy from. - @param Length The number of bytes to copy. - - @return Destination - -**/ -STATIC -VOID * -AlignedCopyMem ( - OUT VOID *DestinationBuffer, - IN CONST VOID *SourceBuffer, - IN UINTN Length - ) -{ - UINT8 *Destination8; - CONST UINT8 *Source8; - UINT32 *Destination32; - CONST UINT32 *Source32; - UINT64 *Destination64; - CONST UINT64 *Source64; - - if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 8) && (Length >= 8)) { - Destination64 = DestinationBuffer; - Source64 = SourceBuffer; - while (Length >= 8) { - *Destination64++ = *Source64++; - Length -= 8; - } - - Destination8 = (UINT8 *)Destination64; - Source8 = (CONST UINT8 *)Source64; - } else if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 4) && (Length >= 4)) { - Destination32 = DestinationBuffer; - Source32 = SourceBuffer; - while (Length >= 4) { - *Destination32++ = *Source32++; - Length -= 4; - } - - Destination8 = (UINT8 *)Destination32; - Source8 = (CONST UINT8 *)Source32; - } else { - Destination8 = DestinationBuffer; - Source8 = SourceBuffer; - } - - while (Length-- != 0) { - *Destination8++ = *Source8++; - } - - return DestinationBuffer; -} - EFI_STATUS NorFlashReadBlocks ( IN NOR_FLASH_INSTANCE *Instance, @@ -516,7 +455,7 @@ NorFlashReadBlocks ( SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); // Readout the data - AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes); + CopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes); return EFI_SUCCESS; } @@ -558,7 +497,7 @@ NorFlashRead ( SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); // Readout the data - AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes); + CopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes); return EFI_SUCCESS; } diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index f9a41f6aab..ff3121af2a 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -394,14 +394,14 @@ NorFlashFvbInitialize ( EfiGcdMemoryTypeMemoryMappedIo, Instance->DeviceBaseAddress, RuntimeMmioRegionSize, - EFI_MEMORY_UC | EFI_MEMORY_RUNTIME + EFI_MEMORY_WC | EFI_MEMORY_RUNTIME ); ASSERT_EFI_ERROR (Status); Status = gDS->SetMemorySpaceAttributes ( Instance->DeviceBaseAddress, RuntimeMmioRegionSize, - EFI_MEMORY_UC | EFI_MEMORY_RUNTIME + EFI_MEMORY_WC | EFI_MEMORY_RUNTIME ); ASSERT_EFI_ERROR (Status); From bdfca393d9f4d66b735ad06fc06a5862c8854c17 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 18:41:22 +0200 Subject: [PATCH 0235/1529] ArmVirtPkg/ArmVirtQemu: migrate to OVMF's VirtNorFlashDxe Switch to the virt specific NorFlashDxe driver implementation that was added recently. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- ArmVirtPkg/ArmVirtQemu.dsc | 4 ++-- ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc | 2 +- ArmVirtPkg/ArmVirtQemuKernel.dsc | 4 ++-- ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c | 12 ++++++------ .../Library/NorFlashQemuLib/NorFlashQemuLib.inf | 4 ++-- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 28a4453068..f77443229e 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -65,7 +65,7 @@ QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf - NorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf + VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf @@ -423,7 +423,7 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf # diff --git a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc index 7872861330..e06ca74244 100644 --- a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc +++ b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc @@ -73,7 +73,7 @@ READ_LOCK_STATUS = TRUE INF ArmPkg/Drivers/ArmGic/ArmGicDxe.inf INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf - INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf + INF OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf # diff --git a/ArmVirtPkg/ArmVirtQemuKernel.dsc b/ArmVirtPkg/ArmVirtQemuKernel.dsc index a80ae92faa..f5db3ac432 100644 --- a/ArmVirtPkg/ArmVirtQemuKernel.dsc +++ b/ArmVirtPkg/ArmVirtQemuKernel.dsc @@ -65,7 +65,7 @@ ArmVirtMemInfoLib|ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.inf TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf - NorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf + VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf @@ -331,7 +331,7 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf # diff --git a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c index 2b39f021d0..55bce88bc8 100644 --- a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c +++ b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c @@ -8,8 +8,8 @@ #include #include -#include #include +#include #include @@ -18,19 +18,19 @@ #define MAX_FLASH_BANKS 4 EFI_STATUS -NorFlashPlatformInitialization ( +VirtNorFlashPlatformInitialization ( VOID ) { return EFI_SUCCESS; } -NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_BANKS]; +STATIC VIRT_NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_BANKS]; EFI_STATUS -NorFlashPlatformGetDevices ( - OUT NOR_FLASH_DESCRIPTION **NorFlashDescriptions, - OUT UINT32 *Count +VirtNorFlashPlatformGetDevices ( + OUT VIRT_NOR_FLASH_DESCRIPTION **NorFlashDescriptions, + OUT UINT32 *Count ) { FDT_CLIENT_PROTOCOL *FdtClient; diff --git a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf index 4c3683bf5d..a6b5865be9 100644 --- a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf +++ b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf @@ -14,17 +14,17 @@ FILE_GUID = 339B7829-4C5F-4EFC-B2DD-5050E530DECE MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 - LIBRARY_CLASS = NorFlashPlatformLib + LIBRARY_CLASS = VirtNorFlashPlatformLib [Sources.common] NorFlashQemuLib.c [Packages] MdePkg/MdePkg.dec - ArmPlatformPkg/ArmPlatformPkg.dec ArmPkg/ArmPkg.dec ArmVirtPkg/ArmVirtPkg.dec EmbeddedPkg/EmbeddedPkg.dec + OvmfPkg/OvmfPkg.dec [LibraryClasses] BaseLib From 55c2d33fbbfee94fb2962652a2f33215ea5c5ec8 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 18:51:43 +0200 Subject: [PATCH 0236/1529] ArmVirtPkg/ArmVirtKvmTool: Migrate to OVMF's VirtNorFlashDxe Migrate to the virt specific NOR flash driver as the ArmPlatformPkg is going away. Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- ArmVirtPkg/ArmVirtKvmTool.dsc | 4 ++-- ArmVirtPkg/ArmVirtKvmTool.fdf | 2 +- .../NorFlashKvmtoolLib/NorFlashKvmtool.c | 20 +++++++++---------- .../NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/ArmVirtPkg/ArmVirtKvmTool.dsc b/ArmVirtPkg/ArmVirtKvmTool.dsc index 3bd3ebd6e0..c598903b33 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.dsc +++ b/ArmVirtPkg/ArmVirtKvmTool.dsc @@ -50,7 +50,7 @@ ArmVirtMemInfoLib|ArmVirtPkg/Library/KvmtoolVirtMemInfoLib/KvmtoolVirtMemInfoLib.inf TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf - NorFlashPlatformLib|ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf + VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf @@ -291,7 +291,7 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf diff --git a/ArmVirtPkg/ArmVirtKvmTool.fdf b/ArmVirtPkg/ArmVirtKvmTool.fdf index 9e006e83ee..b696bffc7c 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.fdf +++ b/ArmVirtPkg/ArmVirtKvmTool.fdf @@ -154,7 +154,7 @@ READ_LOCK_STATUS = TRUE INF ArmPkg/Drivers/ArmGic/ArmGicDxe.inf INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf - INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf + INF OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf # # FAT filesystem + GPT/MBR partitioning + UDF filesystem diff --git a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c index 39d2615b54..129c16b711 100644 --- a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c +++ b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c @@ -9,8 +9,8 @@ #include #include -#include #include +#include #include /** Macro defining the NOR block size configured in Kvmtool. @@ -25,10 +25,10 @@ */ #define LABEL_UEFI_VAR_STORE "System-firmware" -STATIC NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_DEVICES]; -STATIC UINTN mNorFlashDeviceCount = 0; -STATIC INT32 mUefiVarStoreNode = MAX_INT32; -STATIC FDT_CLIENT_PROTOCOL *mFdtClient; +STATIC VIRT_NOR_FLASH_DESCRIPTION mNorFlashDevices[MAX_FLASH_DEVICES]; +STATIC UINTN mNorFlashDeviceCount = 0; +STATIC INT32 mUefiVarStoreNode = MAX_INT32; +STATIC FDT_CLIENT_PROTOCOL *mFdtClient; /** This function performs platform specific actions to initialise the NOR flash, if required. @@ -36,7 +36,7 @@ STATIC FDT_CLIENT_PROTOCOL *mFdtClient; @retval EFI_SUCCESS Success. **/ EFI_STATUS -NorFlashPlatformInitialization ( +VirtNorFlashPlatformInitialization ( VOID ) { @@ -89,7 +89,7 @@ NorFlashPlatformInitialization ( STATIC EFI_STATUS SetupVariableStore ( - IN NOR_FLASH_DESCRIPTION *FlashDevice + IN VIRT_NOR_FLASH_DESCRIPTION *FlashDevice ) { UINTN FlashRegion; @@ -187,9 +187,9 @@ SetupVariableStore ( @retval EFI_NOT_FOUND Flash device not found. **/ EFI_STATUS -NorFlashPlatformGetDevices ( - OUT NOR_FLASH_DESCRIPTION **NorFlashDescriptions, - OUT UINT32 *Count +VirtNorFlashPlatformGetDevices ( + OUT VIRT_NOR_FLASH_DESCRIPTION **NorFlashDescriptions, + OUT UINT32 *Count ) { if (mNorFlashDeviceCount > 0) { diff --git a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf index 04d6723295..b5f35d4782 100644 --- a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf +++ b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtoolLib.inf @@ -12,7 +12,7 @@ FILE_GUID = E75F07A1-B160-4893-BDD4-09E32FF847DC MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 - LIBRARY_CLASS = NorFlashPlatformLib + LIBRARY_CLASS = VirtNorFlashPlatformLib CONSTRUCTOR = NorFlashPlatformLibConstructor [Sources.common] @@ -20,11 +20,11 @@ [Packages] ArmPkg/ArmPkg.dec - ArmPlatformPkg/ArmPlatformPkg.dec ArmVirtPkg/ArmVirtPkg.dec EmbeddedPkg/EmbeddedPkg.dec MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec + OvmfPkg/OvmfPkg.dec [LibraryClasses] BaseLib From de6480b7eba8658885423b75269f253355681641 Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Fri, 28 Oct 2022 11:51:18 +0800 Subject: [PATCH 0237/1529] UefiCpuPkg: Restore HpetTimer after CpuExceptionHandlerLib test Disable/Restore HpetTimer before and after running the Dxe CpuExceptionHandlerLib unit test module. During the UnitTest, a new Idt is initialized for the test. There is no handler for timer intrrupt in this new idt. After the test module, HpetTimer does not work any more since the comparator value register and main counter value register for timer does not match. To fix this issue, disable/restore HpetTimer before and after Unit Test if HpetTimer driver has been dispatched. We don't need to send Apic Eoi in this unit test module.When disabling timer, after RaiseTPL(), if there is a pending timer interrupt, bit64 of Interrupt Request Register (IRR) will be set to 1 to indicate there is a pending timer interrupt. After RestoreTPL(), CPU will handle the pending interrupt in IRR.Then TimerInterruptHandler calls SendApicEoi(). Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Cc: Michael D Kinney --- .../DxeCpuExceptionHandlerLibUnitTest.inf | 1 + .../UnitTest/DxeCpuExceptionHandlerUnitTest.c | 30 ++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf index e3dbe7b9ab..a904eb2504 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf @@ -53,6 +53,7 @@ [Protocols] gEfiMpServiceProtocolGuid + gEfiTimerArchProtocolGuid [Depex] gEfiMpServiceProtocolGuid diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c index 917fc549bf..1cec3ed809 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c @@ -8,6 +8,7 @@ #include "CpuExceptionHandlerTest.h" #include +#include /** Initialize Bsp Idt with a new Idt table and return the IA32_DESCRIPTOR buffer. @@ -162,8 +163,12 @@ CpuExceptionHandlerTestEntry ( { EFI_STATUS Status; UNIT_TEST_FRAMEWORK_HANDLE Framework; + EFI_TIMER_ARCH_PROTOCOL *TimerArchProtocol; + UINT64 TimerPeriod; - Framework = NULL; + Framework = NULL; + TimerArchProtocol = NULL; + TimerPeriod = 0; DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION)); @@ -182,11 +187,34 @@ CpuExceptionHandlerTestEntry ( goto EXIT; } + // + // If HpetTimer driver has been dispatched, disable HpetTimer before Unit Test. + // + gBS->LocateProtocol (&gEfiTimerArchProtocolGuid, NULL, (VOID **)&TimerArchProtocol); + if (TimerArchProtocol != NULL) { + Status = TimerArchProtocol->GetTimerPeriod (TimerArchProtocol, &TimerPeriod); + ASSERT_EFI_ERROR (Status); + if (TimerPeriod > 0) { + DEBUG ((DEBUG_INFO, "HpetTimer has been dispatched. Disable HpetTimer.\n")); + Status = TimerArchProtocol->SetTimerPeriod (TimerArchProtocol, 0); + ASSERT_EFI_ERROR (Status); + } + } + // // Execute the tests. // Status = RunAllTestSuites (Framework); + // + // Restore HpetTimer after Unit Test. + // + if ((TimerArchProtocol != NULL) && (TimerPeriod > 0)) { + DEBUG ((DEBUG_INFO, "Restore HpetTimer after DxeCpuExceptionHandlerLib UnitTest.\n")); + Status = TimerArchProtocol->SetTimerPeriod (TimerArchProtocol, TimerPeriod); + ASSERT_EFI_ERROR (Status); + } + EXIT: if (Framework) { FreeUnitTestFramework (Framework); From 6bc3516ea0f21e6279fc4bf8b26d23b85c212f0b Mon Sep 17 00:00:00 2001 From: Cheripally Gopi Date: Wed, 26 Oct 2022 17:37:25 +0530 Subject: [PATCH 0238/1529] MdeModulePkg/ScsiDiskDxe: Update proper device name for ScsiDisk drive REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4100 ScsiDiskDxe driver updates ControllerNameTable with common string "SCSI Disk Device" for all SCSI disks. Due to this, when multiple SCSI disk devices connected, facing difficulty in identifying correct SCSI disk device. As per SCSI spec, standard Inquiry Data is having the fields to know Vendor and Product information. Updated "ControllerNameTable" with Vendor and Product information. So that, device specific name can be retrieved using ComponentName protocol. Cc: Vasudevan Sambandan Cc: Sundaresan Selvaraj Signed-off-by: Cheripally Gopi Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 53 ++++++++++++++++++- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h | 9 ++++ .../Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf | 2 + 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index 98e84b4ea8..0928605dc4 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -2,6 +2,7 @@ SCSI disk driver that layers on every SCSI IO protocol in the system. Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 1985 - 2022, American Megatrends International LLC.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -67,6 +68,33 @@ FreeAlignedBuffer ( } } +/** + Remove trailing spaces from the string. + + @param String The ASCII string to remove the trailing spaces. + + @retval the new length of the string. +**/ +UINTN +RemoveTrailingSpaces ( + IN OUT CHAR8 *String + ) +{ + UINTN Length; + + Length = AsciiStrLen (String); + if (Length == 0) { + return 0; + } + + while ((Length > 0) && (String[Length-1] == ' ')) { + Length--; + } + + String[Length] = '\0'; + return Length; +} + /** The user Entry Point for module ScsiDisk. @@ -203,6 +231,9 @@ ScsiDiskDriverBindingStart ( UINT8 MaxRetry; BOOLEAN NeedRetry; BOOLEAN MustReadCapacity; + CHAR8 VendorStr[VENDOR_IDENTIFICATION_LENGTH + 1]; + CHAR8 ProductStr[PRODUCT_IDENTIFICATION_LENGTH + 1]; + CHAR16 DeviceStr[VENDOR_IDENTIFICATION_LENGTH + PRODUCT_IDENTIFICATION_LENGTH + 2]; MustReadCapacity = TRUE; @@ -354,19 +385,37 @@ ScsiDiskDriverBindingStart ( } } + CopyMem ( + VendorStr, + &ScsiDiskDevice->InquiryData.Reserved_5_95[VENDOR_IDENTIFICATION_OFFSET], + VENDOR_IDENTIFICATION_LENGTH + ); + VendorStr[VENDOR_IDENTIFICATION_LENGTH] = 0; + RemoveTrailingSpaces (VendorStr); + + CopyMem ( + ProductStr, + &ScsiDiskDevice->InquiryData.Reserved_5_95[PRODUCT_IDENTIFICATION_OFFSET], + PRODUCT_IDENTIFICATION_LENGTH + ); + ProductStr[PRODUCT_IDENTIFICATION_LENGTH] = 0; + RemoveTrailingSpaces (ProductStr); + + UnicodeSPrint (DeviceStr, sizeof (DeviceStr), L"%a %a", VendorStr, ProductStr); + ScsiDiskDevice->ControllerNameTable = NULL; AddUnicodeString2 ( "eng", gScsiDiskComponentName.SupportedLanguages, &ScsiDiskDevice->ControllerNameTable, - L"SCSI Disk Device", + DeviceStr, TRUE ); AddUnicodeString2 ( "en", gScsiDiskComponentName2.SupportedLanguages, &ScsiDiskDevice->ControllerNameTable, - L"SCSI Disk Device", + DeviceStr, FALSE ); return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h index d54282df5f..5b4047e1db 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h @@ -2,6 +2,7 @@ Header file for SCSI Disk Driver. Copyright (c) 2004 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 1985 - 2022, American Megatrends International LLC.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -30,6 +31,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include @@ -179,6 +181,13 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gScsiDiskComponentName2; #define SCSI_COMMAND_VERSION_2 0x02 #define SCSI_COMMAND_VERSION_3 0x03 +// Per SCSI spec, EFI_SCSI_INQUIRY_DATA.Reserved_5_95[3 - 10] has the Vendor identification +// EFI_SCSI_INQUIRY_DATA.Reserved_5_95[11 - 26] has the product identification +#define VENDOR_IDENTIFICATION_OFFSET 3 +#define VENDOR_IDENTIFICATION_LENGTH 8 +#define PRODUCT_IDENTIFICATION_OFFSET 11 +#define PRODUCT_IDENTIFICATION_LENGTH 16 + // // SCSI Disk Timeout Experience Value // diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf index 40818e669b..26227132e8 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf @@ -4,6 +4,7 @@ # the device handle. # # Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 1985 - 2022, American Megatrends International LLC.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -46,6 +47,7 @@ UefiDriverEntryPoint DebugLib DevicePathLib + PrintLib [Protocols] gEfiDiskInfoProtocolGuid ## BY_START From ffe50bcb5a85f9b745c245a1f10307ff683dcf99 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:45 +0200 Subject: [PATCH 0239/1529] DynamicTablesPkg: Use correct print formatter In C, the 'long long' types are 64-bits. The 'll' printf length specifier should be used to pring these values. Just '%x' allows to print values that are on 16-bits or more. Use that instead. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../ConfigurationManagerObjectParser.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 08b4f60dfb..13e6c0e321 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -1,7 +1,7 @@ /** @file Configuration Manager Object parser. - Copyright (c) 2021, ARM Limited. All rights reserved.
+ Copyright (c) 2021 - 2022, ARM Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -384,12 +384,12 @@ STATIC CONST CM_OBJ_PARSER AcpiGenericAddressParser[] = { /** A parser for EArmObjLpiInfo. */ STATIC CONST CM_OBJ_PARSER CmArmLpiInfoParser[] = { - { "MinResidency", 4, "0x%llx", NULL }, - { "WorstCaseWakeLatency", 4, "0x%llx", NULL }, - { "Flags", 4, "0x%llx", NULL }, - { "ArchFlags", 4, "0x%llx", NULL }, - { "ResCntFreq", 4, "0x%llx", NULL }, - { "EnableParentState", 4, "0x%llx", NULL }, + { "MinResidency", 4, "0x%x", NULL }, + { "WorstCaseWakeLatency", 4, "0x%x", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "ArchFlags", 4, "0x%x", NULL }, + { "ResCntFreq", 4, "0x%x", NULL }, + { "EnableParentState", 4, "0x%x", NULL }, { "IsInteger", 1, "%d", NULL }, { "IntegerEntryMethod", 8, "0x%llx", NULL }, { "RegisterEntryMethod", sizeof (EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE), From a2eb080aa8731e39eaea68c8a86178bc67a3480b Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:46 +0200 Subject: [PATCH 0240/1529] DynamicTablesPkg: Add PrintString to CmObjParser Add a PrintString to print strings in the CmObjParser. String must be NULL terminated and no buffer overrun check is done by this function. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../ConfigurationManagerObjectParser.c | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 13e6c0e321..b46f19693b 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -19,6 +19,14 @@ PrintOemId ( UINT8 *Ptr ); +STATIC +VOID +EFIAPI +PrintString ( + CONST CHAR8 *Format, + UINT8 *Ptr + ); + /** A parser for EArmObjBootArchInfo. */ STATIC CONST CM_OBJ_PARSER CmArmBootArchInfoParser[] = { @@ -646,6 +654,24 @@ PrintOemId ( )); } +/** Print string. + + The string must be NULL terminated. + + @param [in] Format Format to print the Ptr. + @param [in] Ptr Pointer to the string. +**/ +STATIC +VOID +EFIAPI +PrintString ( + CONST CHAR8 *Format, + UINT8 *Ptr + ) +{ + DEBUG ((DEBUG_ERROR, "%a", Ptr)); +} + /** Print fields of the objects. @param [in] Data Pointer to the object to print. From 3777dd1696e16951c227c3e98fe763bf3ebbe795 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:47 +0200 Subject: [PATCH 0241/1529] DynamicTablesPkg: Update CmObjParser for IORT Rev E.d commit de200b7e2c3c ("DynamicTablesPkg: Update ArmNameSpaceObjects for IORT Rev E.d") adds new CmObj structures and fields to the ArmNameSpaceObjects. Update the CmObjectParser accordingly. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../ConfigurationManagerObjectParser.c | 59 ++++++++++++++----- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index b46f19693b..1204ebb6ab 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -183,21 +183,23 @@ STATIC CONST CM_OBJ_PARSER CmArmFixedFeatureFlagsParser[] = { STATIC CONST CM_OBJ_PARSER CmArmItsGroupNodeParser[] = { { "Token", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, { "ItsIdCount", 4, "0x%x", NULL }, - { "ItsIdToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } + { "ItsIdToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjNamedComponent. */ STATIC CONST CM_OBJ_PARSER CmArmNamedComponentNodeParser[] = { - { "Token", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, - { "IdMappingCount", 4, "0x%x", NULL }, - { "IdMappingToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, - { "Flags", 4, "0x%x", NULL }, - { "CacheCoherent", 4, "0x%x", NULL }, - { "AllocationHints", 1, "0x%x", NULL }, - { "MemoryAccessFlags", 1, "0x%x", NULL }, - { "AddressSizeLimit", 1, "0x%x", NULL }, - { "ObjectName", sizeof (CHAR8 *), "%a", NULL } + { "Token", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "IdMappingCount", 4, "0x%x", NULL }, + { "IdMappingToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "CacheCoherent", 4, "0x%x", NULL }, + { "AllocationHints", 1, "0x%x", NULL }, + { "MemoryAccessFlags", 1, "0x%x", NULL }, + { "AddressSizeLimit", 1, "0x%x", NULL }, + { "ObjectName", sizeof (CHAR8 *), NULL, PrintString }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjRootComplex. @@ -211,7 +213,10 @@ STATIC CONST CM_OBJ_PARSER CmArmRootComplexNodeParser[] = { { "MemoryAccessFlags", 1, "0x%x", NULL }, { "AtsAttribute", 4, "0x%x", NULL }, { "PciSegmentNumber", 4, "0x%x", NULL }, - { "MemoryAddressSize", 1, "0x%x", NULL } + { "MemoryAddressSize", 1, "0x%x", NULL }, + { "PasidCapabilities", 2, "0x%x", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjSmmuV1SmmuV2. @@ -231,7 +236,8 @@ STATIC CONST CM_OBJ_PARSER CmArmSmmuV1SmmuV2NodeParser[] = { { "SMMU_NSgIrpt", 4, "0x%x", NULL }, { "SMMU_NSgIrptFlags", 4, "0x%x", NULL }, { "SMMU_NSgCfgIrpt", 4, "0x%x", NULL }, - { "SMMU_NSgCfgIrptFlags", 4, "0x%x", NULL } + { "SMMU_NSgCfgIrptFlags", 4, "0x%x", NULL }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjSmmuV3. @@ -249,7 +255,8 @@ STATIC CONST CM_OBJ_PARSER CmArmSmmuV3NodeParser[] = { { "GerrInterrupt", 4, "0x%x", NULL }, { "SyncInterrupt", 4, "0x%x", NULL }, { "ProximityDomain", 4, "0x%x", NULL }, - { "DeviceIdMappingIndex", 4, "0x%x", NULL } + { "DeviceIdMappingIndex", 4, "0x%x", NULL }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjPmcg. @@ -261,7 +268,8 @@ STATIC CONST CM_OBJ_PARSER CmArmPmcgNodeParser[] = { { "BaseAddress", 8, "0x%llx", NULL }, { "OverflowInterrupt", 4, "0x%x", NULL }, { "Page1BaseAddress", 8, "0x%llx", NULL }, - { "ReferenceToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } + { "ReferenceToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "Identifier", 4, "0x%x", NULL }, }; /** A parser for EArmObjGicItsIdentifierArray. @@ -432,6 +440,25 @@ STATIC CONST CM_OBJ_PARSER CmPciInterruptMapInfoParser[] = { ARRAY_SIZE (CmArmGenericInterruptParser) }, }; +/** A parser for EArmObjRmr. +*/ +STATIC CONST CM_OBJ_PARSER CmArmRmrInfoParser[] = { + { "Token", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "IdMappingCount", 4, "0x%x", NULL }, + { "IdMappingToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "Identifier", 4, "0x%x", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "MemRangeDescCount", 4, "0x%x", NULL }, + { "MemRangeDescToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, +}; + +/** A parser for EArmObjMemoryRangeDescriptor. +*/ +STATIC CONST CM_OBJ_PARSER CmArmMemoryRangeDescriptorInfoParser[] = { + { "BaseAddress", 8, "0x%llx", NULL }, + { "Length", 8, "0x%llx", NULL }, +}; + /** A parser for EArmObjCpcInfo. */ STATIC CONST CM_OBJ_PARSER CmArmCpcInfoParser[] = { @@ -588,6 +615,10 @@ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { ARRAY_SIZE (CmArmPciAddressMapInfoParser) }, { "EArmObjPciInterruptMapInfo", CmPciInterruptMapInfoParser, ARRAY_SIZE (CmPciInterruptMapInfoParser) }, + { "EArmObjRmr", CmArmRmrInfoParser, + ARRAY_SIZE (CmArmRmrInfoParser) }, + { "EArmObjMemoryRangeDescriptor", CmArmMemoryRangeDescriptorInfoParser, + ARRAY_SIZE (CmArmMemoryRangeDescriptorInfoParser) }, { "EArmObjCpcInfo", CmArmCpcInfoParser, ARRAY_SIZE (CmArmCpcInfoParser) }, { "EArmObjMax", NULL, 0 }, From 6047ab82df894d51f7167ac8047390219b6bee36 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:48 +0200 Subject: [PATCH 0242/1529] DynamicTablesPkg: Update CmObjParser for MinorRevision commit 0d23c447d6f5 ("DynamicTablesPkg: Add support to specify FADT minor revision") adds new 'MinorRevision' field to CM_STD_OBJ_ACPI_TABLE_INFO. Reflect the change in this patch to the CmObjectParser. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Common/TableHelperLib/ConfigurationManagerObjectParser.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 1204ebb6ab..fe5908f4d3 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -639,7 +639,8 @@ STATIC CONST CM_OBJ_PARSER StdObjAcpiTableInfoParser[] = { { "TableGeneratorId", sizeof (ACPI_TABLE_GENERATOR_ID), "0x%x", NULL }, { "AcpiTableData", sizeof (EFI_ACPI_DESCRIPTION_HEADER *), "0x%p", NULL }, { "OemTableId", 8, "0x%LLX", NULL }, - { "OemRevision", 4, "0x%x", NULL } + { "OemRevision", 4, "0x%x", NULL }, + { "MinorRevision", 1, "0x%x", NULL }, }; /** A parser for EStdObjSmbiosTableList. From 7a754186350f8dee1404897b97abb2d825202c94 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:49 +0200 Subject: [PATCH 0243/1529] DynamicTablesPkg: Fix GTBlock and GTBlockTimerFrame CmObjParsers The CmObjParsers of the following objects was inverted, probably due to a wrong ordering placement in the file defining the structures: -EArmObjGTBlockTimerFrameInfo -EArmObjPlatformGTBlockInfo Assign the correct parser for each object, and re-order the structures in the file defining them. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Include/ArmNameSpaceObjects.h | 32 +++++++++---------- .../ConfigurationManagerObjectParser.c | 22 ++++++------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h index c66b441d53..cd39e609d6 100644 --- a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h @@ -353,6 +353,22 @@ typedef struct CmArmGenericTimerInfo { UINT32 VirtualPL2TimerFlags; } CM_ARM_GENERIC_TIMER_INFO; +/** A structure that describes the + Platform Generic Block Timer information for the Platform. + + ID: EArmObjPlatformGTBlockInfo +*/ +typedef struct CmArmGTBlockInfo { + /// The physical base address for the GT Block Timer structure + UINT64 GTBlockPhysicalAddress; + + /// The number of timer frames implemented in the GT Block + UINT32 GTBlockTimerFrameCount; + + /// Reference token for the GT Block timer frame list + CM_OBJECT_TOKEN GTBlockTimerFrameToken; +} CM_ARM_GTBLOCK_INFO; + /** A structure that describes the Platform Generic Block Timer Frame information for the Platform. @@ -390,22 +406,6 @@ typedef struct CmArmGTBlockTimerFrameInfo { UINT32 CommonFlags; } CM_ARM_GTBLOCK_TIMER_FRAME_INFO; -/** A structure that describes the - Platform Generic Block Timer information for the Platform. - - ID: EArmObjPlatformGTBlockInfo -*/ -typedef struct CmArmGTBlockInfo { - /// The physical base address for the GT Block Timer structure - UINT64 GTBlockPhysicalAddress; - - /// The number of timer frames implemented in the GT Block - UINT32 GTBlockTimerFrameCount; - - /// Reference token for the GT Block timer frame list - CM_OBJECT_TOKEN GTBlockTimerFrameToken; -} CM_ARM_GTBLOCK_INFO; - /** A structure that describes the Arm Generic Watchdog information for the Platform. diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index fe5908f4d3..45e3a0f4ab 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -127,6 +127,14 @@ STATIC CONST CM_OBJ_PARSER CmArmGenericTimerInfoParser[] = { /** A parser for EArmObjPlatformGTBlockInfo. */ +STATIC CONST CM_OBJ_PARSER CmArmGTBlockInfoParser[] = { + { "GTBlockPhysicalAddress", 8, "0x%llx", NULL }, + { "GTBlockTimerFrameCount", 4, "0x%x", NULL }, + { "GTBlockTimerFrameToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } +}; + +/** A parser for EArmObjGTBlockTimerFrameInfo. +*/ STATIC CONST CM_OBJ_PARSER CmArmGTBlockTimerFrameInfoParser[] = { { "FrameNumber", 1, "0x%x", NULL }, { "PhysicalAddressCntBase", 8, "0x%llx", NULL }, @@ -138,14 +146,6 @@ STATIC CONST CM_OBJ_PARSER CmArmGTBlockTimerFrameInfoParser[] = { { "CommonFlags", 4, "0x%x", NULL } }; -/** A parser for EArmObjGTBlockTimerFrameInfo. -*/ -STATIC CONST CM_OBJ_PARSER CmArmGTBlockInfoParser[] = { - { "GTBlockPhysicalAddress", 8, "0x%llx", NULL }, - { "GTBlockTimerFrameCount", 4, "0x%x", NULL }, - { "GTBlockTimerFrameToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } -}; - /** A parser for EArmObjPlatformGenericWatchdogInfo. */ STATIC CONST CM_OBJ_PARSER CmArmGenericWatchdogInfoParser[] = { @@ -560,10 +560,10 @@ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { ARRAY_SIZE (CmArmSerialPortInfoParser) }, { "EArmObjGenericTimerInfo", CmArmGenericTimerInfoParser, ARRAY_SIZE (CmArmGenericTimerInfoParser) }, - { "EArmObjPlatformGTBlockInfo", CmArmGTBlockTimerFrameInfoParser, - ARRAY_SIZE (CmArmGTBlockTimerFrameInfoParser) }, - { "EArmObjGTBlockTimerFrameInfo", CmArmGTBlockInfoParser, + { "EArmObjPlatformGTBlockInfo", CmArmGTBlockInfoParser, ARRAY_SIZE (CmArmGTBlockInfoParser) }, + { "EArmObjGTBlockTimerFrameInfo", CmArmGTBlockTimerFrameInfoParser, + ARRAY_SIZE (CmArmGTBlockTimerFrameInfoParser) }, { "EArmObjPlatformGenericWatchdogInfo", CmArmGenericWatchdogInfoParser, ARRAY_SIZE (CmArmGenericWatchdogInfoParser) }, { "EArmObjPciConfigSpaceInfo", CmArmPciConfigSpaceInfoParser, From 9d9091f78b820b7ff34914c301f803f9fc01e707 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:50 +0200 Subject: [PATCH 0244/1529] DynamicTablesPkg: Fix wrong/missing fields in CmObjParser Add missing fields to the following CmObjParser objects: - EArmObjGicDInfo - EArmObjCacheInfo and fix wrong formatting of: - EArmObjLpiInfo Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../ConfigurationManagerObjectParser.c | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 45e3a0f4ab..467b3072bf 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -303,7 +303,8 @@ STATIC CONST CM_OBJ_PARSER CmArmProcHierarchyInfoParser[] = { { "ParentToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, { "GicCToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, { "NoOfPrivateResources", 4, "0x%x", NULL }, - { "PrivateResourcesArrayToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL } + { "PrivateResourcesArrayToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "LpiToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, }; /** A parser for EArmObjCacheInfo. @@ -315,7 +316,8 @@ STATIC CONST CM_OBJ_PARSER CmArmCacheInfoParser[] = { { "NumberOfSets", 4, "0x%x", NULL }, { "Associativity", 4, "0x%x", NULL }, { "Attributes", 1, "0x%x", NULL }, - { "LineSize", 2, "0x%x", NULL } + { "LineSize", 2, "0x%x", NULL }, + { "CacheId", 4, "0x%x", NULL }, }; /** A parser for EArmObjProcNodeIdInfo. @@ -400,14 +402,14 @@ STATIC CONST CM_OBJ_PARSER AcpiGenericAddressParser[] = { /** A parser for EArmObjLpiInfo. */ STATIC CONST CM_OBJ_PARSER CmArmLpiInfoParser[] = { - { "MinResidency", 4, "0x%x", NULL }, - { "WorstCaseWakeLatency", 4, "0x%x", NULL }, - { "Flags", 4, "0x%x", NULL }, - { "ArchFlags", 4, "0x%x", NULL }, - { "ResCntFreq", 4, "0x%x", NULL }, - { "EnableParentState", 4, "0x%x", NULL }, - { "IsInteger", 1, "%d", NULL }, - { "IntegerEntryMethod", 8, "0x%llx", NULL }, + { "MinResidency", 4, "0x%x", NULL }, + { "WorstCaseWakeLatency", 4, "0x%x", NULL }, + { "Flags", 4, "0x%x", NULL }, + { "ArchFlags", 4, "0x%x", NULL }, + { "ResCntFreq", 4, "0x%x", NULL }, + { "EnableParentState", 4, "0x%x", NULL }, + { "IsInteger", 1, "%d", NULL }, + { "IntegerEntryMethod", 8, "0x%llx", NULL }, { "RegisterEntryMethod", sizeof (EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE), NULL, NULL, AcpiGenericAddressParser, ARRAY_SIZE (AcpiGenericAddressParser) }, @@ -417,7 +419,7 @@ STATIC CONST CM_OBJ_PARSER CmArmLpiInfoParser[] = { { "UsageCounterRegister", sizeof (EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE), NULL, NULL, AcpiGenericAddressParser, ARRAY_SIZE (AcpiGenericAddressParser) }, - { "StateName", 16, "0x%a", NULL }, + { "StateName", 16, NULL, PrintString }, }; /** A parser for EArmObjPciAddressMapInfo. From df2449d8f245f48f91ea979e0001cdc49ec34f67 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:51 +0200 Subject: [PATCH 0245/1529] DynamicTablesPkg: Remove deprecated APIs commit 691c5f776274 ("DynamicTablesPkg: Deprecate Crs specific methods in AmlLib") deprecates some APIs. Finally remove them. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Include/Library/AmlLib/AmlLib.h | 138 ------------------ .../Library/Common/AmlLib/Api/AmlApi.c | 85 ----------- .../AmlLib/CodeGen/AmlResourceDataCodeGen.c | 76 ---------- 3 files changed, 299 deletions(-) diff --git a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h index 0d8446d782..9210c50915 100644 --- a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h +++ b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h @@ -1390,142 +1390,4 @@ AmlCreateCpcNode ( OUT AML_OBJECT_NODE_HANDLE *NewCpcNode OPTIONAL ); -// DEPRECATED APIS -#ifndef DISABLE_NEW_DEPRECATED_INTERFACES - -/** DEPRECATED API - - Get the first Resource Data element contained in a "_CRS" object. - - In the following ASL code, the function will return the Resource Data - node corresponding to the "QWordMemory ()" ASL macro. - Name (_CRS, ResourceTemplate() { - QWordMemory (...) {...}, - Interrupt (...) {...} - } - ) - - Note: - - The "_CRS" object must be declared using ASL "Name (Declare Named Object)". - - "_CRS" declared using ASL "Method (Declare Control Method)" is not - supported. - - @ingroup UserApis - - @param [in] NameOpCrsNode NameOp object node defining a "_CRS" object. - Must have an OpCode=AML_NAME_OP, SubOpCode=0. - NameOp object nodes are defined in ASL - using the "Name ()" function. - @param [out] OutRdNode Pointer to the first Resource Data element of - the "_CRS" object. A Resource Data element - is stored in a data node. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. -**/ -EFI_STATUS -EFIAPI -AmlNameOpCrsGetFirstRdNode ( - IN AML_OBJECT_NODE_HANDLE NameOpCrsNode, - OUT AML_DATA_NODE_HANDLE *OutRdNode - ); - -/** DEPRECATED API - - Get the Resource Data element following the CurrRdNode Resource Data. - - In the following ASL code, if CurrRdNode corresponds to the first - "QWordMemory ()" ASL macro, the function will return the Resource Data - node corresponding to the "Interrupt ()" ASL macro. - Name (_CRS, ResourceTemplate() { - QwordMemory (...) {...}, - Interrupt (...) {...} - } - ) - - The CurrRdNode Resource Data node must be defined in an object named "_CRS" - and defined by a "Name ()" ASL function. - - @ingroup UserApis - - @param [in] CurrRdNode Pointer to the current Resource Data element of - the "_CRS" variable. - @param [out] OutRdNode Pointer to the Resource Data element following - the CurrRdNode. - Contain a NULL pointer if CurrRdNode is the - last Resource Data element in the list. - The "End Tag" is not considered as a resource - data element and is not returned. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. -**/ -EFI_STATUS -EFIAPI -AmlNameOpCrsGetNextRdNode ( - IN AML_DATA_NODE_HANDLE CurrRdNode, - OUT AML_DATA_NODE_HANDLE *OutRdNode - ); - -/** DEPRECATED API - - Add an Interrupt Resource Data node. - - This function creates a Resource Data element corresponding to the - "Interrupt ()" ASL function, stores it in an AML Data Node. - - It then adds it after the input CurrRdNode in the list of resource data - element. - - The Resource Data effectively created is an Extended Interrupt Resource - Data. See ACPI 6.3 specification, s6.4.3.6 "Extended Interrupt Descriptor" - for more information about Extended Interrupt Resource Data. - - The Extended Interrupt contains one single interrupt. - - This function allocates memory to create a data node. It is the caller's - responsibility to either: - - attach this node to an AML tree; - - delete this node. - - Note: The _CRS node must be defined using the ASL Name () function. - e.g. Name (_CRS, ResourceTemplate () { - ... - } - - @ingroup CodeGenApis - - @param [in] NameOpCrsNode NameOp object node defining a "_CRS" object. - Must have an OpCode=AML_NAME_OP, SubOpCode=0. - NameOp object nodes are defined in ASL - using the "Name ()" function. - @param [in] ResourceConsumer The device consumes the specified interrupt - or produces it for use by a child device. - @param [in] EdgeTriggered The interrupt is edge triggered or - level triggered. - @param [in] ActiveLow The interrupt is active-high or active-low. - @param [in] Shared The interrupt can be shared with other - devices or not (Exclusive). - @param [in] IrqList Interrupt list. Must be non-NULL. - @param [in] IrqCount Interrupt count. Must be non-zero. - - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. - @retval EFI_OUT_OF_RESOURCES Could not allocate memory. -**/ -EFI_STATUS -EFIAPI -AmlCodeGenCrsAddRdInterrupt ( - IN AML_OBJECT_NODE_HANDLE NameOpCrsNode, - IN BOOLEAN ResourceConsumer, - IN BOOLEAN EdgeTriggered, - IN BOOLEAN ActiveLow, - IN BOOLEAN Shared, - IN UINT32 *IrqList, - IN UINT8 IrqCount - ); - -#endif // DISABLE_NEW_DEPRECATED_INTERFACES - #endif // AML_LIB_H_ diff --git a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c index 519afdc1ea..9f162abe2d 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c @@ -429,88 +429,3 @@ AmlAttachNode ( { return AmlVarListAddTail (ParentNode, NewNode); } - -// DEPRECATED APIS -#ifndef DISABLE_NEW_DEPRECATED_INTERFACES - -/** DEPRECATED API - - Get the first Resource Data element contained in a "_CRS" object. - - In the following ASL code, the function will return the Resource Data - node corresponding to the "QWordMemory ()" ASL macro. - Name (_CRS, ResourceTemplate() { - QWordMemory (...) {...}, - Interrupt (...) {...} - } - ) - - Note: - - The "_CRS" object must be declared using ASL "Name (Declare Named Object)". - - "_CRS" declared using ASL "Method (Declare Control Method)" is not - supported. - - @ingroup UserApis - - @param [in] NameOpCrsNode NameOp object node defining a "_CRS" object. - Must have an OpCode=AML_NAME_OP, SubOpCode=0. - NameOp object nodes are defined in ASL - using the "Name ()" function. - @param [out] OutRdNode Pointer to the first Resource Data element of - the "_CRS" object. A Resource Data element - is stored in a data node. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. -**/ -EFI_STATUS -EFIAPI -AmlNameOpCrsGetFirstRdNode ( - IN AML_OBJECT_NODE_HANDLE NameOpCrsNode, - OUT AML_DATA_NODE_HANDLE *OutRdNode - ) -{ - return AmlNameOpGetFirstRdNode (NameOpCrsNode, OutRdNode); -} - -/** DEPRECATED API - - Get the Resource Data element following the CurrRdNode Resource Data. - - In the following ASL code, if CurrRdNode corresponds to the first - "QWordMemory ()" ASL macro, the function will return the Resource Data - node corresponding to the "Interrupt ()" ASL macro. - Name (_CRS, ResourceTemplate() { - QwordMemory (...) {...}, - Interrupt (...) {...} - } - ) - - The CurrRdNode Resource Data node must be defined in an object named "_CRS" - and defined by a "Name ()" ASL function. - - @ingroup UserApis - - @param [in] CurrRdNode Pointer to the current Resource Data element of - the "_CRS" variable. - @param [out] OutRdNode Pointer to the Resource Data element following - the CurrRdNode. - Contain a NULL pointer if CurrRdNode is the - last Resource Data element in the list. - The "End Tag" is not considered as a resource - data element and is not returned. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. -**/ -EFI_STATUS -EFIAPI -AmlNameOpCrsGetNextRdNode ( - IN AML_DATA_NODE_HANDLE CurrRdNode, - OUT AML_DATA_NODE_HANDLE *OutRdNode - ) -{ - return AmlNameOpGetNextRdNode (CurrRdNode, OutRdNode); -} - -#endif // DISABLE_NEW_DEPRECATED_INTERFACES diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c index 32c3ab534d..332962bed4 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c @@ -1406,79 +1406,3 @@ AmlCodeGenEndTag ( return Status; } - -// DEPRECATED APIS -#ifndef DISABLE_NEW_DEPRECATED_INTERFACES - -/** DEPRECATED API - - Add an Interrupt Resource Data node. - - This function creates a Resource Data element corresponding to the - "Interrupt ()" ASL function, stores it in an AML Data Node. - - It then adds it after the input CurrRdNode in the list of resource data - element. - - The Resource Data effectively created is an Extended Interrupt Resource - Data. See ACPI 6.3 specification, s6.4.3.6 "Extended Interrupt Descriptor" - for more information about Extended Interrupt Resource Data. - - The Extended Interrupt contains one single interrupt. - - This function allocates memory to create a data node. It is the caller's - responsibility to either: - - attach this node to an AML tree; - - delete this node. - - Note: The _CRS node must be defined using the ASL Name () function. - e.g. Name (_CRS, ResourceTemplate () { - ... - } - - @ingroup UserApis - - @param [in] NameOpCrsNode NameOp object node defining a "_CRS" object. - Must have an OpCode=AML_NAME_OP, SubOpCode=0. - NameOp object nodes are defined in ASL - using the "Name ()" function. - @param [in] ResourceConsumer The device consumes the specified interrupt - or produces it for use by a child device. - @param [in] EdgeTriggered The interrupt is edge triggered or - level triggered. - @param [in] ActiveLow The interrupt is active-high or active-low. - @param [in] Shared The interrupt can be shared with other - devices or not (Exclusive). - @param [in] IrqList Interrupt list. Must be non-NULL. - @param [in] IrqCount Interrupt count. Must be non-zero. - - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_INVALID_PARAMETER Invalid parameter. - @retval EFI_OUT_OF_RESOURCES Could not allocate memory. -**/ -EFI_STATUS -EFIAPI -AmlCodeGenCrsAddRdInterrupt ( - IN AML_OBJECT_NODE_HANDLE NameOpCrsNode, - IN BOOLEAN ResourceConsumer, - IN BOOLEAN EdgeTriggered, - IN BOOLEAN ActiveLow, - IN BOOLEAN Shared, - IN UINT32 *IrqList, - IN UINT8 IrqCount - ) -{ - return AmlCodeGenRdInterrupt ( - ResourceConsumer, - EdgeTriggered, - ActiveLow, - Shared, - IrqList, - IrqCount, - NameOpCrsNode, - NULL - ); -} - -#endif // DISABLE_NEW_DEPRECATED_INTERFACES From 2c167c8d730c296908de4e12d12e832a8819ea31 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:52 +0200 Subject: [PATCH 0246/1529] DynamicTablesPkg: FdtHwInfoParserLib: Remove wrong comment commit 13136cc3111f ("DynamicTablesPkg: FdtHwInfoParserLib: Parse Pmu info") adds support for pmu parsing. Thus, remove the wrong comment. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c | 3 --- .../Library/FdtHwInfoParserLib/Gic/ArmGicCParser.h | 3 --- 2 files changed, 6 deletions(-) diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c index fb01aa0d19..2c72bd0c58 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c @@ -785,9 +785,6 @@ GicCPmuNodeParser ( UINT32 AffinityFlags; // {default = 0} } CM_ARM_GICC_INFO; - The pmu information can be found in the pmu node. There is no support - for now. - A parser parses a Device Tree to populate a specific CmObj type. None, one or many CmObj can be created by the parser. The created CmObj are then handed to the parser's caller through the diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.h b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.h index fd980484a2..539f39cecb 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.h +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.h @@ -41,9 +41,6 @@ UINT32 AffinityFlags; // {default = 0} } CM_ARM_GICC_INFO; - The pmu information can be found in the pmu node. There is no support - for now. - A parser parses a Device Tree to populate a specific CmObj type. None, one or many CmObj can be created by the parser. The created CmObj are then handed to the parser's caller through the From f1f7c9084f3aaa5f54e0b9206c6d2516ae7ffc90 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:53 +0200 Subject: [PATCH 0247/1529] DynamicTablesPkg: Fix Ssdt PCI generation comments The second model of the _PRT object is used. Indeed: - the interrupts described are not re-configurable - OSes are aware of the polarity of PCI legacy interrupts, so there is no need to accurately describe the polarity. Also, fix a comment for the CM_ARM_PCI_INTERRUPT_MAP_INFO obj. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/Include/ArmNameSpaceObjects.h | 2 +- .../Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h index cd39e609d6..d711f3ec59 100644 --- a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h @@ -1014,7 +1014,7 @@ typedef struct CmArmPciInterruptMapInfo { /// Value on 8 bits (max 255). UINT8 PciBus; - /// Pci Bus. + /// Pci Device. /// Value on 5 bits (max 31). UINT8 PciDevice; diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c index 85098752c6..c54ae6f551 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c @@ -288,12 +288,6 @@ GeneratePciDeviceInfo ( Cf. ACPI 6.4 specification, s6.2.13 "_PRT (PCI Routing Table)" - The first model (defining a _CRS object) is used. This is necessary because - PCI legacy interrupts are active low and GICv2 SPI interrupts are active - high. - Even though PCI interrupts cannot be re-routed, only the first model allows - to specify the activation state (low/high). - @param [in] Generator The SSDT Pci generator. @param [in] CfgMgrProtocol Pointer to the Configuration Manager Protocol interface. @@ -397,6 +391,8 @@ GeneratePrt ( High word-Device #, Low word-Function #. (for example, device 3, function 2 is 0x00030002). To refer to all the functions on a device #, use a function number of FFFF). + + Use the second model for _PRT object and describe a hardwired interrupt. */ Status = AmlAddPrtEntry ( (IrqMapInfo->PciDevice << 16) | 0xFFFF, From a1a4d6b868ca6cd3ed5590130e77fcbe26577982 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:54 +0200 Subject: [PATCH 0248/1529] DynamicTablesPkg: Add PCCT related objects Introduce the following CmObj in the ArmNameSpaceObjects: - CM_ARM_MAILBOX_REGISTER_INFO - CM_ARM_PCC_SUBSPACE_CHANNEL_TIMING_INFO - CM_ARM_PCC_SUBSPACE_GENERIC_INFO - CM_ARM_PCC_SUBPSACE_TYPE0_INFO - CM_ARM_PCC_SUBPSACE_TYPE1_INFO - CM_ARM_PCC_SUBPSACE_TYPE2_INFO - CM_ARM_PCC_SUBPSACE_TYPE3_INFO - CM_ARM_PCC_SUBPSACE_TYPE4_INFO - CM_ARM_PCC_SUBPSACE_TYPE5_INFO These objects allow to describe mailbox registers, pcc timings and PCCT subspaces. They prepare the enablement of a PCCT generator. Also add the CmObjParsers associated to each object. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Include/ArmNameSpaceObjects.h | 277 +++++++++++++++--- .../ConfigurationManagerObjectParser.c | 107 +++++++ 2 files changed, 341 insertions(+), 43 deletions(-) diff --git a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h index d711f3ec59..6aafd41a2e 100644 --- a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h @@ -22,49 +22,55 @@ in the ARM Namespace */ typedef enum ArmObjectID { - EArmObjReserved, ///< 0 - Reserved - EArmObjBootArchInfo, ///< 1 - Boot Architecture Info - EArmObjCpuInfo, ///< 2 - CPU Info - EArmObjPowerManagementProfileInfo, ///< 3 - Power Management Profile Info - EArmObjGicCInfo, ///< 4 - GIC CPU Interface Info - EArmObjGicDInfo, ///< 5 - GIC Distributor Info - EArmObjGicMsiFrameInfo, ///< 6 - GIC MSI Frame Info - EArmObjGicRedistributorInfo, ///< 7 - GIC Redistributor Info - EArmObjGicItsInfo, ///< 8 - GIC ITS Info - EArmObjSerialConsolePortInfo, ///< 9 - Serial Console Port Info - EArmObjSerialDebugPortInfo, ///< 10 - Serial Debug Port Info - EArmObjGenericTimerInfo, ///< 11 - Generic Timer Info - EArmObjPlatformGTBlockInfo, ///< 12 - Platform GT Block Info - EArmObjGTBlockTimerFrameInfo, ///< 13 - Generic Timer Block Frame Info - EArmObjPlatformGenericWatchdogInfo, ///< 14 - Platform Generic Watchdog - EArmObjPciConfigSpaceInfo, ///< 15 - PCI Configuration Space Info - EArmObjHypervisorVendorIdentity, ///< 16 - Hypervisor Vendor Id - EArmObjFixedFeatureFlags, ///< 17 - Fixed feature flags for FADT - EArmObjItsGroup, ///< 18 - ITS Group - EArmObjNamedComponent, ///< 19 - Named Component - EArmObjRootComplex, ///< 20 - Root Complex - EArmObjSmmuV1SmmuV2, ///< 21 - SMMUv1 or SMMUv2 - EArmObjSmmuV3, ///< 22 - SMMUv3 - EArmObjPmcg, ///< 23 - PMCG - EArmObjGicItsIdentifierArray, ///< 24 - GIC ITS Identifier Array - EArmObjIdMappingArray, ///< 25 - ID Mapping Array - EArmObjSmmuInterruptArray, ///< 26 - SMMU Interrupt Array - EArmObjProcHierarchyInfo, ///< 27 - Processor Hierarchy Info - EArmObjCacheInfo, ///< 28 - Cache Info - EArmObjReserved29, ///< 29 - Reserved - EArmObjCmRef, ///< 30 - CM Object Reference - EArmObjMemoryAffinityInfo, ///< 31 - Memory Affinity Info - EArmObjDeviceHandleAcpi, ///< 32 - Device Handle Acpi - EArmObjDeviceHandlePci, ///< 33 - Device Handle Pci - EArmObjGenericInitiatorAffinityInfo, ///< 34 - Generic Initiator Affinity - EArmObjSerialPortInfo, ///< 35 - Generic Serial Port Info - EArmObjCmn600Info, ///< 36 - CMN-600 Info - EArmObjLpiInfo, ///< 37 - Lpi Info - EArmObjPciAddressMapInfo, ///< 38 - Pci Address Map Info - EArmObjPciInterruptMapInfo, ///< 39 - Pci Interrupt Map Info - EArmObjRmr, ///< 40 - Reserved Memory Range Node - EArmObjMemoryRangeDescriptor, ///< 41 - Memory Range Descriptor - EArmObjCpcInfo, ///< 42 - Continuous Performance Control Info + EArmObjReserved, ///< 0 - Reserved + EArmObjBootArchInfo, ///< 1 - Boot Architecture Info + EArmObjCpuInfo, ///< 2 - CPU Info + EArmObjPowerManagementProfileInfo, ///< 3 - Power Management Profile Info + EArmObjGicCInfo, ///< 4 - GIC CPU Interface Info + EArmObjGicDInfo, ///< 5 - GIC Distributor Info + EArmObjGicMsiFrameInfo, ///< 6 - GIC MSI Frame Info + EArmObjGicRedistributorInfo, ///< 7 - GIC Redistributor Info + EArmObjGicItsInfo, ///< 8 - GIC ITS Info + EArmObjSerialConsolePortInfo, ///< 9 - Serial Console Port Info + EArmObjSerialDebugPortInfo, ///< 10 - Serial Debug Port Info + EArmObjGenericTimerInfo, ///< 11 - Generic Timer Info + EArmObjPlatformGTBlockInfo, ///< 12 - Platform GT Block Info + EArmObjGTBlockTimerFrameInfo, ///< 13 - Generic Timer Block Frame Info + EArmObjPlatformGenericWatchdogInfo, ///< 14 - Platform Generic Watchdog + EArmObjPciConfigSpaceInfo, ///< 15 - PCI Configuration Space Info + EArmObjHypervisorVendorIdentity, ///< 16 - Hypervisor Vendor Id + EArmObjFixedFeatureFlags, ///< 17 - Fixed feature flags for FADT + EArmObjItsGroup, ///< 18 - ITS Group + EArmObjNamedComponent, ///< 19 - Named Component + EArmObjRootComplex, ///< 20 - Root Complex + EArmObjSmmuV1SmmuV2, ///< 21 - SMMUv1 or SMMUv2 + EArmObjSmmuV3, ///< 22 - SMMUv3 + EArmObjPmcg, ///< 23 - PMCG + EArmObjGicItsIdentifierArray, ///< 24 - GIC ITS Identifier Array + EArmObjIdMappingArray, ///< 25 - ID Mapping Array + EArmObjSmmuInterruptArray, ///< 26 - SMMU Interrupt Array + EArmObjProcHierarchyInfo, ///< 27 - Processor Hierarchy Info + EArmObjCacheInfo, ///< 28 - Cache Info + EArmObjReserved29, ///< 29 - Reserved + EArmObjCmRef, ///< 30 - CM Object Reference + EArmObjMemoryAffinityInfo, ///< 31 - Memory Affinity Info + EArmObjDeviceHandleAcpi, ///< 32 - Device Handle Acpi + EArmObjDeviceHandlePci, ///< 33 - Device Handle Pci + EArmObjGenericInitiatorAffinityInfo, ///< 34 - Generic Initiator Affinity + EArmObjSerialPortInfo, ///< 35 - Generic Serial Port Info + EArmObjCmn600Info, ///< 36 - CMN-600 Info + EArmObjLpiInfo, ///< 37 - Lpi Info + EArmObjPciAddressMapInfo, ///< 38 - Pci Address Map Info + EArmObjPciInterruptMapInfo, ///< 39 - Pci Interrupt Map Info + EArmObjRmr, ///< 40 - Reserved Memory Range Node + EArmObjMemoryRangeDescriptor, ///< 41 - Memory Range Descriptor + EArmObjCpcInfo, ///< 42 - Continuous Performance Control Info + EArmObjPccSubspaceType0Info, ///< 43 - Pcc Subspace Type 0 Info + EArmObjPccSubspaceType1Info, ///< 44 - Pcc Subspace Type 2 Info + EArmObjPccSubspaceType2Info, ///< 45 - Pcc Subspace Type 2 Info + EArmObjPccSubspaceType3Info, ///< 46 - Pcc Subspace Type 3 Info + EArmObjPccSubspaceType4Info, ///< 47 - Pcc Subspace Type 4 Info + EArmObjPccSubspaceType5Info, ///< 48 - Pcc Subspace Type 5 Info EArmObjMax } EARM_OBJECT_ID; @@ -1095,6 +1101,191 @@ typedef struct CmArmRmrDescriptor { */ typedef AML_CPC_INFO CM_ARM_CPC_INFO; +/** A structure that describes a + PCC Mailbox Register. +*/ +typedef struct PccMailboxRegisterInfo { + /// GAS describing the Register. + EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE Register; + + /** Mask of bits to preserve when writing. + + This mask is also used for registers. The Register is only read + and there is no write mask required. E.g.: + - Error Status mask (Cf. PCC Subspace types 3/4/5). + - Command Complete Check mask (Cf. PCC Subspace types 3/4/5). + */ + UINT64 PreserveMask; + + /// Mask of bits to set when writing. + UINT64 WriteMask; +} PCC_MAILBOX_REGISTER_INFO; + +/** A structure that describes the + PCC Subspace CHannel Timings. +*/ +typedef struct PccSubspaceChannelTimingInfo { + /// Expected latency to process a command, in microseconds. + UINT32 NominalLatency; + + /** Maximum number of periodic requests that the subspace channel can + support, reported in commands per minute. 0 indicates no limitation. + + This field is ignored for the PCC Subspace type 5 (HW Registers based). + */ + UINT32 MaxPeriodicAccessRate; + + /** Minimum amount of time that OSPM must wait after the completion + of a command before issuing the next command, in microseconds. + */ + UINT16 MinRequestTurnaroundTime; +} PCC_SUBSPACE_CHANNEL_TIMING_INFO; + +/** A structure that describes a + Generic PCC Subspace (Type 0). +*/ +typedef struct CmArmPccSubspaceGenericInfo { + /** Subspace Id. + + Cf. ACPI 6.4, s14.7 Referencing the PCC address space + Cf. s14.1.2 Platform Communications Channel Subspace Structures + The subspace ID of a PCC subspace is its index in the array of + subspace structures, starting with subspace 0. + + At most 256 subspaces are supported. + */ + UINT8 SubspaceId; + + /// Table type (or subspace). + UINT8 Type; + + /// Base address of the shared memory range. + /// This field is ignored for the PCC Subspace type 5 (HW Registers based). + UINT64 BaseAddress; + + /// Address length. + UINT64 AddressLength; + + /// Doorbell Register. + PCC_MAILBOX_REGISTER_INFO DoorbellReg; + + /// Mailbox Timings. + PCC_SUBSPACE_CHANNEL_TIMING_INFO ChannelTiming; +} PCC_SUBSPACE_GENERIC_INFO; + +/** A structure that describes a + PCC Subspace of type 0 (Generic). + + ID: EArmObjPccSubspaceType0Info +*/ +typedef PCC_SUBSPACE_GENERIC_INFO CM_ARM_PCC_SUBSPACE_TYPE0_INFO; + +/** A structure that describes a + PCC Subspace of type 1 (HW-Reduced). + + ID: EArmObjPccSubspaceType1Info +*/ +typedef struct CmArmPccSubspaceType1Info { + /** Generic Pcc information. + + The Subspace of Type0 contains information that can be re-used + in other Subspace types. + */ + PCC_SUBSPACE_GENERIC_INFO GenericPccInfo; + + /// Platform Interrupt. + CM_ARM_GENERIC_INTERRUPT PlatIrq; +} CM_ARM_PCC_SUBSPACE_TYPE1_INFO; + +/** A structure that describes a + PCC Subspace of type 2 (HW-Reduced). + + ID: EArmObjPccSubspaceType2Info +*/ +typedef struct CmArmPccSubspaceType2Info { + /** Generic Pcc information. + + The Subspace of Type0 contains information that can be re-used + in other Subspace types. + */ + PCC_SUBSPACE_GENERIC_INFO GenericPccInfo; + + /// Platform Interrupt. + CM_ARM_GENERIC_INTERRUPT PlatIrq; + + /// Platform Interrupt Register. + PCC_MAILBOX_REGISTER_INFO PlatIrqAckReg; +} CM_ARM_PCC_SUBSPACE_TYPE2_INFO; + +/** A structure that describes a + PCC Subspace of type 3 (Extended) + + ID: EArmObjPccSubspaceType3Info +*/ +typedef struct CmArmPccSubspaceType3Info { + /** Generic Pcc information. + + The Subspace of Type0 contains information that can be re-used + in other Subspace types. + */ + PCC_SUBSPACE_GENERIC_INFO GenericPccInfo; + + /// Platform Interrupt. + CM_ARM_GENERIC_INTERRUPT PlatIrq; + + /// Platform Interrupt Register. + PCC_MAILBOX_REGISTER_INFO PlatIrqAckReg; + + /// Command Complete Check Register. + /// The WriteMask field is not used. + PCC_MAILBOX_REGISTER_INFO CmdCompleteCheckReg; + + /// Command Complete Update Register. + PCC_MAILBOX_REGISTER_INFO CmdCompleteUpdateReg; + + /// Error Status Register. + /// The WriteMask field is not used. + PCC_MAILBOX_REGISTER_INFO ErrorStatusReg; +} CM_ARM_PCC_SUBSPACE_TYPE3_INFO; + +/** A structure that describes a + PCC Subspace of type 4 (Extended) + + ID: EArmObjPccSubspaceType4Info +*/ +typedef CM_ARM_PCC_SUBSPACE_TYPE3_INFO CM_ARM_PCC_SUBSPACE_TYPE4_INFO; + +/** A structure that describes a + PCC Subspace of type 5 (HW-Registers). + + ID: EArmObjPccSubspaceType5Info +*/ +typedef struct CmArmPccSubspaceType5Info { + /** Generic Pcc information. + + The Subspace of Type0 contains information that can be re-used + in other Subspace types. + + MaximumPeriodicAccessRate doesn't need to be populated for + this structure. + */ + PCC_SUBSPACE_GENERIC_INFO GenericPccInfo; + + /// Version. + UINT16 Version; + + /// Platform Interrupt. + CM_ARM_GENERIC_INTERRUPT PlatIrq; + + /// Command Complete Check Register. + /// The WriteMask field is not used. + PCC_MAILBOX_REGISTER_INFO CmdCompleteCheckReg; + + /// Error Status Register. + /// The WriteMask field is not used. + PCC_MAILBOX_REGISTER_INFO ErrorStatusReg; +} CM_ARM_PCC_SUBSPACE_TYPE5_INFO; + #pragma pack() #endif // ARM_NAMESPACE_OBJECTS_H_ diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 467b3072bf..5a01ed0fb8 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -539,6 +539,101 @@ STATIC CONST CM_OBJ_PARSER CmArmCpcInfoParser[] = { { "NominalFrequencyInteger", 4, "0x%lx", NULL }, }; +/** A parser for the PCC_MAILBOX_REGISTER_INFO struct. +*/ +STATIC CONST CM_OBJ_PARSER CmArmMailboxRegisterInfoParser[] = { + { "Register", sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE), NULL, NULL, + AcpiGenericAddressParser, ARRAY_SIZE (AcpiGenericAddressParser) }, + { "PreserveMask", 8, "0x%llx", NULL }, + { "WriteMask", 8, "0x%llx", NULL }, +}; + +/** A parser for the PCC_SUBSPACE_CHANNEL_TIMING_INFO struct. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceChannelTimingInfoParser[] = { + { "NominalLatency", 4, "0x%x", NULL }, + { "MaxPeriodicAccessRate", 4, "0x%x", NULL }, + { "MinRequestTurnaroundTime", 2, "0x%x", NULL }, +}; + +/** A parser for EArmObjPccSubspaceType0Info. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceType0InfoParser[] = { + { "SubspaceId", 1, "0x%x", NULL }, + { "Type", 1, "0x%x", NULL }, + { "BaseAddress", 8, "0x%llx", NULL }, + { "AddressLength", 8, "0x%llx", NULL }, + { "DoorbellReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, + { "ChannelTiming", sizeof (PCC_SUBSPACE_CHANNEL_TIMING_INFO), + NULL, NULL, CmArmPccSubspaceChannelTimingInfoParser, + ARRAY_SIZE (CmArmPccSubspaceChannelTimingInfoParser) }, +}; + +/** A parser for EArmObjPccSubspaceType1Info. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceType1InfoParser[] = { + { "GenericPccInfo", sizeof (PCC_SUBSPACE_GENERIC_INFO), + NULL, NULL, CmArmPccSubspaceType0InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType0InfoParser) }, + { "PlatIrq", sizeof (CM_ARM_GENERIC_INTERRUPT), + NULL, NULL, CmArmGenericInterruptParser, + ARRAY_SIZE (CmArmGenericInterruptParser) }, +}; + +/** A parser for EArmObjPccSubspaceType2Info. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceType2InfoParser[] = { + { "GenericPccInfo", sizeof (PCC_SUBSPACE_GENERIC_INFO), + NULL, NULL, CmArmPccSubspaceType0InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType0InfoParser) }, + { "PlatIrq", sizeof (CM_ARM_GENERIC_INTERRUPT), NULL,NULL, + CmArmGenericInterruptParser, ARRAY_SIZE (CmArmGenericInterruptParser) }, + { "PlatIrqAckReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, +}; + +/** A parser for EArmObjPccSubspaceType3Info or EArmObjPccSubspaceType4Info. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceType34InfoParser[] = { + { "GenericPccInfo", sizeof (PCC_SUBSPACE_GENERIC_INFO), + NULL, NULL, CmArmPccSubspaceType0InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType0InfoParser) }, + { "PlatIrq", sizeof (CM_ARM_GENERIC_INTERRUPT), NULL,NULL, + CmArmGenericInterruptParser, ARRAY_SIZE (CmArmGenericInterruptParser) }, + { "PlatIrqAckReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, + { "CmdCompleteCheckReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, + { "CmdCompleteUpdateReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, + { "ErrorStatusReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, +}; + +/** A parser for EArmObjPccSubspaceType5Info. +*/ +STATIC CONST CM_OBJ_PARSER CmArmPccSubspaceType5InfoParser[] = { + { "GenericPccInfo", sizeof (PCC_SUBSPACE_GENERIC_INFO), + NULL, NULL, CmArmPccSubspaceType0InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType0InfoParser) }, + { "Version", 2, "0x%x",NULL }, + { "PlatIrq", sizeof (CM_ARM_GENERIC_INTERRUPT), NULL, NULL, + CmArmGenericInterruptParser, ARRAY_SIZE (CmArmGenericInterruptParser) }, + { "CmdCompleteCheckReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, + { "ErrorStatusReg", sizeof (PCC_MAILBOX_REGISTER_INFO), + NULL, NULL, CmArmMailboxRegisterInfoParser, + ARRAY_SIZE (CmArmMailboxRegisterInfoParser) }, +}; + /** A parser for Arm namespace objects. */ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { @@ -623,6 +718,18 @@ STATIC CONST CM_OBJ_PARSER_ARRAY ArmNamespaceObjectParser[] = { ARRAY_SIZE (CmArmMemoryRangeDescriptorInfoParser) }, { "EArmObjCpcInfo", CmArmCpcInfoParser, ARRAY_SIZE (CmArmCpcInfoParser) }, + { "EArmObjPccSubspaceType0Info", CmArmPccSubspaceType0InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType0InfoParser) }, + { "EArmObjPccSubspaceType1Info", CmArmPccSubspaceType1InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType1InfoParser) }, + { "EArmObjPccSubspaceType2Info", CmArmPccSubspaceType2InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType2InfoParser) }, + { "EArmObjPccSubspaceType3Info", CmArmPccSubspaceType34InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType34InfoParser) }, + { "EArmObjPccSubspaceType4Info", CmArmPccSubspaceType34InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType34InfoParser) }, + { "EArmObjPccSubspaceType5Info", CmArmPccSubspaceType5InfoParser, + ARRAY_SIZE (CmArmPccSubspaceType5InfoParser) }, { "EArmObjMax", NULL, 0 }, }; From a1c890c19587901faff5e736ab982fcf605eb143 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:55 +0200 Subject: [PATCH 0249/1529] DynamicTablesPkg: Add PCCT Generator The Platform Communication Channel Table (PCCT) generator collates the relevant information required for generating a PCCT table from configuration manager using the configuration manager protocol. The DynamicTablesManager then install the PCCT table. From ACPI 6.4, s14 PLATFORM COMMUNICATIONS CHANNEL (PCC): The platform communication channel (PCC) is a generic mechanism for OSPM to communicate with an entity in the platform. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/DynamicTables.dsc.inc | 4 +- DynamicTablesPkg/Include/AcpiTableGenerator.h | 3 +- .../Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf | 30 + .../Acpi/Arm/AcpiPcctLibArm/PcctGenerator.c | 1186 +++++++++++++++++ .../Acpi/Arm/AcpiPcctLibArm/PcctGenerator.h | 43 + 5 files changed, 1264 insertions(+), 2 deletions(-) create mode 100644 DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf create mode 100644 DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.c create mode 100644 DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.h diff --git a/DynamicTablesPkg/DynamicTables.dsc.inc b/DynamicTablesPkg/DynamicTables.dsc.inc index 3d4fa0c4c4..3e38fa0d0d 100644 --- a/DynamicTablesPkg/DynamicTables.dsc.inc +++ b/DynamicTablesPkg/DynamicTables.dsc.inc @@ -1,7 +1,7 @@ ## @file # Dsc include file for Dynamic Tables Framework. # -# Copyright (c) 2017 - 2021, Arm Limited. All rights reserved.
+# Copyright (c) 2017 - 2022, Arm Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -33,6 +33,7 @@ DynamicTablesPkg/Library/Acpi/Arm/AcpiRawLibArm/AcpiRawLibArm.inf DynamicTablesPkg/Library/Acpi/Arm/AcpiSpcrLibArm/AcpiSpcrLibArm.inf DynamicTablesPkg/Library/Acpi/Arm/AcpiSratLibArm/AcpiSratLibArm.inf + DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf # AML Fixup DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortLibArm.inf @@ -57,6 +58,7 @@ NULL|DynamicTablesPkg/Library/Acpi/Arm/AcpiRawLibArm/AcpiRawLibArm.inf NULL|DynamicTablesPkg/Library/Acpi/Arm/AcpiSpcrLibArm/AcpiSpcrLibArm.inf NULL|DynamicTablesPkg/Library/Acpi/Arm/AcpiSratLibArm/AcpiSratLibArm.inf + NULL|DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf # AML Fixup NULL|DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortLibArm.inf diff --git a/DynamicTablesPkg/Include/AcpiTableGenerator.h b/DynamicTablesPkg/Include/AcpiTableGenerator.h index f962dbff57..d0eda011c3 100644 --- a/DynamicTablesPkg/Include/AcpiTableGenerator.h +++ b/DynamicTablesPkg/Include/AcpiTableGenerator.h @@ -1,6 +1,6 @@ /** @file - Copyright (c) 2017 - 2021, Arm Limited. All rights reserved.
+ Copyright (c) 2017 - 2022, Arm Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -98,6 +98,7 @@ typedef enum StdAcpiTableId { EStdAcpiTableIdSsdtCmn600, ///< SSDT Cmn-600 Generator EStdAcpiTableIdSsdtCpuTopology, ///< SSDT Cpu Topology EStdAcpiTableIdSsdtPciExpress, ///< SSDT Pci Express Generator + EStdAcpiTableIdPcct, ///< PCCT Generator EStdAcpiTableIdMax } ESTD_ACPI_TABLE_ID; diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf new file mode 100644 index 0000000000..da54585c2d --- /dev/null +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/AcpiPcctLibArm.inf @@ -0,0 +1,30 @@ +## @file +# Pcct Table Generator +# +# Copyright (c) 2022, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = AcpiPcctLibArm + FILE_GUID = 38FE945C-D6ED-4CD6-8D20-FCEF3260D15A + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = NULL|DXE_DRIVER + CONSTRUCTOR = AcpiPcctLibConstructor + DESTRUCTOR = AcpiPcctLibDestructor + +[Sources] + PcctGenerator.c + PcctGenerator.h + +[Packages] + DynamicTablesPkg/DynamicTablesPkg.dec + EmbeddedPkg/EmbeddedPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseLib diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.c new file mode 100644 index 0000000000..36caf4aaea --- /dev/null +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.c @@ -0,0 +1,1186 @@ +/** @file + PCCT Table Generator + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.4 Specification - January 2021 + s14 PLATFORM COMMUNICATIONS CHANNEL (PCC) + +**/ + +#include +#include +#include +#include +#include + +// Module specific include files. +#include +#include +#include +#include +#include +#include "PcctGenerator.h" + +/** ARM standard PCCT Generator + +Requirements: + The following Configuration Manager Object(s) are required by + this Generator: + - EArmObjPccSubspaceType0Info + - EArmObjPccSubspaceType1Info + - EArmObjPccSubspaceType2Info + - EArmObjPccSubspaceType3Info + - EArmObjPccSubspaceType4Info + - EArmObjPccSubspaceType5Info +*/ + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 0 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType0Info, + CM_ARM_PCC_SUBSPACE_TYPE0_INFO + ); + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 1 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType1Info, + CM_ARM_PCC_SUBSPACE_TYPE1_INFO + ); + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 2 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType2Info, + CM_ARM_PCC_SUBSPACE_TYPE2_INFO + ); + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 3 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType3Info, + CM_ARM_PCC_SUBSPACE_TYPE3_INFO + ); + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 4 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType4Info, + CM_ARM_PCC_SUBSPACE_TYPE4_INFO + ); + +/** This macro expands to a function that retrieves the PCC + Subspace of Type 5 Information from the Configuration Manager. +*/ +GET_OBJECT_LIST ( + EObjNameSpaceArm, + EArmObjPccSubspaceType5Info, + CM_ARM_PCC_SUBSPACE_TYPE5_INFO + ); + +/** The Platform is capable of generating an interrupt + to indicate completion of a command. + + Cf: s14.1.1 Platform Communications Channel Global Flags + Platform Interrupt flag + and s14.1.6 Extended PCC subspaces (types 3 and 4) + If a responder subspace is included in the PCCT, + then the global Platform Interrupt flag must be set to 1 + + Set this variable and populate the PCCT flag accordingly if either: + - One of the PCCT Subspace uses interrupts. + - A PCC Subspace of type 4 is used. +*/ +STATIC BOOLEAN mHasPlatformInterrupt; + +/** Initialize the MappingTable. + + @param [in] MappingTable The mapping table structure. + @param [in] Count Number of entries to allocate in the + MappingTable. + + @retval EFI_SUCCESS Success. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. +**/ +STATIC +EFI_STATUS +EFIAPI +MappingTableInitialize ( + IN MAPPING_TABLE *MappingTable, + IN UINT32 Count + ) +{ + VOID **Table; + + if ((MappingTable == NULL) || + (Count == 0)) + { + ASSERT (0); + return EFI_INVALID_PARAMETER; + } + + Table = AllocateZeroPool (sizeof (*Table) * Count); + if (Table == NULL) { + ASSERT (0); + return EFI_OUT_OF_RESOURCES; + } + + MappingTable->Table = Table; + MappingTable->MaxIndex = Count; + + return EFI_SUCCESS; +} + +/** Free the MappingTable. + + @param [in, out] MappingTable The mapping table structure. +**/ +STATIC +VOID +EFIAPI +MappingTableFree ( + IN OUT MAPPING_TABLE *MappingTable + ) +{ + ASSERT (MappingTable != NULL); + ASSERT (MappingTable->Table != NULL); + + if (MappingTable->Table != NULL) { + FreePool (MappingTable->Table); + } +} + +/** Add a new entry for CmArmPccSubspace at Index. + + @param [in] MappingTable The mapping table structure. + @param [in] CmArmPccSubspace Pointer to a CM_ARM_PCC_SUBSPACE_TYPE[X]_INFO. + @param [in] Index Index at which CmArmPccSubspace must be added. + This is the Subspace Id. + + @retval EFI_SUCCESS Success. + @retval EFI_BUFFER_TOO_SMALL Buffer too small. + @retval EFI_INVALID_PARAMETER Invalid parameter. +**/ +STATIC +EFI_STATUS +EFIAPI +MappingTableAdd ( + IN MAPPING_TABLE *MappingTable, + IN VOID *CmArmPccSubspace, + IN UINT32 Index + ) +{ + if ((MappingTable == NULL) || + (MappingTable->Table == NULL) || + (CmArmPccSubspace == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + if ((Index >= MappingTable->MaxIndex) || + (MappingTable->Table[Index] != 0)) + { + ASSERT_EFI_ERROR (EFI_BUFFER_TOO_SMALL); + return EFI_BUFFER_TOO_SMALL; + } + + // Just map the Pcc Subspace in the Table. + MappingTable->Table[Index] = CmArmPccSubspace; + return EFI_SUCCESS; +} + +/** Parse the CmPccArray objects and add them to the MappingTable. + + @param [in] MappingTable The mapping table structure. + @param [in] CmPccArray Pointer to an array of CM_ARM_PCC_SUBSPACE_TYPE[X]_INFO. + @param [in] CmPccCount Count of objects in CmPccArray. + + @retval EFI_SUCCESS Success. + @retval EFI_BUFFER_TOO_SMALL Buffer too small. + @retval EFI_INVALID_PARAMETER Invalid parameter. +**/ +STATIC +EFI_STATUS +EFIAPI +MapPccSubspaceId ( + IN MAPPING_TABLE *MappingTable, + IN VOID *CmPccArray, + IN UINT32 CmPccCount + ) +{ + EFI_STATUS Status; + UINT8 *PccBuffer; + UINT32 Index; + UINT32 CmObjSize; + PCC_SUBSPACE_GENERIC_INFO *GenericPcc; + + if (CmPccCount == 0) { + return EFI_SUCCESS; + } + + if ((CmPccArray == NULL) || (MappingTable == NULL)) { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + GenericPcc = (PCC_SUBSPACE_GENERIC_INFO *)CmPccArray; + + switch (GenericPcc->Type) { + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_GENERIC: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE0_INFO); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_1_HW_REDUCED_COMMUNICATIONS: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE1_INFO); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_2_HW_REDUCED_COMMUNICATIONS: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE2_INFO); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_3_EXTENDED_PCC: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE3_INFO); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE4_INFO); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_5_HW_REGISTERS_COMMUNICATIONS: + CmObjSize = sizeof (CM_ARM_PCC_SUBSPACE_TYPE5_INFO); + break; + + default: + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + PccBuffer = (UINT8 *)CmPccArray; + + // Map the Pcc channel to their Subspace Id. + for (Index = 0; Index < CmPccCount; Index++) { + GenericPcc = (PCC_SUBSPACE_GENERIC_INFO *)PccBuffer; + + Status = MappingTableAdd ( + MappingTable, + PccBuffer, + GenericPcc->SubspaceId + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + PccBuffer += CmObjSize; + } + + return EFI_SUCCESS; +} + +/** Add one PCCT Subspace structure of Type 0 (Generic). + + @param [in] PccCmObj Pointer to a CmObj PCCT Subspace info structure. + @param [in] PccAcpi Pointer to the ACPI PCCT Subspace structure to populate. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +AddSubspaceStructType0 ( + IN CM_ARM_PCC_SUBSPACE_TYPE0_INFO *PccCmObj, + IN EFI_ACPI_6_4_PCCT_SUBSPACE_GENERIC *PccAcpi + ) +{ + PCC_MAILBOX_REGISTER_INFO *Doorbell; + PCC_SUBSPACE_CHANNEL_TIMING_INFO *ChannelTiming; + + if ((PccCmObj == NULL) || + (PccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_GENERIC) || + (PccAcpi == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Doorbell = &PccCmObj->DoorbellReg; + ChannelTiming = &PccCmObj->ChannelTiming; + + PccAcpi->Type = PccCmObj->Type; + PccAcpi->Length = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_GENERIC); + *(UINT32 *)&PccAcpi->Reserved[0] = EFI_ACPI_RESERVED_DWORD; + *(UINT16 *)&PccAcpi->Reserved[4] = EFI_ACPI_RESERVED_WORD; + PccAcpi->BaseAddress = PccCmObj->BaseAddress; + PccAcpi->AddressLength = PccCmObj->AddressLength; + + CopyMem ( + &PccAcpi->DoorbellRegister, + &Doorbell->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->DoorbellPreserve = Doorbell->PreserveMask; + PccAcpi->DoorbellWrite = Doorbell->WriteMask; + + PccAcpi->NominalLatency = ChannelTiming->NominalLatency; + PccAcpi->MaximumPeriodicAccessRate = ChannelTiming->MaxPeriodicAccessRate; + PccAcpi->MinimumRequestTurnaroundTime = ChannelTiming->MinRequestTurnaroundTime; + + return EFI_SUCCESS; +} + +/** Add one PCCT subspace structure of Type 1 (HW-Reduced). + + @param [in] PccCmObj Pointer to a CmObj PCCT Subspace info structure. + @param [in] PccAcpi Pointer to the ACPI PCCT Subspace structure to populate. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +AddSubspaceStructType1 ( + IN CM_ARM_PCC_SUBSPACE_TYPE1_INFO *PccCmObj, + IN EFI_ACPI_6_4_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS *PccAcpi + ) +{ + CM_ARM_PCC_SUBSPACE_TYPE0_INFO *GenericPccCmObj; + PCC_MAILBOX_REGISTER_INFO *Doorbell; + PCC_SUBSPACE_CHANNEL_TIMING_INFO *ChannelTiming; + + GenericPccCmObj = (CM_ARM_PCC_SUBSPACE_TYPE0_INFO *)PccCmObj; + + if ((PccCmObj == NULL) || + (GenericPccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_1_HW_REDUCED_COMMUNICATIONS) || + (PccAcpi == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Doorbell = &GenericPccCmObj->DoorbellReg; + ChannelTiming = &GenericPccCmObj->ChannelTiming; + + PccAcpi->Type = GenericPccCmObj->Type; + PccAcpi->Length = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS); + PccAcpi->PlatformInterrupt = PccCmObj->PlatIrq.Interrupt; + PccAcpi->PlatformInterruptFlags = PccCmObj->PlatIrq.Flags; + PccAcpi->Reserved = EFI_ACPI_RESERVED_BYTE; + PccAcpi->BaseAddress = GenericPccCmObj->BaseAddress; + PccAcpi->AddressLength = GenericPccCmObj->AddressLength; + + CopyMem ( + &PccAcpi->DoorbellRegister, + &Doorbell->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->DoorbellPreserve = Doorbell->PreserveMask; + PccAcpi->DoorbellWrite = Doorbell->WriteMask; + + PccAcpi->NominalLatency = ChannelTiming->NominalLatency; + PccAcpi->MaximumPeriodicAccessRate = ChannelTiming->MaxPeriodicAccessRate; + PccAcpi->MinimumRequestTurnaroundTime = ChannelTiming->MinRequestTurnaroundTime; + + if ((PccCmObj->PlatIrq.Interrupt != 0)) { + mHasPlatformInterrupt = TRUE; + } + + return EFI_SUCCESS; +} + +/** Add one PCCT subspace structure of Type 2 (HW-Reduced). + + @param [in] PccCmObj Pointer to a CmObj PCCT Subspace info structure. + @param [in] PccAcpi Pointer to the ACPI PCCT Subspace structure to populate. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +AddSubspaceStructType2 ( + IN CM_ARM_PCC_SUBSPACE_TYPE2_INFO *PccCmObj, + IN EFI_ACPI_6_4_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS *PccAcpi + ) +{ + CM_ARM_PCC_SUBSPACE_TYPE0_INFO *GenericPccCmObj; + PCC_MAILBOX_REGISTER_INFO *Doorbell; + PCC_MAILBOX_REGISTER_INFO *PlatIrqAck; + PCC_SUBSPACE_CHANNEL_TIMING_INFO *ChannelTiming; + + GenericPccCmObj = (CM_ARM_PCC_SUBSPACE_TYPE0_INFO *)PccCmObj; + + if ((PccCmObj == NULL) || + (GenericPccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_2_HW_REDUCED_COMMUNICATIONS) || + (PccAcpi == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Doorbell = &GenericPccCmObj->DoorbellReg; + PlatIrqAck = &PccCmObj->PlatIrqAckReg; + ChannelTiming = &GenericPccCmObj->ChannelTiming; + + PccAcpi->Type = GenericPccCmObj->Type; + PccAcpi->Length = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS); + PccAcpi->PlatformInterrupt = PccCmObj->PlatIrq.Interrupt; + PccAcpi->PlatformInterruptFlags = PccCmObj->PlatIrq.Flags; + PccAcpi->BaseAddress = GenericPccCmObj->BaseAddress; + PccAcpi->Reserved = EFI_ACPI_RESERVED_BYTE; + PccAcpi->BaseAddress = GenericPccCmObj->BaseAddress; + PccAcpi->AddressLength = GenericPccCmObj->AddressLength; + + CopyMem ( + &PccAcpi->DoorbellRegister, + &Doorbell->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->DoorbellPreserve = Doorbell->PreserveMask; + PccAcpi->DoorbellWrite = Doorbell->WriteMask; + + PccAcpi->NominalLatency = ChannelTiming->NominalLatency; + PccAcpi->MaximumPeriodicAccessRate = ChannelTiming->MaxPeriodicAccessRate; + PccAcpi->MinimumRequestTurnaroundTime = ChannelTiming->MinRequestTurnaroundTime; + + CopyMem ( + &PccAcpi->PlatformInterruptAckRegister, + &PlatIrqAck->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->PlatformInterruptAckPreserve = PlatIrqAck->PreserveMask; + PccAcpi->PlatformInterruptAckWrite = PlatIrqAck->WriteMask; + + if ((PccCmObj->PlatIrq.Interrupt != 0)) { + mHasPlatformInterrupt = TRUE; + } + + return EFI_SUCCESS; +} + +/** Add one PCCT subspace structure of Type 3 or 4 (Extended). + + @param [in] PccCmObj Pointer to a CmObj PCCT Subspace info structure. + @param [in] PccAcpi Pointer to the ACPI PCCT Subspace structure to populate. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +AddSubspaceStructType34 ( + IN CM_ARM_PCC_SUBSPACE_TYPE3_INFO *PccCmObj, + IN EFI_ACPI_6_4_PCCT_SUBSPACE_3_EXTENDED_PCC *PccAcpi + ) +{ + CM_ARM_PCC_SUBSPACE_TYPE0_INFO *GenericPccCmObj; + PCC_MAILBOX_REGISTER_INFO *Doorbell; + PCC_MAILBOX_REGISTER_INFO *PlatIrqAck; + PCC_MAILBOX_REGISTER_INFO *CmdCompleteCheck; + PCC_MAILBOX_REGISTER_INFO *CmdCompleteUpdate; + PCC_MAILBOX_REGISTER_INFO *ErrorStatus; + PCC_SUBSPACE_CHANNEL_TIMING_INFO *ChannelTiming; + + GenericPccCmObj = (CM_ARM_PCC_SUBSPACE_TYPE0_INFO *)PccCmObj; + + if ((PccCmObj == NULL) || + ((GenericPccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_3_EXTENDED_PCC) && + (GenericPccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC)) || + (PccAcpi == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Doorbell = &GenericPccCmObj->DoorbellReg; + PlatIrqAck = &PccCmObj->PlatIrqAckReg; + CmdCompleteCheck = &PccCmObj->CmdCompleteCheckReg; + CmdCompleteUpdate = &PccCmObj->CmdCompleteUpdateReg; + ErrorStatus = &PccCmObj->ErrorStatusReg; + ChannelTiming = &GenericPccCmObj->ChannelTiming; + + PccAcpi->Type = GenericPccCmObj->Type; + PccAcpi->Length = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_3_EXTENDED_PCC); + PccAcpi->PlatformInterrupt = PccCmObj->PlatIrq.Interrupt; + PccAcpi->PlatformInterruptFlags = PccCmObj->PlatIrq.Flags; + PccAcpi->Reserved = EFI_ACPI_RESERVED_BYTE; + PccAcpi->BaseAddress = GenericPccCmObj->BaseAddress; + PccAcpi->AddressLength = GenericPccCmObj->AddressLength; + + CopyMem ( + &PccAcpi->DoorbellRegister, + &Doorbell->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->DoorbellPreserve = Doorbell->PreserveMask; + PccAcpi->DoorbellWrite = Doorbell->WriteMask; + + PccAcpi->NominalLatency = ChannelTiming->NominalLatency; + PccAcpi->MaximumPeriodicAccessRate = ChannelTiming->MaxPeriodicAccessRate; + PccAcpi->MinimumRequestTurnaroundTime = ChannelTiming->MinRequestTurnaroundTime; + + CopyMem ( + &PccAcpi->PlatformInterruptAckRegister, + &PlatIrqAck->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->PlatformInterruptAckPreserve = PlatIrqAck->PreserveMask; + PccAcpi->PlatformInterruptAckSet = PlatIrqAck->WriteMask; + + PccAcpi->Reserved1[0] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[1] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[1] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[3] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[4] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[5] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[6] = EFI_ACPI_RESERVED_BYTE; + PccAcpi->Reserved1[7] = EFI_ACPI_RESERVED_BYTE; + + CopyMem ( + &PccAcpi->CommandCompleteCheckRegister, + &CmdCompleteCheck->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->CommandCompleteCheckMask = CmdCompleteCheck->PreserveMask; + // No Write mask. + + CopyMem ( + &PccAcpi->CommandCompleteUpdateRegister, + &CmdCompleteUpdate->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->CommandCompleteUpdatePreserve = CmdCompleteUpdate->PreserveMask; + PccAcpi->CommandCompleteUpdateSet = CmdCompleteUpdate->WriteMask; + + CopyMem ( + &PccAcpi->ErrorStatusRegister, + &ErrorStatus->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->ErrorStatusMask = ErrorStatus->PreserveMask; + // No Write mask. + + if (GenericPccCmObj->Type == EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) { + mHasPlatformInterrupt = TRUE; + } else if ((PccCmObj->PlatIrq.Interrupt != 0)) { + mHasPlatformInterrupt = TRUE; + } + + return EFI_SUCCESS; +} + +/** Add one PCCT subspace structure of Type 5 (HW-Registers). + + @param [in] PccCmObj Pointer to a CmObj PCCT Subspace info structure. + @param [in] PccAcpi Pointer to the ACPI PCCT Subspace structure to populate. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +AddSubspaceStructType5 ( + IN CM_ARM_PCC_SUBSPACE_TYPE5_INFO *PccCmObj, + IN EFI_ACPI_6_4_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS *PccAcpi + ) +{ + CM_ARM_PCC_SUBSPACE_TYPE0_INFO *GenericPccCmObj; + PCC_MAILBOX_REGISTER_INFO *Doorbell; + PCC_MAILBOX_REGISTER_INFO *CmdCompleteCheck; + PCC_MAILBOX_REGISTER_INFO *ErrorStatus; + PCC_SUBSPACE_CHANNEL_TIMING_INFO *ChannelTiming; + + GenericPccCmObj = (CM_ARM_PCC_SUBSPACE_TYPE0_INFO *)PccCmObj; + + if ((PccCmObj == NULL) || + (GenericPccCmObj->Type != EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_5_HW_REGISTERS_COMMUNICATIONS) || + (PccAcpi == NULL)) + { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Doorbell = &GenericPccCmObj->DoorbellReg; + CmdCompleteCheck = &PccCmObj->CmdCompleteCheckReg; + ErrorStatus = &PccCmObj->ErrorStatusReg; + ChannelTiming = &GenericPccCmObj->ChannelTiming; + + PccAcpi->Type = GenericPccCmObj->Type; + PccAcpi->Length = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS); + PccAcpi->Version = PccCmObj->Version; + PccAcpi->BaseAddress = GenericPccCmObj->BaseAddress; + PccAcpi->SharedMemoryRangeLength = GenericPccCmObj->AddressLength; + + CopyMem ( + &PccAcpi->DoorbellRegister, + &Doorbell->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->DoorbellPreserve = Doorbell->PreserveMask; + PccAcpi->DoorbellWrite = Doorbell->WriteMask; + + CopyMem ( + &PccAcpi->CommandCompleteCheckRegister, + &CmdCompleteCheck->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->CommandCompleteCheckMask = CmdCompleteCheck->PreserveMask; + // No Write mask. + + CopyMem ( + &PccAcpi->ErrorStatusRegister, + &ErrorStatus->Register, + sizeof (EFI_ACPI_6_4_GENERIC_ADDRESS_STRUCTURE) + ); + PccAcpi->ErrorStatusMask = ErrorStatus->PreserveMask; + // No Write mask. + + PccAcpi->NominalLatency = ChannelTiming->NominalLatency; + // No MaximumPeriodicAccessRate. + PccAcpi->MinimumRequestTurnaroundTime = ChannelTiming->MinRequestTurnaroundTime; + + return EFI_SUCCESS; +} + +/** Populate the PCCT table using the MappingTable. + + @param [in] MappingTable The mapping table structure. + @param [in] Pcc Pointer to an array of Pcc Subpace structures. + @param [in] Size Size of the Pcc array. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_BUFFER_TOO_SMALL Buffer too small. + @retval EFI_INVALID_PARAMETER A parameter is invalid. +**/ +STATIC +EFI_STATUS +EFIAPI +PopulatePcctTable ( + IN MAPPING_TABLE *MappingTable, + IN VOID *Pcc, + IN UINT32 Size + ) +{ + EFI_STATUS Status; + UINT8 *PccBuffer; + UINT32 CmObjSize; + UINT32 Index; + UINT32 MaxIndex; + VOID **Table; + VOID *CurrentPccSubspace; + + ASSERT (MappingTable != NULL); + ASSERT (MappingTable->Table != NULL); + + PccBuffer = Pcc; + MaxIndex = MappingTable->MaxIndex; + Table = MappingTable->Table; + + for (Index = 0; Index < MaxIndex; Index++) { + CurrentPccSubspace = Table[Index]; + if (CurrentPccSubspace == NULL) { + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + switch (((PCC_SUBSPACE_GENERIC_INFO *)CurrentPccSubspace)->Type) { + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_GENERIC: + Status = AddSubspaceStructType0 ( + (CM_ARM_PCC_SUBSPACE_TYPE0_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_GENERIC *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_GENERIC); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_1_HW_REDUCED_COMMUNICATIONS: + Status = AddSubspaceStructType1 ( + (CM_ARM_PCC_SUBSPACE_TYPE1_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_2_HW_REDUCED_COMMUNICATIONS: + Status = AddSubspaceStructType2 ( + (CM_ARM_PCC_SUBSPACE_TYPE2_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_3_EXTENDED_PCC: + Status = AddSubspaceStructType34 ( + (CM_ARM_PCC_SUBSPACE_TYPE3_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_3_EXTENDED_PCC *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_3_EXTENDED_PCC); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC: + Status = AddSubspaceStructType34 ( + (CM_ARM_PCC_SUBSPACE_TYPE4_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_4_EXTENDED_PCC *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_4_EXTENDED_PCC); + break; + + case EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_5_HW_REGISTERS_COMMUNICATIONS: + Status = AddSubspaceStructType5 ( + (CM_ARM_PCC_SUBSPACE_TYPE5_INFO *)CurrentPccSubspace, + (EFI_ACPI_6_4_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS *)PccBuffer + ); + + CmObjSize = sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS); + break; + + default: + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } // switch + + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + if (Size < CmObjSize) { + ASSERT_EFI_ERROR (EFI_BUFFER_TOO_SMALL); + return EFI_BUFFER_TOO_SMALL; + } + + PccBuffer += CmObjSize; + Size -= CmObjSize; + } // for + + return EFI_SUCCESS; +} + +/** Construct the PCCT ACPI table. + + Called by the Dynamic Table Manager, this function invokes the + Configuration Manager protocol interface to get the required hardware + information for generating the ACPI table. + + If this function allocates any resources then they must be freed + in the FreeXXXXTableResources function. + + @param [in] This Pointer to the table generator. + @param [in] AcpiTableInfo Pointer to the ACPI Table Info. + @param [in] CfgMgrProtocol Pointer to the Configuration Manager + Protocol Interface. + @param [out] Table Pointer to the constructed ACPI Table. + + @retval EFI_SUCCESS Table generated successfully. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_NOT_FOUND The required object was not found. + @retval EFI_BAD_BUFFER_SIZE The size returned by the Configuration + Manager is less than the Object size for the + requested object. + @retval EFI_BUFFER_TOO_SMALL Buffer too small. + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. +**/ +STATIC +EFI_STATUS +EFIAPI +BuildPcctTable ( + IN CONST ACPI_TABLE_GENERATOR *CONST This, + IN CONST CM_STD_OBJ_ACPI_TABLE_INFO *CONST AcpiTableInfo, + IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, + OUT EFI_ACPI_DESCRIPTION_HEADER **CONST Table + ) +{ + EFI_STATUS Status; + ACPI_PCCT_GENERATOR *Generator; + UINT32 TableSize; + EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER *Pcct; + UINT8 *Buffer; + + MAPPING_TABLE *MappingTable; + UINT32 MappingTableCount; + + CM_ARM_PCC_SUBSPACE_TYPE0_INFO *PccType0; + UINT32 PccType0Count; + CM_ARM_PCC_SUBSPACE_TYPE1_INFO *PccType1; + UINT32 PccType1Count; + CM_ARM_PCC_SUBSPACE_TYPE2_INFO *PccType2; + UINT32 PccType2Count; + CM_ARM_PCC_SUBSPACE_TYPE3_INFO *PccType3; + UINT32 PccType3Count; + CM_ARM_PCC_SUBSPACE_TYPE4_INFO *PccType4; + UINT32 PccType4Count; + CM_ARM_PCC_SUBSPACE_TYPE5_INFO *PccType5; + UINT32 PccType5Count; + + ASSERT (This != NULL); + ASSERT (AcpiTableInfo != NULL); + ASSERT (CfgMgrProtocol != NULL); + ASSERT (Table != NULL); + ASSERT (AcpiTableInfo->TableGeneratorId == This->GeneratorID); + ASSERT (AcpiTableInfo->AcpiTableSignature == This->AcpiTableSignature); + + if ((AcpiTableInfo->AcpiTableRevision < This->MinAcpiTableRevision) || + (AcpiTableInfo->AcpiTableRevision > This->AcpiTableRevision)) + { + DEBUG (( + DEBUG_ERROR, + "ERROR: PCCT: Requested table revision = %d, is not supported." + "Supported table revision: Minimum = %d, Maximum = %d\n", + AcpiTableInfo->AcpiTableRevision, + This->MinAcpiTableRevision, + This->AcpiTableRevision + )); + ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + Generator = (ACPI_PCCT_GENERATOR *)This; + MappingTable = &Generator->MappingTable; + *Table = NULL; + + // First get all the Pcc Subpace CmObj of type X. + + Status = GetEArmObjPccSubspaceType0Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType0, + &PccType0Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = GetEArmObjPccSubspaceType1Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType1, + &PccType1Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = GetEArmObjPccSubspaceType2Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType2, + &PccType2Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = GetEArmObjPccSubspaceType3Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType3, + &PccType3Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = GetEArmObjPccSubspaceType4Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType4, + &PccType4Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = GetEArmObjPccSubspaceType5Info ( + CfgMgrProtocol, + CM_NULL_TOKEN, + &PccType5, + &PccType5Count + ); + if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + // Count the number of Pcc Subspaces. + MappingTableCount = PccType0Count; + MappingTableCount += PccType1Count; + MappingTableCount += PccType2Count; + MappingTableCount += PccType3Count; + MappingTableCount += PccType4Count; + MappingTableCount += PccType5Count; + + Status = MappingTableInitialize (MappingTable, MappingTableCount); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + // Map the Subspace Ids for all types. + + Status = MapPccSubspaceId (MappingTable, PccType0, PccType0Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = MapPccSubspaceId (MappingTable, PccType1, PccType1Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = MapPccSubspaceId (MappingTable, PccType2, PccType2Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = MapPccSubspaceId (MappingTable, PccType3, PccType3Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = MapPccSubspaceId (MappingTable, PccType4, PccType4Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Status = MapPccSubspaceId (MappingTable, PccType5, PccType5Count); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + // Compute the size of the PCCT table. + TableSize = sizeof (EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER); + TableSize += PccType0Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_GENERIC); + TableSize += PccType1Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS); + TableSize += PccType2Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS); + TableSize += PccType3Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_3_EXTENDED_PCC); + TableSize += PccType4Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_4_EXTENDED_PCC); + TableSize += PccType5Count * sizeof (EFI_ACPI_6_4_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS); + + // Allocate a Buffer for the PCCT table. + *Table = (EFI_ACPI_DESCRIPTION_HEADER *)AllocateZeroPool (TableSize); + if (*Table == NULL) { + Status = EFI_OUT_OF_RESOURCES; + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Pcct = (EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER *)*Table; + + Status = AddAcpiHeader ( + CfgMgrProtocol, + This, + &Pcct->Header, + AcpiTableInfo, + TableSize + ); + if (EFI_ERROR (Status)) { + DEBUG (( + DEBUG_ERROR, + "ERROR: PCCT: Failed to add ACPI header. Status = %r\n", + Status + )); + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + Buffer = (UINT8 *)Pcct; + Buffer += sizeof (EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER); + TableSize -= sizeof (EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER); + + // Populate the PCCT table by following the Subspace Id mapping. + Status = PopulatePcctTable (MappingTable, Buffer, TableSize); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + goto error_handler; + } + + // Setup the Reserved fields once mHasPlatformInterrupt hase been populated. + Pcct->Flags = mHasPlatformInterrupt; + Pcct->Reserved = EFI_ACPI_RESERVED_QWORD; + + MappingTableFree (MappingTable); + + return Status; + +error_handler: + DEBUG (( + DEBUG_ERROR, + "ERROR: PCCT: Failed to install table. Status = %r\n", + Status + )); + + if (*Table != NULL) { + FreePool (*Table); + *Table = NULL; + } + + MappingTableFree (MappingTable); + + return Status; +} + +/** Free any resources allocated for constructing the PCCT. + + @param [in] This Pointer to the table generator. + @param [in] AcpiTableInfo Pointer to the ACPI Table Info. + @param [in] CfgMgrProtocol Pointer to the Configuration Manager + Protocol Interface. + @param [in, out] Table Pointer to the ACPI Table. + + @retval EFI_SUCCESS The resources were freed successfully. + @retval EFI_INVALID_PARAMETER The table pointer is NULL or invalid. +**/ +STATIC +EFI_STATUS +FreePcctTableResources ( + IN CONST ACPI_TABLE_GENERATOR *CONST This, + IN CONST CM_STD_OBJ_ACPI_TABLE_INFO *CONST AcpiTableInfo, + IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, + IN OUT EFI_ACPI_DESCRIPTION_HEADER **CONST Table + ) +{ + ASSERT (This != NULL); + ASSERT (AcpiTableInfo != NULL); + ASSERT (CfgMgrProtocol != NULL); + ASSERT (AcpiTableInfo->TableGeneratorId == This->GeneratorID); + ASSERT (AcpiTableInfo->AcpiTableSignature == This->AcpiTableSignature); + + if ((Table == NULL) || (*Table == NULL)) { + DEBUG ((DEBUG_ERROR, "ERROR: PCCT: Invalid Table Pointer\n")); + ASSERT ((Table != NULL) && (*Table != NULL)); + return EFI_INVALID_PARAMETER; + } + + FreePool (*Table); + *Table = NULL; + return EFI_SUCCESS; +} + +/** This macro defines the PCCT Table Generator revision. +*/ +#define PCCT_GENERATOR_REVISION CREATE_REVISION (1, 0) + +/** The interface for the PCCT Table Generator. +*/ +STATIC +ACPI_PCCT_GENERATOR PcctGenerator = { + // ACPI table generator header + { + // Generator ID + CREATE_STD_ACPI_TABLE_GEN_ID (EStdAcpiTableIdPcct), + // Generator Description + L"ACPI.STD.PCCT.GENERATOR", + // ACPI Table Signature + EFI_ACPI_6_4_PLATFORM_COMMUNICATIONS_CHANNEL_TABLE_SIGNATURE, + // ACPI Table Revision supported by this Generator + EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_REVISION, + // Minimum ACPI Table Revision supported by this Generator + EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL_TABLE_REVISION, + // Creator ID + TABLE_GENERATOR_CREATOR_ID_ARM, + // Creator Revision + PCCT_GENERATOR_REVISION, + // Build Table function + BuildPcctTable, + // Free Resource function + FreePcctTableResources, + // Extended build function not needed + NULL, + // Extended build function not implemented by the generator. + // Hence extended free resource function is not required. + NULL + }, + + // Private fields are defined from here. + + // Mapping Table + { + // Table + NULL, + // MaxIndex + 0, + }, +}; + +/** Register the Generator with the ACPI Table Factory. + + @param [in] ImageHandle The handle to the image. + @param [in] SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS The Generator is registered. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_ALREADY_STARTED The Generator for the Table ID + is already registered. +**/ +EFI_STATUS +EFIAPI +AcpiPcctLibConstructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + Status = RegisterAcpiTableGenerator (&PcctGenerator.Header); + DEBUG ((DEBUG_INFO, "PCCT: Register Generator. Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); + return Status; +} + +/** Deregister the Generator from the ACPI Table Factory. + + @param [in] ImageHandle The handle to the image. + @param [in] SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS The Generator is deregistered. + @retval EFI_INVALID_PARAMETER A parameter is invalid. + @retval EFI_NOT_FOUND The Generator is not registered. +**/ +EFI_STATUS +EFIAPI +AcpiPcctLibDestructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + Status = DeregisterAcpiTableGenerator (&PcctGenerator.Header); + DEBUG ((DEBUG_INFO, "PCCT: Deregister Generator. Status = %r\n", Status)); + ASSERT_EFI_ERROR (Status); + return Status; +} diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.h b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.h new file mode 100644 index 0000000000..0631a1f5b7 --- /dev/null +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiPcctLibArm/PcctGenerator.h @@ -0,0 +1,43 @@ +/** @file + PCCT Table Generator + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.4 Specification - January 2021 + s14 PLATFORM COMMUNICATIONS CHANNEL (PCC) + +**/ + +#ifndef PCCT_GENERATOR_H_ +#define PCCT_GENERATOR_H_ + +#pragma pack(1) + +/** Structure used to map a Pcc Subspace to an index. +*/ +typedef struct MappingTable { + /// Mapping table for Subspace Ids. + /// Subspace ID/Index <-> CM_ARM_PCC_SUBSPACE_TYPE[X]_INFO pointer + VOID **Table; + + /// Number of entries in the Table. + UINT32 MaxIndex; +} MAPPING_TABLE; + +/** A structure holding the Pcct generator and additional private data. +*/ +typedef struct AcpiPcctGenerator { + /// ACPI Table generator header + ACPI_TABLE_GENERATOR Header; + + // Private fields are defined from here. + + /// Table to map: Subspace ID/Index <-> CM_ARM_PCC_SUBSPACE_TYPE[X]_INFO pointer + MAPPING_TABLE MappingTable; +} ACPI_PCCT_GENERATOR; + +#pragma pack() + +#endif // PCCT_GENERATOR_H_ From bcfcbc1ffd47b65b376bb1011a1c33010cb9cb79 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:56 +0200 Subject: [PATCH 0250/1529] DynamicTablesPkg/AmlLib: Allow larger AccessSize for Pcc address space For Pcc address space, the AccessSize field of a Register is used to delcare the Pcc Subspace Id. This Id can be up to 256. Cf. ACPI 6.4, s14.7 Referencing the PCC address space Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c index 332962bed4..4ca63ccd23 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlResourceDataCodeGen.c @@ -1257,7 +1257,12 @@ AmlCodeGenRdRegister ( AML_DATA_NODE *RdNode; EFI_ACPI_GENERIC_REGISTER_DESCRIPTOR RdRegister; - if ((AccessSize > EFI_ACPI_6_4_QWORD) || + // Cf. ACPI 6.4, s14.7 Referencing the PCC address space + // The AccessSize represents the Subspace Id for the PCC address space. + if (((AddressSpace == EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL) && + (AccessSize > 256)) || + ((AddressSpace != EFI_ACPI_6_4_PLATFORM_COMMUNICATION_CHANNEL) && + (AccessSize > EFI_ACPI_6_4_QWORD)) || ((NameOpNode == NULL) && (NewRdNode == NULL))) { ASSERT (0); From f9e92438ab0888989f8ed74580884c89ef94ae41 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:57 +0200 Subject: [PATCH 0251/1529] DynamicTablesPkg: Readme.md: Update available tables for generation The following tables can now be generated by the DynamicTablesPkg: - PCCT - PPTT - SRAT Update the documentation accordingly. Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DynamicTablesPkg/Readme.md b/DynamicTablesPkg/Readme.md index 5f92d4c6cb..6b0a6c7a40 100644 --- a/DynamicTablesPkg/Readme.md +++ b/DynamicTablesPkg/Readme.md @@ -53,7 +53,10 @@ The framework currently supports the following table generators for ARM: * MADT - Multiple APIC Description Table * MCFG - PCI Express memory mapped configuration space base address Description Table +* PCCT - Platform Communications Channel Table +* PPTT - Processor Properties Topology Table * SPCR - Serial Port Console Redirection Table +* SRAT - System Resource Affinity Table * SSDT - Secondary System Description Table. This is essentially a RAW table generator. From c15ab03f30b1b44a65cb1a6bd6e65b788a5f5c35 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 10 Oct 2022 11:20:58 +0200 Subject: [PATCH 0252/1529] ShellPkg/AcpiView: Update PCCT fields for ACPI 6.5 The ACPI specification updated some terms in accordance with: s1.1.1 Principle of Inclusive Terminology Update the PCCT parser accordincly with these new terms. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Pierre Gondois Reviewed-by: Ray Ni Reviewed-by: Sami Mujawar --- .../UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c index 8cffdaaf07..8ad39090af 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c @@ -146,7 +146,7 @@ ValidatePccDoorbellGas ( IN VOID *Context ) { - // For slave subspaces this field is optional, if not present the field + // For responder subspaces this field is optional, if not present the field // should just contain zeros. if (*PccSubspaceType == EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) { if (IsZeroBuffer ( @@ -214,7 +214,7 @@ ValidatePccErrStatusGas ( IN VOID *Context ) { - // This field is ignored by the OSPM on slave channels. + // This field is ignored by the OSPM on responder channels. if (*PccSubspaceType == EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) { return; } @@ -237,7 +237,7 @@ ValidatePlatInterrupt ( IN VOID *Context ) { - // If a slave subspace is present in the PCCT, then the global Platform + // If a responder subspace is present in the PCCT, then the global Platform // Interrupt flag must be set to 1. if ((*PccSubspaceType == EFI_ACPI_6_4_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) && ((*PccGlobalFlags & EFI_ACPI_6_4_PCCT_FLAGS_PLATFORM_INTERRUPT) != From d7772d78ba24acf345694bb55132033adeb4cf43 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 23 Sep 2022 15:35:01 +0200 Subject: [PATCH 0253/1529] Maintainers.txt: Add 'Pierre Gondois' as DynamicTablesPkg reviewer Add myself as reviewer for the DynamicTablesPkg. Signed-off-by: Pierre Gondois Reviewed-by: Michael D Kinney Reviewed-by: Alexei Fedorov Reviewed-by: Sami Mujawar --- Maintainers.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Maintainers.txt b/Maintainers.txt index 8e81ccfdec..889990fa56 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -183,6 +183,7 @@ F: DynamicTablesPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/DynamicTablesPkg M: Sami Mujawar [samimujawar] M: Alexei Fedorov [AlexeiFedorov] +R: Pierre Gondois [pierregondois] EmbeddedPkg F: EmbeddedPkg/ From f58156ec8173b8642e4e7a9d35aca65a95331410 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 28 Oct 2022 18:16:55 +0800 Subject: [PATCH 0254/1529] RedfishPkg/RedfishDiscoverDxe: Fix memory free issue Check the memory block pointer before freeing it. Cc: Nickle Wang Cc: Igor Kulchytskyy Signed-off-by: Abner Chang Reviewed-by: Nickle Wang --- .../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c index 1293ddd633..042d6d5fd5 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c @@ -261,6 +261,7 @@ Tcp6GetSubnetInfo ( Tcp6 = (EFI_TCP6_PROTOCOL *)Instance->NetworkInterfaceProtocolInfo.NetworkProtocolInterface; + ZeroMem ((VOID *)&IpModedata, sizeof (EFI_IP6_MODE_DATA)); Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__)); @@ -282,12 +283,15 @@ Tcp6GetSubnetInfo ( } Instance->SubnetAddrInfoIPv6Number = IpModedata.AddressCount; - CopyMem ( - (VOID *)Instance->SubnetAddrInfoIPv6, - (VOID *)&IpModedata.AddressList, - IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO) - ); - FreePool (IpModedata.AddressList); + if ((IpModedata.AddressCount != 0) && (IpModedata.AddressList != NULL)) { + CopyMem ( + (VOID *)Instance->SubnetAddrInfoIPv6, + (VOID *)&IpModedata.AddressList, + IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO) + ); + FreePool (IpModedata.AddressList); + } + return EFI_SUCCESS; } From 6ba18379a857722624cbd7c18a6572419f42e8a3 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:40 +0800 Subject: [PATCH 0255/1529] MdeModulePkg: Add PrePiHob.h RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is defined for unaccepted memory. But this defitinion has not been officially in the PI spec. Base on the code-first we define BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED at MdeModulePkg/Include/Pi/PrePiHob.h. Cc: Jian J Wang Cc: Liming Gao Cc: Ray Ni Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Reviewed-by: Liming Gao Signed-off-by: Min Xu --- MdeModulePkg/Include/Pi/PrePiHob.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 MdeModulePkg/Include/Pi/PrePiHob.h diff --git a/MdeModulePkg/Include/Pi/PrePiHob.h b/MdeModulePkg/Include/Pi/PrePiHob.h new file mode 100644 index 0000000000..ac575e5972 --- /dev/null +++ b/MdeModulePkg/Include/Pi/PrePiHob.h @@ -0,0 +1,20 @@ +/** @file + HOB related definitions which has not been officially published in PI. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef MDE_MODULEPKG_PRE_PI_HOB_H_ +#define MDE_MODULEPKG_PRE_PI_HOB_H_ + +// +// BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is defined for unaccepted memory. +// But this defitinion has not been officially in the PI spec. Base +// on the code-first we define BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED at +// MdeModulePkg/Include/Pi/PrePiHob.h. +// +#define BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED 0x00000007 + +#endif From 55773c3a1bc9d50e9cfaad3319471819b5af623f Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:41 +0800 Subject: [PATCH 0256/1529] MdePkg: Increase EFI_RESOURCE_MAX_MEMORY_TYPE RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is defined for unaccepted memory. But this defitinion has not been officially in the PI spec. Base on the code-first we define EFI_RESOURCE_MEMORY_UNACCEPTED at MdeModulePkg/Include/Pi/PrePiHob.h and update EFI_RESOURCE_MAX_MEMORY_TYPE to 8. After BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is officially published in PI spec, we will re-visit here. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Jiewen Yao Reviewed-by: Liming Gao Signed-off-by: Min Xu --- MdePkg/Include/Pi/PiHob.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/Pi/PiHob.h b/MdePkg/Include/Pi/PiHob.h index e9f0ab4309..4605da56e2 100644 --- a/MdePkg/Include/Pi/PiHob.h +++ b/MdePkg/Include/Pi/PiHob.h @@ -232,7 +232,16 @@ typedef UINT32 EFI_RESOURCE_TYPE; #define EFI_RESOURCE_MEMORY_MAPPED_IO_PORT 0x00000004 #define EFI_RESOURCE_MEMORY_RESERVED 0x00000005 #define EFI_RESOURCE_IO_RESERVED 0x00000006 -#define EFI_RESOURCE_MAX_MEMORY_TYPE 0x00000007 +// +// BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is defined for unaccepted memory. +// But this defitinion has not been officially in the PI spec. Base +// on the code-first we define BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED at +// MdeModulePkg/Include/Pi/PrePiHob.h and update EFI_RESOURCE_MAX_MEMORY_TYPE +// to 8. After BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is officially published +// in PI spec, we will re-visit here. +// +// #define BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED 0x00000007 +#define EFI_RESOURCE_MAX_MEMORY_TYPE 0x00000008 /// /// A type of recount attribute type. From 9d4e0a889485efa2fd82ab48ddada17ee7baaed2 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:42 +0800 Subject: [PATCH 0257/1529] OvmfPkg: Use BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED defined in MdeModulePkg RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED is defined in MdeModulePkg. The files which use the definition are updated as well. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PeilessStartupLib/Hob.c | 5 ++--- OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 10 +++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/Library/PeilessStartupLib/Hob.c b/OvmfPkg/Library/PeilessStartupLib/Hob.c index 5fc84a8090..630ce445eb 100644 --- a/OvmfPkg/Library/PeilessStartupLib/Hob.c +++ b/OvmfPkg/Library/PeilessStartupLib/Hob.c @@ -20,10 +20,9 @@ #include #include #include +#include #include "PeilessStartupInternal.h" -#define EFI_RESOURCE_MEMORY_UNACCEPTED 7 - /** * Construct the HobList in SEC phase. * @@ -92,7 +91,7 @@ ConstructFwHobList ( // while (!END_OF_HOB_LIST (Hob)) { if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - if (Hob.ResourceDescriptor->ResourceType == EFI_RESOURCE_MEMORY_UNACCEPTED) { + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength; ResourceLength = Hob.ResourceDescriptor->ResourceLength; diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c index c6d7c8bb6e..797f880df0 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c @@ -20,11 +20,11 @@ #include #include #include +#include #include #include -#define ALIGNED_2MB_MASK 0x1fffff -#define EFI_RESOURCE_MEMORY_UNACCEPTED 7 +#define ALIGNED_2MB_MASK 0x1fffff /** This function will be called to accept pages. Only BSP accepts pages. @@ -211,7 +211,7 @@ ValidateHobList ( EFI_RESOURCE_MEMORY_MAPPED_IO_PORT, EFI_RESOURCE_MEMORY_RESERVED, EFI_RESOURCE_IO_RESERVED, - EFI_RESOURCE_MEMORY_UNACCEPTED + BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED }; if (VmmHobList == NULL) { @@ -387,7 +387,7 @@ ProcessHobList ( if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { DEBUG ((DEBUG_INFO, "\nResourceType: 0x%x\n", Hob.ResourceDescriptor->ResourceType)); - if (Hob.ResourceDescriptor->ResourceType == EFI_RESOURCE_MEMORY_UNACCEPTED) { + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", Hob.ResourceDescriptor->PhysicalStart)); DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); @@ -488,7 +488,7 @@ TransferTdxHobList ( ResourceType = Hob.ResourceDescriptor->ResourceType; ResourceAttribute = Hob.ResourceDescriptor->ResourceAttribute; - if (ResourceType == EFI_RESOURCE_MEMORY_UNACCEPTED) { + if (ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { ResourceType = EFI_RESOURCE_SYSTEM_MEMORY; ResourceAttribute |= (EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED); } From 999f4de61e849e5f8855266a3d4a6a08b74574a3 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:43 +0800 Subject: [PATCH 0258/1529] MdePkg: Add UEFI Unaccepted memory definition RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 Plase refer to: UEFI Spec v2.9 Table 7-5 Memory Type Usage before ExitBootServices() Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann Reviewed-by: Liming Gao Signed-off-by: Min Xu --- MdeModulePkg/Include/Pi/PrePiDxeCis.h | 25 +++++++++++++++++++++++++ MdePkg/Include/Pi/PiDxeCis.h | 10 +++++++++- MdePkg/Include/Uefi/UefiMultiPhase.h | 5 +++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 MdeModulePkg/Include/Pi/PrePiDxeCis.h diff --git a/MdeModulePkg/Include/Pi/PrePiDxeCis.h b/MdeModulePkg/Include/Pi/PrePiDxeCis.h new file mode 100644 index 0000000000..113ac37924 --- /dev/null +++ b/MdeModulePkg/Include/Pi/PrePiDxeCis.h @@ -0,0 +1,25 @@ +/** @file + Include file matches things in PI. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef MDE_MODULEPKG_PRE_PI_DXE_CIS_H_ +#define MDE_MODULEPKG_PRE_PI_DXE_CIS_H_ + +/// +/// A memory region that describes system memory that has not been accepted +/// by a corresponding call to the underlying isolation architecture. +/// +/// This memory region has not been defined in PI spec, so it is defined in +/// PrePiDxeCis.h. And it is defined in the format of captial letters +/// because only capital letters are allowed to be used for #define declarations. +/// +/// After this memory region is defined in PI spec, it should be a value in +/// EFI_GCD_MEMORY_TYPE in PiDxeCis.h. +/// +#define EFI_GCD_MEMORY_TYPE_UNACCEPTED 7 + +#endif diff --git a/MdePkg/Include/Pi/PiDxeCis.h b/MdePkg/Include/Pi/PiDxeCis.h index d0f2ed0e58..27b219aa3f 100644 --- a/MdePkg/Include/Pi/PiDxeCis.h +++ b/MdePkg/Include/Pi/PiDxeCis.h @@ -56,7 +56,15 @@ typedef enum { /// system. If all memory has the same reliability, then this bit is not used. /// EfiGcdMemoryTypeMoreReliable, - EfiGcdMemoryTypeMaximum + // /// + // /// A memory region that describes system memory that has not been accepted + // /// by a corresponding call to the underlying isolation architecture. + // /// + // /// Please be noted: + // /// EfiGcdMemoryTypeUnaccepted is defined in PrePiDxeCis.h because it has not been + // /// defined in PI spec. + // EfiGcdMemoryTypeUnaccepted, + EfiGcdMemoryTypeMaximum = 8 } EFI_GCD_MEMORY_TYPE; /// diff --git a/MdePkg/Include/Uefi/UefiMultiPhase.h b/MdePkg/Include/Uefi/UefiMultiPhase.h index 22bae43e36..7884913371 100644 --- a/MdePkg/Include/Uefi/UefiMultiPhase.h +++ b/MdePkg/Include/Uefi/UefiMultiPhase.h @@ -103,6 +103,11 @@ typedef enum { /// however it happens to also support byte-addressable non-volatility. /// EfiPersistentMemory, + /// + /// A memory region that describes system memory that has not been accepted + /// by a corresponding call to the underlying isolation architecture. + /// + EfiUnacceptedMemoryType, EfiMaxMemoryType } EFI_MEMORY_TYPE; From 9fd1cb39a331b7ad1020b6e9310494a0461d2fbd Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:44 +0800 Subject: [PATCH 0259/1529] MdeModulePkg: Update Dxe to handle unaccepted memory type RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 Unaccepted memory is a kind of new memory type, CoreInitializeGcdServices() and CoreGetMemoryMap() are updated to handle the unaccepted memory type. Ref: microsoft/mu_basecore@97e9c31 Cc: Jian J Wang Cc: Liming Gao Cc: Ray Ni Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Reviewed-by: Liming Gao Signed-off-by: Min Xu --- MdeModulePkg/Core/Dxe/Gcd/Gcd.c | 6 +++ MdeModulePkg/Core/Dxe/Mem/Page.c | 63 +++++++++++++++++++++++--------- 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c index 3763467bdb..792cd2e0af 100644 --- a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c +++ b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c @@ -8,6 +8,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include +#include #include "DxeMain.h" #include "Gcd.h" #include "Mem/HeapGuard.h" @@ -103,6 +105,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdMemoryTypeNames[] = { "MMIO ", // EfiGcdMemoryTypeMemoryMappedIo "PersisMem", // EfiGcdMemoryTypePersistent "MoreRelia", // EfiGcdMemoryTypeMoreReliable + "Unaccepte", // EFI_GCD_MEMORY_TYPE_UNACCEPTED "Unknown " // EfiGcdMemoryTypeMaximum }; @@ -2600,6 +2603,9 @@ CoreInitializeGcdServices ( case EFI_RESOURCE_MEMORY_RESERVED: GcdMemoryType = EfiGcdMemoryTypeReserved; break; + case BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED: + GcdMemoryType = EFI_GCD_MEMORY_TYPE_UNACCEPTED; + break; case EFI_RESOURCE_IO: GcdIoType = EfiGcdIoTypeIo; break; diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c index cc0b90ac0d..160289c1f9 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Page.c +++ b/MdeModulePkg/Core/Dxe/Mem/Page.c @@ -9,6 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "Imem.h" #include "HeapGuard.h" +#include // // Entry for tracking the memory regions for each memory type to coalesce similar memory types @@ -61,6 +62,7 @@ EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = { { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }, // EfiMemoryMappedIOPortSpace { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE, TRUE }, // EfiPalCode { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }, // EfiPersistentMemory + { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE, FALSE }, // EfiUnacceptedMemoryType { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE } // EfiMaxMemoryType }; @@ -68,22 +70,23 @@ EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = MAX_ALLOC_ADDRESS; EFI_PHYSICAL_ADDRESS mDefaultBaseAddress = MAX_ALLOC_ADDRESS; EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = { - { EfiReservedMemoryType, 0 }, - { EfiLoaderCode, 0 }, - { EfiLoaderData, 0 }, - { EfiBootServicesCode, 0 }, - { EfiBootServicesData, 0 }, - { EfiRuntimeServicesCode, 0 }, - { EfiRuntimeServicesData, 0 }, - { EfiConventionalMemory, 0 }, - { EfiUnusableMemory, 0 }, - { EfiACPIReclaimMemory, 0 }, - { EfiACPIMemoryNVS, 0 }, - { EfiMemoryMappedIO, 0 }, - { EfiMemoryMappedIOPortSpace, 0 }, - { EfiPalCode, 0 }, - { EfiPersistentMemory, 0 }, - { EfiMaxMemoryType, 0 } + { EfiReservedMemoryType, 0 }, + { EfiLoaderCode, 0 }, + { EfiLoaderData, 0 }, + { EfiBootServicesCode, 0 }, + { EfiBootServicesData, 0 }, + { EfiRuntimeServicesCode, 0 }, + { EfiRuntimeServicesData, 0 }, + { EfiConventionalMemory, 0 }, + { EfiUnusableMemory, 0 }, + { EfiACPIReclaimMemory, 0 }, + { EfiACPIMemoryNVS, 0 }, + { EfiMemoryMappedIO, 0 }, + { EfiMemoryMappedIOPortSpace, 0 }, + { EfiPalCode, 0 }, + { EfiPersistentMemory, 0 }, + { EFI_GCD_MEMORY_TYPE_UNACCEPTED, 0 }, + { EfiMaxMemoryType, 0 } }; // // Only used when load module at fixed address feature is enabled. True means the memory is alreay successfully allocated @@ -1286,7 +1289,7 @@ CoreInternalAllocatePages ( } if (((MemoryType >= EfiMaxMemoryType) && (MemoryType < MEMORY_TYPE_OEM_RESERVED_MIN)) || - (MemoryType == EfiConventionalMemory) || (MemoryType == EfiPersistentMemory)) + (MemoryType == EfiConventionalMemory) || (MemoryType == EfiPersistentMemory) || (MemoryType == EfiUnacceptedMemoryType)) { return EFI_INVALID_PARAMETER; } @@ -1961,6 +1964,32 @@ CoreGetMemoryMap ( MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size); } + if (MergeGcdMapEntry.GcdMemoryType == EFI_GCD_MEMORY_TYPE_UNACCEPTED) { + // + // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR, + // it will be recorded as page PhysicalStart and NumberOfPages. + // + ASSERT ((MergeGcdMapEntry.BaseAddress & EFI_PAGE_MASK) == 0); + ASSERT (((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1) & EFI_PAGE_MASK) == 0); + + // + // Create EFI_MEMORY_DESCRIPTOR for every Unaccepted GCD entries + // + MemoryMap->PhysicalStart = MergeGcdMapEntry.BaseAddress; + MemoryMap->VirtualStart = 0; + MemoryMap->NumberOfPages = RShiftU64 ((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1), EFI_PAGE_SHIFT); + MemoryMap->Attribute = MergeGcdMapEntry.Attributes | + (MergeGcdMapEntry.Capabilities & (EFI_MEMORY_RP | EFI_MEMORY_WP | EFI_MEMORY_XP | EFI_MEMORY_RO | + EFI_MEMORY_UC | EFI_MEMORY_UCE | EFI_MEMORY_WC | EFI_MEMORY_WT | EFI_MEMORY_WB)); + MemoryMap->Type = EfiUnacceptedMemoryType; + + // + // Check to see if the new Memory Map Descriptor can be merged with an + // existing descriptor if they are adjacent and have the same attributes + // + MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size); + } + if (Link == &mGcdMemorySpaceMap) { // // break loop when arrive at head. From b99525170ef6e89fa7abd436f0662970e10d6e6b Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:45 +0800 Subject: [PATCH 0260/1529] ShellPkg: Update shell command memmap to show unaccepted memory RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 ShellCommandRunMemMap() is updated to handle the case of unaccepted memory type. Cc: Ray Ni Cc: Zhichao Gao Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Acked-by: Zhichao Gao Signed-off-by: Min Xu --- .../Library/UefiShellDebug1CommandsLib/MemMap.c | 13 +++++++++++++ .../UefiShellDebug1CommandsLib.uni | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c index 72f3c58b09..a089953b28 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/MemMap.c @@ -26,6 +26,7 @@ STATIC CONST CHAR16 NameEfiACPIMemoryNVS[] = L"ACPIMemoryNVS"; STATIC CONST CHAR16 NameEfiMemoryMappedIO[] = L"MemoryMappedIO"; STATIC CONST CHAR16 NameEfiMemoryMappedIOPortSpace[] = L"MemoryMappedIOPortSpace"; STATIC CONST CHAR16 NameEfiPalCode[] = L"PalCode"; +STATIC CONST CHAR16 NameEfiUnacceptedMemoryType[] = L"Unaccepted"; // // Need short names for some memory types @@ -151,6 +152,8 @@ ShellCommandRunMemMap ( UINT64 UnusableMemoryPagesSize; UINT64 PalCodePages; UINT64 PalCodePagesSize; + UINT64 UnacceptedPages; + UINT64 UnacceptedPagesSize; UINT64 PersistentPages; UINT64 PersistentPagesSize; BOOLEAN Sfo; @@ -175,6 +178,7 @@ ShellCommandRunMemMap ( PalCodePages = 0; PersistentPages = 0; Size = 0; + UnacceptedPages = 0; Descriptors = NULL; ShellStatus = SHELL_SUCCESS; Status = EFI_SUCCESS; @@ -303,6 +307,11 @@ ShellCommandRunMemMap ( TotalPages += Walker->NumberOfPages; PalCodePages += Walker->NumberOfPages; break; + case EfiUnacceptedMemoryType: + ShellPrintHiiEx (-1, -1, NULL, (EFI_STRING_ID)(!Sfo ? STRING_TOKEN (STR_MEMMAP_LIST_ITEM) : STRING_TOKEN (STR_MEMMAP_LIST_ITEM_SFO)), gShellDebug1HiiHandle, NameEfiUnacceptedMemoryType, Walker->PhysicalStart, Walker->PhysicalStart+MultU64x64 (SIZE_4KB, Walker->NumberOfPages)-1, Walker->NumberOfPages, Walker->Attribute); + TotalPages += Walker->NumberOfPages; + UnacceptedPages += Walker->NumberOfPages; + break; default: // // Shell Spec defines the SFO format. @@ -335,6 +344,7 @@ ShellCommandRunMemMap ( MmioSpacePagesSize = MultU64x64 (SIZE_4KB, MmioSpacePages); MmioPortPagesSize = MultU64x64 (SIZE_4KB, MmioPortPages); PalCodePagesSize = MultU64x64 (SIZE_4KB, PalCodePages); + UnacceptedPagesSize = MultU64x64 (SIZE_4KB, UnacceptedPages); PersistentPagesSize = MultU64x64 (SIZE_4KB, PersistentPages); UnusableMemoryPagesSize = MultU64x64 (SIZE_4KB, UnusableMemoryPages); if (!Sfo) { @@ -368,6 +378,8 @@ ShellCommandRunMemMap ( MmioPortPagesSize, PalCodePages, PalCodePagesSize, + UnacceptedPages, + UnacceptedPagesSize, AvailPages, AvailPagesSize, PersistentPages, @@ -422,6 +434,7 @@ ShellCommandRunMemMap ( AcpiReclaimPagesSize, AcpiNvsPagesSize, PalCodePagesSize, + UnacceptedPagesSize, PersistentPagesSize ); } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni index 6693be26e6..b1d239ed37 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni @@ -88,13 +88,14 @@ " MMIO : %,14ld Pages (%,ld Bytes)\r\n" " MMIO_Port : %,14ld Pages (%,ld Bytes)\r\n" " PalCode : %,14ld Pages (%,ld Bytes)\r\n" + " Unaccepted: %,14ld Pages (%,ld Bytes)\r\n" " Available : %,14ld Pages (%,ld Bytes)\r\n" " Persistent: %,14ld Pages (%,ld Bytes)\r\n" #string STR_MEMMAP_LIST_SUMM_OTHER #language en-US " %08x : %,14ld Pages (%,ld Bytes)\r\n" #string STR_MEMMAP_LIST_SUMM2 #language en-US " -------------- \r\n" "Total Memory: %,14ld MB (%,ld Bytes)\r\n" #string STR_MEMMAP_LIST_ITEM_SFO #language en-US "MemoryMap,"%s","%LX","%LX","%LX","%LX"\r\n" -#string STR_MEMMAP_LIST_SUMM_SFO #language en-US "MemoryMapSummary,"%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld"\r\n" +#string STR_MEMMAP_LIST_SUMM_SFO #language en-US "MemoryMapSummary,"%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld","%Ld", "%Ld"\r\n" #string STR_EFI_COMPRESS_FAIL #language en-US "Unable to compress: %r.\r\n" #string STR_EFI_DECOMPRESS_FAIL #language en-US "Unable to decompress: %r.\r\n" From 23e31388fb1b234383c428ae2342d852d6ea7580 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:46 +0800 Subject: [PATCH 0261/1529] OvmfPkg: Introduce lazy accept in PlatformInitLib and PlatformPei RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 There are below major changes in PlatformInitLib/PlatformPei 1. ProcessHobList The unaccepted memory is accepted if it is under 4G address. Please be noted: in current stage, we only accept the memory under 4G. We will re-visit here in the future when on-demand accept memory is required. 2. TransferTdxHobList Transfer the unaccepted memory hob to EFI_RESOURCE_SYSTEM_MEMORY hob if it is accepted. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 88 ++++++++++++++++++--- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 2 + 2 files changed, 81 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c index 797f880df0..acd114e38e 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c @@ -7,6 +7,7 @@ **/ +#include #include #include #include @@ -25,6 +26,7 @@ #include #define ALIGNED_2MB_MASK 0x1fffff +#define MEGABYTE_SHIFT 20 /** This function will be called to accept pages. Only BSP accepts pages. @@ -375,11 +377,15 @@ ProcessHobList ( EFI_STATUS Status; EFI_PEI_HOB_POINTERS Hob; EFI_PHYSICAL_ADDRESS PhysicalEnd; + UINT64 ResourceLength; + UINT64 AccumulateAcceptedMemory; Status = EFI_SUCCESS; ASSERT (VmmHobList != NULL); Hob.Raw = (UINT8 *)VmmHobList; + AccumulateAcceptedMemory = 0; + // // Parse the HOB list until end of list or matching type is found. // @@ -393,7 +399,15 @@ ProcessHobList ( DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); - PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength; + PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength; + ResourceLength = Hob.ResourceDescriptor->ResourceLength; + + if (Hob.ResourceDescriptor->PhysicalStart >= BASE_4GB) { + // + // In current stage, we only accept the memory under 4G + // + break; + } Status = BspAcceptMemoryResourceRange ( Hob.ResourceDescriptor->PhysicalStart, @@ -402,6 +416,8 @@ ProcessHobList ( if (EFI_ERROR (Status)) { break; } + + AccumulateAcceptedMemory += ResourceLength; } } @@ -460,6 +476,60 @@ ProcessTdxHobList ( return Status; } +/** + * Build ResourceDescriptorHob for the unaccepted memory region. + * This memory region may be splitted into 2 parts because of lazy accept. + * + * @param Hob Point to the EFI_HOB_RESOURCE_DESCRIPTOR + * @return VOID + */ +VOID +BuildResourceDescriptorHobForUnacceptedMemory ( + IN EFI_HOB_RESOURCE_DESCRIPTOR *Hob + ) +{ + EFI_PHYSICAL_ADDRESS PhysicalStart; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + UINT64 ResourceLength; + EFI_RESOURCE_TYPE ResourceType; + EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute; + UINT64 MaxAcceptedMemoryAddress; + + ASSERT (Hob->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED); + + ResourceType = BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED; + ResourceAttribute = Hob->ResourceAttribute; + PhysicalStart = Hob->PhysicalStart; + ResourceLength = Hob->ResourceLength; + PhysicalEnd = PhysicalStart + ResourceLength; + + // + // In the first stage of lazy-accept, all the memory under 4G will be accepted. + // The memory above 4G will not be accepted. + // + MaxAcceptedMemoryAddress = BASE_4GB; + + if (PhysicalEnd <= MaxAcceptedMemoryAddress) { + // + // This memory region has been accepted. + // + ResourceType = EFI_RESOURCE_SYSTEM_MEMORY; + ResourceAttribute |= (EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED); + } else if (PhysicalStart >= MaxAcceptedMemoryAddress) { + // + // This memory region hasn't been accepted. + // So keep the ResourceType and ResourceAttribute unchange. + // + } + + BuildResourceDescriptorHob ( + ResourceType, + ResourceAttribute, + PhysicalStart, + ResourceLength + ); +} + /** Transfer the incoming HobList for the TD to the final HobList for Dxe. The Hobs transferred in this function are ResourceDescriptor hob and @@ -489,16 +559,16 @@ TransferTdxHobList ( ResourceAttribute = Hob.ResourceDescriptor->ResourceAttribute; if (ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { - ResourceType = EFI_RESOURCE_SYSTEM_MEMORY; - ResourceAttribute |= (EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED); + BuildResourceDescriptorHobForUnacceptedMemory (Hob.ResourceDescriptor); + } else { + BuildResourceDescriptorHob ( + ResourceType, + ResourceAttribute, + Hob.ResourceDescriptor->PhysicalStart, + Hob.ResourceDescriptor->ResourceLength + ); } - BuildResourceDescriptorHob ( - ResourceType, - ResourceAttribute, - Hob.ResourceDescriptor->PhysicalStart, - Hob.ResourceDescriptor->ResourceLength - ); break; case EFI_HOB_TYPE_MEMORY_ALLOCATION: BuildMemoryAllocationHob ( diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index ae217d0242..b8feae4309 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -42,6 +42,8 @@ Module Name: #include +#define MEGABYTE_SHIFT 20 + VOID EFIAPI PlatformQemuUc32BaseInitialization ( From afb70505f251b9e8a9886d8bfa73e1aa5568a19f Mon Sep 17 00:00:00 2001 From: Jiaqi Gao Date: Tue, 1 Nov 2022 13:13:47 +0800 Subject: [PATCH 0262/1529] MdePkg: The prototype definition of EdkiiMemoryAcceptProtocol RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 EdkiiMemoryAcceptProtocol is defined in MdePkg, the method AcceptMemory() can be called when memory needs to be accepted. EdkiiMemoryAcceptProtocol can be installed by architecture-specific drivers such as TdxDxe. This allows different isolation architectures to realize their own low-level methods to accept memory. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Reviewed-by: Liming Gao Signed-off-by: Jiaqi Gao Signed-off-by: Min Xu --- MdePkg/Include/Protocol/MemoryAccept.h | 37 ++++++++++++++++++++++++++ MdePkg/MdePkg.dec | 3 +++ 2 files changed, 40 insertions(+) create mode 100644 MdePkg/Include/Protocol/MemoryAccept.h diff --git a/MdePkg/Include/Protocol/MemoryAccept.h b/MdePkg/Include/Protocol/MemoryAccept.h new file mode 100644 index 0000000000..f7646e04d8 --- /dev/null +++ b/MdePkg/Include/Protocol/MemoryAccept.h @@ -0,0 +1,37 @@ +/** @file + The file provides the protocol to provide interface to accept memory. + + Copyright (c) 2021 - 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MEMORY_ACCEPT_H_ +#define MEMORY_ACCEPT_H_ + +#define EDKII_MEMORY_ACCEPT_PROTOCOL_GUID \ + { 0x38c74800, 0x5590, 0x4db4, { 0xa0, 0xf3, 0x67, 0x5d, 0x9b, 0x8e, 0x80, 0x26 } }; + +typedef struct _EDKII_MEMORY_ACCEPT_PROTOCOL EDKII_MEMORY_ACCEPT_PROTOCOL; + +/** + @param This A pointer to a EDKII_MEMORY_ACCEPT_PROTOCOL. +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_ACCEPT_MEMORY)( + IN EDKII_MEMORY_ACCEPT_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS StartAddress, + IN UINTN Size + ); + +/// +/// The EDKII_MEMORY_ACCEPT_PROTOCOL provides the ability for memory services +/// to accept memory. +/// +struct _EDKII_MEMORY_ACCEPT_PROTOCOL { + EDKII_ACCEPT_MEMORY AcceptMemory; +}; + +extern EFI_GUID gEdkiiMemoryAcceptProtocolGuid; + +#endif diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 4c81cbd75a..ba287d9b3c 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -1023,6 +1023,9 @@ gEfiPeiDelayedDispatchPpiGuid = { 0x869c711d, 0x649c, 0x44fe, { 0x8b, 0x9e, 0x2c, 0xbb, 0x29, 0x11, 0xc3, 0xe6 }} [Protocols] + ## Include/Protocol/MemoryAccept.h + gEdkiiMemoryAcceptProtocolGuid = { 0x38c74800, 0x5590, 0x4db4, { 0xa0, 0xf3, 0x67, 0x5d, 0x9b, 0x8e, 0x80, 0x26 }} + ## Include/Protocol/Pcd.h gPcdProtocolGuid = { 0x11B34006, 0xD85B, 0x4D0A, { 0xA2, 0x90, 0xD5, 0xA5, 0x71, 0x31, 0x0E, 0xF7 }} From 5eac08507fe803d0cdcd4dc74b8520e3dab9a31e Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:48 +0800 Subject: [PATCH 0263/1529] OvmfPkg: Realize EdkiiMemoryAcceptProtocol in TdxDxe RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 Memory usage may exceed the amount accepted at the begining (SEC), TDVF needs to accept memory dynamically when OUT_OF_RESOURCE occurs. Another usage is in SetOrClearSharedBit. If a memory region is changed from shared to private, it must be accepted again. EdkiiMemoryAcceptProtocol is defined in MdePkg and is implementated / installed in TdxDxe for Intel TDX memory acceptance. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Gerd Hoffmann Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/TdxDxe/TdxDxe.c | 103 ++++++++++++++++++++++++++++++++++++++ OvmfPkg/TdxDxe/TdxDxe.inf | 2 + 2 files changed, 105 insertions(+) diff --git a/OvmfPkg/TdxDxe/TdxDxe.c b/OvmfPkg/TdxDxe/TdxDxe.c index 05cfb597dc..30732f421b 100644 --- a/OvmfPkg/TdxDxe/TdxDxe.c +++ b/OvmfPkg/TdxDxe/TdxDxe.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -32,6 +33,95 @@ #include #include +#define ALIGNED_2MB_MASK 0x1fffff +EFI_HANDLE mTdxDxeHandle = NULL; + +EFI_STATUS +EFIAPI +TdxMemoryAccept ( + IN EDKII_MEMORY_ACCEPT_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS StartAddress, + IN UINTN Size + ) +{ + EFI_STATUS Status; + UINT32 AcceptPageSize; + UINT64 StartAddress1; + UINT64 StartAddress2; + UINT64 StartAddress3; + UINT64 Length1; + UINT64 Length2; + UINT64 Length3; + UINT64 Pages; + + AcceptPageSize = FixedPcdGet32 (PcdTdxAcceptPageSize); + StartAddress1 = 0; + StartAddress2 = 0; + StartAddress3 = 0; + Length1 = 0; + Length2 = 0; + Length3 = 0; + + if (Size == 0) { + return EFI_SUCCESS; + } + + if (ALIGN_VALUE (StartAddress, SIZE_2MB) != StartAddress) { + StartAddress1 = StartAddress; + Length1 = ALIGN_VALUE (StartAddress, SIZE_2MB) - StartAddress; + if (Length1 >= Size) { + Length1 = Size; + } + + StartAddress += Length1; + Size -= Length1; + } + + if (Size > SIZE_2MB) { + StartAddress2 = StartAddress; + Length2 = Size & ~(UINT64)ALIGNED_2MB_MASK; + StartAddress += Length2; + Size -= Length2; + } + + if (Size) { + StartAddress3 = StartAddress; + Length3 = Size; + } + + Status = EFI_SUCCESS; + if (Length1 > 0) { + Pages = Length1 / SIZE_4KB; + Status = TdAcceptPages (StartAddress1, Pages, SIZE_4KB); + if (EFI_ERROR (Status)) { + return Status; + } + } + + if (Length2 > 0) { + Pages = Length2 / AcceptPageSize; + Status = TdAcceptPages (StartAddress2, Pages, AcceptPageSize); + if (EFI_ERROR (Status)) { + return Status; + } + } + + if (Length3 > 0) { + Pages = Length3 / SIZE_4KB; + Status = TdAcceptPages (StartAddress3, Pages, SIZE_4KB); + ASSERT (!EFI_ERROR (Status)); + if (EFI_ERROR (Status)) { + return Status; + } + } + + return Status; +} + +EDKII_MEMORY_ACCEPT_PROTOCOL mMemoryAcceptProtocol = { + TdxMemoryAccept +}; + VOID SetPcdSettings ( EFI_HOB_PLATFORM_INFO *PlatformInfoHob @@ -279,6 +369,19 @@ TdxDxeEntryPoint ( NULL ); + // + // Install MemoryAccept protocol for TDX + // + Status = gBS->InstallProtocolInterface ( + &mTdxDxeHandle, + &gEdkiiMemoryAcceptProtocolGuid, + EFI_NATIVE_INTERFACE, + &mMemoryAcceptProtocol + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Install EdkiiMemoryAcceptProtocol failed.\n")); + } + // // Call TDINFO to get actual number of cpus in domain // diff --git a/OvmfPkg/TdxDxe/TdxDxe.inf b/OvmfPkg/TdxDxe/TdxDxe.inf index 3ce8a5c32c..9793562884 100644 --- a/OvmfPkg/TdxDxe/TdxDxe.inf +++ b/OvmfPkg/TdxDxe/TdxDxe.inf @@ -52,6 +52,7 @@ gEfiAcpiTableProtocolGuid ## CONSUMES gEfiMpInitLibMpDepProtocolGuid gEfiMpInitLibUpDepProtocolGuid + gEdkiiMemoryAcceptProtocolGuid [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdPciIoBase @@ -69,3 +70,4 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdTdxSharedBitMask gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved + gUefiOvmfPkgTokenSpaceGuid.PcdTdxAcceptPageSize From 0433c8247e2e84f3ddabcf82fdb0763b98f04f3f Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 1 Nov 2022 13:13:49 +0800 Subject: [PATCH 0264/1529] OvmfPkg: Call gEdkiiMemoryAcceptProtocolGuid to accept pages RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 After EdkiiMemoryAcceptProtocol is implemented in TdxDxe driver, we can call it to accept pages in DXE phase. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Acked-by: Gerd Hoffmann Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- .../BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf | 3 +++ .../Library/BaseMemEncryptTdxLib/MemoryEncryption.c | 12 +++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf b/OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf index a8abfec12f..11768825f8 100644 --- a/OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf +++ b/OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf @@ -42,3 +42,6 @@ [Pcd] gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr + +[Protocols] + gEdkiiMemoryAcceptProtocolGuid diff --git a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c index 9d11c6e4df..503f626d75 100644 --- a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c +++ b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c @@ -27,6 +27,8 @@ #include "VirtualMemory.h" #include #include +#include +#include #include typedef enum { @@ -517,8 +519,9 @@ SetOrClearSharedBit ( IN UINT64 Length ) { - UINT64 AddressEncMask; - UINT64 Status; + UINT64 AddressEncMask; + UINT64 Status; + EDKII_MEMORY_ACCEPT_PROTOCOL *MemoryAcceptProtocol; AddressEncMask = GetMemEncryptionAddressMask (); @@ -539,7 +542,10 @@ SetOrClearSharedBit ( // If changing shared to private, must accept-page again // if (Mode == ClearSharedBit) { - TdAcceptPages (PhysicalAddress, Length / EFI_PAGE_SIZE, EFI_PAGE_SIZE); + Status = gBS->LocateProtocol (&gEdkiiMemoryAcceptProtocolGuid, NULL, (VOID **)&MemoryAcceptProtocol); + ASSERT (!EFI_ERROR (Status)); + Status = MemoryAcceptProtocol->AcceptMemory (MemoryAcceptProtocol, PhysicalAddress, Length); + ASSERT (!EFI_ERROR (Status)); } DEBUG (( From 064c89996d8700a33a8deae45cd4f780c78545f6 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 28 Oct 2022 08:41:34 -0700 Subject: [PATCH 0265/1529] UnitTestFrameworkPkg: Support FILE_GUID override in host based unit tests REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4129 Always use the module name with FILE_GUID to generate the host-based unit test executable image and symbol files. This allows the same host-based unit test INF file to be used more than once in a single DSC file with FILE_GUID override. This is valuable when there is a requirement to run the same host-based unit test with different PCD settings, library mappings, or build options. Cc: Michael Kubacki Cc: Sean Brogan Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki Reviewed-by: Sean Brogan --- UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 4dd8d4ac67..f249813713 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -30,7 +30,7 @@ # # MSFT # - MSFT:*_*_*_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /IGNORE:4001 /NOLOGO /SUBSYSTEM:CONSOLE /DEBUG /STACK:0x40000,0x40000 /NODEFAULTLIB:libcmt.lib libcmtd.lib + MSFT:*_*_*_DLINK_FLAGS == /out:"$(BIN_DIR)\$(MODULE_NAME_GUID).exe" /pdb:"$(BIN_DIR)\$(MODULE_NAME_GUID).pdb" /IGNORE:4001 /NOLOGO /SUBSYSTEM:CONSOLE /DEBUG /STACK:0x40000,0x40000 /NODEFAULTLIB:libcmt.lib libcmtd.lib MSFT:*_*_IA32_DLINK_FLAGS = /MACHINE:I386 MSFT:*_*_X64_DLINK_FLAGS = /MACHINE:AMD64 @@ -47,8 +47,8 @@ # # GCC # - GCC:*_*_IA32_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m32 -no-pie - GCC:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m64 -no-pie + GCC:*_*_IA32_DLINK_FLAGS == -o $(BIN_DIR)/$(MODULE_NAME_GUID) -m32 -no-pie + GCC:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(MODULE_NAME_GUID) -m64 -no-pie GCC:*_*_*_DLINK2_FLAGS == -lgcov # @@ -56,10 +56,10 @@ # XCODE:*_*_IA32_DLINK_PATH == gcc XCODE:*_*_IA32_CC_FLAGS = -I$(WORKSPACE)/EmulatorPkg/Unix/Host/X11IncludeHack - XCODE:*_*_IA32_DLINK_FLAGS == -arch i386 -o $(BIN_DIR)/Host -L/usr/X11R6/lib -lXext -lX11 -framework Carbon + XCODE:*_*_IA32_DLINK_FLAGS == -arch i386 -o $(BIN_DIR)/$(MODULE_NAME_GUID) -L/usr/X11R6/lib -lXext -lX11 -framework Carbon XCODE:*_*_IA32_ASM_FLAGS == -arch i386 -g XCODE:*_*_X64_DLINK_PATH == gcc - XCODE:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/Host -L/usr/X11R6/lib -lXext -lX11 -framework Carbon -Wl,-no_pie + XCODE:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(MODULE_NAME_GUID) -L/usr/X11R6/lib -lXext -lX11 -framework Carbon -Wl,-no_pie XCODE:*_*_X64_ASM_FLAGS == -g XCODE:*_*_X64_CC_FLAGS = -O0 -target x86_64-apple-darwin -I$(WORKSPACE)/EmulatorPkg/Unix/Host/X11IncludeHack "-DEFIAPI=__attribute__((ms_abi))" From c59c7b0879b36060bdf85bc643be69223115639c Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 2 Nov 2022 07:40:14 +0800 Subject: [PATCH 0266/1529] pip-requirements.txt: Bump pytool extensions and library Fixes edk2 CI failure due to VM images being updated to Python 3.11 and the old pip modules not being compatible with Python 3.11. Updates the following pip modules: - edk2-pytool-library from 0.11.2 to 0.11.6 - edk2-pytool-extensions from 0.16 to 0.19.1 Needed to fix an issue with Python 3.11 compatibility. Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Cc: Chasel Chiu Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Liming Gao --- pip-requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 40e9ad72ee..74d1bb35f2 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -12,7 +12,7 @@ # https://www.python.org/dev/peps/pep-0440/#version-specifiers ## -edk2-pytool-library==0.11.2 -edk2-pytool-extensions~=0.16.0 +edk2-pytool-library==0.11.6 +edk2-pytool-extensions~=0.19.1 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 From adc99bbdd1be05c6357b7c18973f96086e5c7fb3 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 28 Oct 2022 11:58:24 -0700 Subject: [PATCH 0267/1529] CryptoPkg/Test: Simplify BaseCryptLib host based unit tests REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4130 Remove TestBaseCryptLibHostAccel.inf and instead use FILE_GUID override in DSC file to run the same unit test INF against OpensslLibFull.inf and OpensslLibFullAccel.inf Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Test/CryptoPkgHostUnitTest.dsc | 10 +++- .../TestBaseCryptLibHostAccel.inf | 56 ------------------- 2 files changed, 7 insertions(+), 59 deletions(-) delete mode 100644 CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf diff --git a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc index 369a1cb699..3ed3e9b75d 100644 --- a/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc +++ b/CryptoPkg/Test/CryptoPkgHostUnitTest.dsc @@ -20,7 +20,6 @@ !include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc [LibraryClasses] - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/UnitTestHostBaseCryptLib.inf MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf @@ -33,8 +32,13 @@ # # Build HOST_APPLICATION that tests the SampleUnitTest # - CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf - CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf { + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf { + + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFull.inf + } + CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHost.inf { + + FILE_GUID = 3604CCB8-138C-488F-8045-18704F73E734 OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf } diff --git a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf b/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf deleted file mode 100644 index 9d0fcfd357..0000000000 --- a/CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLibHostAccel.inf +++ /dev/null @@ -1,56 +0,0 @@ -## @file -# Host-based UnitTest for BaseCryptLib -# -# Copyright (c) Microsoft Corporation.
-# Copyright (c) 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseCryptLibUnitTestHostAccel - FILE_GUID = B1AED64E-B53A-4D69-B0BA-60EEDAC47A6B - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - UnitTestMain.c - BaseCryptLibUnitTests.c - TestBaseCryptLib.h - HashTests.c - HmacTests.c - BlockCipherTests.c - RsaTests.c - RsaPkcs7Tests.c - Pkcs5Pbkdf2Tests.c - AuthenticodeTests.c - TSTests.c - DhTests.c - RandTests.c - Pkcs7EkuTests.c - OaepEncryptTests.c - RsaPssTests.c - ParallelhashTests.c - HkdfTests.c - AeadAesGcmTests.c - BnTests.c - EcTests.c - X509Tests.c - -[Packages] - MdePkg/MdePkg.dec - CryptoPkg/CryptoPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - BaseCryptLib - UnitTestLib - MmServicesTableLib - SynchronizationLib From f5eb03ea00b5c883484733bd195370cfb7734522 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Sat, 1 Oct 2022 23:09:54 +0800 Subject: [PATCH 0268/1529] UefiCpuPkg/SmmCpuFeaturesLib: Rename the common C file BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code Rename SmmCpuFeaturesLiCommon.c to IntelSmmCpuFeaturesLib, because it was developed specifically for Intel implementation. The code that can be shared by other archs or vendors will be stripped away and put in the common file in the next patch. Signed-off-by: Abner Chang Cc: Abdul Lateef Attar Cc: Garrett Kirkendall Cc: Paul Grimes Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Reviewed-by: Ray Ni --- .../{SmmCpuFeaturesLibCommon.c => IntelSmmCpuFeaturesLib.c} | 0 UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 2 +- UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf | 2 +- .../Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename UefiCpuPkg/Library/SmmCpuFeaturesLib/{SmmCpuFeaturesLibCommon.c => IntelSmmCpuFeaturesLib.c} (100%) diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c similarity index 100% rename from UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c rename to UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf index 7b5cef9700..6254a14698 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf @@ -18,8 +18,8 @@ [Sources] CpuFeaturesLib.h + IntelSmmCpuFeaturesLib.c SmmCpuFeaturesLib.c - SmmCpuFeaturesLibCommon.c SmmCpuFeaturesLibNoStm.c TraditionalMmCpuFeaturesLib.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf index 85214ee31c..d64d8e66b3 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf @@ -19,7 +19,7 @@ [Sources] CpuFeaturesLib.h - SmmCpuFeaturesLibCommon.c + IntelSmmCpuFeaturesLib.c SmmStm.c SmmStm.h TraditionalMmCpuFeaturesLib.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf index 3eacab48db..5935b3e1fd 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf @@ -20,8 +20,8 @@ [Sources] CpuFeaturesLib.h + IntelSmmCpuFeaturesLib.c StandaloneMmCpuFeaturesLib.c - SmmCpuFeaturesLibCommon.c SmmCpuFeaturesLibNoStm.c [Packages] From 86df593514001a579b236ca33ca1d5ab5738573d Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 31 Oct 2022 10:37:49 +0800 Subject: [PATCH 0269/1529] UefiCpuPkg/SmmCpuFeaturesLib: Abstract arch dependent code BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code This change stripped away the code that can be shared with other archs or vendors from Intel implementation and put in to the common file, leaves the Intel X86 implementation in the IntelSmmCpuFeatureLib. Also updates the header file and INF file. Signed-off-by: Abner Chang Cc: Abdul Lateef Attar Cc: Garrett Kirkendall Cc: Paul Grimes Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Reviewed-by: Ray Ni --- .../SmmCpuFeaturesLib/CpuFeaturesLib.h | 6 + .../IntelSmmCpuFeaturesLib.c | 207 +---------------- .../SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 1 + .../SmmCpuFeaturesLibCommon.c | 216 ++++++++++++++++++ .../SmmCpuFeaturesLibStm.inf | 1 + .../StandaloneMmCpuFeaturesLib.inf | 1 + 6 files changed, 227 insertions(+), 205 deletions(-) create mode 100644 UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h index 8a1c2adc5c..fd3e902547 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h @@ -9,6 +9,12 @@ #ifndef CPU_FEATURES_LIB_H_ #define CPU_FEATURES_LIB_H_ +#include +#include +#include +#include +#include + /** Performs library initialization. diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c index 75a0ec8e94..d5eaaa7a99 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c @@ -7,16 +7,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include -#include -#include +#include "CpuFeaturesLib.h" + #include -#include -#include -#include #include #include -#include "CpuFeaturesLib.h" // // Machine Specific Registers (MSRs) @@ -287,64 +282,6 @@ SmmCpuFeaturesInitializeProcessor ( FinishSmmCpuFeaturesInitializeProcessor (); } -/** - This function updates the SMRAM save state on the currently executing CPU - to resume execution at a specific address after an RSM instruction. This - function must evaluate the SMRAM save state to determine the execution mode - the RSM instruction resumes and update the resume execution address with - either NewInstructionPointer32 or NewInstructionPoint. The auto HALT restart - flag in the SMRAM save state must always be cleared. This function returns - the value of the instruction pointer from the SMRAM save state that was - replaced. If this function returns 0, then the SMRAM save state was not - modified. - - This function is called during the very first SMI on each CPU after - SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode - to signal that the SMBASE of each CPU has been updated before the default - SMBASE address is used for the first SMI to the next CPU. - - @param[in] CpuIndex The index of the CPU to hook. The value - must be between 0 and the NumberOfCpus - field in the System Management System Table - (SMST). - @param[in] CpuState Pointer to SMRAM Save State Map for the - currently executing CPU. - @param[in] NewInstructionPointer32 Instruction pointer to use if resuming to - 32-bit execution mode from 64-bit SMM. - @param[in] NewInstructionPointer Instruction pointer to use if resuming to - same execution mode as SMM. - - @retval 0 This function did modify the SMRAM save state. - @retval > 0 The original instruction pointer value from the SMRAM save state - before it was replaced. -**/ -UINT64 -EFIAPI -SmmCpuFeaturesHookReturnFromSmm ( - IN UINTN CpuIndex, - IN SMRAM_SAVE_STATE_MAP *CpuState, - IN UINT64 NewInstructionPointer32, - IN UINT64 NewInstructionPointer - ) -{ - return 0; -} - -/** - Hook point in normal execution mode that allows the one CPU that was elected - as monarch during System Management Mode initialization to perform additional - initialization actions immediately after all of the CPUs have processed their - first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE - into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm(). -**/ -VOID -EFIAPI -SmmCpuFeaturesSmmRelocationComplete ( - VOID - ) -{ -} - /** Determines if MTRR registers must be configured to set SMRAM cache-ability when executing in System Management Mode. @@ -414,48 +351,6 @@ SmmCpuFeaturesRendezvousEntry ( } } -/** - Processor specific hook point each time a CPU exits System Management Mode. - - @param[in] CpuIndex The index of the CPU that is exiting SMM. The value must - be between 0 and the NumberOfCpus field in the System - Management System Table (SMST). -**/ -VOID -EFIAPI -SmmCpuFeaturesRendezvousExit ( - IN UINTN CpuIndex - ) -{ -} - -/** - Check to see if an SMM register is supported by a specified CPU. - - @param[in] CpuIndex The index of the CPU to check for SMM register support. - The value must be between 0 and the NumberOfCpus field - in the System Management System Table (SMST). - @param[in] RegName Identifies the SMM register to check for support. - - @retval TRUE The SMM register specified by RegName is supported by the CPU - specified by CpuIndex. - @retval FALSE The SMM register specified by RegName is not supported by the - CPU specified by CpuIndex. -**/ -BOOLEAN -EFIAPI -SmmCpuFeaturesIsSmmRegisterSupported ( - IN UINTN CpuIndex, - IN SMM_REG_NAME RegName - ) -{ - if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName == SmmRegFeatureControl)) { - return TRUE; - } - - return FALSE; -} - /** Returns the current value of the SMM register for the specified CPU. If the SMM register is not supported, then 0 is returned. @@ -505,101 +400,3 @@ SmmCpuFeaturesSetSmmRegister ( AsmWriteMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL, Value); } } - -/** - Read an SMM Save State register on the target processor. If this function - returns EFI_UNSUPPORTED, then the caller is responsible for reading the - SMM Save Sate register. - - @param[in] CpuIndex The index of the CPU to read the SMM Save State. The - value must be between 0 and the NumberOfCpus field in - the System Management System Table (SMST). - @param[in] Register The SMM Save State register to read. - @param[in] Width The number of bytes to read from the CPU save state. - @param[out] Buffer Upon return, this holds the CPU register value read - from the save state. - - @retval EFI_SUCCESS The register was read from Save State. - @retval EFI_INVALID_PARAMETER Buffer is NULL. - @retval EFI_UNSUPPORTED This function does not support reading Register. - -**/ -EFI_STATUS -EFIAPI -SmmCpuFeaturesReadSaveStateRegister ( - IN UINTN CpuIndex, - IN EFI_SMM_SAVE_STATE_REGISTER Register, - IN UINTN Width, - OUT VOID *Buffer - ) -{ - return EFI_UNSUPPORTED; -} - -/** - Writes an SMM Save State register on the target processor. If this function - returns EFI_UNSUPPORTED, then the caller is responsible for writing the - SMM Save Sate register. - - @param[in] CpuIndex The index of the CPU to write the SMM Save State. The - value must be between 0 and the NumberOfCpus field in - the System Management System Table (SMST). - @param[in] Register The SMM Save State register to write. - @param[in] Width The number of bytes to write to the CPU save state. - @param[in] Buffer Upon entry, this holds the new CPU register value. - - @retval EFI_SUCCESS The register was written to Save State. - @retval EFI_INVALID_PARAMETER Buffer is NULL. - @retval EFI_UNSUPPORTED This function does not support writing Register. -**/ -EFI_STATUS -EFIAPI -SmmCpuFeaturesWriteSaveStateRegister ( - IN UINTN CpuIndex, - IN EFI_SMM_SAVE_STATE_REGISTER Register, - IN UINTN Width, - IN CONST VOID *Buffer - ) -{ - return EFI_UNSUPPORTED; -} - -/** - This function is hook point called after the gEfiSmmReadyToLockProtocolGuid - notification is completely processed. -**/ -VOID -EFIAPI -SmmCpuFeaturesCompleteSmmReadyToLock ( - VOID - ) -{ -} - -/** - This API provides a method for a CPU to allocate a specific region for storing page tables. - - This API can be called more once to allocate memory for page tables. - - Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the - allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL - is returned. If there is not enough memory remaining to satisfy the request, then NULL is - returned. - - This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM. - - @param Pages The number of 4 KB pages to allocate. - - @return A pointer to the allocated buffer for page tables. - @retval NULL Fail to allocate a specific region for storing page tables, - Or there is no preference on where the page tables are allocated in SMRAM. - -**/ -VOID * -EFIAPI -SmmCpuFeaturesAllocatePageTableMemory ( - IN UINTN Pages - ) -{ - return NULL; -} diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf index 6254a14698..9ac7dde78f 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf @@ -20,6 +20,7 @@ CpuFeaturesLib.h IntelSmmCpuFeaturesLib.c SmmCpuFeaturesLib.c + SmmCpuFeaturesLibCommon.c SmmCpuFeaturesLibNoStm.c TraditionalMmCpuFeaturesLib.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c new file mode 100644 index 0000000000..7777e52740 --- /dev/null +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c @@ -0,0 +1,216 @@ +/** @file +Implementation shared across all library instances. + +Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include + +#include "CpuFeaturesLib.h" + +/** + This function updates the SMRAM save state on the currently executing CPU + to resume execution at a specific address after an RSM instruction. This + function must evaluate the SMRAM save state to determine the execution mode + the RSM instruction resumes and update the resume execution address with + either NewInstructionPointer32 or NewInstructionPoint. The auto HALT restart + flag in the SMRAM save state must always be cleared. This function returns + the value of the instruction pointer from the SMRAM save state that was + replaced. If this function returns 0, then the SMRAM save state was not + modified. + + This function is called during the very first SMI on each CPU after + SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode + to signal that the SMBASE of each CPU has been updated before the default + SMBASE address is used for the first SMI to the next CPU. + + @param[in] CpuIndex The index of the CPU to hook. The value + must be between 0 and the NumberOfCpus + field in the System Management System Table + (SMST). + @param[in] CpuState Pointer to SMRAM Save State Map for the + currently executing CPU. + @param[in] NewInstructionPointer32 Instruction pointer to use if resuming to + 32-bit execution mode from 64-bit SMM. + @param[in] NewInstructionPointer Instruction pointer to use if resuming to + same execution mode as SMM. + + @retval 0 This function did modify the SMRAM save state. + @retval > 0 The original instruction pointer value from the SMRAM save state + before it was replaced. +**/ +UINT64 +EFIAPI +SmmCpuFeaturesHookReturnFromSmm ( + IN UINTN CpuIndex, + IN SMRAM_SAVE_STATE_MAP *CpuState, + IN UINT64 NewInstructionPointer32, + IN UINT64 NewInstructionPointer + ) +{ + return 0; +} + +/** + Hook point in normal execution mode that allows the one CPU that was elected + as monarch during System Management Mode initialization to perform additional + initialization actions immediately after all of the CPUs have processed their + first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE + into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm(). +**/ +VOID +EFIAPI +SmmCpuFeaturesSmmRelocationComplete ( + VOID + ) +{ +} + +/** + Processor specific hook point each time a CPU exits System Management Mode. + + @param[in] CpuIndex The index of the CPU that is exiting SMM. The value must + be between 0 and the NumberOfCpus field in the System + Management System Table (SMST). +**/ +VOID +EFIAPI +SmmCpuFeaturesRendezvousExit ( + IN UINTN CpuIndex + ) +{ +} + +/** + Check to see if an SMM register is supported by a specified CPU. + + @param[in] CpuIndex The index of the CPU to check for SMM register support. + The value must be between 0 and the NumberOfCpus field + in the System Management System Table (SMST). + @param[in] RegName Identifies the SMM register to check for support. + + @retval TRUE The SMM register specified by RegName is supported by the CPU + specified by CpuIndex. + @retval FALSE The SMM register specified by RegName is not supported by the + CPU specified by CpuIndex. +**/ +BOOLEAN +EFIAPI +SmmCpuFeaturesIsSmmRegisterSupported ( + IN UINTN CpuIndex, + IN SMM_REG_NAME RegName + ) +{ + if (FeaturePcdGet (PcdSmmFeatureControlEnable) && (RegName == SmmRegFeatureControl)) { + return TRUE; + } + + return FALSE; +} + +/** + Read an SMM Save State register on the target processor. If this function + returns EFI_UNSUPPORTED, then the caller is responsible for reading the + SMM Save Sate register. + + @param[in] CpuIndex The index of the CPU to read the SMM Save State. The + value must be between 0 and the NumberOfCpus field in + the System Management System Table (SMST). + @param[in] Register The SMM Save State register to read. + @param[in] Width The number of bytes to read from the CPU save state. + @param[out] Buffer Upon return, this holds the CPU register value read + from the save state. + + @retval EFI_SUCCESS The register was read from Save State. + @retval EFI_INVALID_PARAMETER Buffer is NULL. + @retval EFI_UNSUPPORTED This function does not support reading Register. + +**/ +EFI_STATUS +EFIAPI +SmmCpuFeaturesReadSaveStateRegister ( + IN UINTN CpuIndex, + IN EFI_SMM_SAVE_STATE_REGISTER Register, + IN UINTN Width, + OUT VOID *Buffer + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Writes an SMM Save State register on the target processor. If this function + returns EFI_UNSUPPORTED, then the caller is responsible for writing the + SMM Save Sate register. + + @param[in] CpuIndex The index of the CPU to write the SMM Save State. The + value must be between 0 and the NumberOfCpus field in + the System Management System Table (SMST). + @param[in] Register The SMM Save State register to write. + @param[in] Width The number of bytes to write to the CPU save state. + @param[in] Buffer Upon entry, this holds the new CPU register value. + + @retval EFI_SUCCESS The register was written to Save State. + @retval EFI_INVALID_PARAMETER Buffer is NULL. + @retval EFI_UNSUPPORTED This function does not support writing Register. +**/ +EFI_STATUS +EFIAPI +SmmCpuFeaturesWriteSaveStateRegister ( + IN UINTN CpuIndex, + IN EFI_SMM_SAVE_STATE_REGISTER Register, + IN UINTN Width, + IN CONST VOID *Buffer + ) +{ + return EFI_UNSUPPORTED; +} + +/** + This function is hook point called after the gEfiSmmReadyToLockProtocolGuid + notification is completely processed. +**/ +VOID +EFIAPI +SmmCpuFeaturesCompleteSmmReadyToLock ( + VOID + ) +{ +} + +/** + This API provides a method for a CPU to allocate a specific region for storing page tables. + + This API can be called more once to allocate memory for page tables. + + Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the + allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL + is returned. If there is not enough memory remaining to satisfy the request, then NULL is + returned. + + This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM. + + @param Pages The number of 4 KB pages to allocate. + + @return A pointer to the allocated buffer for page tables. + @retval NULL Fail to allocate a specific region for storing page tables, + Or there is no preference on where the page tables are allocated in SMRAM. + +**/ +VOID * +EFIAPI +SmmCpuFeaturesAllocatePageTableMemory ( + IN UINTN Pages + ) +{ + return NULL; +} diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf index d64d8e66b3..86d367e0a0 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf @@ -20,6 +20,7 @@ [Sources] CpuFeaturesLib.h IntelSmmCpuFeaturesLib.c + SmmCpuFeaturesLibCommon.c SmmStm.c SmmStm.h TraditionalMmCpuFeaturesLib.c diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf index 5935b3e1fd..b1f60a5505 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf @@ -21,6 +21,7 @@ [Sources] CpuFeaturesLib.h IntelSmmCpuFeaturesLib.c + SmmCpuFeaturesLibCommon.c StandaloneMmCpuFeaturesLib.c SmmCpuFeaturesLibNoStm.c From 8f1c5718c5d733d04680ef54aeb37ab6bbb46f11 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 31 Oct 2022 15:59:36 +0800 Subject: [PATCH 0270/1529] UefiCpuPkg/SmmCpuFeaturesLib: Clean up header file inclusion in SmmStm.c BZ# 4093: Abstract SmmCpuFeaturesLib for sharing common code Remove the header files those are already included in CpuFeatureLib.h. Signed-off-by: Abner Chang Cc: Abdul Lateef Attar Cc: Garrett Kirkendall Cc: Paul Grimes Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Reviewed-by: Ray Ni --- UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c index 4e8f897f5e..3cf162ada0 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c @@ -7,11 +7,8 @@ **/ #include -#include #include -#include #include -#include #include #include #include From 553896e5282333ffed1999bfdefab4279c37d473 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Thu, 27 Oct 2022 19:37:27 -0700 Subject: [PATCH 0271/1529] IntelFsp2Pkg: Update Function header to support IA32/X64. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4126 Common functions will have either 32bit or 64bit instances which having different return code size. Function header should support both scenarios. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- IntelFsp2Pkg/FspSecCore/SecFsp.h | 4 ++-- IntelFsp2Pkg/Include/Library/FspSecPlatformLib.h | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/SecFsp.h b/IntelFsp2Pkg/FspSecCore/SecFsp.h index e84528b378..d7a5976c12 100644 --- a/IntelFsp2Pkg/FspSecCore/SecFsp.h +++ b/IntelFsp2Pkg/FspSecCore/SecFsp.h @@ -70,7 +70,7 @@ FspDataPointerFixUp ( @return FSP binary base address. **/ -UINT32 +UINTN EFIAPI AsmGetFspBaseAddress ( VOID @@ -82,7 +82,7 @@ AsmGetFspBaseAddress ( @return FSP binary base address. **/ -UINT32 +UINTN EFIAPI AsmGetFspInfoHeader ( VOID diff --git a/IntelFsp2Pkg/Include/Library/FspSecPlatformLib.h b/IntelFsp2Pkg/Include/Library/FspSecPlatformLib.h index c91ea4a78f..598fdb9ec5 100644 --- a/IntelFsp2Pkg/Include/Library/FspSecPlatformLib.h +++ b/IntelFsp2Pkg/Include/Library/FspSecPlatformLib.h @@ -17,10 +17,10 @@ The callee should not use XMM6/XMM7. The return address is saved in MM7. - @retval in saved in EAX - 0 means platform initialization success. + @retval in saved in EAX/RAX - 0 means platform initialization success. other means platform initialization fail. **/ -UINT32 +UINTN EFIAPI SecPlatformInit ( VOID @@ -37,10 +37,10 @@ SecPlatformInit ( @param[in] FsptUpdDataPtr Address pointer to the FSPT_UPD data structure. It is saved in ESP. - @retval in saved in EAX - 0 means Microcode is loaded successfully. + @retval in saved in EAX/RAX - 0 means Microcode is loaded successfully. other means Microcode is not loaded successfully. **/ -UINT32 +UINTN EFIAPI LoadMicrocode ( IN VOID *FsptUpdDataPtr @@ -56,10 +56,10 @@ LoadMicrocode ( @param[in] FsptUpdDataPtr Address pointer to the FSPT_UPD data structure. It is saved in ESP. - @retval in saved in EAX - 0 means CAR initialization success. + @retval in saved in EAX/RAX - 0 means CAR initialization success. other means CAR initialization fail. **/ -UINT32 +UINTN EFIAPI SecCarInit ( IN VOID *FsptUpdDataPtr From 3b9c264e53695ca776c3fe536b826f6abdb5fcdf Mon Sep 17 00:00:00 2001 From: Miki Demeter Date: Thu, 27 Oct 2022 16:20:54 -0700 Subject: [PATCH 0272/1529] =?UTF-8?q?MdeModulePkg/PiSmmCore:=20SmmEntryPoi?= =?UTF-8?q?nt=20underflow=C2=A0(CVE-2021-38578)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3387 Added use of SafeIntLib to validate values are not causing overflows or underflows in user controlled values when calculating buffer sizes. Signed-off-by: Miki Demeter Reviewed-by: Michael D Kinney Cc: Jian J Wang Cc: Liming Gao Reviewed-by: Liming Gao --- MdeModulePkg/Core/PiSmmCore/PiSmmCore.c | 41 ++++++++++++++++++----- MdeModulePkg/Core/PiSmmCore/PiSmmCore.h | 1 + MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf | 1 + MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c | 31 +++++++++++++---- MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf | 1 + 5 files changed, 60 insertions(+), 15 deletions(-) diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c index 9e5c6cbe33..875c7c0258 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c @@ -610,6 +610,7 @@ SmmEndOfS3ResumeHandler ( @param[in] Size2 Size of Buff2 @retval TRUE Buffers overlap in memory. + @retval TRUE Math error. Prevents potential math over and underflows. @retval FALSE Buffer doesn't overlap. **/ @@ -621,11 +622,24 @@ InternalIsBufferOverlapped ( IN UINTN Size2 ) { + UINTN End1; + UINTN End2; + BOOLEAN IsOverUnderflow1; + BOOLEAN IsOverUnderflow2; + + // Check for over or underflow + IsOverUnderflow1 = EFI_ERROR (SafeUintnAdd ((UINTN)Buff1, Size1, &End1)); + IsOverUnderflow2 = EFI_ERROR (SafeUintnAdd ((UINTN)Buff2, Size2, &End2)); + + if (IsOverUnderflow1 || IsOverUnderflow2) { + return TRUE; + } + // // If buff1's end is less than the start of buff2, then it's ok. // Also, if buff1's start is beyond buff2's end, then it's ok. // - if (((Buff1 + Size1) <= Buff2) || (Buff1 >= (Buff2 + Size2))) { + if ((End1 <= (UINTN)Buff2) || ((UINTN)Buff1 >= End2)) { return FALSE; } @@ -651,6 +665,7 @@ SmmEntryPoint ( EFI_SMM_COMMUNICATE_HEADER *CommunicateHeader; BOOLEAN InLegacyBoot; BOOLEAN IsOverlapped; + BOOLEAN IsOverUnderflow; VOID *CommunicationBuffer; UINTN BufferSize; @@ -699,23 +714,31 @@ SmmEntryPoint ( (UINT8 *)gSmmCorePrivate, sizeof (*gSmmCorePrivate) ); - if (!SmmIsBufferOutsideSmmValid ((UINTN)CommunicationBuffer, BufferSize) || IsOverlapped) { + // + // Check for over or underflows + // + IsOverUnderflow = EFI_ERROR (SafeUintnSub (BufferSize, OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data), &BufferSize)); + + if (!SmmIsBufferOutsideSmmValid ((UINTN)CommunicationBuffer, BufferSize) || + IsOverlapped || IsOverUnderflow) + { // // If CommunicationBuffer is not in valid address scope, // or there is overlap between gSmmCorePrivate and CommunicationBuffer, + // or there is over or underflow, // return EFI_INVALID_PARAMETER // gSmmCorePrivate->CommunicationBuffer = NULL; gSmmCorePrivate->ReturnStatus = EFI_ACCESS_DENIED; } else { CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)CommunicationBuffer; - BufferSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); - Status = SmiManage ( - &CommunicateHeader->HeaderGuid, - NULL, - CommunicateHeader->Data, - &BufferSize - ); + // BufferSize was updated by the SafeUintnSub() call above. + Status = SmiManage ( + &CommunicateHeader->HeaderGuid, + NULL, + CommunicateHeader->Data, + &BufferSize + ); // // Update CommunicationBuffer, BufferSize and ReturnStatus // Communicate service finished, reset the pointer to CommBuffer to NULL diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h index 71422b9dfc..b8a490a8c3 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h @@ -54,6 +54,7 @@ #include #include #include +#include #include "PiSmmCorePrivateData.h" #include "HeapGuard.h" diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf index c8bfae3860..3df44b38f1 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf @@ -60,6 +60,7 @@ PerformanceLib HobLib SmmMemLib + SafeIntLib [Protocols] gEfiDxeSmmReadyToLockProtocolGuid ## UNDEFINED # SmiHandlerRegister diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c index 4f00cebaf5..fbba868fd0 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c @@ -34,8 +34,8 @@ #include #include #include - #include "PiSmmCorePrivateData.h" +#include #define SMRAM_CAPABILITIES (EFI_MEMORY_WB | EFI_MEMORY_UC) @@ -1354,6 +1354,7 @@ SmmSplitSmramEntry ( @param[in] ReservedRangeToCompare Pointer to EFI_SMM_RESERVED_SMRAM_REGION to compare. @retval TRUE There is overlap. + @retval TRUE Math error. @retval FALSE There is no overlap. **/ @@ -1363,11 +1364,29 @@ SmmIsSmramOverlap ( IN EFI_SMM_RESERVED_SMRAM_REGION *ReservedRangeToCompare ) { - UINT64 RangeToCompareEnd; - UINT64 ReservedRangeToCompareEnd; - - RangeToCompareEnd = RangeToCompare->CpuStart + RangeToCompare->PhysicalSize; - ReservedRangeToCompareEnd = ReservedRangeToCompare->SmramReservedStart + ReservedRangeToCompare->SmramReservedSize; + UINT64 RangeToCompareEnd; + UINT64 ReservedRangeToCompareEnd; + BOOLEAN IsOverUnderflow1; + BOOLEAN IsOverUnderflow2; + + // Check for over or underflow. + IsOverUnderflow1 = EFI_ERROR ( + SafeUint64Add ( + (UINT64)RangeToCompare->CpuStart, + RangeToCompare->PhysicalSize, + &RangeToCompareEnd + ) + ); + IsOverUnderflow2 = EFI_ERROR ( + SafeUint64Add ( + (UINT64)ReservedRangeToCompare->SmramReservedStart, + ReservedRangeToCompare->SmramReservedSize, + &ReservedRangeToCompareEnd + ) + ); + if (IsOverUnderflow1 || IsOverUnderflow2) { + return TRUE; + } if ((RangeToCompare->CpuStart >= ReservedRangeToCompare->SmramReservedStart) && (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf index 6109d6b544..ddeb39cee2 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf @@ -46,6 +46,7 @@ DxeServicesLib PcdLib ReportStatusCodeLib + SafeIntLib [Protocols] gEfiSmmBase2ProtocolGuid ## PRODUCES From ace212a10c5ca2767b15cacc799d0b8476efd537 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Sun, 23 Oct 2022 20:00:57 -0700 Subject: [PATCH 0273/1529] IntelFsp2Pkg: FSP should support input UPD as NULL. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4114 FSP specification supports input UPD as NULL cases which FSP will use built-in UPD region instead. FSP should not return INVALID_PARAMETER in such cases. In FSP-T entry point case, the valid FSP-T UPD region pointer will be passed to platform FSP code to consume. In FSP-M and FSP-S cases, valid UPD pointer will be decided when updating corresponding pointer field in FspGlobalData. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone Reviewed-by: Ted Kuo --- .../FspSecCore/Ia32/FspApiEntryT.nasm | 73 ++++++++++++++----- IntelFsp2Pkg/FspSecCore/SecFspApiChk.c | 12 ++- IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm | 40 ++++++---- 3 files changed, 91 insertions(+), 34 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm index 61030a843b..73821ad22a 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm @@ -21,7 +21,7 @@ extern ASM_PFX(PcdGet32 (PcdFspReservedBufferSize)) ; Following functions will be provided in PlatformSecLib ; extern ASM_PFX(AsmGetFspBaseAddress) -extern ASM_PFX(AsmGetFspInfoHeader) +extern ASM_PFX(AsmGetFspInfoHeaderNoStack) ;extern ASM_PFX(LoadMicrocode) ; @todo: needs a weak implementation extern ASM_PFX(SecPlatformInit) ; @todo: needs a weak implementation extern ASM_PFX(SecCarInit) @@ -160,6 +160,47 @@ endstruc RET_ESI_EXT mm7 %endmacro +%macro CALL_EDI 1 + + mov edi, %%ReturnAddress + jmp %1 +%%ReturnAddress: + +%endmacro + +%macro CALL_EBP 1 + mov ebp, %%ReturnAddress + jmp %1 +%%ReturnAddress: +%endmacro + +%macro RET_EBP 0 + jmp ebp ; restore EIP from EBP +%endmacro + +; +; Load UPD region pointer in ECX +; +global ASM_PFX(LoadUpdPointerToECX) +ASM_PFX(LoadUpdPointerToECX): + ; + ; esp + 4 is input UPD parameter + ; If esp + 4 is NULL the default UPD should be used + ; ecx will be the UPD region that should be used + ; + mov ecx, dword [esp + 4] + cmp ecx, 0 + jnz ParamValid + + ; + ; Fall back to default UPD region + ; + CALL_EDI ASM_PFX(AsmGetFspInfoHeaderNoStack) + mov ecx, DWORD [eax + 01Ch] ; Read FsptImageBaseAddress + add ecx, DWORD [eax + 024h] ; Get Cfg Region base address = FsptImageBaseAddress + CfgRegionOffset +ParamValid: + RET_EBP + ; ; @todo: The strong/weak implementation does not work. ; This needs to be reviewed later. @@ -187,10 +228,9 @@ endstruc global ASM_PFX(LoadMicrocodeDefault) ASM_PFX(LoadMicrocodeDefault): ; Inputs: - ; esp -> LoadMicrocodeParams pointer + ; ecx -> UPD region contains LoadMicrocodeParams pointer ; Register Usage: - ; esp Preserved - ; All others destroyed + ; All are destroyed ; Assumptions: ; No memory available, stack is hard-coded and used for return address ; Executed by SBSP and NBSP @@ -201,12 +241,9 @@ ASM_PFX(LoadMicrocodeDefault): ; movd ebp, mm7 + mov esp, ecx ; ECX has been assigned to UPD region cmp esp, 0 jz ParamError - mov eax, dword [esp + 4] ; Parameter pointer - cmp eax, 0 - jz ParamError - mov esp, eax ; skip loading Microcode if the MicrocodeCodeSize is zero ; and report error if size is less than 2k @@ -444,13 +481,15 @@ Done: Exit2: jmp ebp - +; +; EstablishStackFsp: EDI should be preserved cross this function +; global ASM_PFX(EstablishStackFsp) ASM_PFX(EstablishStackFsp): ; ; Save parameter pointer in edx ; - mov edx, dword [esp + 4] + mov edx, ecx ; ECX has been assigned to UPD region ; ; Enable FSP STACK @@ -555,39 +594,37 @@ ASM_PFX(TempRamInitApi): SAVE_EAX SAVE_EDX - ; - ; Check Parameter - ; - mov eax, dword [esp + 4] - cmp eax, 0 - mov eax, 80000002h - jz TempRamInitExit - ; ; Sec Platform Init ; + CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param CALL_MMX ASM_PFX(SecPlatformInit) cmp eax, 0 jnz TempRamInitExit ; Load microcode LOAD_ESP + CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param CALL_MMX ASM_PFX(LoadMicrocodeDefault) SXMMN xmm6, 3, eax ;Save microcode return status in ECX-SLOT 3 in xmm6. ;@note If return value eax is not 0, microcode did not load, but continue and attempt to boot. ; Call Sec CAR Init LOAD_ESP + CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param CALL_MMX ASM_PFX(SecCarInit) cmp eax, 0 jnz TempRamInitExit LOAD_ESP + CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param + mov edi, ecx ; Save UPD param to EDI for later code use CALL_MMX ASM_PFX(EstablishStackFsp) cmp eax, 0 jnz TempRamInitExit LXMMN xmm6, eax, 3 ;Restore microcode status if no CAR init error from ECX-SLOT 3 in xmm6. + SXMMN xmm6, 3, edi ;Save FSP-T UPD parameter pointer in ECX-SLOT 3 in xmm6. TempRamInitExit: mov bl, al ; save al data in bl diff --git a/IntelFsp2Pkg/FspSecCore/SecFspApiChk.c b/IntelFsp2Pkg/FspSecCore/SecFspApiChk.c index a44fbf2a50..5f59938518 100644 --- a/IntelFsp2Pkg/FspSecCore/SecFspApiChk.c +++ b/IntelFsp2Pkg/FspSecCore/SecFspApiChk.c @@ -44,6 +44,8 @@ FspApiCallingCheck ( // if (((UINTN)FspData != MAX_ADDRESS) && ((UINTN)FspData != MAX_UINT32)) { Status = EFI_UNSUPPORTED; + } else if (ApiParam == NULL) { + Status = EFI_SUCCESS; } else if (EFI_ERROR (FspUpdSignatureCheck (ApiIdx, ApiParam))) { Status = EFI_INVALID_PARAMETER; } @@ -67,9 +69,13 @@ FspApiCallingCheck ( } else { if (FspData->Signature != FSP_GLOBAL_DATA_SIGNATURE) { Status = EFI_UNSUPPORTED; - } else if (EFI_ERROR (FspUpdSignatureCheck (FspSiliconInitApiIndex, ApiParam))) { - Status = EFI_INVALID_PARAMETER; } else if (ApiIdx == FspSiliconInitApiIndex) { + if (ApiParam == NULL) { + Status = EFI_SUCCESS; + } else if (EFI_ERROR (FspUpdSignatureCheck (FspSiliconInitApiIndex, ApiParam))) { + Status = EFI_INVALID_PARAMETER; + } + // // Reset MultiPhase NumberOfPhases to zero // @@ -89,6 +95,8 @@ FspApiCallingCheck ( } else { if (FspData->Signature != FSP_GLOBAL_DATA_SIGNATURE) { Status = EFI_UNSUPPORTED; + } else if (ApiParam == NULL) { + Status = EFI_SUCCESS; } else if (EFI_ERROR (FspUpdSignatureCheck (FspSmmInitApiIndex, ApiParam))) { Status = EFI_INVALID_PARAMETER; } diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm index 7dd89c531a..cdebe90fab 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm @@ -21,7 +21,7 @@ extern ASM_PFX(PcdGet32 (PcdFspReservedBufferSize)) ; Following functions will be provided in PlatformSecLib ; extern ASM_PFX(AsmGetFspBaseAddress) -extern ASM_PFX(AsmGetFspInfoHeader) +extern ASM_PFX(AsmGetFspInfoHeaderNoStack) ;extern ASM_PFX(LoadMicrocode) ; @todo: needs a weak implementation extern ASM_PFX(SecPlatformInit) ; @todo: needs a weak implementation extern ASM_PFX(SecCarInit) @@ -87,6 +87,14 @@ struc LoadMicrocodeParamsFsp24 .size: endstruc +%macro CALL_RDI 1 + + mov rdi, %%ReturnAddress + jmp %1 +%%ReturnAddress: + +%endmacro + ; ; @todo: The strong/weak implementation does not work. ; This needs to be reviewed later. @@ -116,8 +124,7 @@ ASM_PFX(LoadMicrocodeDefault): ; Inputs: ; rcx -> LoadMicrocodeParams pointer ; Register Usage: - ; rsp Preserved - ; All others destroyed + ; All are destroyed ; Assumptions: ; No memory available, stack is hard-coded and used for return address ; Executed by SBSP and NBSP @@ -420,10 +427,6 @@ ASM_PFX(TempRamInitApi): ENABLE_SSE ENABLE_AVX ; - ; Save Input Parameter in YMM10 - ; - SAVE_RCX - ; ; Save RBP, RBX, RSI, RDI and RSP in YMM7, YMM8 and YMM6 ; SAVE_REGS @@ -433,6 +436,22 @@ ASM_PFX(TempRamInitApi): ; SAVE_BFV rbp + ; + ; Save Input Parameter in YMM10 + ; + cmp rcx, 0 + jnz ParamValid + + ; + ; Fall back to default UPD + ; + CALL_RDI ASM_PFX(AsmGetFspInfoHeaderNoStack) + xor rcx, rcx + mov ecx, DWORD [rax + 01Ch] ; Read FsptImageBaseAddress + add ecx, DWORD [rax + 024h] ; Get Cfg Region base address = FsptImageBaseAddress + CfgRegionOffset +ParamValid: + SAVE_RCX + ; ; Save timestamp into YMM6 ; @@ -441,13 +460,6 @@ ASM_PFX(TempRamInitApi): or rax, rdx SAVE_TS rax - ; - ; Check Parameter - ; - cmp rcx, 0 - mov rcx, 08000000000000002h - jz TempRamInitExit - ; ; Sec Platform Init ; From 32df1f47c91c7175137985cf957d4aa4f5bbbd8a Mon Sep 17 00:00:00 2001 From: Sivaparvathi C Date: Thu, 27 Oct 2022 16:36:59 +0530 Subject: [PATCH 0274/1529] MdeModulePkg/scsi :Coverity scan flags multiple issues in edk2-stable202205 Added changes to resolve the SCSI driver Coverity issues. Cc: Vasudevan Sambandan Cc: Sundaresan Selvaraj Signed-off-by: Sivaparvathi chellaiah Reviewed-by: Liming Gao --- MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c | 5 ++++ MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 24 ++++++++++++-------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c index 9ea69ee740..fbe14c7724 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c @@ -3,6 +3,8 @@ Extended SCSI Pass Thru protocol in the system. Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 1985 - 2022, American Megatrends International LLC.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -531,6 +533,9 @@ SCSIBusDriverBindingStart ( // then create handle and install scsi i/o protocol. // Status = ScsiScanCreateDevice (This, Controller, &ScsiTargetId, Lun, ScsiBusDev); + if (Status == EFI_OUT_OF_RESOURCES) { + goto ErrorExit; + } } return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index 0928605dc4..6555aeed7d 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -3,6 +3,10 @@ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
Copyright (c) 1985 - 2022, American Megatrends International LLC.
+<<<<<<< HEAD +======= + +>>>>>>> ace365b4e0 (MdeModulePkg/scsi :Coverity scan flags multiple issues in edk2-stable202205) SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -4296,7 +4300,7 @@ ScsiDiskRead10 ( if ((TargetStatus == EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION) || (EFI_ERROR (ReturnStatus))) { DEBUG ((DEBUG_ERROR, "ScsiDiskRead10: Check Condition happened!\n")); - Status = DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); + DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); if (Action == ACTION_RETRY_COMMAND_LATER) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; @@ -4420,7 +4424,7 @@ ScsiDiskWrite10 ( if ((TargetStatus == EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION) || (EFI_ERROR (ReturnStatus))) { DEBUG ((DEBUG_ERROR, "ScsiDiskWrite10: Check Condition happened!\n")); - Status = DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); + DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); if (Action == ACTION_RETRY_COMMAND_LATER) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; @@ -4543,7 +4547,7 @@ ScsiDiskRead16 ( if ((TargetStatus == EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION) || (EFI_ERROR (ReturnStatus))) { DEBUG ((DEBUG_ERROR, "ScsiDiskRead16: Check Condition happened!\n")); - Status = DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); + DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); if (Action == ACTION_RETRY_COMMAND_LATER) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; @@ -4667,7 +4671,7 @@ ScsiDiskWrite16 ( if ((TargetStatus == EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION) || (EFI_ERROR (ReturnStatus))) { DEBUG ((DEBUG_ERROR, "ScsiDiskWrite16: Check Condition happened!\n")); - Status = DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); + DetectMediaParsingSenseKeys (ScsiDiskDevice, ScsiDiskDevice->SenseData, SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), &Action); if (Action == ACTION_RETRY_COMMAND_LATER) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; @@ -4777,12 +4781,12 @@ ScsiDiskNotify ( if (Request->TargetStatus == EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION) { DEBUG ((DEBUG_ERROR, "ScsiDiskNotify: Check Condition happened!\n")); - Status = DetectMediaParsingSenseKeys ( - ScsiDiskDevice, - Request->SenseData, - Request->SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), - &Action - ); + DetectMediaParsingSenseKeys ( + ScsiDiskDevice, + Request->SenseData, + Request->SenseDataLength / sizeof (EFI_SCSI_SENSE_DATA), + &Action + ); if (Action == ACTION_RETRY_COMMAND_LATER) { if (++Request->TimesRetry > MaxRetry) { Token->TransactionStatus = EFI_DEVICE_ERROR; From c83a9050e47ce804180e28a22a5bc4355e06a885 Mon Sep 17 00:00:00 2001 From: Sivaparvathi C Date: Fri, 28 Oct 2022 12:48:32 +0530 Subject: [PATCH 0275/1529] MdeModulePkg/Ufs :Coverity scan flags multiple issues in edk2-stable202205 BugZilla ID:https://bugzilla.tianocore.org/show_bug.cgi?id=3989 Added changes to resolve the Coverity Issues in UFS driver Cc: Vasudevan Sambandan Cc: Sundaresan Selvaraj Signed-off-by: Sivaparvathi Chellaiah Reviewed-by: Liming Gao --- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c | 20 ++++++++++++------- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c | 17 ++++++++++------ 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c index 62aeaf86c8..5aa046873c 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c @@ -2,7 +2,7 @@ The DMA memory help function. Copyright (c) 2017, Intel Corporation. All rights reserved.
- + Copyright (c) 1985 - 2022, American Megatrends International LLC.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -240,10 +240,16 @@ IoMmuInit ( VOID ) { - PeiServicesLocatePpi ( - &gEdkiiIoMmuPpiGuid, - 0, - NULL, - (VOID **)&mIoMmu - ); + EFI_STATUS Status; + + Status = PeiServicesLocatePpi ( + &gEdkiiIoMmuPpiGuid, + 0, + NULL, + (VOID **)&mIoMmu + ); + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_INFO, "Locate mIoMmu Ppi is failed!!!\n")); + } } diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c index b7dd9b6acd..562a77676c 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c @@ -1,6 +1,7 @@ /** @file Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 1985 - 2022, American Megatrends International LLC.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -18,7 +19,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UFS_PEIM_MEM_BLOCK * UfsPeimAllocMemBlock ( - IN UINTN Pages + IN UINTN Pages ) { UFS_PEIM_MEM_BLOCK *Block; @@ -107,8 +108,8 @@ UfsPeimFreeMemBlock ( **/ VOID * UfsPeimAllocMemFromBlock ( - IN UFS_PEIM_MEM_BLOCK *Block, - IN UINTN Units + IN UFS_PEIM_MEM_BLOCK *Block, + IN UINTN Units ) { UINTN Byte; @@ -221,7 +222,7 @@ UfsPeimIsMemBlockEmpty ( **/ EFI_STATUS UfsPeimInitMemPool ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { UFS_PEIM_MEM_POOL *Pool; @@ -292,8 +293,8 @@ UfsPeimFreeMemPool ( **/ VOID * UfsPeimAllocateMem ( - IN UFS_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN UFS_PEIM_MEM_POOL *Pool, + IN UINTN Size ) { UFS_PEIM_MEM_BLOCK *Head; @@ -414,6 +415,10 @@ UfsPeimFreeMem ( // ASSERT (Block != NULL); + if (Block == NULL) { + return; + } + // // Release the current memory block if it is empty and not the head // From 6fdbd65c92b8c7aa8c91d007a61a58d7b08a9781 Mon Sep 17 00:00:00 2001 From: VictorX Hsu Date: Thu, 3 Nov 2022 18:52:41 +0800 Subject: [PATCH 0276/1529] UefiPayloadPkg: Boot mode in PHIT HOB will not be updated REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4136 System will depend on Boot Mode value to do different behavior Update during Capsule Update process. So UPL need to support update boot mode. Cc: Guo Dong Cc: Ray Ni Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: VictorX Hsu --- UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c index edb3c20471..09aee89680 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c +++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c @@ -309,6 +309,7 @@ BuildHobs ( EFI_HOB_FIRMWARE_VOLUME *FvHob; UNIVERSAL_PAYLOAD_ACPI_TABLE *AcpiTable; ACPI_BOARD_INFO *AcpiBoardInfo; + EFI_HOB_HANDOFF_INFO_TABLE *HobInfo; Hob.Raw = (UINT8 *)BootloaderParameter; MinimalNeededSize = FixedPcdGet32 (PcdSystemMemoryUefiRegionSize); @@ -368,7 +369,8 @@ BuildHobs ( MemoryTop = FreeMemoryTop; } - HobConstructor ((VOID *)(UINTN)MemoryBottom, (VOID *)(UINTN)MemoryTop, (VOID *)(UINTN)FreeMemoryBottom, (VOID *)(UINTN)FreeMemoryTop); + HobInfo = HobConstructor ((VOID *)(UINTN)MemoryBottom, (VOID *)(UINTN)MemoryTop, (VOID *)(UINTN)FreeMemoryBottom, (VOID *)(UINTN)FreeMemoryTop); + HobInfo->BootMode = Hob.HandoffInformationTable->BootMode; // // From now on, mHobList will point to the new Hob range. // From d9f7b5b20d4468a3414d938efcc87214c5313634 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 28 Oct 2022 16:24:01 +0800 Subject: [PATCH 0277/1529] OvmfPkg/VmgExitLig: HALT on #VE when access to private memory BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4125 EPT-violation #VE should be always on shared memory, which means the shared bit of the GuestPA should be set. But in current #VE Handler it is not checked. When it occurs, stop TD immediately and log out the error. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Reviewed-by: Guorui Yu Tested-by: Guorui Yu --- .../Library/VmgExitLib/VmTdExitVeHandler.c | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c b/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c index b73e877c09..c89268c5d8 100644 --- a/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c +++ b/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c @@ -300,23 +300,41 @@ MmioExit ( IN TDCALL_VEINFO_RETURN_DATA *Veinfo ) { - UINT64 Status; - UINT32 MmioSize; - UINT32 RegSize; - UINT8 OpCode; - BOOLEAN SeenRex; - UINT64 *Reg; - UINT8 *Rip; - UINT64 Val; - UINT32 OpSize; - MODRM ModRm; - REX Rex; + UINT64 Status; + UINT32 MmioSize; + UINT32 RegSize; + UINT8 OpCode; + BOOLEAN SeenRex; + UINT64 *Reg; + UINT8 *Rip; + UINT64 Val; + UINT32 OpSize; + MODRM ModRm; + REX Rex; + TD_RETURN_DATA TdReturnData; + UINT8 Gpaw; + UINT64 TdSharedPageMask; Rip = (UINT8 *)Regs->Rip; Val = 0; Rex.Val = 0; SeenRex = FALSE; + Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (Status == TDX_EXIT_REASON_SUCCESS) { + Gpaw = (UINT8)(TdReturnData.TdInfo.Gpaw & 0x3f); + TdSharedPageMask = 1ULL << (Gpaw - 1); + } else { + DEBUG ((DEBUG_ERROR, "TDCALL failed with status=%llx\n", Status)); + return Status; + } + + if ((Veinfo->GuestPA & TdSharedPageMask) == 0) { + DEBUG ((DEBUG_ERROR, "EPT-violation #VE on private memory is not allowed!")); + TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0); + CpuDeadLoop (); + } + // // Default to 32bit transfer // From fbe043386e608a932bb17bdc9667f273e2feedbb Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 24 Oct 2022 18:53:35 +0200 Subject: [PATCH 0278/1529] ArmPlatformPkg: Retire NorFlashDxe driver The NorFlashDxe driver in ArmPlatformPkg was shared between development platforms built by ARM Ltd, and virtual platforms that were once modeled after Versatile Express, but have very little in common with actual bare metal implementations. Both sides have migrated to a domain specific version of the driver, so we can retire the old one. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Sunil V L --- ArmPlatformPkg/ArmPlatformPkg.dec | 6 - ArmPlatformPkg/ArmPlatformPkg.dsc | 6 - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.c | 991 ------------------ ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.h | 422 -------- .../Drivers/NorFlashDxe/NorFlashBlockIoDxe.c | 123 --- .../Drivers/NorFlashDxe/NorFlashDxe.c | 506 --------- .../Drivers/NorFlashDxe/NorFlashDxe.inf | 71 -- .../Drivers/NorFlashDxe/NorFlashFvb.c | 777 -------------- .../NorFlashDxe/NorFlashStandaloneMm.c | 383 ------- .../NorFlashDxe/NorFlashStandaloneMm.inf | 66 -- .../Include/Library/NorFlashPlatformLib.h | 30 - .../NorFlashPlatformNullLib.c | 28 - .../NorFlashPlatformNullLib.inf | 24 - 13 files changed, 3433 deletions(-) delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.c delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.h delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.c delete mode 100644 ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf delete mode 100644 ArmPlatformPkg/Include/Library/NorFlashPlatformLib.h delete mode 100644 ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.c delete mode 100644 ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf diff --git a/ArmPlatformPkg/ArmPlatformPkg.dec b/ArmPlatformPkg/ArmPlatformPkg.dec index dd6e78f62a..7b5d7e6cb5 100644 --- a/ArmPlatformPkg/ArmPlatformPkg.dec +++ b/ArmPlatformPkg/ArmPlatformPkg.dec @@ -38,10 +38,6 @@ # LcdPlatformLib|Include/Library/LcdPlatformLib.h - ## @libraryclass Provides a Nor flash interface. - # - NorFlashPlatformLib|Include/Library/NorFlashPlatformLib.h - ## @libraryclass Provides an interface to the clock of a PL011 device. # PL011UartClockLib|Include/Library/PL011UartClockLib.h @@ -56,8 +52,6 @@ [PcdsFeatureFlag.common] gArmPlatformTokenSpaceGuid.PcdSendSgiToBringUpSecondaryCores|FALSE|BOOLEAN|0x00000004 - gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked|FALSE|BOOLEAN|0x0000003C - # Disable the GOP controller on ExitBootServices(). By default the value is FALSE, # we assume the OS will handle the FrameBuffer from the UEFI GOP information. gArmPlatformTokenSpaceGuid.PcdGopDisableOnExitBootServices|FALSE|BOOLEAN|0x0000003D diff --git a/ArmPlatformPkg/ArmPlatformPkg.dsc b/ArmPlatformPkg/ArmPlatformPkg.dsc index 661a4cea22..ddd128f9e6 100644 --- a/ArmPlatformPkg/ArmPlatformPkg.dsc +++ b/ArmPlatformPkg/ArmPlatformPkg.dsc @@ -55,7 +55,6 @@ LzmaDecompressLib|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf MemoryInitPeiLib|ArmPlatformPkg/MemoryInitPei/MemoryInitPeiLib.inf - NorFlashPlatformLib|ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -100,7 +99,6 @@ [Components.common] ArmPlatformPkg/Drivers/LcdGraphicsOutputDxe/LcdGraphicsOutputDxe.inf - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf ArmPlatformPkg/Drivers/PL061GpioDxe/PL061GpioDxe.inf ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805WatchdogDxe.inf @@ -109,7 +107,6 @@ ArmPlatformPkg/Library/HdLcd/HdLcd.inf ArmPlatformPkg/Library/LcdHwNullLib/LcdHwNullLib.inf ArmPlatformPkg/Library/LcdPlatformNullLib/LcdPlatformNullLib.inf - ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.inf ArmPlatformPkg/Library/PL011UartClockLib/PL011UartClockLib.inf ArmPlatformPkg/Library/PL011UartLib/PL011UartLib.inf @@ -130,6 +127,3 @@ ArmPlatformPkg/PrePi/PeiUniCore.inf ArmPlatformPkg/Library/ArmMaliDp/ArmMaliDp.inf - -[Components.AARCH64] - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.c deleted file mode 100644 index 1b431073ee..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.c +++ /dev/null @@ -1,991 +0,0 @@ -/** @file NorFlash.c - - Copyright (c) 2011 - 2020, Arm Limited. All rights reserved.
- Copyright (c) 2020, Linaro, Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -#include "NorFlash.h" - -// -// Global variable declarations -// -extern NOR_FLASH_INSTANCE **mNorFlashInstances; -extern UINT32 mNorFlashDeviceCount; - -UINT32 -NorFlashReadStatusRegister ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN SR_Address - ) -{ - // Prepare to read the status register - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER); - return MmioRead32 (Instance->DeviceBaseAddress); -} - -STATIC -BOOLEAN -NorFlashBlockIsLocked ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - UINT32 LockStatus; - - // Send command for reading device id - SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID); - - // Read block lock status - LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2)); - - // Decode block lock status - LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus); - - if ((LockStatus & 0x2) != 0) { - DEBUG ((DEBUG_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n")); - } - - return ((LockStatus & 0x1) != 0); -} - -STATIC -EFI_STATUS -NorFlashUnlockSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - UINT32 LockStatus; - - // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations - // and to protect shared data structures. - - if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) { - do { - // Request a lock setup - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); - - // Request an unlock - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); - - // Send command for reading device id - SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID); - - // Read block lock status - LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2)); - - // Decode block lock status - LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus); - } while ((LockStatus & 0x1) == 1); - } else { - // Request a lock setup - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP); - - // Request an unlock - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK); - - // Wait until the status register gives us the all clear - do { - LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress); - } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); - } - - // Put device back into Read Array mode - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY); - - DEBUG ((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress)); - - return EFI_SUCCESS; -} - -EFI_STATUS -NorFlashUnlockSingleBlockIfNecessary ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - EFI_STATUS Status; - - Status = EFI_SUCCESS; - - if (NorFlashBlockIsLocked (Instance, BlockAddress)) { - Status = NorFlashUnlockSingleBlock (Instance, BlockAddress); - } - - return Status; -} - -/** - * The following function presumes that the block has already been unlocked. - **/ -EFI_STATUS -NorFlashEraseSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - EFI_STATUS Status; - UINT32 StatusRegister; - - Status = EFI_SUCCESS; - - // Request a block erase and then confirm it - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP); - SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM); - - // Wait until the status register gives us the all clear - do { - StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress); - } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); - - if (StatusRegister & P30_SR_BIT_VPP) { - DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress)); - Status = EFI_DEVICE_ERROR; - } - - if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) { - DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_ERASE) { - DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { - // The debug level message has been reduced because a device lock might happen. In this case we just retry it ... - DEBUG ((DEBUG_INFO, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress)); - Status = EFI_WRITE_PROTECTED; - } - - if (EFI_ERROR (Status)) { - // Clear the Status Register - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); - } - - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - - return Status; -} - -EFI_STATUS -NorFlashWriteSingleWord ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN WordAddress, - IN UINT32 WriteData - ) -{ - EFI_STATUS Status; - UINT32 StatusRegister; - - Status = EFI_SUCCESS; - - // Request a write single word command - SEND_NOR_COMMAND (WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP); - - // Store the word into NOR Flash; - MmioWrite32 (WordAddress, WriteData); - - // Wait for the write to complete and then check for any errors; i.e. check the Status Register - do { - // Prepare to read the status register - StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress); - // The chip is busy while the WRITE bit is not asserted - } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); - - // Perform a full status check: - // Mask the relevant bits of Status Register. - // Everything should be zero, if not, we have a problem - - if (StatusRegister & P30_SR_BIT_VPP) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n", WordAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_PROGRAM) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n", WordAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n", WordAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (!EFI_ERROR (Status)) { - // Clear the Status Register - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); - } - - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - - return Status; -} - -/* - * Writes data to the NOR Flash using the Buffered Programming method. - * - * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions. - * Therefore this function will only handle buffers up to 32 words or 128 bytes. - * To deal with larger buffers, call this function again. - * - * This function presumes that both the TargetAddress and the TargetAddress+BufferSize - * exist entirely within the NOR Flash. Therefore these conditions will not be checked here. - * - * In buffered programming, if the target address not at the beginning of a 32-bit word boundary, - * then programming time is doubled and power consumption is increased. - * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries. - * i.e. the last 4 bits of the target start address must be zero: 0x......00 - */ -EFI_STATUS -NorFlashWriteBuffer ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN TargetAddress, - IN UINTN BufferSizeInBytes, - IN UINT32 *Buffer - ) -{ - EFI_STATUS Status; - UINTN BufferSizeInWords; - UINTN Count; - volatile UINT32 *Data; - UINTN WaitForBuffer; - BOOLEAN BufferAvailable; - UINT32 StatusRegister; - - WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS; - BufferAvailable = FALSE; - - // Check that the target address does not cross a 32-word boundary. - if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) { - return EFI_INVALID_PARAMETER; - } - - // Check there are some data to program - if (BufferSizeInBytes == 0) { - return EFI_BUFFER_TOO_SMALL; - } - - // Check that the buffer size does not exceed the maximum hardware buffer size on chip. - if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) { - return EFI_BAD_BUFFER_SIZE; - } - - // Check that the buffer size is a multiple of 32-bit words - if ((BufferSizeInBytes % 4) != 0) { - return EFI_BAD_BUFFER_SIZE; - } - - // Pre-programming conditions checked, now start the algorithm. - - // Prepare the data destination address - Data = (UINT32 *)TargetAddress; - - // Check the availability of the buffer - do { - // Issue the Buffered Program Setup command - SEND_NOR_COMMAND (TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP); - - // Read back the status register bit#7 from the same address - if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) { - BufferAvailable = TRUE; - } - - // Update the loop counter - WaitForBuffer--; - } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE)); - - // The buffer was not available for writing - if (WaitForBuffer == 0) { - Status = EFI_DEVICE_ERROR; - goto EXIT; - } - - // From now on we work in 32-bit words - BufferSizeInWords = BufferSizeInBytes / (UINTN)4; - - // Write the word count, which is (buffer_size_in_words - 1), - // because word count 0 means one word. - SEND_NOR_COMMAND (TargetAddress, 0, (BufferSizeInWords - 1)); - - // Write the data to the NOR Flash, advancing each address by 4 bytes - for (Count = 0; Count < BufferSizeInWords; Count++, Data++, Buffer++) { - MmioWrite32 ((UINTN)Data, *Buffer); - } - - // Issue the Buffered Program Confirm command, to start the programming operation - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM); - - // Wait for the write to complete and then check for any errors; i.e. check the Status Register - do { - StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress); - // The chip is busy while the WRITE bit is not asserted - } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE); - - // Perform a full status check: - // Mask the relevant bits of Status Register. - // Everything should be zero, if not, we have a problem - - Status = EFI_SUCCESS; - - if (StatusRegister & P30_SR_BIT_VPP) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_PROGRAM) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n", TargetAddress)); - Status = EFI_DEVICE_ERROR; - } - - if (!EFI_ERROR (Status)) { - // Clear the Status Register - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER); - } - -EXIT: - // Put device back into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - - return Status; -} - -EFI_STATUS -NorFlashWriteBlocks ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ) -{ - UINT32 *pWriteBuffer; - EFI_STATUS Status; - EFI_LBA CurrentBlock; - UINT32 BlockSizeInWords; - UINT32 NumBlocks; - UINT32 BlockCount; - - Status = EFI_SUCCESS; - - // The buffer must be valid - if (Buffer == NULL) { - return EFI_INVALID_PARAMETER; - } - - if (Instance->Media.ReadOnly == TRUE) { - return EFI_WRITE_PROTECTED; - } - - // We must have some bytes to read - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes)); - if (BufferSizeInBytes == 0) { - return EFI_BAD_BUFFER_SIZE; - } - - // The size of the buffer must be a multiple of the block size - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize)); - if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { - return EFI_BAD_BUFFER_SIZE; - } - - // All blocks must be within the device - NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; - - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba)); - - if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n")); - return EFI_INVALID_PARAMETER; - } - - BlockSizeInWords = Instance->Media.BlockSize / 4; - - // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer - // to a proper data type, so use *ReadBuffer - pWriteBuffer = (UINT32 *)Buffer; - - CurrentBlock = Lba; - for (BlockCount = 0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) { - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock)); - - Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords); - - if (EFI_ERROR (Status)) { - break; - } - } - - DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status)); - return Status; -} - -#define BOTH_ALIGNED(a, b, align) ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0) - -/** - Copy Length bytes from Source to Destination, using aligned accesses only. - Note that this implementation uses memcpy() semantics rather then memmove() - semantics, i.e., SourceBuffer and DestinationBuffer should not overlap. - - @param DestinationBuffer The target of the copy request. - @param SourceBuffer The place to copy from. - @param Length The number of bytes to copy. - - @return Destination - -**/ -STATIC -VOID * -AlignedCopyMem ( - OUT VOID *DestinationBuffer, - IN CONST VOID *SourceBuffer, - IN UINTN Length - ) -{ - UINT8 *Destination8; - CONST UINT8 *Source8; - UINT32 *Destination32; - CONST UINT32 *Source32; - UINT64 *Destination64; - CONST UINT64 *Source64; - - if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 8) && (Length >= 8)) { - Destination64 = DestinationBuffer; - Source64 = SourceBuffer; - while (Length >= 8) { - *Destination64++ = *Source64++; - Length -= 8; - } - - Destination8 = (UINT8 *)Destination64; - Source8 = (CONST UINT8 *)Source64; - } else if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 4) && (Length >= 4)) { - Destination32 = DestinationBuffer; - Source32 = SourceBuffer; - while (Length >= 4) { - *Destination32++ = *Source32++; - Length -= 4; - } - - Destination8 = (UINT8 *)Destination32; - Source8 = (CONST UINT8 *)Source32; - } else { - Destination8 = DestinationBuffer; - Source8 = SourceBuffer; - } - - while (Length-- != 0) { - *Destination8++ = *Source8++; - } - - return DestinationBuffer; -} - -EFI_STATUS -NorFlashReadBlocks ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ) -{ - UINT32 NumBlocks; - UINTN StartAddress; - - DEBUG (( - DEBUG_BLKIO, - "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n", - BufferSizeInBytes, - Instance->Media.BlockSize, - Instance->Media.LastBlock, - Lba - )); - - // The buffer must be valid - if (Buffer == NULL) { - return EFI_INVALID_PARAMETER; - } - - // Return if we have not any byte to read - if (BufferSizeInBytes == 0) { - return EFI_SUCCESS; - } - - // The size of the buffer must be a multiple of the block size - if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) { - return EFI_BAD_BUFFER_SIZE; - } - - // All blocks must be within the device - NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize; - - if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) { - DEBUG ((DEBUG_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n")); - return EFI_INVALID_PARAMETER; - } - - // Get the address to start reading from - StartAddress = GET_NOR_BLOCK_ADDRESS ( - Instance->RegionBaseAddress, - Lba, - Instance->Media.BlockSize - ); - - // Put the device into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - - // Readout the data - AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes); - - return EFI_SUCCESS; -} - -EFI_STATUS -NorFlashRead ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN Offset, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ) -{ - UINTN StartAddress; - - // The buffer must be valid - if (Buffer == NULL) { - return EFI_INVALID_PARAMETER; - } - - // Return if we have not any byte to read - if (BufferSizeInBytes == 0) { - return EFI_SUCCESS; - } - - if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) { - DEBUG ((DEBUG_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n")); - return EFI_INVALID_PARAMETER; - } - - // Get the address to start reading from - StartAddress = GET_NOR_BLOCK_ADDRESS ( - Instance->RegionBaseAddress, - Lba, - Instance->Media.BlockSize - ); - - // Put the device into Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - - // Readout the data - AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes); - - return EFI_SUCCESS; -} - -/* - Write a full or portion of a block. It must not span block boundaries; that is, - Offset + *NumBytes <= Instance->Media.BlockSize. -*/ -EFI_STATUS -NorFlashWriteSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer - ) -{ - EFI_STATUS TempStatus; - UINT32 Tmp; - UINT32 TmpBuf; - UINT32 WordToWrite; - UINT32 Mask; - BOOLEAN DoErase; - UINTN BytesToWrite; - UINTN CurOffset; - UINTN WordAddr; - UINTN BlockSize; - UINTN BlockAddress; - UINTN PrevBlockAddress; - - PrevBlockAddress = 0; - - DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer)); - - // Detect WriteDisabled state - if (Instance->Media.ReadOnly == TRUE) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n")); - // It is in WriteDisabled state, return an error right away - return EFI_ACCESS_DENIED; - } - - // Cache the block size to avoid de-referencing pointers all the time - BlockSize = Instance->Media.BlockSize; - - // The write must not span block boundaries. - // We need to check each variable individually because adding two large values together overflows. - if ((Offset >= BlockSize) || - (*NumBytes > BlockSize) || - ((Offset + *NumBytes) > BlockSize)) - { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); - return EFI_BAD_BUFFER_SIZE; - } - - // We must have some bytes to write - if (*NumBytes == 0) { - DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); - return EFI_BAD_BUFFER_SIZE; - } - - // Pick 128bytes as a good start for word operations as opposed to erasing the - // block and writing the data regardless if an erase is really needed. - // It looks like most individual NV variable writes are smaller than 128bytes. - if (*NumBytes <= 128) { - // Check to see if we need to erase before programming the data into NOR. - // If the destination bits are only changing from 1s to 0s we can just write. - // After a block is erased all bits in the block is set to 1. - // If any byte requires us to erase we just give up and rewrite all of it. - DoErase = FALSE; - BytesToWrite = *NumBytes; - CurOffset = Offset; - - while (BytesToWrite > 0) { - // Read full word from NOR, splice as required. A word is the smallest - // unit we can write. - TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof (Tmp), &Tmp); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } - - // Physical address of word in NOR to write. - WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS ( - Instance->RegionBaseAddress, - Lba, - BlockSize - ); - // The word of data that is to be written. - TmpBuf = *((UINT32 *)(Buffer + (*NumBytes - BytesToWrite))); - - // First do word aligned chunks. - if ((CurOffset & 0x3) == 0) { - if (BytesToWrite >= 4) { - // Is the destination still in 'erased' state? - if (~Tmp != 0) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Write this word to NOR - WordToWrite = TmpBuf; - CurOffset += sizeof (TmpBuf); - BytesToWrite -= sizeof (TmpBuf); - } else { - // BytesToWrite < 4. Do small writes and left-overs - Mask = ~((~0) << (BytesToWrite * 8)); - // Mask out the bytes we want. - TmpBuf &= Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - CurOffset += BytesToWrite; - BytesToWrite = 0; - } - } else { - // Do multiple words, but starting unaligned. - if (BytesToWrite > (4 - (CurOffset & 0x3))) { - Mask = ((~0) << ((CurOffset & 0x3) * 8)); - // Mask out the bytes we want. - TmpBuf &= Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - BytesToWrite -= (4 - (CurOffset & 0x3)); - CurOffset += (4 - (CurOffset & 0x3)); - } else { - // Unaligned and fits in one word. - Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8); - // Mask out the bytes we want. - TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask; - // Is the destination still in 'erased' state? - if ((Tmp & Mask) != Mask) { - // Check to see if we are only changing bits to zero. - if ((Tmp ^ TmpBuf) & TmpBuf) { - DoErase = TRUE; - break; - } - } - - // Merge old and new data. Write merged word to NOR - WordToWrite = (Tmp & ~Mask) | TmpBuf; - CurOffset += BytesToWrite; - BytesToWrite = 0; - } - } - - // - // Write the word to NOR. - // - - BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize); - if (BlockAddress != PrevBlockAddress) { - TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } - - PrevBlockAddress = BlockAddress; - } - - TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } - } - - // Exit if we got here and could write all the data. Otherwise do the - // Erase-Write cycle. - if (!DoErase) { - return EFI_SUCCESS; - } - } - - // Check we did get some memory. Buffer is BlockSize. - if (Instance->ShadowBuffer == NULL) { - DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n")); - return EFI_DEVICE_ERROR; - } - - // Read NOR Flash data into shadow buffer - TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); - if (EFI_ERROR (TempStatus)) { - // Return one of the pre-approved error statuses - return EFI_DEVICE_ERROR; - } - - // Put the data at the appropriate location inside the buffer area - CopyMem ((VOID *)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes); - - // Write the modified buffer back to the NorFlash - TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer); - if (EFI_ERROR (TempStatus)) { - // Return one of the pre-approved error statuses - return EFI_DEVICE_ERROR; - } - - return EFI_SUCCESS; -} - -/* - Although DiskIoDxe will automatically install the DiskIO protocol whenever - we install the BlockIO protocol, its implementation is sub-optimal as it reads - and writes entire blocks using the BlockIO protocol. In fact we can access - NOR flash with a finer granularity than that, so we can improve performance - by directly producing the DiskIO protocol. -*/ - -/** - Read BufferSize bytes from Offset into Buffer. - - @param This Protocol instance pointer. - @param MediaId Id of the media, changes every time the media is replaced. - @param Offset The starting byte offset to read from - @param BufferSize Size of Buffer - @param Buffer Buffer containing read data - - @retval EFI_SUCCESS The data was read correctly from the device. - @retval EFI_DEVICE_ERROR The device reported an error while performing the read. - @retval EFI_NO_MEDIA There is no media in the device. - @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. - @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not - valid for the device. - -**/ -EFI_STATUS -EFIAPI -NorFlashDiskIoReadDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 DiskOffset, - IN UINTN BufferSize, - OUT VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - UINT32 BlockSize; - UINT32 BlockOffset; - EFI_LBA Lba; - - Instance = INSTANCE_FROM_DISKIO_THIS (This); - - if (MediaId != Instance->Media.MediaId) { - return EFI_MEDIA_CHANGED; - } - - BlockSize = Instance->Media.BlockSize; - Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); - - return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer); -} - -/** - Writes a specified number of bytes to a device. - - @param This Indicates a pointer to the calling context. - @param MediaId ID of the medium to be written. - @param Offset The starting byte offset on the logical block I/O device to write. - @param BufferSize The size in bytes of Buffer. The number of bytes to write to the device. - @param Buffer A pointer to the buffer containing the data to be written. - - @retval EFI_SUCCESS The data was written correctly to the device. - @retval EFI_WRITE_PROTECTED The device can not be written to. - @retval EFI_DEVICE_ERROR The device reported an error while performing the write. - @retval EFI_NO_MEDIA There is no media in the device. - @retval EFI_MEDIA_CHANGED The MediaId does not match the current device. - @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not - valid for the device. - -**/ -EFI_STATUS -EFIAPI -NorFlashDiskIoWriteDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 DiskOffset, - IN UINTN BufferSize, - IN VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - UINT32 BlockSize; - UINT32 BlockOffset; - EFI_LBA Lba; - UINTN RemainingBytes; - UINTN WriteSize; - EFI_STATUS Status; - - Instance = INSTANCE_FROM_DISKIO_THIS (This); - - if (MediaId != Instance->Media.MediaId) { - return EFI_MEDIA_CHANGED; - } - - BlockSize = Instance->Media.BlockSize; - Lba = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset); - - RemainingBytes = BufferSize; - - // Write either all the remaining bytes, or the number of bytes that bring - // us up to a block boundary, whichever is less. - // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next - // block boundary (even if it is already on one). - WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset); - - do { - if (WriteSize == BlockSize) { - // Write a full block - Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32)); - } else { - // Write a partial block - Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer); - } - - if (EFI_ERROR (Status)) { - return Status; - } - - // Now continue writing either all the remaining bytes or single blocks. - RemainingBytes -= WriteSize; - Buffer = (UINT8 *)Buffer + WriteSize; - Lba++; - BlockOffset = 0; - WriteSize = MIN (RemainingBytes, BlockSize); - } while (RemainingBytes); - - return Status; -} - -EFI_STATUS -NorFlashReset ( - IN NOR_FLASH_INSTANCE *Instance - ) -{ - // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode - SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY); - return EFI_SUCCESS; -} - -/** - 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 -NorFlashVirtualNotifyEvent ( - IN EFI_EVENT Event, - IN VOID *Context - ) -{ - UINTN Index; - - for (Index = 0; Index < mNorFlashDeviceCount; Index++) { - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress); - - // Convert BlockIo protocol - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.Reset); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks); - - // Convert Fvb - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Read); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes); - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Write); - - if (mNorFlashInstances[Index]->ShadowBuffer != NULL) { - EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->ShadowBuffer); - } - } - - return; -} diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.h b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.h deleted file mode 100644 index c83032e87d..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlash.h +++ /dev/null @@ -1,422 +0,0 @@ -/** @file NorFlash.h - - Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __NOR_FLASH_H__ -#define __NOR_FLASH_H__ - -#include -#include - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#define NOR_FLASH_ERASE_RETRY 10 - -// Device access macros -// These are necessary because we use 2 x 16bit parts to make up 32bit data - -#define HIGH_16_BITS 0xFFFF0000 -#define LOW_16_BITS 0x0000FFFF -#define LOW_8_BITS 0x000000FF - -#define FOLD_32BIT_INTO_16BIT(value) ( ( value >> 16 ) | ( value & LOW_16_BITS ) ) - -#define GET_LOW_BYTE(value) ( value & LOW_8_BITS ) -#define GET_HIGH_BYTE(value) ( GET_LOW_BYTE( value >> 16 ) ) - -// Each command must be sent simultaneously to both chips, -// i.e. at the lower 16 bits AND at the higher 16 bits -#define CREATE_NOR_ADDRESS(BaseAddr, OffsetAddr) ((BaseAddr) + ((OffsetAddr) << 2)) -#define CREATE_DUAL_CMD(Cmd) ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) ) -#define SEND_NOR_COMMAND(BaseAddr, Offset, Cmd) MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd)) -#define GET_NOR_BLOCK_ADDRESS(BaseAddr, Lba, LbaSize) ( BaseAddr + (UINTN)((Lba) * LbaSize) ) - -// Status Register Bits -#define P30_SR_BIT_WRITE (BIT7 << 16 | BIT7) -#define P30_SR_BIT_ERASE_SUSPEND (BIT6 << 16 | BIT6) -#define P30_SR_BIT_ERASE (BIT5 << 16 | BIT5) -#define P30_SR_BIT_PROGRAM (BIT4 << 16 | BIT4) -#define P30_SR_BIT_VPP (BIT3 << 16 | BIT3) -#define P30_SR_BIT_PROGRAM_SUSPEND (BIT2 << 16 | BIT2) -#define P30_SR_BIT_BLOCK_LOCKED (BIT1 << 16 | BIT1) -#define P30_SR_BIT_BEFP (BIT0 << 16 | BIT0) - -// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family - -// On chip buffer size for buffered programming operations -// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes. -// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes -#define P30_MAX_BUFFER_SIZE_IN_BYTES ((UINTN)128) -#define P30_MAX_BUFFER_SIZE_IN_WORDS (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4)) -#define MAX_BUFFERED_PROG_ITERATIONS 10000000 -#define BOUNDARY_OF_32_WORDS 0x7F - -// CFI Addresses -#define P30_CFI_ADDR_QUERY_UNIQUE_QRY 0x10 -#define P30_CFI_ADDR_VENDOR_ID 0x13 - -// CFI Data -#define CFI_QRY 0x00595251 - -// READ Commands -#define P30_CMD_READ_DEVICE_ID 0x0090 -#define P30_CMD_READ_STATUS_REGISTER 0x0070 -#define P30_CMD_CLEAR_STATUS_REGISTER 0x0050 -#define P30_CMD_READ_ARRAY 0x00FF -#define P30_CMD_READ_CFI_QUERY 0x0098 - -// WRITE Commands -#define P30_CMD_WORD_PROGRAM_SETUP 0x0040 -#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP 0x0010 -#define P30_CMD_BUFFERED_PROGRAM_SETUP 0x00E8 -#define P30_CMD_BUFFERED_PROGRAM_CONFIRM 0x00D0 -#define P30_CMD_BEFP_SETUP 0x0080 -#define P30_CMD_BEFP_CONFIRM 0x00D0 - -// ERASE Commands -#define P30_CMD_BLOCK_ERASE_SETUP 0x0020 -#define P30_CMD_BLOCK_ERASE_CONFIRM 0x00D0 - -// SUSPEND Commands -#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND 0x00B0 -#define P30_CMD_SUSPEND_RESUME 0x00D0 - -// BLOCK LOCKING / UNLOCKING Commands -#define P30_CMD_LOCK_BLOCK_SETUP 0x0060 -#define P30_CMD_LOCK_BLOCK 0x0001 -#define P30_CMD_UNLOCK_BLOCK 0x00D0 -#define P30_CMD_LOCK_DOWN_BLOCK 0x002F - -// PROTECTION Commands -#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP 0x00C0 - -// CONFIGURATION Commands -#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP 0x0060 -#define P30_CMD_READ_CONFIGURATION_REGISTER 0x0003 - -#define NOR_FLASH_SIGNATURE SIGNATURE_32('n', 'o', 'r', '0') -#define INSTANCE_FROM_FVB_THIS(a) CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE) -#define INSTANCE_FROM_BLKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE) -#define INSTANCE_FROM_DISKIO_THIS(a) CR(a, NOR_FLASH_INSTANCE, DiskIoProtocol, NOR_FLASH_SIGNATURE) - -typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE; - -#pragma pack (1) -typedef struct { - VENDOR_DEVICE_PATH Vendor; - UINT8 Index; - EFI_DEVICE_PATH_PROTOCOL End; -} NOR_FLASH_DEVICE_PATH; -#pragma pack () - -struct _NOR_FLASH_INSTANCE { - UINT32 Signature; - EFI_HANDLE Handle; - - UINTN DeviceBaseAddress; - UINTN RegionBaseAddress; - UINTN Size; - EFI_LBA StartLba; - - EFI_BLOCK_IO_PROTOCOL BlockIoProtocol; - EFI_BLOCK_IO_MEDIA Media; - EFI_DISK_IO_PROTOCOL DiskIoProtocol; - - EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL FvbProtocol; - VOID *ShadowBuffer; - - NOR_FLASH_DEVICE_PATH DevicePath; -}; - -EFI_STATUS -NorFlashReadCfiData ( - IN UINTN DeviceBaseAddress, - IN UINTN CFI_Offset, - IN UINT32 NumberOfBytes, - OUT UINT32 *Data - ); - -EFI_STATUS -NorFlashWriteBuffer ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN TargetAddress, - IN UINTN BufferSizeInBytes, - IN UINT32 *Buffer - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ); - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This - ); - -// -// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.ReadDisk -// -EFI_STATUS -EFIAPI -NorFlashDiskIoReadDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Offset, - IN UINTN BufferSize, - OUT VOID *Buffer - ); - -// -// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.WriteDisk -// -EFI_STATUS -EFIAPI -NorFlashDiskIoWriteDisk ( - IN EFI_DISK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Offset, - IN UINTN BufferSize, - IN VOID *Buffer - ); - -// -// NorFlashFvbDxe.c -// - -EFI_STATUS -EFIAPI -FvbGetAttributes ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - OUT EFI_FVB_ATTRIBUTES_2 *Attributes - ); - -EFI_STATUS -EFIAPI -FvbSetAttributes ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes - ); - -EFI_STATUS -EFIAPI -FvbGetPhysicalAddress ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - OUT EFI_PHYSICAL_ADDRESS *Address - ); - -EFI_STATUS -EFIAPI -FvbGetBlockSize ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - OUT UINTN *BlockSize, - OUT UINTN *NumberOfBlocks - ); - -EFI_STATUS -EFIAPI -FvbRead ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN OUT UINT8 *Buffer - ); - -EFI_STATUS -EFIAPI -FvbWrite ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer - ); - -EFI_STATUS -EFIAPI -FvbEraseBlocks ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - ... - ); - -EFI_STATUS -ValidateFvHeader ( - IN NOR_FLASH_INSTANCE *Instance - ); - -EFI_STATUS -InitializeFvAndVariableStoreHeaders ( - IN NOR_FLASH_INSTANCE *Instance - ); - -VOID -EFIAPI -FvbVirtualNotifyEvent ( - IN EFI_EVENT Event, - IN VOID *Context - ); - -// -// NorFlashDxe.c -// - -EFI_STATUS -NorFlashWriteFullBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINT32 *DataBuffer, - IN UINT32 BlockSizeInWords - ); - -EFI_STATUS -NorFlashUnlockAndEraseSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ); - -EFI_STATUS -NorFlashCreateInstance ( - IN UINTN NorFlashDeviceBase, - IN UINTN NorFlashRegionBase, - IN UINTN NorFlashSize, - IN UINT32 Index, - IN UINT32 BlockSize, - IN BOOLEAN SupportFvb, - OUT NOR_FLASH_INSTANCE **NorFlashInstance - ); - -EFI_STATUS -EFIAPI -NorFlashFvbInitialize ( - IN NOR_FLASH_INSTANCE *Instance - ); - -// -// NorFlash.c -// -EFI_STATUS -NorFlashWriteSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer - ); - -EFI_STATUS -NorFlashWriteBlocks ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ); - -EFI_STATUS -NorFlashReadBlocks ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ); - -EFI_STATUS -NorFlashRead ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN Offset, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ); - -EFI_STATUS -NorFlashWrite ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer - ); - -EFI_STATUS -NorFlashReset ( - IN NOR_FLASH_INSTANCE *Instance - ); - -EFI_STATUS -NorFlashEraseSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ); - -EFI_STATUS -NorFlashUnlockSingleBlockIfNecessary ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ); - -EFI_STATUS -NorFlashWriteSingleWord ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN WordAddress, - IN UINT32 WriteData - ); - -VOID -EFIAPI -NorFlashVirtualNotifyEvent ( - IN EFI_EVENT Event, - IN VOID *Context - ); - -#endif /* __NOR_FLASH_H__ */ diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c deleted file mode 100644 index 9d4732c690..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c +++ /dev/null @@ -1,123 +0,0 @@ -/** @file NorFlashBlockIoDxe.c - - Copyright (c) 2011-2013, ARM Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -#include "NorFlash.h" - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification - ) -{ - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReset(MediaId=0x%x)\n", This->Media->MediaId)); - - return NorFlashReset (Instance); -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - OUT VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - - if (This == NULL) { - return EFI_INVALID_PARAMETER; - } - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - Media = This->Media; - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoReadBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes (%d kB), BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, BufferSizeInBytes, Buffer)); - - if (!Media) { - Status = EFI_INVALID_PARAMETER; - } else if (!Media->MediaPresent) { - Status = EFI_NO_MEDIA; - } else if (Media->MediaId != MediaId) { - Status = EFI_MEDIA_CHANGED; - } else if ((Media->IoAlign > 2) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { - Status = EFI_INVALID_PARAMETER; - } else { - Status = NorFlashReadBlocks (Instance, Lba, BufferSizeInBytes, Buffer); - } - - return Status; -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSizeInBytes, - IN VOID *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - EFI_STATUS Status; - - Instance = INSTANCE_FROM_BLKIO_THIS (This); - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoWriteBlocks(MediaId=0x%x, Lba=%ld, BufferSize=0x%x bytes, BufferPtr @ 0x%08x)\n", MediaId, Lba, BufferSizeInBytes, Buffer)); - - if ( !This->Media->MediaPresent ) { - Status = EFI_NO_MEDIA; - } else if ( This->Media->MediaId != MediaId ) { - Status = EFI_MEDIA_CHANGED; - } else if ( This->Media->ReadOnly ) { - Status = EFI_WRITE_PROTECTED; - } else { - Status = NorFlashWriteBlocks (Instance, Lba, BufferSizeInBytes, Buffer); - } - - return Status; -} - -// -// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks -// -EFI_STATUS -EFIAPI -NorFlashBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This - ) -{ - // No Flush required for the NOR Flash driver - // because cache operations are not permitted. - - DEBUG ((DEBUG_BLKIO, "NorFlashBlockIoFlushBlocks: Function NOT IMPLEMENTED (not required).\n")); - - // Nothing to do so just return without error - return EFI_SUCCESS; -} diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c deleted file mode 100644 index f7b92de21a..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.c +++ /dev/null @@ -1,506 +0,0 @@ -/** @file NorFlashDxe.c - - Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include -#include - -#include "NorFlash.h" - -STATIC EFI_EVENT mNorFlashVirtualAddrChangeEvent; - -// -// Global variable declarations -// -NOR_FLASH_INSTANCE **mNorFlashInstances; -UINT32 mNorFlashDeviceCount; -UINTN mFlashNvStorageVariableBase; -EFI_EVENT mFvbVirtualAddrChangeEvent; - -NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = { - NOR_FLASH_SIGNATURE, // Signature - NULL, // Handle ... NEED TO BE FILLED - - 0, // DeviceBaseAddress ... NEED TO BE FILLED - 0, // RegionBaseAddress ... NEED TO BE FILLED - 0, // Size ... NEED TO BE FILLED - 0, // StartLba - - { - EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision - NULL, // Media ... NEED TO BE FILLED - NorFlashBlockIoReset, // Reset; - NorFlashBlockIoReadBlocks, // ReadBlocks - NorFlashBlockIoWriteBlocks, // WriteBlocks - NorFlashBlockIoFlushBlocks // FlushBlocks - }, // BlockIoProtocol - - { - 0, // MediaId ... NEED TO BE FILLED - FALSE, // RemovableMedia - TRUE, // MediaPresent - FALSE, // LogicalPartition - FALSE, // ReadOnly - FALSE, // WriteCaching; - 0, // BlockSize ... NEED TO BE FILLED - 4, // IoAlign - 0, // LastBlock ... NEED TO BE FILLED - 0, // LowestAlignedLba - 1, // LogicalBlocksPerPhysicalBlock - }, // Media; - - { - EFI_DISK_IO_PROTOCOL_REVISION, // Revision - NorFlashDiskIoReadDisk, // ReadDisk - NorFlashDiskIoWriteDisk // WriteDisk - }, - - { - FvbGetAttributes, // GetAttributes - FvbSetAttributes, // SetAttributes - FvbGetPhysicalAddress, // GetPhysicalAddress - FvbGetBlockSize, // GetBlockSize - FvbRead, // Read - FvbWrite, // Write - FvbEraseBlocks, // EraseBlocks - NULL, // ParentHandle - }, // FvbProtoccol; - NULL, // ShadowBuffer - { - { - { - HARDWARE_DEVICE_PATH, - HW_VENDOR_DP, - { - (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End)), - (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End) >> 8) - } - }, - { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } - }, // GUID ... NEED TO BE FILLED - }, - 0, // Index - { - END_DEVICE_PATH_TYPE, - END_ENTIRE_DEVICE_PATH_SUBTYPE, - { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 } - } - } // DevicePath -}; - -EFI_STATUS -NorFlashCreateInstance ( - IN UINTN NorFlashDeviceBase, - IN UINTN NorFlashRegionBase, - IN UINTN NorFlashSize, - IN UINT32 Index, - IN UINT32 BlockSize, - IN BOOLEAN SupportFvb, - OUT NOR_FLASH_INSTANCE **NorFlashInstance - ) -{ - EFI_STATUS Status; - NOR_FLASH_INSTANCE *Instance; - - ASSERT (NorFlashInstance != NULL); - - Instance = AllocateRuntimeCopyPool (sizeof (NOR_FLASH_INSTANCE), &mNorFlashInstanceTemplate); - if (Instance == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - Instance->DeviceBaseAddress = NorFlashDeviceBase; - Instance->RegionBaseAddress = NorFlashRegionBase; - Instance->Size = NorFlashSize; - - Instance->BlockIoProtocol.Media = &Instance->Media; - Instance->Media.MediaId = Index; - Instance->Media.BlockSize = BlockSize; - Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1; - - CopyGuid (&Instance->DevicePath.Vendor.Guid, &gEfiCallerIdGuid); - Instance->DevicePath.Index = (UINT8)Index; - - Instance->ShadowBuffer = AllocateRuntimePool (BlockSize); - if (Instance->ShadowBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - if (SupportFvb) { - NorFlashFvbInitialize (Instance); - - Status = gBS->InstallMultipleProtocolInterfaces ( - &Instance->Handle, - &gEfiDevicePathProtocolGuid, - &Instance->DevicePath, - &gEfiBlockIoProtocolGuid, - &Instance->BlockIoProtocol, - &gEfiFirmwareVolumeBlockProtocolGuid, - &Instance->FvbProtocol, - NULL - ); - if (EFI_ERROR (Status)) { - FreePool (Instance); - return Status; - } - } else { - Status = gBS->InstallMultipleProtocolInterfaces ( - &Instance->Handle, - &gEfiDevicePathProtocolGuid, - &Instance->DevicePath, - &gEfiBlockIoProtocolGuid, - &Instance->BlockIoProtocol, - &gEfiDiskIoProtocolGuid, - &Instance->DiskIoProtocol, - NULL - ); - if (EFI_ERROR (Status)) { - FreePool (Instance); - return Status; - } - } - - *NorFlashInstance = Instance; - return Status; -} - -/** - * This function unlock and erase an entire NOR Flash block. - **/ -EFI_STATUS -NorFlashUnlockAndEraseSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - EFI_STATUS Status; - UINTN Index; - EFI_TPL OriginalTPL; - - if (!EfiAtRuntime ()) { - // Raise TPL to TPL_HIGH to stop anyone from interrupting us. - OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); - } else { - // This initialization is only to prevent the compiler to complain about the - // use of uninitialized variables - OriginalTPL = TPL_HIGH_LEVEL; - } - - Index = 0; - // The block erase might fail a first time (SW bug ?). Retry it ... - do { - // Unlock the block if we have to - Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); - if (EFI_ERROR (Status)) { - break; - } - - Status = NorFlashEraseSingleBlock (Instance, BlockAddress); - Index++; - } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED)); - - if (Index == NOR_FLASH_ERASE_RETRY) { - DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index)); - } - - if (!EfiAtRuntime ()) { - // Interruptions can resume. - gBS->RestoreTPL (OriginalTPL); - } - - return Status; -} - -EFI_STATUS -NorFlashWriteFullBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINT32 *DataBuffer, - IN UINT32 BlockSizeInWords - ) -{ - EFI_STATUS Status; - UINTN WordAddress; - UINT32 WordIndex; - UINTN BufferIndex; - UINTN BlockAddress; - UINTN BuffersInBlock; - UINTN RemainingWords; - EFI_TPL OriginalTPL; - UINTN Cnt; - - Status = EFI_SUCCESS; - - // Get the physical address of the block - BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4); - - // Start writing from the first address at the start of the block - WordAddress = BlockAddress; - - if (!EfiAtRuntime ()) { - // Raise TPL to TPL_HIGH to stop anyone from interrupting us. - OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); - } else { - // This initialization is only to prevent the compiler to complain about the - // use of uninitialized variables - OriginalTPL = TPL_HIGH_LEVEL; - } - - Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress)); - goto EXIT; - } - - // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method. - - // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero - if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) { - // First, break the entire block into buffer-sized chunks. - BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES; - - // Then feed each buffer chunk to the NOR Flash - // If a buffer does not contain any data, don't write it. - for (BufferIndex = 0; - BufferIndex < BuffersInBlock; - BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS - ) - { - // Check the buffer to see if it contains any data (not set all 1s). - for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) { - if (~DataBuffer[Cnt] != 0 ) { - // Some data found, write the buffer. - Status = NorFlashWriteBuffer ( - Instance, - WordAddress, - P30_MAX_BUFFER_SIZE_IN_BYTES, - DataBuffer - ); - if (EFI_ERROR (Status)) { - goto EXIT; - } - - break; - } - } - } - - // Finally, finish off any remaining words that are less than the maximum size of the buffer - RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS; - - if (RemainingWords != 0) { - Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer); - if (EFI_ERROR (Status)) { - goto EXIT; - } - } - } else { - // For now, use the single word programming algorithm - // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range, - // i.e. which ends in the range 0x......01 - 0x......7F. - for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) { - Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer); - if (EFI_ERROR (Status)) { - goto EXIT; - } - } - } - -EXIT: - if (!EfiAtRuntime ()) { - // Interruptions can resume. - gBS->RestoreTPL (OriginalTPL); - } - - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status)); - } - - return Status; -} - -EFI_STATUS -EFIAPI -NorFlashInitialise ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) -{ - EFI_STATUS Status; - UINT32 Index; - NOR_FLASH_DESCRIPTION *NorFlashDevices; - BOOLEAN ContainVariableStorage; - - Status = NorFlashPlatformInitialization (); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to initialize Nor Flash devices\n")); - return Status; - } - - Status = NorFlashPlatformGetDevices (&NorFlashDevices, &mNorFlashDeviceCount); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to get Nor Flash devices\n")); - return Status; - } - - mNorFlashInstances = AllocateRuntimePool (sizeof (NOR_FLASH_INSTANCE *) * mNorFlashDeviceCount); - - for (Index = 0; Index < mNorFlashDeviceCount; Index++) { - // Check if this NOR Flash device contain the variable storage region - - if (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) { - ContainVariableStorage = - (NorFlashDevices[Index].RegionBaseAddress <= PcdGet64 (PcdFlashNvStorageVariableBase64)) && - (PcdGet64 (PcdFlashNvStorageVariableBase64) + PcdGet32 (PcdFlashNvStorageVariableSize) <= - NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); - } else { - ContainVariableStorage = - (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) && - (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= - NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); - } - - Status = NorFlashCreateInstance ( - NorFlashDevices[Index].DeviceBaseAddress, - NorFlashDevices[Index].RegionBaseAddress, - NorFlashDevices[Index].Size, - Index, - NorFlashDevices[Index].BlockSize, - ContainVariableStorage, - &mNorFlashInstances[Index] - ); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to create instance for NorFlash[%d]\n", Index)); - } - } - - // - // Register for the virtual address change event - // - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, - TPL_NOTIFY, - NorFlashVirtualNotifyEvent, - NULL, - &gEfiEventVirtualAddressChangeGuid, - &mNorFlashVirtualAddrChangeEvent - ); - ASSERT_EFI_ERROR (Status); - - return Status; -} - -EFI_STATUS -EFIAPI -NorFlashFvbInitialize ( - IN NOR_FLASH_INSTANCE *Instance - ) -{ - EFI_STATUS Status; - UINT32 FvbNumLba; - EFI_BOOT_MODE BootMode; - UINTN RuntimeMmioRegionSize; - - DEBUG ((DEBUG_BLKIO, "NorFlashFvbInitialize\n")); - ASSERT ((Instance != NULL)); - - // - // Declare the Non-Volatile storage as EFI_MEMORY_RUNTIME - // - - // Note: all the NOR Flash region needs to be reserved into the UEFI Runtime memory; - // even if we only use the small block region at the top of the NOR Flash. - // The reason is when the NOR Flash memory is set into program mode, the command - // is written as the base of the flash region (ie: Instance->DeviceBaseAddress) - RuntimeMmioRegionSize = (Instance->RegionBaseAddress - Instance->DeviceBaseAddress) + Instance->Size; - - Status = gDS->AddMemorySpace ( - EfiGcdMemoryTypeMemoryMappedIo, - Instance->DeviceBaseAddress, - RuntimeMmioRegionSize, - EFI_MEMORY_UC | EFI_MEMORY_RUNTIME - ); - ASSERT_EFI_ERROR (Status); - - Status = gDS->SetMemorySpaceAttributes ( - Instance->DeviceBaseAddress, - RuntimeMmioRegionSize, - EFI_MEMORY_UC | EFI_MEMORY_RUNTIME - ); - ASSERT_EFI_ERROR (Status); - - mFlashNvStorageVariableBase = (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) ? - PcdGet64 (PcdFlashNvStorageVariableBase64) : PcdGet32 (PcdFlashNvStorageVariableBase); - - // Set the index of the first LBA for the FVB - Instance->StartLba = (mFlashNvStorageVariableBase - Instance->RegionBaseAddress) / Instance->Media.BlockSize; - - BootMode = GetBootModeHob (); - if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) { - Status = EFI_INVALID_PARAMETER; - } else { - // Determine if there is a valid header at the beginning of the NorFlash - Status = ValidateFvHeader (Instance); - } - - // Install the Default FVB header if required - if (EFI_ERROR (Status)) { - // There is no valid header, so time to install one. - DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__)); - DEBUG (( - DEBUG_INFO, - "%a: Installing a correct one for this volume.\n", - __FUNCTION__ - )); - - // Erase all the NorFlash that is reserved for variable storage - FvbNumLba = (PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize; - - Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR); - if (EFI_ERROR (Status)) { - return Status; - } - - // Install all appropriate headers - Status = InitializeFvAndVariableStoreHeaders (Instance); - if (EFI_ERROR (Status)) { - return Status; - } - } - - // - // The driver implementing the variable read service can now be dispatched; - // the varstore headers are in place. - // - Status = gBS->InstallProtocolInterface ( - &gImageHandle, - &gEdkiiNvVarStoreFormattedGuid, - EFI_NATIVE_INTERFACE, - NULL - ); - ASSERT_EFI_ERROR (Status); - - // - // Register for the virtual address change event - // - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, - TPL_NOTIFY, - FvbVirtualNotifyEvent, - NULL, - &gEfiEventVirtualAddressChangeGuid, - &mFvbVirtualAddrChangeEvent - ); - ASSERT_EFI_ERROR (Status); - - return Status; -} diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf deleted file mode 100644 index f8d4c27031..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf +++ /dev/null @@ -1,71 +0,0 @@ -#/** @file -# -# Component description file for NorFlashDxe module -# -# Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -#**/ - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = ArmVeNorFlashDxe - FILE_GUID = 93E34C7E-B50E-11DF-9223-2443DFD72085 - MODULE_TYPE = DXE_RUNTIME_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = NorFlashInitialise - -[Sources.common] - NorFlash.c - NorFlash.h - NorFlashDxe.c - NorFlashFvb.c - NorFlashBlockIoDxe.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - ArmPlatformPkg/ArmPlatformPkg.dec - EmbeddedPkg/EmbeddedPkg.dec - -[LibraryClasses] - IoLib - BaseLib - DebugLib - HobLib - NorFlashPlatformLib - UefiLib - UefiDriverEntryPoint - UefiBootServicesTableLib - UefiRuntimeLib - DxeServicesTableLib - -[Guids] - gEfiSystemNvDataFvGuid - gEfiVariableGuid - gEfiAuthenticatedVariableGuid - gEfiEventVirtualAddressChangeGuid - gEdkiiNvVarStoreFormattedGuid ## PRODUCES ## PROTOCOL - -[Protocols] - gEfiBlockIoProtocolGuid - gEfiDevicePathProtocolGuid - gEfiFirmwareVolumeBlockProtocolGuid - gEfiDiskIoProtocolGuid - -[Pcd.common] - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize - - gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked - -[Depex] - gEfiCpuArchProtocolGuid diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c deleted file mode 100644 index 0767581308..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvb.c +++ /dev/null @@ -1,777 +0,0 @@ -/*++ @file NorFlashFvbDxe.c - - Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - - --*/ - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "NorFlash.h" - -extern UINTN mFlashNvStorageVariableBase; -/// -/// The Firmware Volume Block Protocol is the low-level interface -/// to a firmware volume. File-level access to a firmware volume -/// should not be done using the Firmware Volume Block Protocol. -/// Normal access to a firmware volume must use the Firmware -/// Volume Protocol. Typically, only the file system driver that -/// produces the Firmware Volume Protocol will bind to the -/// Firmware Volume Block Protocol. -/// - -/** - Initialises the FV Header and Variable Store Header - to support variable operations. - - @param[in] Ptr - Location to initialise the headers - -**/ -EFI_STATUS -InitializeFvAndVariableStoreHeaders ( - IN NOR_FLASH_INSTANCE *Instance - ) -{ - EFI_STATUS Status; - VOID *Headers; - UINTN HeadersLength; - EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader; - VARIABLE_STORE_HEADER *VariableStoreHeader; - UINT32 NvStorageFtwSpareSize; - UINT32 NvStorageFtwWorkingSize; - UINT32 NvStorageVariableSize; - UINT64 NvStorageFtwSpareBase; - UINT64 NvStorageFtwWorkingBase; - UINT64 NvStorageVariableBase; - - HeadersLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY) + sizeof (VARIABLE_STORE_HEADER); - Headers = AllocateZeroPool (HeadersLength); - - NvStorageFtwWorkingSize = PcdGet32 (PcdFlashNvStorageFtwWorkingSize); - NvStorageFtwSpareSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize); - NvStorageVariableSize = PcdGet32 (PcdFlashNvStorageVariableSize); - - NvStorageFtwSpareBase = (PcdGet64 (PcdFlashNvStorageFtwSpareBase64) != 0) ? - PcdGet64 (PcdFlashNvStorageFtwSpareBase64) : PcdGet32 (PcdFlashNvStorageFtwSpareBase); - NvStorageFtwWorkingBase = (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) != 0) ? - PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) : PcdGet32 (PcdFlashNvStorageFtwWorkingBase); - NvStorageVariableBase = (PcdGet64 (PcdFlashNvStorageVariableBase64) != 0) ? - PcdGet64 (PcdFlashNvStorageVariableBase64) : PcdGet32 (PcdFlashNvStorageVariableBase); - - // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous. - if ((NvStorageVariableBase + NvStorageVariableSize) != NvStorageFtwWorkingBase) { - DEBUG (( - DEBUG_ERROR, - "%a: NvStorageFtwWorkingBase is not contiguous with NvStorageVariableBase region\n", - __FUNCTION__ - )); - return EFI_INVALID_PARAMETER; - } - - if ((NvStorageFtwWorkingBase + NvStorageFtwWorkingSize) != NvStorageFtwSpareBase) { - DEBUG (( - DEBUG_ERROR, - "%a: NvStorageFtwSpareBase is not contiguous with NvStorageFtwWorkingBase region\n", - __FUNCTION__ - )); - return EFI_INVALID_PARAMETER; - } - - // Check if the size of the area is at least one block size - if ((NvStorageVariableSize <= 0) || (NvStorageVariableSize / Instance->Media.BlockSize <= 0)) { - DEBUG (( - DEBUG_ERROR, - "%a: NvStorageVariableSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, - NvStorageVariableSize - )); - return EFI_INVALID_PARAMETER; - } - - if ((NvStorageFtwWorkingSize <= 0) || (NvStorageFtwWorkingSize / Instance->Media.BlockSize <= 0)) { - DEBUG (( - DEBUG_ERROR, - "%a: NvStorageFtwWorkingSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, - NvStorageFtwWorkingSize - )); - return EFI_INVALID_PARAMETER; - } - - if ((NvStorageFtwSpareSize <= 0) || (NvStorageFtwSpareSize / Instance->Media.BlockSize <= 0)) { - DEBUG (( - DEBUG_ERROR, - "%a: NvStorageFtwSpareSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, - NvStorageFtwSpareSize - )); - return EFI_INVALID_PARAMETER; - } - - // Ensure the Variable area Base Addresses are aligned on a block size boundaries - if ((NvStorageVariableBase % Instance->Media.BlockSize != 0) || - (NvStorageFtwWorkingBase % Instance->Media.BlockSize != 0) || - (NvStorageFtwSpareBase % Instance->Media.BlockSize != 0)) - { - DEBUG ((DEBUG_ERROR, "%a: NvStorage Base addresses must be aligned to block size boundaries", __FUNCTION__)); - return EFI_INVALID_PARAMETER; - } - - // - // EFI_FIRMWARE_VOLUME_HEADER - // - FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Headers; - CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid); - FirmwareVolumeHeader->FvLength = - PcdGet32 (PcdFlashNvStorageVariableSize) + - PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + - PcdGet32 (PcdFlashNvStorageFtwSpareSize); - FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE; - FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2)( - EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled - EFI_FVB2_READ_STATUS | // Reads are currently enabled - EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY - EFI_FVB2_MEMORY_MAPPED | // It is memory mapped - EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1') - EFI_FVB2_WRITE_STATUS | // Writes are currently enabled - EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled - ); - FirmwareVolumeHeader->HeaderLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY); - FirmwareVolumeHeader->Revision = EFI_FVH_REVISION; - FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1; - FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize; - FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0; - FirmwareVolumeHeader->BlockMap[1].Length = 0; - FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FirmwareVolumeHeader, FirmwareVolumeHeader->HeaderLength); - - // - // VARIABLE_STORE_HEADER - // - VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)Headers + FirmwareVolumeHeader->HeaderLength); - CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid); - VariableStoreHeader->Size = PcdGet32 (PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength; - VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED; - VariableStoreHeader->State = VARIABLE_STORE_HEALTHY; - - // Install the combined super-header in the NorFlash - Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers); - - FreePool (Headers); - return Status; -} - -/** - Check the integrity of firmware volume header. - - @param[in] FwVolHeader - A pointer to a firmware volume header - - @retval EFI_SUCCESS - The firmware volume is consistent - @retval EFI_NOT_FOUND - The firmware volume has been corrupted. - -**/ -EFI_STATUS -ValidateFvHeader ( - IN NOR_FLASH_INSTANCE *Instance - ) -{ - UINT16 Checksum; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - VARIABLE_STORE_HEADER *VariableStoreHeader; - UINTN VariableStoreLength; - UINTN FvLength; - - FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Instance->RegionBaseAddress; - - FvLength = PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + - PcdGet32 (PcdFlashNvStorageFtwSpareSize); - - // - // Verify the header revision, header signature, length - // Length of FvBlock cannot be 2**64-1 - // HeaderLength cannot be an odd number - // - if ( (FwVolHeader->Revision != EFI_FVH_REVISION) - || (FwVolHeader->Signature != EFI_FVH_SIGNATURE) - || (FwVolHeader->FvLength != FvLength) - ) - { - DEBUG (( - DEBUG_INFO, - "%a: No Firmware Volume header present\n", - __FUNCTION__ - )); - return EFI_NOT_FOUND; - } - - // Check the Firmware Volume Guid - if ( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) { - DEBUG (( - DEBUG_INFO, - "%a: Firmware Volume Guid non-compatible\n", - __FUNCTION__ - )); - return EFI_NOT_FOUND; - } - - // Verify the header checksum - Checksum = CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength); - if (Checksum != 0) { - DEBUG (( - DEBUG_INFO, - "%a: FV checksum is invalid (Checksum:0x%X)\n", - __FUNCTION__, - Checksum - )); - return EFI_NOT_FOUND; - } - - VariableStoreHeader = (VARIABLE_STORE_HEADER *)((UINTN)FwVolHeader + FwVolHeader->HeaderLength); - - // Check the Variable Store Guid - if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) && - !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid)) - { - DEBUG (( - DEBUG_INFO, - "%a: Variable Store Guid non-compatible\n", - __FUNCTION__ - )); - return EFI_NOT_FOUND; - } - - VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength; - if (VariableStoreHeader->Size != VariableStoreLength) { - DEBUG (( - DEBUG_INFO, - "%a: Variable Store Length does not match\n", - __FUNCTION__ - )); - return EFI_NOT_FOUND; - } - - return EFI_SUCCESS; -} - -/** - The GetAttributes() function retrieves the attributes and - current settings of the block. - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and - current settings are returned. - Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER. - - @retval EFI_SUCCESS The firmware volume attributes were returned. - - **/ -EFI_STATUS -EFIAPI -FvbGetAttributes ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - OUT EFI_FVB_ATTRIBUTES_2 *Attributes - ) -{ - EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes; - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2)( - - EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled - EFI_FVB2_READ_STATUS | // Reads are currently enabled - EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY - EFI_FVB2_MEMORY_MAPPED | // It is memory mapped - EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1') - - ); - - // Check if it is write protected - if (Instance->Media.ReadOnly != TRUE) { - FlashFvbAttributes = FlashFvbAttributes | - EFI_FVB2_WRITE_STATUS | // Writes are currently enabled - EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled - } - - *Attributes = FlashFvbAttributes; - - DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes)); - - return EFI_SUCCESS; -} - -/** - The SetAttributes() function sets configurable firmware volume attributes - and returns the new settings of the firmware volume. - - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2 - that contains the desired firmware volume settings. - On successful return, it contains the new settings of - the firmware volume. - Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER. - - @retval EFI_SUCCESS The firmware volume attributes were returned. - - @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities - as declared in the firmware volume header. - - **/ -EFI_STATUS -EFIAPI -FvbSetAttributes ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes - ) -{ - DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n", *Attributes)); - return EFI_UNSUPPORTED; -} - -/** - The GetPhysicalAddress() function retrieves the base address of - a memory-mapped firmware volume. This function should be called - only for memory-mapped firmware volumes. - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Address Pointer to a caller-allocated - EFI_PHYSICAL_ADDRESS that, on successful - return from GetPhysicalAddress(), contains the - base address of the firmware volume. - - @retval EFI_SUCCESS The firmware volume base address was returned. - - @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped. - - **/ -EFI_STATUS -EFIAPI -FvbGetPhysicalAddress ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - OUT EFI_PHYSICAL_ADDRESS *Address - ) -{ - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress)); - - ASSERT (Address != NULL); - - *Address = mFlashNvStorageVariableBase; - return EFI_SUCCESS; -} - -/** - The GetBlockSize() function retrieves the size of the requested - block. It also returns the number of additional blocks with - the identical size. The GetBlockSize() function is used to - retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER). - - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Lba Indicates the block for which to return the size. - - @param BlockSize Pointer to a caller-allocated UINTN in which - the size of the block is returned. - - @param NumberOfBlocks Pointer to a caller-allocated UINTN in - which the number of consecutive blocks, - starting with Lba, is returned. All - blocks in this range have a size of - BlockSize. - - - @retval EFI_SUCCESS The firmware volume base address was returned. - - @retval EFI_INVALID_PARAMETER The requested LBA is out of range. - - **/ -EFI_STATUS -EFIAPI -FvbGetBlockSize ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - OUT UINTN *BlockSize, - OUT UINTN *NumberOfBlocks - ) -{ - EFI_STATUS Status; - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock)); - - if (Lba > Instance->Media.LastBlock) { - DEBUG ((DEBUG_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock)); - Status = EFI_INVALID_PARAMETER; - } else { - // This is easy because in this platform each NorFlash device has equal sized blocks. - *BlockSize = (UINTN)Instance->Media.BlockSize; - *NumberOfBlocks = (UINTN)(Instance->Media.LastBlock - Lba + 1); - - DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks)); - - Status = EFI_SUCCESS; - } - - return Status; -} - -/** - Reads the specified number of bytes into a buffer from the specified block. - - The Read() function reads the requested number of bytes from the - requested block and stores them in the provided buffer. - Implementations should be mindful that the firmware volume - might be in the ReadDisabled state. If it is in this state, - the Read() function must return the status code - EFI_ACCESS_DENIED without modifying the contents of the - buffer. The Read() function must also prevent spanning block - boundaries. If a read is requested that would span a block - boundary, the read must read up to the boundary but not - beyond. The output parameter NumBytes must be set to correctly - indicate the number of bytes actually read. The caller must be - aware that a read may be partially completed. - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Lba The starting logical block index from which to read. - - @param Offset Offset into the block at which to begin reading. - - @param NumBytes Pointer to a UINTN. - At entry, *NumBytes contains the total size of the buffer. - At exit, *NumBytes contains the total number of bytes read. - - @param Buffer Pointer to a caller-allocated buffer that will be used - to hold the data that is read. - - @retval EFI_SUCCESS The firmware volume was read successfully, and contents are - in Buffer. - - @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary. - On output, NumBytes contains the total number of bytes - returned in Buffer. - - @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state. - - @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read. - - **/ -EFI_STATUS -EFIAPI -FvbRead ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN OUT UINT8 *Buffer - ) -{ - EFI_STATUS TempStatus; - UINTN BlockSize; - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer)); - - TempStatus = EFI_SUCCESS; - - // Cache the block size to avoid de-referencing pointers all the time - BlockSize = Instance->Media.BlockSize; - - DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); - - // The read must not span block boundaries. - // We need to check each variable individually because adding two large values together overflows. - if ((Offset >= BlockSize) || - (*NumBytes > BlockSize) || - ((Offset + *NumBytes) > BlockSize)) - { - DEBUG ((DEBUG_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize)); - return EFI_BAD_BUFFER_SIZE; - } - - // We must have some bytes to read - if (*NumBytes == 0) { - return EFI_BAD_BUFFER_SIZE; - } - - // Decide if we are doing full block reads or not. - if (*NumBytes % BlockSize != 0) { - TempStatus = NorFlashRead (Instance, Instance->StartLba + Lba, Offset, *NumBytes, Buffer); - if (EFI_ERROR (TempStatus)) { - return EFI_DEVICE_ERROR; - } - } else { - // Read NOR Flash data into shadow buffer - TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, Buffer); - if (EFI_ERROR (TempStatus)) { - // Return one of the pre-approved error statuses - return EFI_DEVICE_ERROR; - } - } - - return EFI_SUCCESS; -} - -/** - Writes the specified number of bytes from the input buffer to the block. - - The Write() function writes the specified number of bytes from - the provided buffer to the specified block and offset. If the - firmware volume is sticky write, the caller must ensure that - all the bits of the specified range to write are in the - EFI_FVB_ERASE_POLARITY state before calling the Write() - function, or else the result will be unpredictable. This - unpredictability arises because, for a sticky-write firmware - volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY - state but cannot flip it back again. Before calling the - Write() function, it is recommended for the caller to first call - the EraseBlocks() function to erase the specified block to - write. A block erase cycle will transition bits from the - (NOT)EFI_FVB_ERASE_POLARITY state back to the - EFI_FVB_ERASE_POLARITY state. Implementations should be - mindful that the firmware volume might be in the WriteDisabled - state. If it is in this state, the Write() function must - return the status code EFI_ACCESS_DENIED without modifying the - contents of the firmware volume. The Write() function must - also prevent spanning block boundaries. If a write is - requested that spans a block boundary, the write must store up - to the boundary but not beyond. The output parameter NumBytes - must be set to correctly indicate the number of bytes actually - written. The caller must be aware that a write may be - partially completed. All writes, partial or otherwise, must be - fully flushed to the hardware before the Write() service - returns. - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance. - - @param Lba The starting logical block index to write to. - - @param Offset Offset into the block at which to begin writing. - - @param NumBytes The pointer to a UINTN. - At entry, *NumBytes contains the total size of the buffer. - At exit, *NumBytes contains the total number of bytes actually written. - - @param Buffer The pointer to a caller-allocated buffer that contains the source for the write. - - @retval EFI_SUCCESS The firmware volume was written successfully. - - @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary. - On output, NumBytes contains the total number of bytes - actually written. - - @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state. - - @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written. - - - **/ -EFI_STATUS -EFIAPI -FvbWrite ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer - ) -{ - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - return NorFlashWriteSingleBlock (Instance, Instance->StartLba + Lba, Offset, NumBytes, Buffer); -} - -/** - Erases and initialises a firmware volume block. - - The EraseBlocks() function erases one or more blocks as denoted - by the variable argument list. The entire parameter list of - blocks must be verified before erasing any blocks. If a block is - requested that does not exist within the associated firmware - volume (it has a larger index than the last block of the - firmware volume), the EraseBlocks() function must return the - status code EFI_INVALID_PARAMETER without modifying the contents - of the firmware volume. Implementations should be mindful that - the firmware volume might be in the WriteDisabled state. If it - is in this state, the EraseBlocks() function must return the - status code EFI_ACCESS_DENIED without modifying the contents of - the firmware volume. All calls to EraseBlocks() must be fully - flushed to the hardware before the EraseBlocks() service - returns. - - @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL - instance. - - @param ... The variable argument list is a list of tuples. - Each tuple describes a range of LBAs to erase - and consists of the following: - - An EFI_LBA that indicates the starting LBA - - A UINTN that indicates the number of blocks to erase. - - The list is terminated with an EFI_LBA_LIST_TERMINATOR. - For example, the following indicates that two ranges of blocks - (5-7 and 10-11) are to be erased: - EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR); - - @retval EFI_SUCCESS The erase request successfully completed. - - @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state. - - @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written. - The firmware device may have been partially erased. - - @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do - not exist in the firmware volume. - - **/ -EFI_STATUS -EFIAPI -FvbEraseBlocks ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This, - ... - ) -{ - EFI_STATUS Status; - VA_LIST Args; - UINTN BlockAddress; // Physical address of Lba to erase - EFI_LBA StartingLba; // Lba from which we start erasing - UINTN NumOfLba; // Number of Lba blocks to erase - NOR_FLASH_INSTANCE *Instance; - - Instance = INSTANCE_FROM_FVB_THIS (This); - - DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n")); - - Status = EFI_SUCCESS; - - // Detect WriteDisabled state - if (Instance->Media.ReadOnly == TRUE) { - // Firmware volume is in WriteDisabled state - DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n")); - return EFI_ACCESS_DENIED; - } - - // Before erasing, check the entire list of parameters to ensure all specified blocks are valid - - VA_START (Args, This); - do { - // Get the Lba from which we start erasing - StartingLba = VA_ARG (Args, EFI_LBA); - - // Have we reached the end of the list? - if (StartingLba == EFI_LBA_LIST_TERMINATOR) { - // Exit the while loop - break; - } - - // How many Lba blocks are we requested to erase? - NumOfLba = VA_ARG (Args, UINTN); - - // All blocks must be within range - DEBUG (( - DEBUG_BLKIO, - "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%Lu - 1 ) > LastBlock=%ld.\n", - Instance->StartLba + StartingLba, - (UINT64)NumOfLba, - Instance->Media.LastBlock - )); - if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) { - VA_END (Args); - DEBUG ((DEBUG_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n")); - Status = EFI_INVALID_PARAMETER; - goto EXIT; - } - } while (TRUE); - - VA_END (Args); - - // - // To get here, all must be ok, so start erasing - // - VA_START (Args, This); - do { - // Get the Lba from which we start erasing - StartingLba = VA_ARG (Args, EFI_LBA); - - // Have we reached the end of the list? - if (StartingLba == EFI_LBA_LIST_TERMINATOR) { - // Exit the while loop - break; - } - - // How many Lba blocks are we requested to erase? - NumOfLba = VA_ARG (Args, UINTN); - - // Go through each one and erase it - while (NumOfLba > 0) { - // Get the physical address of Lba to erase - BlockAddress = GET_NOR_BLOCK_ADDRESS ( - Instance->RegionBaseAddress, - Instance->StartLba + StartingLba, - Instance->Media.BlockSize - ); - - // Erase it - DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress)); - Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress); - if (EFI_ERROR (Status)) { - VA_END (Args); - Status = EFI_DEVICE_ERROR; - goto EXIT; - } - - // Move to the next Lba - StartingLba++; - NumOfLba--; - } - } while (TRUE); - - VA_END (Args); - -EXIT: - return Status; -} - -/** - 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 -FvbVirtualNotifyEvent ( - IN EFI_EVENT Event, - IN VOID *Context - ) -{ - EfiConvertPointer (0x0, (VOID **)&mFlashNvStorageVariableBase); - return; -} diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.c deleted file mode 100644 index b72ad97b0b..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.c +++ /dev/null @@ -1,383 +0,0 @@ -/** @file NorFlashStandaloneMm.c - - Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
- Copyright (c) 2020, Linaro, Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -#include "NorFlash.h" - -// -// Global variable declarations -// -NOR_FLASH_INSTANCE **mNorFlashInstances; -UINT32 mNorFlashDeviceCount; -UINTN mFlashNvStorageVariableBase; - -NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = { - NOR_FLASH_SIGNATURE, // Signature - NULL, // Handle ... NEED TO BE FILLED - - 0, // DeviceBaseAddress ... NEED TO BE FILLED - 0, // RegionBaseAddress ... NEED TO BE FILLED - 0, // Size ... NEED TO BE FILLED - 0, // StartLba - - { - EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision - NULL, // Media ... NEED TO BE FILLED - NULL, // Reset; - NULL, // ReadBlocks - NULL, // WriteBlocks - NULL // FlushBlocks - }, // BlockIoProtocol - - { - 0, // MediaId ... NEED TO BE FILLED - FALSE, // RemovableMedia - TRUE, // MediaPresent - FALSE, // LogicalPartition - FALSE, // ReadOnly - FALSE, // WriteCaching; - 0, // BlockSize ... NEED TO BE FILLED - 4, // IoAlign - 0, // LastBlock ... NEED TO BE FILLED - 0, // LowestAlignedLba - 1, // LogicalBlocksPerPhysicalBlock - }, // Media; - - { - EFI_DISK_IO_PROTOCOL_REVISION, // Revision - NULL, // ReadDisk - NULL // WriteDisk - }, - - { - FvbGetAttributes, // GetAttributes - FvbSetAttributes, // SetAttributes - FvbGetPhysicalAddress, // GetPhysicalAddress - FvbGetBlockSize, // GetBlockSize - FvbRead, // Read - FvbWrite, // Write - FvbEraseBlocks, // EraseBlocks - NULL, // ParentHandle - }, // FvbProtoccol; - NULL, // ShadowBuffer - { - { - { - HARDWARE_DEVICE_PATH, - HW_VENDOR_DP, - { - (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End)), - (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End) >> 8) - } - }, - { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } - }, // GUID ... NEED TO BE FILLED - }, - 0, // Index - { - END_DEVICE_PATH_TYPE, - END_ENTIRE_DEVICE_PATH_SUBTYPE, - { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 } - } - } // DevicePath -}; - -EFI_STATUS -NorFlashCreateInstance ( - IN UINTN NorFlashDeviceBase, - IN UINTN NorFlashRegionBase, - IN UINTN NorFlashSize, - IN UINT32 Index, - IN UINT32 BlockSize, - IN BOOLEAN SupportFvb, - OUT NOR_FLASH_INSTANCE **NorFlashInstance - ) -{ - EFI_STATUS Status; - NOR_FLASH_INSTANCE *Instance; - - ASSERT (NorFlashInstance != NULL); - - Instance = AllocateRuntimeCopyPool (sizeof (NOR_FLASH_INSTANCE), &mNorFlashInstanceTemplate); - if (Instance == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - Instance->DeviceBaseAddress = NorFlashDeviceBase; - Instance->RegionBaseAddress = NorFlashRegionBase; - Instance->Size = NorFlashSize; - - Instance->BlockIoProtocol.Media = &Instance->Media; - Instance->Media.MediaId = Index; - Instance->Media.BlockSize = BlockSize; - Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1; - - CopyGuid (&Instance->DevicePath.Vendor.Guid, &gEfiCallerIdGuid); - Instance->DevicePath.Index = (UINT8)Index; - - Instance->ShadowBuffer = AllocateRuntimePool (BlockSize); - if (Instance->ShadowBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - if (SupportFvb) { - NorFlashFvbInitialize (Instance); - - Status = gMmst->MmInstallProtocolInterface ( - &Instance->Handle, - &gEfiSmmFirmwareVolumeBlockProtocolGuid, - EFI_NATIVE_INTERFACE, - &Instance->FvbProtocol - ); - if (EFI_ERROR (Status)) { - FreePool (Instance); - return Status; - } - } else { - DEBUG ((DEBUG_ERROR, "standalone MM NOR Flash driver only support FVB.\n")); - FreePool (Instance); - return EFI_UNSUPPORTED; - } - - *NorFlashInstance = Instance; - return Status; -} - -/** - * This function unlock and erase an entire NOR Flash block. - **/ -EFI_STATUS -NorFlashUnlockAndEraseSingleBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN UINTN BlockAddress - ) -{ - EFI_STATUS Status; - UINTN Index; - - Index = 0; - // The block erase might fail a first time (SW bug ?). Retry it ... - do { - // Unlock the block if we have to - Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress); - if (EFI_ERROR (Status)) { - break; - } - - Status = NorFlashEraseSingleBlock (Instance, BlockAddress); - Index++; - } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED)); - - if (Index == NOR_FLASH_ERASE_RETRY) { - DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index)); - } - - return Status; -} - -EFI_STATUS -NorFlashWriteFullBlock ( - IN NOR_FLASH_INSTANCE *Instance, - IN EFI_LBA Lba, - IN UINT32 *DataBuffer, - IN UINT32 BlockSizeInWords - ) -{ - EFI_STATUS Status; - UINTN WordAddress; - UINT32 WordIndex; - UINTN BufferIndex; - UINTN BlockAddress; - UINTN BuffersInBlock; - UINTN RemainingWords; - UINTN Cnt; - - Status = EFI_SUCCESS; - - // Get the physical address of the block - BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4); - - // Start writing from the first address at the start of the block - WordAddress = BlockAddress; - - Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress)); - goto EXIT; - } - - // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method. - - // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero - if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) { - // First, break the entire block into buffer-sized chunks. - BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES; - - // Then feed each buffer chunk to the NOR Flash - // If a buffer does not contain any data, don't write it. - for (BufferIndex = 0; - BufferIndex < BuffersInBlock; - BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS - ) - { - // Check the buffer to see if it contains any data (not set all 1s). - for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) { - if (~DataBuffer[Cnt] != 0 ) { - // Some data found, write the buffer. - Status = NorFlashWriteBuffer ( - Instance, - WordAddress, - P30_MAX_BUFFER_SIZE_IN_BYTES, - DataBuffer - ); - if (EFI_ERROR (Status)) { - goto EXIT; - } - - break; - } - } - } - - // Finally, finish off any remaining words that are less than the maximum size of the buffer - RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS; - - if (RemainingWords != 0) { - Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer); - if (EFI_ERROR (Status)) { - goto EXIT; - } - } - } else { - // For now, use the single word programming algorithm - // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range, - // i.e. which ends in the range 0x......01 - 0x......7F. - for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) { - Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer); - if (EFI_ERROR (Status)) { - goto EXIT; - } - } - } - -EXIT: - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status)); - } - - return Status; -} - -EFI_STATUS -EFIAPI -NorFlashInitialise ( - IN EFI_HANDLE ImageHandle, - IN EFI_MM_SYSTEM_TABLE *MmSystemTable - ) -{ - EFI_STATUS Status; - UINT32 Index; - NOR_FLASH_DESCRIPTION *NorFlashDevices; - BOOLEAN ContainVariableStorage; - - Status = NorFlashPlatformInitialization (); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to initialize Nor Flash devices\n")); - return Status; - } - - Status = NorFlashPlatformGetDevices (&NorFlashDevices, &mNorFlashDeviceCount); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to get Nor Flash devices\n")); - return Status; - } - - mNorFlashInstances = AllocatePool (sizeof (NOR_FLASH_INSTANCE *) * mNorFlashDeviceCount); - - for (Index = 0; Index < mNorFlashDeviceCount; Index++) { - // Check if this NOR Flash device contain the variable storage region - - if (FixedPcdGet64 (PcdFlashNvStorageVariableBase64) != 0) { - ContainVariableStorage = - (NorFlashDevices[Index].RegionBaseAddress <= FixedPcdGet64 (PcdFlashNvStorageVariableBase64)) && - (FixedPcdGet64 (PcdFlashNvStorageVariableBase64) + FixedPcdGet32 (PcdFlashNvStorageVariableSize) <= - NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); - } else { - ContainVariableStorage = - (NorFlashDevices[Index].RegionBaseAddress <= FixedPcdGet32 (PcdFlashNvStorageVariableBase)) && - (FixedPcdGet32 (PcdFlashNvStorageVariableBase) + FixedPcdGet32 (PcdFlashNvStorageVariableSize) <= - NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size); - } - - Status = NorFlashCreateInstance ( - NorFlashDevices[Index].DeviceBaseAddress, - NorFlashDevices[Index].RegionBaseAddress, - NorFlashDevices[Index].Size, - Index, - NorFlashDevices[Index].BlockSize, - ContainVariableStorage, - &mNorFlashInstances[Index] - ); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "NorFlashInitialise: Fail to create instance for NorFlash[%d]\n", Index)); - } - } - - return Status; -} - -EFI_STATUS -EFIAPI -NorFlashFvbInitialize ( - IN NOR_FLASH_INSTANCE *Instance - ) -{ - EFI_STATUS Status; - UINT32 FvbNumLba; - - ASSERT ((Instance != NULL)); - - mFlashNvStorageVariableBase = (FixedPcdGet64 (PcdFlashNvStorageVariableBase64) != 0) ? - FixedPcdGet64 (PcdFlashNvStorageVariableBase64) : FixedPcdGet32 (PcdFlashNvStorageVariableBase); - // Set the index of the first LBA for the FVB - Instance->StartLba = (mFlashNvStorageVariableBase - Instance->RegionBaseAddress) / Instance->Media.BlockSize; - - // Determine if there is a valid header at the beginning of the NorFlash - Status = ValidateFvHeader (Instance); - - // Install the Default FVB header if required - if (EFI_ERROR (Status)) { - // There is no valid header, so time to install one. - DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__)); - DEBUG (( - DEBUG_INFO, - "%a: Installing a correct one for this volume.\n", - __FUNCTION__ - )); - - // Erase all the NorFlash that is reserved for variable storage - FvbNumLba = (PcdGet32 (PcdFlashNvStorageVariableSize) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) + PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize; - - Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR); - if (EFI_ERROR (Status)) { - return Status; - } - - // Install all appropriate headers - Status = InitializeFvAndVariableStoreHeaders (Instance); - if (EFI_ERROR (Status)) { - return Status; - } - } - - return Status; -} diff --git a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf b/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf deleted file mode 100644 index b8dddd5cbe..0000000000 --- a/ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf +++ /dev/null @@ -1,66 +0,0 @@ -#/** @file -# -# Component description file for NorFlashStandaloneMm module -# -# Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.
-# Copyright (c) 2020, Linaro, Ltd. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -#**/ - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = ArmVeNorFlashStandaloneMm - FILE_GUID = e67d82ad-cd56-4071-9151-95ee44990bb0 - MODULE_TYPE = MM_STANDALONE - VERSION_STRING = 1.0 - PI_SPECIFICATION_VERSION = 0x00010032 - ENTRY_POINT = NorFlashInitialise - -[Sources.common] - NorFlash.h - NorFlash.c - NorFlashStandaloneMm.c - NorFlashFvb.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - ArmPlatformPkg/ArmPlatformPkg.dec - EmbeddedPkg/EmbeddedPkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - IoLib - MemoryAllocationLib - MmServicesTableLib - NorFlashPlatformLib - StandaloneMmDriverEntryPoint - -[Guids] - gEfiSystemNvDataFvGuid - gEfiVariableGuid - gEfiAuthenticatedVariableGuid - -[Protocols] - gEfiSmmFirmwareVolumeBlockProtocolGuid - -[FixedPcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase - gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize - -[FeaturePcd] - gArmPlatformTokenSpaceGuid.PcdNorFlashCheckBlockLocked - -[Depex] - TRUE diff --git a/ArmPlatformPkg/Include/Library/NorFlashPlatformLib.h b/ArmPlatformPkg/Include/Library/NorFlashPlatformLib.h deleted file mode 100644 index 6ef5b70e99..0000000000 --- a/ArmPlatformPkg/Include/Library/NorFlashPlatformLib.h +++ /dev/null @@ -1,30 +0,0 @@ -/** @file - - Copyright (c) 2011-2012, ARM Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - - **/ - -#ifndef _NORFLASHPLATFORMLIB_H_ -#define _NORFLASHPLATFORMLIB_H_ - -typedef struct { - UINTN DeviceBaseAddress; // Start address of the Device Base Address (DBA) - UINTN RegionBaseAddress; // Start address of one single region - UINTN Size; - UINTN BlockSize; -} NOR_FLASH_DESCRIPTION; - -EFI_STATUS -NorFlashPlatformInitialization ( - VOID - ); - -EFI_STATUS -NorFlashPlatformGetDevices ( - OUT NOR_FLASH_DESCRIPTION **NorFlashDescriptions, - OUT UINT32 *Count - ); - -#endif /* _NORFLASHPLATFORMLIB_H_ */ diff --git a/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.c b/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.c deleted file mode 100644 index 6e11b23fdb..0000000000 --- a/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.c +++ /dev/null @@ -1,28 +0,0 @@ -/** @file - - Copyright (c) 2014, Linaro Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - - **/ - -#include - -EFI_STATUS -NorFlashPlatformInitialization ( - VOID - ) -{ - return EFI_SUCCESS; -} - -EFI_STATUS -NorFlashPlatformGetDevices ( - OUT NOR_FLASH_DESCRIPTION **NorFlashDescriptions, - OUT UINT32 *Count - ) -{ - *NorFlashDescriptions = NULL; - *Count = 0; - return EFI_SUCCESS; -} diff --git a/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf b/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf deleted file mode 100644 index 3a2d5a1715..0000000000 --- a/ArmPlatformPkg/Library/NorFlashPlatformNullLib/NorFlashPlatformNullLib.inf +++ /dev/null @@ -1,24 +0,0 @@ -#/** @file -# -# Component description file for NorFlashPlatformNullLib module -# -# Copyright (c) 2017, Linaro Ltd. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -#**/ - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = NorFlashPlatformNullLib - FILE_GUID = 29b733ad-d066-4df6-8a89-b9df1beb818a - MODULE_TYPE = DXE_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = NorFlashPlatformLib - -[Sources.common] - NorFlashPlatformNullLib.c - -[Packages] - MdePkg/MdePkg.dec - ArmPlatformPkg/ArmPlatformPkg.dec From c9abebf875619c6213a053f7e31c936b01fd8131 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:41 +0200 Subject: [PATCH 0279/1529] ArmPkg: PCD to select conduit for monitor calls Define a PCD 'PcdMonitorConduitHvc' to select the conduit to use for monitor calls. PcdMonitorConduitHvc is defined as FALSE by default, meaning the SMC conduit is enabled as default. Adding PcdMonitorConduitHvc allows selection of HVC conduit to be used by virtual firmware implementations. Reviewed-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dec | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ArmPkg/ArmPkg.dec b/ArmPkg/ArmPkg.dec index cfb6fe6024..99cb024d0f 100644 --- a/ArmPkg/ArmPkg.dec +++ b/ArmPkg/ArmPkg.dec @@ -2,7 +2,7 @@ # ARM processor package. # # Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.
-# Copyright (c) 2011 - 2021, ARM Limited. All rights reserved. +# Copyright (c) 2011 - 2022, ARM Limited. All rights reserved. # Copyright (c) 2021, Ampere Computing LLC. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -134,6 +134,11 @@ # Define if the GICv3 controller should use the GICv2 legacy gArmTokenSpaceGuid.PcdArmGicV3WithV2Legacy|FALSE|BOOLEAN|0x00000042 + ## Define the conduit to use for monitor calls. + # Default PcdMonitorConduitHvc = FALSE, conduit = SMC + # If PcdMonitorConduitHvc = TRUE, conduit = HVC + gArmTokenSpaceGuid.PcdMonitorConduitHvc|FALSE|BOOLEAN|0x00000047 + [PcdsFeatureFlag.ARM] # Whether to map normal memory as non-shareable. FALSE is the safe choice, but # TRUE may be appropriate to fix performance problems if you don't care about From 525fabfd1c94282c7778c44217daf208375620df Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:42 +0200 Subject: [PATCH 0280/1529] ArmPkg/ArmMonitorLib: Definition for ArmMonitorLib library class The ArmMonitorLib provides an abstract interface to issue an HyperVisor Call (HVC) or System Monitor Call (SMC) depending on the default conduit. The PcdMonitorConduitHvc PCD allows to select the default conduit. The new library relies on the ArmHvcLib and ArmSmcLib libraries. A Null instance of these libraries can be used for the unused conduit. Reviewed-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dec | 5 +++ ArmPkg/Include/Library/ArmMonitorLib.h | 42 ++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 ArmPkg/Include/Library/ArmMonitorLib.h diff --git a/ArmPkg/ArmPkg.dec b/ArmPkg/ArmPkg.dec index 99cb024d0f..f17ba913e6 100644 --- a/ArmPkg/ArmPkg.dec +++ b/ArmPkg/ArmPkg.dec @@ -71,6 +71,11 @@ # ArmSvcLib|Include/Library/ArmSvcLib.h + ## @libraryclass Provides a Monitor Call interface that will use the + # default conduit (HVC or SMC). + # + ArmMonitorLib|Include/Library/ArmMonitorLib.h + ## @libraryclass Provides a default exception handler. # DefaultExceptionHandlerLib|Include/Library/DefaultExceptionHandlerLib.h diff --git a/ArmPkg/Include/Library/ArmMonitorLib.h b/ArmPkg/Include/Library/ArmMonitorLib.h new file mode 100644 index 0000000000..d6e13b61d6 --- /dev/null +++ b/ArmPkg/Include/Library/ArmMonitorLib.h @@ -0,0 +1,42 @@ +/** @file + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef ARM_MONITOR_LIB_H_ +#define ARM_MONITOR_LIB_H_ + +/** The size of the SMC arguments is different between AArch64 and AArch32. + + The native size is used for the arguments. + It will be casted to either HVC or SMC args. +*/ +typedef struct { + UINTN Arg0; + UINTN Arg1; + UINTN Arg2; + UINTN Arg3; + UINTN Arg4; + UINTN Arg5; + UINTN Arg6; + UINTN Arg7; +} ARM_MONITOR_ARGS; + +/** Monitor call. + + An HyperVisor Call (HVC) or System Monitor Call (SMC) will be issued + depending on the default conduit. PcdMonitorConduitHvc determines the type + of the call: if true, do an HVC. + + @param [in,out] Args Arguments for the HVC/SMC. +**/ +VOID +EFIAPI +ArmMonitorCall ( + IN OUT ARM_MONITOR_ARGS *Args + ); + +#endif // ARM_MONITOR_LIB_H_ From a465911e242f917d615eaa7135c9fb9f67d80d2e Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:43 +0200 Subject: [PATCH 0281/1529] ArmPkg/ArmMonitorLib: Add ArmMonitorLib The ArmMonitorLib provides an abstract interface to issue an HyperVisor Call (HVC) or System Monitor Call (SMC) depending on the default conduit. The PcdMonitorConduitHvc PCD allows to select the default conduit. Reviewed-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dsc | 1 + ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.c | 34 +++++++++++++++++++ .../Library/ArmMonitorLib/ArmMonitorLib.inf | 29 ++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.c create mode 100644 ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 59fd8f295d..3afd212f47 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -135,6 +135,7 @@ ArmPkg/Library/ArmSmcLibNull/ArmSmcLibNull.inf ArmPkg/Library/ArmHvcLib/ArmHvcLib.inf ArmPkg/Library/ArmSvcLib/ArmSvcLib.inf + ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf ArmPkg/Library/OpteeLib/OpteeLib.inf ArmPkg/Filesystem/SemihostFs/SemihostFs.inf diff --git a/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.c b/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.c new file mode 100644 index 0000000000..741f5c6157 --- /dev/null +++ b/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.c @@ -0,0 +1,34 @@ +/** @file + Arm Monitor Library. + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include + +/** Monitor call. + + An HyperVisor Call (HVC) or System Monitor Call (SMC) will be issued + depending on the default conduit. PcdMonitorConduitHvc determines the type + of the call: if true, do an HVC. + + @param [in,out] Args Arguments for the HVC/SMC. +**/ +VOID +EFIAPI +ArmMonitorCall ( + IN OUT ARM_MONITOR_ARGS *Args + ) +{ + if (FeaturePcdGet (PcdMonitorConduitHvc)) { + ArmCallHvc ((ARM_HVC_ARGS *)Args); + } else { + ArmCallSmc ((ARM_SMC_ARGS *)Args); + } +} diff --git a/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf b/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf new file mode 100644 index 0000000000..f504cb80f1 --- /dev/null +++ b/ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf @@ -0,0 +1,29 @@ +## @file +# Arm Monitor Library +# +# Copyright (c) 2022, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = ArmMonitorLib + FILE_GUID = F918DACB-FBB8-4CB6-A61D-08E75AF0E7CD + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ArmMonitorLib + +[Sources] + ArmMonitorLib.c + +[Packages] + ArmPkg/ArmPkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + ArmHvcLib + ArmSmcLib + +[Pcd] + gArmTokenSpaceGuid.PcdMonitorConduitHvc From 6d174216a43ef6d7e1a93d4716fc820d2afa9b8b Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:44 +0200 Subject: [PATCH 0282/1529] ArmPkg: Sort HVC/SMC section alphbetically in ArmPkg.dsc Sort the section containing HVC/SMC libraries prior to adding new libraries in this specific section. Reviewed-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dsc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 3afd212f47..13e20a258e 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -131,11 +131,11 @@ ArmPkg/Library/ArmGenericTimerPhyCounterLib/ArmGenericTimerPhyCounterLib.inf ArmPkg/Library/ArmGenericTimerVirtCounterLib/ArmGenericTimerVirtCounterLib.inf + ArmPkg/Library/ArmHvcLib/ArmHvcLib.inf + ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf ArmPkg/Library/ArmSmcLib/ArmSmcLib.inf ArmPkg/Library/ArmSmcLibNull/ArmSmcLibNull.inf - ArmPkg/Library/ArmHvcLib/ArmHvcLib.inf ArmPkg/Library/ArmSvcLib/ArmSvcLib.inf - ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf ArmPkg/Library/OpteeLib/OpteeLib.inf ArmPkg/Filesystem/SemihostFs/SemihostFs.inf From f6d41adfcef070a8b2e5824330bdb4ea7733ce51 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:45 +0200 Subject: [PATCH 0283/1529] ArmPkg/ArmHvcLibNull: Add NULL instance of ArmHvcLib Add a Null instance of ArmHvcLib in case of library dependencies. Reviewed-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dsc | 1 + ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.c | 29 +++++++++++++++++++ .../Library/ArmHvcLibNull/ArmHvcLibNull.inf | 22 ++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.c create mode 100644 ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 13e20a258e..11b4739744 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -132,6 +132,7 @@ ArmPkg/Library/ArmGenericTimerVirtCounterLib/ArmGenericTimerVirtCounterLib.inf ArmPkg/Library/ArmHvcLib/ArmHvcLib.inf + ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf ArmPkg/Library/ArmSmcLib/ArmSmcLib.inf ArmPkg/Library/ArmSmcLibNull/ArmSmcLibNull.inf diff --git a/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.c b/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.c new file mode 100644 index 0000000000..8edda01a7f --- /dev/null +++ b/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.c @@ -0,0 +1,29 @@ +/** @file + Arm HyperVisor Call (HVC) Null Library. + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Trigger an HVC call + + HVC calls can take up to 8 arguments and return up to 4 return values. + Therefore, the 4 first fields in the ARM_HVC_ARGS structure are used + for both input and output values. + + @param [in,out] Args Arguments for the HVC call. +**/ +VOID +ArmCallHvc ( + IN OUT ARM_HVC_ARGS *Args + ) +{ + ASSERT (FALSE); + return; +} diff --git a/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf b/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf new file mode 100644 index 0000000000..e390a5fbbe --- /dev/null +++ b/ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf @@ -0,0 +1,22 @@ +## @file +# Arm Hvc Null Library +# +# Copyright (c) 2022, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = ArmHvcLibNull + FILE_GUID = 02076A46-D6DB-48DD-8E5F-153172DD73A1 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ArmHvcLib + +[Sources] + ArmHvcLibNull.c + +[Packages] + ArmPkg/ArmPkg.dec + MdePkg/MdePkg.dec From cff3b2148e90496ecc277d35eb29f975bc21382a Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:46 +0200 Subject: [PATCH 0284/1529] MdePkg/ArmTrngLib: Definition for Arm TRNG library class interface Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) The NIST Special Publications 800-90A, 800-90B and 800-90C provide recommendations for random number generation. The NIST 800-90C, Recommendation for Random Bit Generator (RBG) Constructions, defines the GetEntropy() interface that is used to access the entropy source. The GetEntropy() interface is further used by Deterministic Random Bit Generators (DRBG) to generate random numbers. The Arm True Random Number Generator (TRNG) library defines an interface to access the entropy source on a platform, following the 'Arm True Random Number Generator Firmware Interface' specification. Signed-off-by: Pierre Gondois Reviewed-by: Liming Gao --- MdePkg/Include/Library/ArmTrngLib.h | 106 ++++++++++++++++++++++++++++ MdePkg/MdePkg.dec | 5 ++ 2 files changed, 111 insertions(+) create mode 100644 MdePkg/Include/Library/ArmTrngLib.h diff --git a/MdePkg/Include/Library/ArmTrngLib.h b/MdePkg/Include/Library/ArmTrngLib.h new file mode 100644 index 0000000000..551c244137 --- /dev/null +++ b/MdePkg/Include/Library/ArmTrngLib.h @@ -0,0 +1,106 @@ +/** @file + Arm TRNG interface library definitions (Cf. [1]). + + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - [1] Arm True Random Number Generator Firmware, Interface 1.0, + Platform Design Document. + (https://developer.arm.com/documentation/den0098/latest/) + - [2] NIST Special Publication 800-90B, Recommendation for the Entropy + Sources Used for Random Bit Generation. + (https://csrc.nist.gov/publications/detail/sp/800-90b/final) + + @par Glossary: + - TRNG - True Random Number Generator +**/ + +#ifndef ARM_TRNG_LIB_H_ +#define ARM_TRNG_LIB_H_ + +/** Get the version of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the version of the Arm TRNG backend. + The implementation must return NOT_SUPPORTED if a Back end is not present. + + @param [out] MajorRevision Major revision. + @param [out] MinorRevision Minor revision. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Backend not present. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngVersion ( + OUT UINT16 *MajorRevision, + OUT UINT16 *MinorRevision + ); + +/** Get the UUID of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the UUID of the TRNG backend. + Returning the Arm TRNG UUID is optional and if not implemented, + RETURN_UNSUPPORTED shall be returned. + + Note: The caller must not rely on the returned UUID as a trustworthy Arm TRNG + Back end identity + + @param [out] Guid UUID of the Arm TRNG backend. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngUuid ( + OUT GUID *Guid + ); + +/** Returns maximum number of entropy bits that can be returned in a single + call. + + @return Returns the maximum number of Entropy bits that can be returned + in a single call to GetArmTrngEntropy(). +**/ +UINTN +EFIAPI +GetArmTrngMaxSupportedEntropyBits ( + VOID + ); + +/** Returns N bits of conditioned entropy. + + See [2] Section 2.3.1 GetEntropy: An Interface to the Entropy Source + GetEntropy + Input: + bits_of_entropy: the requested amount of entropy + Output: + entropy_bitstring: The string that provides the requested entropy. + status: A Boolean value that is TRUE if the request has been satisfied, + and is FALSE otherwise. + + @param [in] EntropyBits Number of entropy bits requested. + @param [in] BufferSize Size of the Buffer in bytes. + @param [out] Buffer Buffer to return the entropy bits. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. + @retval RETURN_BAD_BUFFER_SIZE Buffer size is too small. + @retval RETURN_NOT_READY No Entropy available. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngEntropy ( + IN UINTN EntropyBits, + IN UINTN BufferSize, + OUT UINT8 *Buffer + ); + +#endif // ARM_TRNG_LIB_H_ diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index ba287d9b3c..e49b2d5b5f 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -8,6 +8,7 @@ # Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# (C) Copyright 2016 - 2021 Hewlett Packard Enterprise Development LP
# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -279,6 +280,10 @@ ## @libraryclass Provides function for SMM CPU Rendezvous Library. SmmCpuRendezvousLib|Include/Library/SmmCpuRendezvousLib.h + ## @libraryclass Provides services to generate Entropy using a TRNG. + # + ArmTrngLib|Include/Library/ArmTrngLib.h + [LibraryClasses.IA32, LibraryClasses.X64, LibraryClasses.AARCH64] ## @libraryclass Provides services to generate random number. # From 87f8334f3eb2451875c6dfd2b769cfba614cd819 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:47 +0200 Subject: [PATCH 0285/1529] MdePkg/ArmTrngLib: Add NULL instance of Arm TRNG Library Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) The Arm True Random Number Generator (TRNG) library defines an interface to access the entropy source on a platform. On platforms that do not have access to an entropy source, a NULL instance of the TRNG library may be useful to satisfy the build dependency. Therefore, add a NULL instance of the Arm TRNG library. Signed-off-by: Pierre Gondois Reviewed-by: Liming Gao --- .../BaseArmTrngLibNull/BaseArmTrngLibNull.c | 121 ++++++++++++++++++ .../BaseArmTrngLibNull/BaseArmTrngLibNull.inf | 30 +++++ .../BaseArmTrngLibNull/BaseArmTrngLibNull.uni | 12 ++ MdePkg/MdeLibs.dsc.inc | 1 + MdePkg/MdePkg.dsc | 1 + 5 files changed, 165 insertions(+) create mode 100644 MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.c create mode 100644 MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf create mode 100644 MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.uni diff --git a/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.c b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.c new file mode 100644 index 0000000000..316d78bf5e --- /dev/null +++ b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.c @@ -0,0 +1,121 @@ +/** @file + Null version of the Arm TRNG (True Random Number Generator) services + (Cf [1]). + + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - [1] Arm True Random Number Generator Firmware, Interface 1.0, + Platform Design Document. + (https://developer.arm.com/documentation/den0098/latest/) + - [2] NIST Special Publication 800-90B, Recommendation for the Entropy + Sources Used for Random Bit Generation. + (https://csrc.nist.gov/publications/detail/sp/800-90b/final) + + @par Glossary: + - TRNG - True Random Number Generator +**/ + +#include +#include + +/** Get the version of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the version of the Arm TRNG backend. + The implementation must return NOT_SUPPORTED if a Back end is not present. + + @param [out] MajorRevision Major revision. + @param [out] MinorRevision Minor revision. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Backend not present. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngVersion ( + OUT UINT16 *MajorRevision, + OUT UINT16 *MinorRevision + ) +{ + ASSERT (FALSE); + return RETURN_UNSUPPORTED; +} + +/** Get the UUID of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the UUID of the TRNG backend. + Returning the Arm TRNG UUID is optional and if not implemented, + RETURN_UNSUPPORTED shall be returned. + + Note: The caller must not rely on the returned UUID as a trustworthy Arm TRNG + Back end identity + + @param [out] Guid UUID of the Arm TRNG backend. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngUuid ( + OUT GUID *Guid + ) +{ + ASSERT (FALSE); + return RETURN_UNSUPPORTED; +} + +/** Returns maximum number of entropy bits that can be returned in a single + call. + + @return Returns the maximum number of Entropy bits that can be returned + in a single call to GetArmTrngEntropy(). +**/ +UINTN +EFIAPI +GetArmTrngMaxSupportedEntropyBits ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + +/** Returns N bits of conditioned entropy. + + See [2] Section 2.3.1 GetEntropy: An Interface to the Entropy Source + GetEntropy + Input: + bits_of_entropy: the requested amount of entropy + Output: + entropy_bitstring: The string that provides the requested entropy. + status: A Boolean value that is TRUE if the request has been satisfied, + and is FALSE otherwise. + + @param [in] EntropyBits Number of entropy bits requested. + @param [in] BufferSize Size of the Buffer in bytes. + @param [out] Buffer Buffer to return the entropy bits. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. + @retval RETURN_BAD_BUFFER_SIZE Buffer size is too small. + @retval RETURN_NOT_READY No Entropy available. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngEntropy ( + IN UINTN EntropyBits, + IN UINTN BufferSize, + OUT UINT8 *Buffer + ) +{ + ASSERT (FALSE); + return RETURN_UNSUPPORTED; +} diff --git a/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf new file mode 100644 index 0000000000..256df1373e --- /dev/null +++ b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf @@ -0,0 +1,30 @@ +## @file +# Null instance of the Arm TRNG (True Random Number Generator) Library. +# +# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = BaseArmTrngLibNull + MODULE_UNI_FILE = BaseArmTrngLibNull.uni + FILE_GUID = ABDE1C87-4F50-4B82-9133-7A79E13F69AB + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ArmTrngLib + +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64 +# + +[Sources] + BaseArmTrngLibNull.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + DebugLib diff --git a/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.uni b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.uni new file mode 100644 index 0000000000..876764b8be --- /dev/null +++ b/MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.uni @@ -0,0 +1,12 @@ +// /** @file +// Null Instance of the Arm TRNG (True Random Number Generator) Library. +// +// Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Null instance of TRNG Library" + +#string STR_MODULE_DESCRIPTION #language en-US "This library instance should be used with modules that inherit an (indirect) dependency on the ArmTrngLib class, but never actually call ArmTrngLib APIs for consuming Entropy." diff --git a/MdePkg/MdeLibs.dsc.inc b/MdePkg/MdeLibs.dsc.inc index fc6f385b30..4580481cb5 100644 --- a/MdePkg/MdeLibs.dsc.inc +++ b/MdePkg/MdeLibs.dsc.inc @@ -12,6 +12,7 @@ ## [LibraryClasses] + ArmTrngLib|MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf RegisterFilterLib|MdePkg/Library/RegisterFilterLibNull/RegisterFilterLibNull.inf CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf SmmCpuRendezvousLib|MdePkg/Library/SmmCpuRendezvousLibNull/SmmCpuRendezvousLibNull.inf diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index 493a13ec91..32a852dc46 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -57,6 +57,7 @@ MdePkg/Library/PciSegmentLibSegmentInfo/BasePciSegmentLibSegmentInfo.inf MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLibSegmentInfo.inf MdePkg/Library/BaseS3PciSegmentLib/BaseS3PciSegmentLib.inf + MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf From df4744e42ca99f98d3c81c9be8776b78fb624171 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:48 +0200 Subject: [PATCH 0286/1529] ArmPkg: Add FID definitions for Arm TRNG Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) The Arm True Random Number Generator Firmware, Interface 1.0, Platform Design Document (https://developer.arm.com/documentation/den0098/latest/) defines an interface between an Operating System (OS) executing at EL1 and Firmware (FW) exposing a conditioned entropy source that is provided by a TRNG back end. New function IDs have been defined by the specification for accessing the TRNG services. Therefore, add these definitions to the Arm standard SMC header. Signed-off-by: Pierre Gondois Reviewed-by: Ard Biesheuvel --- ArmPkg/Include/IndustryStandard/ArmStdSmc.h | 109 +++++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/ArmPkg/Include/IndustryStandard/ArmStdSmc.h b/ArmPkg/Include/IndustryStandard/ArmStdSmc.h index 78ce77cd73..374b9ded7f 100644 --- a/ArmPkg/Include/IndustryStandard/ArmStdSmc.h +++ b/ArmPkg/Include/IndustryStandard/ArmStdSmc.h @@ -1,13 +1,20 @@ /** @file * * Copyright (c) 2020, NUVIA Inc. All rights reserved.
-* Copyright (c) 2012-2017, ARM Limited. All rights reserved. +* Copyright (c) 2012 - 2022, Arm Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * * @par Revision Reference: -* - SMC Calling Convention version 1.2 +* - [1] SMC Calling Convention version 1.2 * (https://developer.arm.com/documentation/den0028/c/?lang=en) +* - [2] Arm True Random Number Generator Firmware, Interface 1.0, +* Platform Design Document. +* (https://developer.arm.com/documentation/den0098/latest/) +* +* @par Glossary: +* - TRNG - True Random Number Generator +* **/ #ifndef ARM_STD_SMC_H_ @@ -139,4 +146,102 @@ /* 0xbf00ff02 is reserved */ #define ARM_SMC_ID_TOS_REVISION 0xbf00ff03 +// Firmware TRNG interface Function IDs + +/* + SMC/HVC call to get the version of the TRNG backend, + Cf. [2], 2.1 TRNG_VERSION + Input values: + W0 0x8400_0050 + W1-W7 Reserved (MBZ) + Return values: + Success (W0 > 0) W0[31] MBZ + W0[30:16] Major revision + W0[15:0] Minor revision + W1 - W3 Reserved (MBZ) + Error (W0 < 0) + NOT_SUPPORTED Function not implemented +*/ +#define ARM_SMC_ID_TRNG_VERSION 0x84000050 + +/* + SMC/HVC call to check if a TRNG function ID is implemented by the backend, + Cf. [2], Section 2.2 TRNG_FEATURES + Input Values + W0 0x8400_0051 + W1 trng_func_id + W2-W7 Reserved (MBZ) + Return values: + Success (W0 >= 0): + SUCCESS Function is implemented. + > 0 Function is implemented and + has specific capabilities, + see function definition. + Error (W0 < 0) + NOT_SUPPORTED Function with FID=trng_func_id + is not implemented +*/ +#define ARM_SMC_ID_TRNG_FEATURES 0x84000051 + +/* + SMC/HVC call to get the UUID of the TRNG backend, + Cf. [2], Section 2.3 TRNG_GET_UUID + Input Values: + W0 0x8400_0052 + W1-W7 Reserved (MBZ) + Return Values: + Success (W0 != -1) + W0 UUID[31:0] + W1 UUID[63:32] + W2 UUID[95:64] + W3 UUID[127:96] + Error (W0 = -1) + W0 NOT_SUPPORTED +*/ +#define ARM_SMC_ID_TRNG_GET_UUID 0x84000052 + +/* + AARCH32 SMC/HVC call to get entropy bits, Cf. [2], Section 2.4 TRNG_RND. + Input values: + W0 0x8400_0053 + W2-W7 Reserved (MBZ) + Return values: + Success (W0 = 0): + W0 MBZ + W1 Entropy[95:64] + W2 Entropy[63:32] + W3 Entropy[31:0] + Error (W0 < 0) + W0 NOT_SUPPORTED + NO_ENTROPY + INVALID_PARAMETERS + W1 - W3 Reserved (MBZ) +*/ +#define ARM_SMC_ID_TRNG_RND_AARCH32 0x84000053 + +/* + AARCH64 SMC/HVC call to get entropy bits, Cf. [2], Section 2.4 TRNG_RND. + Input values: + X0 0xC400_0053 + X2-X7 Reserved (MBZ) + Return values: + Success (X0 = 0): + X0 MBZ + X1 Entropy[191:128] + X2 Entropy[127:64] + X3 Entropy[63:0] + Error (X0 < 0) + X0 NOT_SUPPORTED + NO_ENTROPY + INVALID_PARAMETERS + X1 - X3 Reserved (MBZ) +*/ +#define ARM_SMC_ID_TRNG_RND_AARCH64 0xC4000053 + +// Firmware TRNG status codes +#define TRNG_STATUS_SUCCESS (INT32)(0) +#define TRNG_STATUS_NOT_SUPPORTED (INT32)(-1) +#define TRNG_STATUS_INVALID_PARAMETER (INT32)(-2) +#define TRNG_STATUS_NO_ENTROPY (INT32)(-3) + #endif // ARM_STD_SMC_H_ From 24ab58a5a62cd2b6d99520f2ce9d15a1622a85a3 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:49 +0200 Subject: [PATCH 0287/1529] ArmPkg/ArmTrngLib: Add Arm TRNG library Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) The Arm True Random Number Generator Firmware, Interface 1.0, Platform Design Document (https://developer.arm.com/documentation/den0098/latest/) defines an interface between an Operating System (OS) executing at EL1 and Firmware (FW) exposing a conditioned entropy source that is provided by a TRNG back end. The conditioned entropy, that is provided by the Arm TRNG interface, is commonly used to seed deterministic random number generators. This patch adds an ArmTrngLib library that implements the Arm TRNG interface. Acked-by: Leif Lindholm Signed-off-by: Pierre Gondois --- ArmPkg/ArmPkg.dsc | 1 + ArmPkg/Library/ArmTrngLib/ArmTrngDefs.h | 50 +++ ArmPkg/Library/ArmTrngLib/ArmTrngLib.c | 388 +++++++++++++++++++++++ ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf | 29 ++ 4 files changed, 468 insertions(+) create mode 100644 ArmPkg/Library/ArmTrngLib/ArmTrngDefs.h create mode 100644 ArmPkg/Library/ArmTrngLib/ArmTrngLib.c create mode 100644 ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 11b4739744..ac24ebce48 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -131,6 +131,7 @@ ArmPkg/Library/ArmGenericTimerPhyCounterLib/ArmGenericTimerPhyCounterLib.inf ArmPkg/Library/ArmGenericTimerVirtCounterLib/ArmGenericTimerVirtCounterLib.inf + ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf ArmPkg/Library/ArmHvcLib/ArmHvcLib.inf ArmPkg/Library/ArmHvcLibNull/ArmHvcLibNull.inf ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngDefs.h b/ArmPkg/Library/ArmTrngLib/ArmTrngDefs.h new file mode 100644 index 0000000000..8038a968b5 --- /dev/null +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngDefs.h @@ -0,0 +1,50 @@ +/** @file + Arm Firmware TRNG definitions. + + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - [1] Arm True Random Number Generator Firmware, Interface 1.0, + Platform Design Document. + (https://developer.arm.com/documentation/den0098/latest/) + + @par Glossary: + - TRNG - True Random Number Generator + - FID - Function ID +**/ + +#ifndef ARM_FW_TRNG_DEFS_H_ +#define ARM_FW_TRNG_DEFS_H_ + +#include + +// Firmware TRNG revision mask and shift +#define TRNG_REV_MAJOR_MASK 0x7FFF +#define TRNG_REV_MINOR_MASK 0xFFFF +#define TRNG_REV_MAJOR_SHIFT 16 + +#if defined (MDE_CPU_ARM) + +/** FID to use on AArch32 platform to request entropy. +*/ +#define ARM_SMC_ID_TRNG_RND ARM_SMC_ID_TRNG_RND_AARCH32 + +/** Maximum bits of entropy supported on AArch32. +*/ +#define MAX_ENTROPY_BITS 96 +#elif defined (MDE_CPU_AARCH64) + +/** FID to use on AArch64 platform to request entropy. +*/ +#define ARM_SMC_ID_TRNG_RND ARM_SMC_ID_TRNG_RND_AARCH64 + +/** Maximum bits of entropy supported on AArch64. +*/ +#define MAX_ENTROPY_BITS 192 +#else + #error "Firmware TRNG not supported. Unknown chipset." +#endif + +#endif // ARM_FW_TRNG_DEFS_H_ diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c new file mode 100644 index 0000000000..b974a94238 --- /dev/null +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c @@ -0,0 +1,388 @@ +/** @file + Arm Firmware TRNG interface library. + + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - [1] Arm True Random Number Generator Firmware, Interface 1.0, + Platform Design Document. + (https://developer.arm.com/documentation/den0098/latest/) + - [2] NIST Special Publication 800-90B, Recommendation for the Entropy + Sources Used for Random Bit Generation. + (https://csrc.nist.gov/publications/detail/sp/800-90b/final) + + @par Glossary: + - TRNG - True Random Number Generator + - FID - Function ID +**/ + +#include +#include +#include +#include +#include + +#include "ArmTrngDefs.h" + +/** Convert TRNG status codes to RETURN status codes. + + @param [in] TrngStatus TRNG status code. + + @retval RETURN_SUCCESS Success. + @retval RETURN_UNSUPPORTED Function not implemented or + negative return code. + @retval RETURN_INVALID_PARAMETER A parameter is invalid. + @retval RETURN_NOT_READY No Entropy available. +**/ +STATIC +RETURN_STATUS +TrngStatusToReturnStatus ( + IN INT32 TrngStatus + ) +{ + switch (TrngStatus) { + case TRNG_STATUS_NOT_SUPPORTED: + return RETURN_UNSUPPORTED; + + case TRNG_STATUS_INVALID_PARAMETER: + return RETURN_INVALID_PARAMETER; + + case TRNG_STATUS_NO_ENTROPY: + return RETURN_NOT_READY; + + case TRNG_STATUS_SUCCESS: + return RETURN_SUCCESS; + + default: + if (TrngStatus < 0) { + return RETURN_UNSUPPORTED; + } + + return RETURN_SUCCESS; + } +} + +/** Get the version of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the version of the Arm TRNG backend. + The implementation must return NOT_SUPPORTED if a Back end is not present. + + @param [out] MajorRevision Major revision. + @param [out] MinorRevision Minor revision. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Backend not present. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngVersion ( + OUT UINT16 *MajorRevision, + OUT UINT16 *MinorRevision + ) +{ + RETURN_STATUS Status; + ARM_MONITOR_ARGS Parameters; + INT32 Revision; + + if ((MajorRevision == NULL) || (MinorRevision == NULL)) { + return RETURN_INVALID_PARAMETER; + } + + ZeroMem (&Parameters, sizeof (Parameters)); + + Parameters.Arg0 = ARM_SMC_ID_TRNG_VERSION; + ArmMonitorCall (&Parameters); + + Revision = (INT32)Parameters.Arg0; + Status = TrngStatusToReturnStatus (Revision); + if (RETURN_ERROR (Status)) { + return Status; + } + + *MinorRevision = (Revision & TRNG_REV_MINOR_MASK); + *MajorRevision = ((Revision >> TRNG_REV_MAJOR_SHIFT) & TRNG_REV_MAJOR_MASK); + return RETURN_SUCCESS; +} + +/** Get the features supported by the Arm TRNG backend. + + The caller can determine if functions defined in the Arm TRNG ABI are + present in the ABI implementation. + + @param [in] FunctionId Function Id. + @param [out] Capability Function specific capability if present. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. +**/ +STATIC +RETURN_STATUS +EFIAPI +GetArmTrngFeatures ( + IN CONST UINT32 FunctionId, + OUT UINT32 *Capability OPTIONAL + ) +{ + ARM_MONITOR_ARGS Parameters; + RETURN_STATUS Status; + + ZeroMem (&Parameters, sizeof (Parameters)); + + Parameters.Arg0 = ARM_SMC_ID_TRNG_FEATURES; + Parameters.Arg1 = FunctionId; + ArmMonitorCall (&Parameters); + + Status = TrngStatusToReturnStatus (Parameters.Arg0); + if (RETURN_ERROR (Status)) { + return Status; + } + + if (Capability != NULL) { + *Capability = (UINT32)Parameters.Arg0; + } + + return RETURN_SUCCESS; +} + +/** Get the UUID of the Arm TRNG backend. + + A TRNG may be implemented by the system firmware, in which case this + function shall return the UUID of the TRNG backend. + Returning the Arm TRNG UUID is optional and if not implemented, + RETURN_UNSUPPORTED shall be returned. + + Note: The caller must not rely on the returned UUID as a trustworthy Arm TRNG + Back end identity + + @param [out] Guid UUID of the Arm TRNG backend. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngUuid ( + OUT GUID *Guid + ) +{ + ARM_MONITOR_ARGS Parameters; + + if (Guid == NULL) { + return RETURN_INVALID_PARAMETER; + } + + ZeroMem (&Parameters, sizeof (Parameters)); + + Parameters.Arg0 = ARM_SMC_ID_TRNG_GET_UUID; + ArmMonitorCall (&Parameters); + + // Only invalid value is TRNG_STATUS_NOT_SUPPORTED (-1). + if ((INT32)Parameters.Arg0 == TRNG_STATUS_NOT_SUPPORTED) { + return TrngStatusToReturnStatus ((INT32)Parameters.Arg0); + } + + Guid->Data1 = (Parameters.Arg0 & MAX_UINT32); + Guid->Data2 = (Parameters.Arg1 & MAX_UINT16); + Guid->Data3 = ((Parameters.Arg1 >> 16) & MAX_UINT16); + + Guid->Data4[0] = (Parameters.Arg2 & MAX_UINT8); + Guid->Data4[1] = ((Parameters.Arg2 >> 8) & MAX_UINT8); + Guid->Data4[2] = ((Parameters.Arg2 >> 16) & MAX_UINT8); + Guid->Data4[3] = ((Parameters.Arg2 >> 24) & MAX_UINT8); + + Guid->Data4[4] = (Parameters.Arg3 & MAX_UINT8); + Guid->Data4[5] = ((Parameters.Arg3 >> 8) & MAX_UINT8); + Guid->Data4[6] = ((Parameters.Arg3 >> 16) & MAX_UINT8); + Guid->Data4[7] = ((Parameters.Arg3 >> 24) & MAX_UINT8); + + DEBUG ((DEBUG_INFO, "FW-TRNG: UUID %g\n", Guid)); + + return RETURN_SUCCESS; +} + +/** Returns maximum number of entropy bits that can be returned in a single + call. + + @return Returns the maximum number of Entropy bits that can be returned + in a single call to GetArmTrngEntropy(). +**/ +UINTN +EFIAPI +GetArmTrngMaxSupportedEntropyBits ( + VOID + ) +{ + return MAX_ENTROPY_BITS; +} + +/** Returns N bits of conditioned entropy. + + See [2] Section 2.3.1 GetEntropy: An Interface to the Entropy Source + GetEntropy + Input: + bits_of_entropy: the requested amount of entropy + Output: + entropy_bitstring: The string that provides the requested entropy. + status: A Boolean value that is TRUE if the request has been satisfied, + and is FALSE otherwise. + + @param [in] EntropyBits Number of entropy bits requested. + @param [in] BufferSize Size of the Buffer in bytes. + @param [out] Buffer Buffer to return the entropy bits. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. + @retval RETURN_BAD_BUFFER_SIZE Buffer size is too small. + @retval RETURN_NOT_READY No Entropy available. +**/ +RETURN_STATUS +EFIAPI +GetArmTrngEntropy ( + IN UINTN EntropyBits, + IN UINTN BufferSize, + OUT UINT8 *Buffer + ) +{ + RETURN_STATUS Status; + ARM_MONITOR_ARGS Parameters; + UINTN EntropyBytes; + UINTN LastValidBits; + UINTN BytesToClear; + UINTN EntropyData[3]; + + if ((EntropyBits == 0) || + (EntropyBits > MAX_ENTROPY_BITS) || + (Buffer == NULL)) + { + return RETURN_INVALID_PARAMETER; + } + + EntropyBytes = (EntropyBits + 7) >> 3; + if (EntropyBytes > BufferSize) { + return RETURN_BAD_BUFFER_SIZE; + } + + ZeroMem (Buffer, BufferSize); + ZeroMem (&Parameters, sizeof (Parameters)); + + Parameters.Arg0 = ARM_SMC_ID_TRNG_RND; + Parameters.Arg1 = EntropyBits; + ArmMonitorCall (&Parameters); + + Status = TrngStatusToReturnStatus ((INT32)Parameters.Arg0); + if (RETURN_ERROR (Status)) { + return Status; + } + + // The entropy data is returned in the Parameters.Arg<3..1> + // With the lower order bytes in Parameters.Arg3 and the higher + // order bytes being stored in Parameters.Arg1. + EntropyData[0] = Parameters.Arg3; + EntropyData[1] = Parameters.Arg2; + EntropyData[2] = Parameters.Arg1; + + CopyMem (Buffer, EntropyData, EntropyBytes); + + // Mask off any unused top bytes, in accordance with specification. + BytesToClear = BufferSize - EntropyBytes; + if (BytesToClear != 0) { + ZeroMem (&Buffer[EntropyBytes], BytesToClear); + } + + // Clear the unused MSB bits of the last byte. + LastValidBits = EntropyBits & 0x7; + if (LastValidBits != 0) { + Buffer[EntropyBytes - 1] &= (0xFF >> (8 - LastValidBits)); + } + + return Status; +} + +/** The constructor checks that the FW-TRNG interface is supported + by the host firmware. + + It will ASSERT() if FW-TRNG is not supported. + It will always return RETURN_SUCCESS. + + @retval RETURN_SUCCESS The constructor always returns RETURN_SUCCESS. +**/ +RETURN_STATUS +EFIAPI +ArmTrngLibConstructor ( + VOID + ) +{ + ARM_MONITOR_ARGS Parameters; + RETURN_STATUS Status; + UINT16 MajorRev; + UINT16 MinorRev; + GUID Guid; + + ZeroMem (&Parameters, sizeof (Parameters)); + + Parameters.Arg0 = SMCCC_VERSION; + ArmMonitorCall (&Parameters); + Status = TrngStatusToReturnStatus ((INT32)Parameters.Arg0); + if (RETURN_ERROR (Status)) { + ASSERT_RETURN_ERROR (Status); + goto ErrorHandler; + } + + // Cf [1] s2.1.3 'Caller responsibilities', + // SMCCC version must be greater or equal than 1.1 + if ((INT32)Parameters.Arg0 < 0x10001) { + ASSERT_RETURN_ERROR (RETURN_UNSUPPORTED); + goto ErrorHandler; + } + + Status = GetArmTrngVersion (&MajorRev, &MinorRev); + if (RETURN_ERROR (Status)) { + ASSERT_RETURN_ERROR (Status); + goto ErrorHandler; + } + + // Check that the required features are present. + Status = GetArmTrngFeatures (ARM_SMC_ID_TRNG_RND, NULL); + if (RETURN_ERROR (Status)) { + ASSERT_RETURN_ERROR (Status); + goto ErrorHandler; + } + + // Check if TRNG UUID is supported and if so trace the GUID. + Status = GetArmTrngFeatures (ARM_SMC_ID_TRNG_GET_UUID, NULL); + if (RETURN_ERROR (Status)) { + ASSERT_RETURN_ERROR (Status); + goto ErrorHandler; + } + + DEBUG_CODE_BEGIN (); + + Status = GetArmTrngUuid (&Guid); + if (RETURN_ERROR (Status)) { + ASSERT_RETURN_ERROR (Status); + goto ErrorHandler; + } + + DEBUG (( + DEBUG_INFO, + "FW-TRNG: Version %d.%d, GUID {%g}\n", + MajorRev, + MinorRev, + Guid + )); + + DEBUG_CODE_END (); + + return RETURN_SUCCESS; + +ErrorHandler: + DEBUG ((DEBUG_ERROR, "ArmTrngLib could not be correctly initialized.\n")); + return RETURN_SUCCESS; +} diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf new file mode 100644 index 0000000000..d89efcdc98 --- /dev/null +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf @@ -0,0 +1,29 @@ +## @file +# Arm Firmware TRNG interface library. +# +# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = ArmTrngLib + FILE_GUID = 10DE97C9-28E4-4C9B-A53E-8D7D1B0DD4E0 + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = ArmTrngLib + CONSTRUCTOR = ArmTrngLibConstructor + +[Sources] + ArmTrngDefs.h + ArmTrngLib.c + +[Packages] + ArmPkg/ArmPkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + ArmMonitorLib + BaseLib + BaseMemoryLib From 68d287ec0b97d34a6985f290de29b77ebf791d94 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:50 +0200 Subject: [PATCH 0288/1529] SecurityPkg/RngDxe: Rename RdRandGenerateEntropy to generic name Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) Rename RdRandGenerateEntropy() to GenerateEntropy() to provide a common interface to generate entropy on other architectures. GenerateEntropy() is intended to generate high quality entropy. Also move the definition to RngDxeInternals.h Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/Rand/RdRand.c | 16 +++++-- .../RngDxe/Rand/RdRand.h | 43 ------------------- .../RngDxe/Rand/RngDxe.c | 7 ++- .../RandomNumberGenerator/RngDxe/RngDxe.inf | 2 +- .../RngDxe/RngDxeInternals.h | 19 ++++++++ 5 files changed, 37 insertions(+), 50 deletions(-) delete mode 100644 SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.h diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.c index 5b66441382..4b011c7e8e 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.c @@ -1,15 +1,23 @@ /** @file - Support routines for RDRAND instruction access. - + Support routines for RDRAND instruction access, which will leverage + Intel Secure Key technology to provide high-quality random numbers for use + in applications, or entropy for seeding other random number generators. + Refer to http://software.intel.com/en-us/articles/intel-digital-random-number + -generator-drng-software-implementation-guide/ for more information about Intel + Secure Key technology. + +Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.
(C) Copyright 2015 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include +#include #include +#include #include "AesCore.h" -#include "RdRand.h" #include "RngDxeInternals.h" /** @@ -87,7 +95,7 @@ RdRandGetSeed128 ( **/ EFI_STATUS EFIAPI -RdRandGenerateEntropy ( +GenerateEntropy ( IN UINTN Length, OUT UINT8 *Entropy ) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.h b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.h deleted file mode 100644 index 7fdb6891bd..0000000000 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RdRand.h +++ /dev/null @@ -1,43 +0,0 @@ -/** @file - Header for the RDRAND APIs used by RNG DXE driver. - - Support API definitions for RDRAND instruction access, which will leverage - Intel Secure Key technology to provide high-quality random numbers for use - in applications, or entropy for seeding other random number generators. - Refer to http://software.intel.com/en-us/articles/intel-digital-random-number - -generator-drng-software-implementation-guide/ for more information about Intel - Secure Key technology. - -Copyright (c) 2013, Intel Corporation. All rights reserved.
-(C) Copyright 2015 Hewlett Packard Enterprise Development LP
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __RD_RAND_H__ -#define __RD_RAND_H__ - -#include -#include -#include -#include -#include - -/** - Generate high-quality entropy source through RDRAND. - - @param[in] Length Size of the buffer, in bytes, to fill with. - @param[out] Entropy Pointer to the buffer to store the entropy data. - - @retval EFI_SUCCESS Entropy generation succeeded. - @retval EFI_NOT_READY Failed to request random data. - -**/ -EFI_STATUS -EFIAPI -RdRandGenerateEntropy ( - IN UINTN Length, - OUT UINT8 *Entropy - ); - -#endif // __RD_RAND_H__ diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index 2df4ed4432..8d44f0636c 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -14,13 +14,16 @@ - EFI_RNG_ALGORITHM_X9_31_3DES_GUID - Unsupported - EFI_RNG_ALGORITHM_X9_31_AES_GUID - Unsupported + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.
(C) Copyright 2015 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include "RdRand.h" +#include +#include + #include "RngDxeInternals.h" /** @@ -88,7 +91,7 @@ RngGetRNG ( return EFI_INVALID_PARAMETER; } - Status = RdRandGenerateEntropy (RNGValueLength, RNGValue); + Status = GenerateEntropy (RNGValueLength, RNGValue); return Status; } diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf index f330097199..60efb5562e 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf @@ -10,6 +10,7 @@ # # Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.
# (C) Copyright 2015 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -36,7 +37,6 @@ [Sources.IA32, Sources.X64] Rand/RngDxe.c Rand/RdRand.c - Rand/RdRand.h Rand/AesCore.c Rand/AesCore.h diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h index 224d8bd4ea..48d2d27c16 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h @@ -10,6 +10,8 @@ #ifndef RNGDXE_INTERNALS_H_ #define RNGDXE_INTERNALS_H_ +#include + /** Returns information about the random number generation implementation. @@ -114,4 +116,21 @@ RngGetBytes ( OUT UINT8 *RandBuffer ); +/** + Generate high-quality entropy source using a TRNG or through RDRAND. + + @param[in] Length Size of the buffer, in bytes, to fill with. + @param[out] Entropy Pointer to the buffer to store the entropy data. + + @retval EFI_SUCCESS Entropy generation succeeded. + @retval EFI_NOT_READY Failed to request random data. + +**/ +EFI_STATUS +EFIAPI +GenerateEntropy ( + IN UINTN Length, + OUT UINT8 *Entropy + ); + #endif // RNGDXE_INTERNALS_H_ From b9ed15187fbee40c02f3fba0f93342a40d8b37b7 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:51 +0200 Subject: [PATCH 0289/1529] SecurityPkg/RngDxe: Replace Pcd with Sp80090Ctr256Guid gEfiRngAlgorithmSp80090Ctr256Guid was used as the default algorithm in RngGetRNG(). The commit below set the default algorithm to PcdCpuRngSupportedAlgorithm, which is a zero GUID by default. As the Pcd value is not defined for any platform in the edk2-platfoms repository, assume it was an error and go back to the first version, using gEfiRngAlgorithmSp80090Ctr256Guid. Fixes: 4e5ecdbac8bd ("SecurityPkg: Add support for RngDxe on AARCH64") Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index 8d44f0636c..df7db12b77 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -126,8 +126,7 @@ ArchGetSupportedRngAlgorithms ( OUT EFI_RNG_ALGORITHM *RNGAlgorithmList ) { - UINTN RequiredSize; - EFI_RNG_ALGORITHM *CpuRngSupportedAlgorithm; + UINTN RequiredSize; RequiredSize = 2 * sizeof (EFI_RNG_ALGORITHM); @@ -136,9 +135,7 @@ ArchGetSupportedRngAlgorithms ( return EFI_BUFFER_TOO_SMALL; } - CpuRngSupportedAlgorithm = PcdGetPtr (PcdCpuRngSupportedAlgorithm); - - CopyMem (&RNGAlgorithmList[0], CpuRngSupportedAlgorithm, sizeof (EFI_RNG_ALGORITHM)); + CopyMem (&RNGAlgorithmList[0], &gEfiRngAlgorithmSp80090Ctr256Guid, sizeof (EFI_RNG_ALGORITHM)); // x86 platforms also support EFI_RNG_ALGORITHM_RAW via RDSEED CopyMem (&RNGAlgorithmList[1], &gEfiRngAlgorithmRaw, sizeof (EFI_RNG_ALGORITHM)); From 178b25dacf6224a49a7e0c964021e049837c64d2 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:52 +0200 Subject: [PATCH 0290/1529] SecurityPkg/RngDxe: Remove ArchGetSupportedRngAlgorithms() RngGetInfo() is one of the 2 functions of the EFI_RNG_PROTOCOL. RngGetInfo() is currently a mere wrapper around ArchGetSupportedRngAlgorithms() which is implemented differently depending on the architecture used. RngGetInfo() does nothing more than calling ArchGetSupportedRngAlgorithms(). So remove it, and let RngGetInfo() be implemented differently according to the architecture. This follows the implementation of the other function of the EFI_RNG_PROTOCOL, RngGetRNG(). Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/AArch64/RngDxe.c | 19 +++++-- .../RngDxe/Rand/RngDxe.c | 22 +++++++-- .../RandomNumberGenerator/RngDxe/RngDxe.c | 49 ------------------- .../RngDxe/RngDxeInternals.h | 25 ---------- 4 files changed, 33 insertions(+), 82 deletions(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c index 3daf847d46..6d989f7ea3 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c @@ -14,6 +14,7 @@ Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.
(C) Copyright 2015 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -85,6 +86,7 @@ RngGetRNG ( /** Returns information about the random number generation implementation. + @param[in] This A pointer to the EFI_RNG_PROTOCOL instance. @param[in,out] RNGAlgorithmListSize On input, the size in bytes of RNGAlgorithmList. On output with a return code of EFI_SUCCESS, the size in bytes of the data returned in RNGAlgorithmList. On output @@ -97,14 +99,19 @@ RngGetRNG ( is the default algorithm for the driver. @retval EFI_SUCCESS The RNG algorithm list was returned successfully. + @retval EFI_UNSUPPORTED The services is not supported by this driver. + @retval EFI_DEVICE_ERROR The list of algorithms could not be retrieved due to a + hardware or firmware error. + @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect. @retval EFI_BUFFER_TOO_SMALL The buffer RNGAlgorithmList is too small to hold the result. **/ -UINTN +EFI_STATUS EFIAPI -ArchGetSupportedRngAlgorithms ( - IN OUT UINTN *RNGAlgorithmListSize, - OUT EFI_RNG_ALGORITHM *RNGAlgorithmList +RngGetInfo ( + IN EFI_RNG_PROTOCOL *This, + IN OUT UINTN *RNGAlgorithmListSize, + OUT EFI_RNG_ALGORITHM *RNGAlgorithmList ) { UINTN RequiredSize; @@ -112,6 +119,10 @@ ArchGetSupportedRngAlgorithms ( RequiredSize = sizeof (EFI_RNG_ALGORITHM); + if ((This == NULL) || (RNGAlgorithmListSize == NULL)) { + return EFI_INVALID_PARAMETER; + } + if (*RNGAlgorithmListSize < RequiredSize) { *RNGAlgorithmListSize = RequiredSize; return EFI_BUFFER_TOO_SMALL; diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index df7db12b77..b2d2236380 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -104,6 +104,7 @@ RngGetRNG ( /** Returns information about the random number generation implementation. + @param[in] This A pointer to the EFI_RNG_PROTOCOL instance. @param[in,out] RNGAlgorithmListSize On input, the size in bytes of RNGAlgorithmList. On output with a return code of EFI_SUCCESS, the size in bytes of the data returned in RNGAlgorithmList. On output @@ -116,18 +117,27 @@ RngGetRNG ( is the default algorithm for the driver. @retval EFI_SUCCESS The RNG algorithm list was returned successfully. + @retval EFI_UNSUPPORTED No supported algorithms found. + @retval EFI_DEVICE_ERROR The list of algorithms could not be retrieved due to a + hardware or firmware error. + @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect. @retval EFI_BUFFER_TOO_SMALL The buffer RNGAlgorithmList is too small to hold the result. **/ -UINTN +EFI_STATUS EFIAPI -ArchGetSupportedRngAlgorithms ( - IN OUT UINTN *RNGAlgorithmListSize, - OUT EFI_RNG_ALGORITHM *RNGAlgorithmList +RngGetInfo ( + IN EFI_RNG_PROTOCOL *This, + IN OUT UINTN *RNGAlgorithmListSize, + OUT EFI_RNG_ALGORITHM *RNGAlgorithmList ) { UINTN RequiredSize; + if ((This == NULL) || (RNGAlgorithmListSize == NULL)) { + return EFI_INVALID_PARAMETER; + } + RequiredSize = 2 * sizeof (EFI_RNG_ALGORITHM); if (*RNGAlgorithmListSize < RequiredSize) { @@ -135,6 +145,10 @@ ArchGetSupportedRngAlgorithms ( return EFI_BUFFER_TOO_SMALL; } + if (RNGAlgorithmList == NULL) { + return EFI_INVALID_PARAMETER; + } + CopyMem (&RNGAlgorithmList[0], &gEfiRngAlgorithmSp80090Ctr256Guid, sizeof (EFI_RNG_ALGORITHM)); // x86 platforms also support EFI_RNG_ALGORITHM_RAW via RDSEED diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c index 6f52eeff4a..6608ca8804 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c @@ -28,55 +28,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "RngDxeInternals.h" -/** - Returns information about the random number generation implementation. - - @param[in] This A pointer to the EFI_RNG_PROTOCOL instance. - @param[in,out] RNGAlgorithmListSize On input, the size in bytes of RNGAlgorithmList. - On output with a return code of EFI_SUCCESS, the size - in bytes of the data returned in RNGAlgorithmList. On output - with a return code of EFI_BUFFER_TOO_SMALL, - the size of RNGAlgorithmList required to obtain the list. - @param[out] RNGAlgorithmList A caller-allocated memory buffer filled by the driver - with one EFI_RNG_ALGORITHM element for each supported - RNG algorithm. The list must not change across multiple - calls to the same driver. The first algorithm in the list - is the default algorithm for the driver. - - @retval EFI_SUCCESS The RNG algorithm list was returned successfully. - @retval EFI_UNSUPPORTED The services is not supported by this driver. - @retval EFI_DEVICE_ERROR The list of algorithms could not be retrieved due to a - hardware or firmware error. - @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect. - @retval EFI_BUFFER_TOO_SMALL The buffer RNGAlgorithmList is too small to hold the result. - -**/ -EFI_STATUS -EFIAPI -RngGetInfo ( - IN EFI_RNG_PROTOCOL *This, - IN OUT UINTN *RNGAlgorithmListSize, - OUT EFI_RNG_ALGORITHM *RNGAlgorithmList - ) -{ - EFI_STATUS Status; - - if ((This == NULL) || (RNGAlgorithmListSize == NULL)) { - return EFI_INVALID_PARAMETER; - } - - // - // Return algorithm list supported by driver. - // - if (RNGAlgorithmList != NULL) { - Status = ArchGetSupportedRngAlgorithms (RNGAlgorithmListSize, RNGAlgorithmList); - } else { - Status = EFI_INVALID_PARAMETER; - } - - return Status; -} - // // The Random Number Generator (RNG) protocol // diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h index 48d2d27c16..7ecab14048 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h @@ -74,31 +74,6 @@ RngGetRNG ( OUT UINT8 *RNGValue ); -/** - Returns information about the random number generation implementation. - - @param[in,out] RNGAlgorithmListSize On input, the size in bytes of RNGAlgorithmList. - On output with a return code of EFI_SUCCESS, the size - in bytes of the data returned in RNGAlgorithmList. On output - with a return code of EFI_BUFFER_TOO_SMALL, - the size of RNGAlgorithmList required to obtain the list. - @param[out] RNGAlgorithmList A caller-allocated memory buffer filled by the driver - with one EFI_RNG_ALGORITHM element for each supported - RNG algorithm. The list must not change across multiple - calls to the same driver. The first algorithm in the list - is the default algorithm for the driver. - - @retval EFI_SUCCESS The RNG algorithm list was returned successfully. - @retval EFI_BUFFER_TOO_SMALL The buffer RNGAlgorithmList is too small to hold the result. - -**/ -UINTN -EFIAPI -ArchGetSupportedRngAlgorithms ( - IN OUT UINTN *RNGAlgorithmListSize, - OUT EFI_RNG_ALGORITHM *RNGAlgorithmList - ); - /** Runs CPU RNG instruction to fill a buffer of arbitrary size with random bytes. From 03016c73bdfdd633bc8b051d463e3b5d21a0376b Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:53 +0200 Subject: [PATCH 0291/1529] SecurityPkg/RngDxe: Documentation/include/parameter cleanup This patch: -Update RngGetBytes() documentation to align the function definition and declaration. -Improve input parameter checking. Even though 'This' it is not used, the parameter should always point to the current EFI_RNG_PROTOCOL. -Removes TimerLib inclusion as unused. Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c | 3 +-- SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c | 2 +- SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c | 3 +-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c index 6d989f7ea3..f9c740d761 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c @@ -23,7 +23,6 @@ #include #include #include -#include #include #include "RngDxeInternals.h" @@ -61,7 +60,7 @@ RngGetRNG ( { EFI_STATUS Status; - if ((RNGValueLength == 0) || (RNGValue == NULL)) { + if ((This == NULL) || (RNGValueLength == 0) || (RNGValue == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index b2d2236380..8f5d8e740f 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -59,7 +59,7 @@ RngGetRNG ( { EFI_STATUS Status; - if ((RNGValueLength == 0) || (RNGValue == NULL)) { + if ((This == NULL) || (RNGValueLength == 0) || (RNGValue == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c index 6608ca8804..d7905a7f4d 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c @@ -23,7 +23,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include -#include #include #include "RngDxeInternals.h" @@ -72,7 +71,7 @@ RngDriverEntry ( } /** - Calls RDRAND to fill a buffer of arbitrary size with random bytes. + Runs CPU RNG instruction to fill a buffer of arbitrary size with random bytes. @param[in] Length Size of the buffer, in bytes, to fill with. @param[out] RandBuffer Pointer to the buffer to store the random result. From 14c922930f6a94616b62872ea242eb5666dddc16 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:54 +0200 Subject: [PATCH 0292/1529] SecurityPkg/RngDxe: Check before advertising Cpu Rng algo RngGetBytes() relies on the RngLib. The RngLib might use the RNDR instruction if the FEAT_RNG feature is present. RngGetInfo and RngGetRNG both must check that RngGetBytes() is working before advertising/using it. To do so, allocate an array storing the available algorithms. The Rng algorithm at the lowest index will be the default Rng algorithm. The array is shared between RngGetInfo and RngGetRNG. This array is allocated when the driver is loaded, and freed when unloaded. This patch also prevents from having PcdCpuRngSupportedAlgorithm let to a zero GUID, but let the possibility to have no valid Rng algorithm in such case. Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/AArch64/RngDxe.c | 87 +++++++++++++++++-- .../RngDxe/Rand/RngDxe.c | 26 ++++++ .../RandomNumberGenerator/RngDxe/RngDxe.c | 40 ++++++++- .../RandomNumberGenerator/RngDxe/RngDxe.inf | 1 + .../RngDxe/RngDxeInternals.h | 27 ++++++ 5 files changed, 172 insertions(+), 9 deletions(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c index f9c740d761..09a5924a69 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c @@ -22,11 +22,63 @@ #include #include +#include +#include #include +#include #include #include "RngDxeInternals.h" +// Maximum number of Rng algorithms. +#define RNG_AVAILABLE_ALGO_MAX 1 + +/** Allocate and initialize mAvailableAlgoArray with the available + Rng algorithms. Also update mAvailableAlgoArrayCount. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_OUT_OF_RESOURCES Could not allocate memory. +**/ +EFI_STATUS +EFIAPI +GetAvailableAlgorithms ( + VOID + ) +{ + UINT64 DummyRand; + + // Allocate RNG_AVAILABLE_ALGO_MAX entries to avoid evaluating + // Rng algorithms 2 times, one for the allocation, one to populate. + mAvailableAlgoArray = AllocateZeroPool (RNG_AVAILABLE_ALGO_MAX); + if (mAvailableAlgoArray == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // Check RngGetBytes() before advertising PcdCpuRngSupportedAlgorithm. + if (!EFI_ERROR (RngGetBytes (sizeof (DummyRand), (UINT8 *)&DummyRand))) { + CopyMem ( + &mAvailableAlgoArray[mAvailableAlgoArrayCount], + PcdGetPtr (PcdCpuRngSupportedAlgorithm), + sizeof (EFI_RNG_ALGORITHM) + ); + mAvailableAlgoArrayCount++; + } + + return EFI_SUCCESS; +} + +/** Free mAvailableAlgoArray. +**/ +VOID +EFIAPI +FreeAvailableAlgorithms ( + VOID + ) +{ + FreePool (mAvailableAlgoArray); + return; +} + /** Produces and returns an RNG value using either the default or specified RNG algorithm. @@ -59,6 +111,7 @@ RngGetRNG ( ) { EFI_STATUS Status; + UINTN Index; if ((This == NULL) || (RNGValueLength == 0) || (RNGValue == NULL)) { return EFI_INVALID_PARAMETER; @@ -68,9 +121,21 @@ RngGetRNG ( // // Use the default RNG algorithm if RNGAlgorithm is NULL. // - RNGAlgorithm = PcdGetPtr (PcdCpuRngSupportedAlgorithm); + for (Index = 0; Index < mAvailableAlgoArrayCount; Index++) { + if (!IsZeroGuid (&mAvailableAlgoArray[Index])) { + RNGAlgorithm = &mAvailableAlgoArray[Index]; + goto FoundAlgo; + } + } + + if (Index == mAvailableAlgoArrayCount) { + // No algorithm available. + ASSERT (Index != mAvailableAlgoArrayCount); + return EFI_DEVICE_ERROR; + } } +FoundAlgo: if (CompareGuid (RNGAlgorithm, PcdGetPtr (PcdCpuRngSupportedAlgorithm))) { Status = RngGetBytes (RNGValueLength, RNGValue); return Status; @@ -113,24 +178,30 @@ RngGetInfo ( OUT EFI_RNG_ALGORITHM *RNGAlgorithmList ) { - UINTN RequiredSize; - EFI_RNG_ALGORITHM *CpuRngSupportedAlgorithm; - - RequiredSize = sizeof (EFI_RNG_ALGORITHM); + UINTN RequiredSize; if ((This == NULL) || (RNGAlgorithmListSize == NULL)) { return EFI_INVALID_PARAMETER; } + RequiredSize = mAvailableAlgoArrayCount * sizeof (EFI_RNG_ALGORITHM); + + if (RequiredSize == 0) { + // No supported algorithms found. + return EFI_UNSUPPORTED; + } + if (*RNGAlgorithmListSize < RequiredSize) { *RNGAlgorithmListSize = RequiredSize; return EFI_BUFFER_TOO_SMALL; } - CpuRngSupportedAlgorithm = PcdGetPtr (PcdCpuRngSupportedAlgorithm); - - CopyMem (&RNGAlgorithmList[0], CpuRngSupportedAlgorithm, sizeof (EFI_RNG_ALGORITHM)); + if (RNGAlgorithmList == NULL) { + return EFI_INVALID_PARAMETER; + } + // There is no gap in the array, so copy the block. + CopyMem (RNGAlgorithmList, mAvailableAlgoArray, RequiredSize); *RNGAlgorithmListSize = RequiredSize; return EFI_SUCCESS; } diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index 8f5d8e740f..677600bed7 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -26,6 +26,32 @@ #include "RngDxeInternals.h" +/** Allocate and initialize mAvailableAlgoArray with the available + Rng algorithms. Also update mAvailableAlgoArrayCount. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_OUT_OF_RESOURCES Could not allocate memory. +**/ +EFI_STATUS +EFIAPI +GetAvailableAlgorithms ( + VOID + ) +{ + return EFI_SUCCESS; +} + +/** Free mAvailableAlgoArray. +**/ +VOID +EFIAPI +FreeAvailableAlgorithms ( + VOID + ) +{ + return; +} + /** Produces and returns an RNG value using either the default or specified RNG algorithm. diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c index d7905a7f4d..421abb52b8 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c @@ -27,6 +27,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "RngDxeInternals.h" +// +// Array containing the validated Rng algorithm. +// The entry with the lowest index will be the default algorithm. +// +UINTN mAvailableAlgoArrayCount; +EFI_RNG_ALGORITHM *mAvailableAlgoArray; + // // The Random Number Generator (RNG) protocol // @@ -66,8 +73,39 @@ RngDriverEntry ( &mRngRdRand, NULL ); + if (EFI_ERROR (Status)) { + return Status; + } + + // + // Get the list of available algorithm. + // + return GetAvailableAlgorithms (); +} + +/** + This is the unload handle for RndgDxe module. + + Disconnect the driver specified by ImageHandle from all the devices in the handle database. + Uninstall all the protocols installed in the driver entry point. - return Status; + @param[in] ImageHandle The drivers' driver image. + + @retval EFI_SUCCESS The image is unloaded. + @retval Others Failed to unload the image. + +**/ +EFI_STATUS +EFIAPI +RngDriverUnLoad ( + IN EFI_HANDLE ImageHandle + ) +{ + // + // Free the list of available algorithm. + // + FreeAvailableAlgorithms (); + return EFI_SUCCESS; } /** diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf index 60efb5562e..1985dfbb46 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf @@ -22,6 +22,7 @@ MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 ENTRY_POINT = RngDriverEntry + UNLOAD_IMAGE = RngDriverUnLoad MODULE_UNI_FILE = RngDxe.uni # diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h index 7ecab14048..f751402608 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxeInternals.h @@ -12,6 +12,33 @@ #include +// +// Array containing the validated Rng algorithm. +// The entry with the lowest index will be the default algorithm. +// +extern UINTN mAvailableAlgoArrayCount; +extern EFI_RNG_ALGORITHM *mAvailableAlgoArray; + +/** Allocate and initialize mAvailableAlgoArray with the available + Rng algorithms. Also update mAvailableAlgoArrayCount. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_OUT_OF_RESOURCES Could not allocate memory. +**/ +EFI_STATUS +EFIAPI +GetAvailableAlgorithms ( + VOID + ); + +/** Free mAvailableAlgoArray. +**/ +VOID +EFIAPI +FreeAvailableAlgorithms ( + VOID + ); + /** Returns information about the random number generation implementation. From e7e2eeddadcd631bfe82a6ccc639e47136af0b29 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:55 +0200 Subject: [PATCH 0293/1529] SecurityPkg/RngDxe: Add AArch64 RawAlgorithm support through ArmTrngLib Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) RawAlgorithm is used to provide access to entropy that is suitable for cryptographic applications. Therefore, add RawAlgorithm support that provides access to entropy using the ArmTrngLib. Also remove unused UefiBootServicesTableLib library inclusion and Status variable. Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/AArch64/RngDxe.c | 28 ++++++-- .../RandomNumberGenerator/RngDxe/ArmTrng.c | 71 +++++++++++++++++++ .../RandomNumberGenerator/RngDxe/RngDxe.inf | 5 ++ SecurityPkg/SecurityPkg.dsc | 3 + 4 files changed, 103 insertions(+), 4 deletions(-) create mode 100644 SecurityPkg/RandomNumberGenerator/RngDxe/ArmTrng.c diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c index 09a5924a69..ceddc8f08a 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c @@ -1,11 +1,13 @@ /** @file RNG Driver to produce the UEFI Random Number Generator protocol. - The driver will use the RNDR instruction to produce random numbers. + The driver can use RNDR instruction (through the RngLib and if FEAT_RNG is + present) to produce random numbers. It also uses the Arm FW-TRNG interface + to implement EFI_RNG_ALGORITHM_RAW. RNG Algorithms defined in UEFI 2.4: - EFI_RNG_ALGORITHM_SP800_90_CTR_256_GUID - - EFI_RNG_ALGORITHM_RAW - Unsupported + - EFI_RNG_ALGORITHM_RAW - EFI_RNG_ALGORITHM_SP800_90_HMAC_256_GUID - EFI_RNG_ALGORITHM_SP800_90_HASH_256_GUID - EFI_RNG_ALGORITHM_X9_31_3DES_GUID - Unsupported @@ -26,12 +28,14 @@ #include #include #include +#include +#include #include #include "RngDxeInternals.h" // Maximum number of Rng algorithms. -#define RNG_AVAILABLE_ALGO_MAX 1 +#define RNG_AVAILABLE_ALGO_MAX 2 /** Allocate and initialize mAvailableAlgoArray with the available Rng algorithms. Also update mAvailableAlgoArrayCount. @@ -46,8 +50,9 @@ GetAvailableAlgorithms ( ) { UINT64 DummyRand; + UINT16 MajorRevision; + UINT16 MinorRevision; - // Allocate RNG_AVAILABLE_ALGO_MAX entries to avoid evaluating // Rng algorithms 2 times, one for the allocation, one to populate. mAvailableAlgoArray = AllocateZeroPool (RNG_AVAILABLE_ALGO_MAX); if (mAvailableAlgoArray == NULL) { @@ -64,6 +69,16 @@ GetAvailableAlgorithms ( mAvailableAlgoArrayCount++; } + // Raw algorithm (Trng) + if (!EFI_ERROR (GetArmTrngVersion (&MajorRevision, &MinorRevision))) { + CopyMem ( + &mAvailableAlgoArray[mAvailableAlgoArrayCount], + &gEfiRngAlgorithmRaw, + sizeof (EFI_RNG_ALGORITHM) + ); + mAvailableAlgoArrayCount++; + } + return EFI_SUCCESS; } @@ -141,6 +156,11 @@ RngGetRNG ( return Status; } + // Raw algorithm (Trng) + if (CompareGuid (RNGAlgorithm, &gEfiRngAlgorithmRaw)) { + return GenerateEntropy (RNGValueLength, RNGValue); + } + // // Other algorithms are unsupported by this driver. // diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/ArmTrng.c b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmTrng.c new file mode 100644 index 0000000000..ffe557b692 --- /dev/null +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmTrng.c @@ -0,0 +1,71 @@ +/** @file + RNG Driver to produce the UEFI Random Number Generator protocol. + + The driver implements the EFI_RNG_ALGORITHM_RAW using the FW-TRNG + interface to provide entropy. + + Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +#include "RngDxeInternals.h" + +/** + Generate high-quality entropy source using a TRNG or through RDRAND. + + @param[in] Length Size of the buffer, in bytes, to fill with. + @param[out] Entropy Pointer to the buffer to store the entropy data. + + @retval RETURN_SUCCESS The function completed successfully. + @retval RETURN_INVALID_PARAMETER Invalid parameter. + @retval RETURN_UNSUPPORTED Function not implemented. + @retval RETURN_BAD_BUFFER_SIZE Buffer size is too small. + @retval RETURN_NOT_READY No Entropy available. +**/ +EFI_STATUS +EFIAPI +GenerateEntropy ( + IN UINTN Length, + OUT UINT8 *Entropy + ) +{ + EFI_STATUS Status; + UINTN CollectedEntropyBits; + UINTN RequiredEntropyBits; + UINTN EntropyBits; + UINTN Index; + UINTN MaxBits; + + ZeroMem (Entropy, Length); + + RequiredEntropyBits = (Length << 3); + Index = 0; + CollectedEntropyBits = 0; + MaxBits = GetArmTrngMaxSupportedEntropyBits (); + while (CollectedEntropyBits < RequiredEntropyBits) { + EntropyBits = MIN ((RequiredEntropyBits - CollectedEntropyBits), MaxBits); + Status = GetArmTrngEntropy ( + EntropyBits, + (Length - Index), + &Entropy[Index] + ); + if (EFI_ERROR (Status)) { + // Discard the collected bits. + ZeroMem (Entropy, Length); + return Status; + } + + CollectedEntropyBits += EntropyBits; + Index += (EntropyBits >> 3); + } // while + + return Status; +} diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf index 1985dfbb46..e0e767cbf3 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf @@ -43,8 +43,10 @@ [Sources.AARCH64] AArch64/RngDxe.c + ArmTrng.c [Packages] + MdeModulePkg/MdeModulePkg.dec MdePkg/MdePkg.dec SecurityPkg/SecurityPkg.dec @@ -57,6 +59,9 @@ TimerLib RngLib +[LibraryClasses.AARCH64] + ArmTrngLib + [Guids] gEfiRngAlgorithmSp80090Hash256Guid ## SOMETIMES_PRODUCES ## GUID # Unique ID of the algorithm for RNG gEfiRngAlgorithmSp80090Hmac256Guid ## SOMETIMES_PRODUCES ## GUID # Unique ID of the algorithm for RNG diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index 6bf53c5658..f71ab7738e 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -4,6 +4,7 @@ # Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2015-2020 Hewlett Packard Enterprise Development LP
# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
+# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -89,6 +90,8 @@ ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf + ArmTrngLib|MdePkg/Library/BaseArmTrngLibNull/BaseArmTrngLibNull.inf + [LibraryClasses.ARM] RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf From e1b6ee03986d3716a742ba574e0a811f716949ed Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:56 +0200 Subject: [PATCH 0294/1529] SecurityPkg/RngDxe: Add debug warning for NULL PcdCpuRngSupportedAlgorithm PcdCpuRngSupportedAlgorithm should allow to identify the the algorithm used by the RNDR CPU instruction to generate a random number. Add a debug warning if the Pcd is not set. Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RandomNumberGenerator/RngDxe/AArch64/RngDxe.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c index ceddc8f08a..318876d693 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c @@ -67,6 +67,16 @@ GetAvailableAlgorithms ( sizeof (EFI_RNG_ALGORITHM) ); mAvailableAlgoArrayCount++; + + DEBUG_CODE_BEGIN (); + if (IsZeroGuid (PcdGetPtr (PcdCpuRngSupportedAlgorithm))) { + DEBUG (( + DEBUG_WARN, + "PcdCpuRngSupportedAlgorithm should be a non-zero GUID\n" + )); + } + + DEBUG_CODE_END (); } // Raw algorithm (Trng) From d7aba19497b177e0dca9af08036d0da4852d7afd Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:57 +0200 Subject: [PATCH 0295/1529] SecurityPkg/RngDxe: Rename AArch64/RngDxe.c To re-use the AArch64/RngDxe.c for an Arm implementation, rename AArch64/RngDxe.c to ArmRngDxe.c. Acked-by: Leif Lindholm Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/{AArch64/RngDxe.c => ArmRngDxe.c} | 0 SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename SecurityPkg/RandomNumberGenerator/RngDxe/{AArch64/RngDxe.c => ArmRngDxe.c} (100%) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c similarity index 100% rename from SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/RngDxe.c rename to SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf index e0e767cbf3..1d0bdef57d 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf @@ -42,7 +42,7 @@ Rand/AesCore.h [Sources.AARCH64] - AArch64/RngDxe.c + ArmRngDxe.c ArmTrng.c [Packages] From 7459d1c6ef880c93c3e012f2d2c34dae34172ee7 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Fri, 28 Oct 2022 17:32:58 +0200 Subject: [PATCH 0296/1529] SecurityPkg/RngDxe: Add Arm support of RngDxe Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) Add RngDxe support for Arm. This implementation uses the ArmTrngLib to support the RawAlgorithm and doens't support the RNDR instruction. To re-use the RngGetRNG(), RngGetInfo() and FreeAvailableAlgorithms() functions, create Arm/AArch64 files which implement the arch specific function GetAvailableAlgorithms(). Indeed, FEAT_RNG instruction is not supported on Arm. Signed-off-by: Pierre Gondois Acked-by: Jiewen Yao --- .../RngDxe/AArch64/AArch64Algo.c | 72 +++++++++++++++++++ .../RngDxe/Arm/ArmAlgo.c | 51 +++++++++++++ .../RandomNumberGenerator/RngDxe/ArmRngDxe.c | 60 ---------------- .../RandomNumberGenerator/RngDxe/RngDxe.inf | 12 +++- SecurityPkg/SecurityPkg.dsc | 2 +- 5 files changed, 133 insertions(+), 64 deletions(-) create mode 100644 SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/AArch64Algo.c create mode 100644 SecurityPkg/RandomNumberGenerator/RngDxe/Arm/ArmAlgo.c diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/AArch64Algo.c b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/AArch64Algo.c new file mode 100644 index 0000000000..e8be217f8a --- /dev/null +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/AArch64/AArch64Algo.c @@ -0,0 +1,72 @@ +/** @file + Aarch64 specific code. + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include +#include +#include +#include + +#include "RngDxeInternals.h" + +// Maximum number of Rng algorithms. +#define RNG_AVAILABLE_ALGO_MAX 2 + +/** Allocate and initialize mAvailableAlgoArray with the available + Rng algorithms. Also update mAvailableAlgoArrayCount. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_OUT_OF_RESOURCES Could not allocate memory. +**/ +EFI_STATUS +EFIAPI +GetAvailableAlgorithms ( + VOID + ) +{ + UINT64 DummyRand; + UINT16 MajorRevision; + UINT16 MinorRevision; + + // Rng algorithms 2 times, one for the allocation, one to populate. + mAvailableAlgoArray = AllocateZeroPool (RNG_AVAILABLE_ALGO_MAX); + if (mAvailableAlgoArray == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // Check RngGetBytes() before advertising PcdCpuRngSupportedAlgorithm. + if (!EFI_ERROR (RngGetBytes (sizeof (DummyRand), (UINT8 *)&DummyRand))) { + CopyMem ( + &mAvailableAlgoArray[mAvailableAlgoArrayCount], + PcdGetPtr (PcdCpuRngSupportedAlgorithm), + sizeof (EFI_RNG_ALGORITHM) + ); + mAvailableAlgoArrayCount++; + + DEBUG_CODE_BEGIN (); + if (IsZeroGuid (PcdGetPtr (PcdCpuRngSupportedAlgorithm))) { + DEBUG (( + DEBUG_WARN, + "PcdCpuRngSupportedAlgorithm should be a non-zero GUID\n" + )); + } + + DEBUG_CODE_END (); + } + + // Raw algorithm (Trng) + if (!EFI_ERROR (GetArmTrngVersion (&MajorRevision, &MinorRevision))) { + CopyMem ( + &mAvailableAlgoArray[mAvailableAlgoArrayCount], + &gEfiRngAlgorithmRaw, + sizeof (EFI_RNG_ALGORITHM) + ); + mAvailableAlgoArrayCount++; + } + + return EFI_SUCCESS; +} diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Arm/ArmAlgo.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Arm/ArmAlgo.c new file mode 100644 index 0000000000..4b24f5c4a6 --- /dev/null +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Arm/ArmAlgo.c @@ -0,0 +1,51 @@ +/** @file + Arm specific code. + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include +#include +#include +#include + +#include "RngDxeInternals.h" + +// Maximum number of Rng algorithms. +#define RNG_AVAILABLE_ALGO_MAX 1 + +/** Allocate and initialize mAvailableAlgoArray with the available + Rng algorithms. Also update mAvailableAlgoArrayCount. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_OUT_OF_RESOURCES Could not allocate memory. +**/ +EFI_STATUS +EFIAPI +GetAvailableAlgorithms ( + VOID + ) +{ + UINT16 MajorRevision; + UINT16 MinorRevision; + + // Rng algorithms 2 times, one for the allocation, one to populate. + mAvailableAlgoArray = AllocateZeroPool (RNG_AVAILABLE_ALGO_MAX); + if (mAvailableAlgoArray == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // Raw algorithm (Trng) + if (!EFI_ERROR (GetArmTrngVersion (&MajorRevision, &MinorRevision))) { + CopyMem ( + &mAvailableAlgoArray[mAvailableAlgoArrayCount], + &gEfiRngAlgorithmRaw, + sizeof (EFI_RNG_ALGORITHM) + ); + mAvailableAlgoArrayCount++; + } + + return EFI_SUCCESS; +} diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c index 318876d693..5ba319899c 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c @@ -28,70 +28,10 @@ #include #include #include -#include -#include #include #include "RngDxeInternals.h" -// Maximum number of Rng algorithms. -#define RNG_AVAILABLE_ALGO_MAX 2 - -/** Allocate and initialize mAvailableAlgoArray with the available - Rng algorithms. Also update mAvailableAlgoArrayCount. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_OUT_OF_RESOURCES Could not allocate memory. -**/ -EFI_STATUS -EFIAPI -GetAvailableAlgorithms ( - VOID - ) -{ - UINT64 DummyRand; - UINT16 MajorRevision; - UINT16 MinorRevision; - - // Rng algorithms 2 times, one for the allocation, one to populate. - mAvailableAlgoArray = AllocateZeroPool (RNG_AVAILABLE_ALGO_MAX); - if (mAvailableAlgoArray == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - // Check RngGetBytes() before advertising PcdCpuRngSupportedAlgorithm. - if (!EFI_ERROR (RngGetBytes (sizeof (DummyRand), (UINT8 *)&DummyRand))) { - CopyMem ( - &mAvailableAlgoArray[mAvailableAlgoArrayCount], - PcdGetPtr (PcdCpuRngSupportedAlgorithm), - sizeof (EFI_RNG_ALGORITHM) - ); - mAvailableAlgoArrayCount++; - - DEBUG_CODE_BEGIN (); - if (IsZeroGuid (PcdGetPtr (PcdCpuRngSupportedAlgorithm))) { - DEBUG (( - DEBUG_WARN, - "PcdCpuRngSupportedAlgorithm should be a non-zero GUID\n" - )); - } - - DEBUG_CODE_END (); - } - - // Raw algorithm (Trng) - if (!EFI_ERROR (GetArmTrngVersion (&MajorRevision, &MinorRevision))) { - CopyMem ( - &mAvailableAlgoArray[mAvailableAlgoArrayCount], - &gEfiRngAlgorithmRaw, - sizeof (EFI_RNG_ALGORITHM) - ); - mAvailableAlgoArrayCount++; - } - - return EFI_SUCCESS; -} - /** Free mAvailableAlgoArray. **/ VOID diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf index 1d0bdef57d..c8e0ee4ae5 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf @@ -28,7 +28,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# VALID_ARCHITECTURES = IA32 X64 AARCH64 ARM # [Sources.common] @@ -41,10 +41,16 @@ Rand/AesCore.c Rand/AesCore.h -[Sources.AARCH64] +[Sources.AARCH64, Sources.ARM] ArmRngDxe.c ArmTrng.c +[Sources.AARCH64] + AArch64/AArch64Algo.c + +[Sources.ARM] + Arm/ArmAlgo.c + [Packages] MdeModulePkg/MdeModulePkg.dec MdePkg/MdePkg.dec @@ -59,7 +65,7 @@ TimerLib RngLib -[LibraryClasses.AARCH64] +[LibraryClasses.AARCH64, LibraryClasses.ARM] ArmTrngLib [Guids] diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index f71ab7738e..30d911d8a1 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -291,7 +291,7 @@ SecurityPkg/EnrollFromDefaultKeysApp/EnrollFromDefaultKeysApp.inf SecurityPkg/VariableAuthenticated/SecureBootDefaultKeysDxe/SecureBootDefaultKeysDxe.inf -[Components.IA32, Components.X64, Components.AARCH64] +[Components.IA32, Components.X64, Components.AARCH64, Components.ARM] # # Random Number Generator # From b3a120f0ac05d01b33b743853706b5d9516b0af4 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 28 Oct 2022 17:32:59 +0200 Subject: [PATCH 0297/1529] ArmVirtPkg: Kvmtool: Add RNG support using Arm TRNG interface Bugzilla: 3668 (https://bugzilla.tianocore.org/show_bug.cgi?id=3668) The EFI_RNG_PROTOCOL published by RngDxe has been updated to implement the EFI_RNG_ALGORITHM_RAW using the Arm TRNG interface to provide access to entropy. Therefore, enable EFI_RNG_PROTOCOL for the Kvmtool guest/virtual firmware. Signed-off-by: Pierre Gondois Reviewed-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtKvmTool.dsc | 10 ++++++++++ ArmVirtPkg/ArmVirtKvmTool.fdf | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/ArmVirtPkg/ArmVirtKvmTool.dsc b/ArmVirtPkg/ArmVirtKvmTool.dsc index c598903b33..2ba00bd08f 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.dsc +++ b/ArmVirtPkg/ArmVirtKvmTool.dsc @@ -81,6 +81,9 @@ HwInfoParserLib|DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf DynamicPlatRepoLib|DynamicTablesPkg/Library/Common/DynamicPlatRepoLib/DynamicPlatRepoLib.inf + ArmMonitorLib|ArmPkg/Library/ArmMonitorLib/ArmMonitorLib.inf + ArmTrngLib|ArmPkg/Library/ArmTrngLib/ArmTrngLib.inf + [LibraryClasses.common.SEC, LibraryClasses.common.PEI_CORE, LibraryClasses.common.PEIM] PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf PlatformHookLib|ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf @@ -112,6 +115,8 @@ # Use MMIO for accessing RTC controller registers. gPcAtChipsetPkgTokenSpaceGuid.PcdRtcUseMmio|TRUE + gArmTokenSpaceGuid.PcdMonitorConduitHvc|TRUE + [PcdsFixedAtBuild.common] gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000000F @@ -362,6 +367,11 @@ OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf OvmfPkg/Virtio10Dxe/Virtio10.inf + # + # Rng Support + # + SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf + !if $(ARCH) == AARCH64 # # ACPI Support diff --git a/ArmVirtPkg/ArmVirtKvmTool.fdf b/ArmVirtPkg/ArmVirtKvmTool.fdf index b696bffc7c..82aff47673 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.fdf +++ b/ArmVirtPkg/ArmVirtKvmTool.fdf @@ -224,6 +224,11 @@ READ_LOCK_STATUS = TRUE # INF MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf + # + # Rng Support + # + INF SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf + [FV.FVMAIN_COMPACT] FvAlignment = 16 ERASE_POLARITY = 1 From 8676a1eec1b30d5952ff7b07f64febc7efebbc2b Mon Sep 17 00:00:00 2001 From: Pedro Falcato Date: Thu, 3 Nov 2022 09:11:49 +0800 Subject: [PATCH 0298/1529] MdePkg/BaseLib: Fix out-of-bounds reads in SafeString There was a OOB access in *StrHexTo* functions, when passed strings like "XDEADBEEF". OpenCore folks established an ASAN-equipped project to fuzz Ext4Dxe, which was able to catch these (mostly harmless) issues. Cc: Vitaly Cheptsov Cc: Marvin H?user Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Pedro Falcato Acked-by: Michael D Kinney Reviewed-by: Jiewen Yao Reviewed-by: Liming Gao --- MdePkg/Library/BaseLib/SafeString.c | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/MdePkg/Library/BaseLib/SafeString.c b/MdePkg/Library/BaseLib/SafeString.c index f338a32a3a..b75b333817 100644 --- a/MdePkg/Library/BaseLib/SafeString.c +++ b/MdePkg/Library/BaseLib/SafeString.c @@ -863,6 +863,9 @@ StrHexToUintnS ( OUT UINTN *Data ) { + BOOLEAN FoundLeadingZero; + + FoundLeadingZero = FALSE; ASSERT (((UINTN)String & BIT0) == 0); // @@ -892,12 +895,14 @@ StrHexToUintnS ( // // Ignore leading Zeros after the spaces // + + FoundLeadingZero = *String == L'0'; while (*String == L'0') { String++; } if (CharToUpper (*String) == L'X') { - if (*(String - 1) != L'0') { + if (!FoundLeadingZero) { *Data = 0; return RETURN_SUCCESS; } @@ -992,6 +997,9 @@ StrHexToUint64S ( OUT UINT64 *Data ) { + BOOLEAN FoundLeadingZero; + + FoundLeadingZero = FALSE; ASSERT (((UINTN)String & BIT0) == 0); // @@ -1021,12 +1029,13 @@ StrHexToUint64S ( // // Ignore leading Zeros after the spaces // + FoundLeadingZero = *String == L'0'; while (*String == L'0') { String++; } if (CharToUpper (*String) == L'X') { - if (*(String - 1) != L'0') { + if (!FoundLeadingZero) { *Data = 0; return RETURN_SUCCESS; } @@ -2393,6 +2402,9 @@ AsciiStrHexToUintnS ( OUT UINTN *Data ) { + BOOLEAN FoundLeadingZero; + + FoundLeadingZero = FALSE; // // 1. Neither String nor Data shall be a null pointer. // @@ -2420,12 +2432,13 @@ AsciiStrHexToUintnS ( // // Ignore leading Zeros after the spaces // + FoundLeadingZero = *String == '0'; while (*String == '0') { String++; } if (AsciiCharToUpper (*String) == 'X') { - if (*(String - 1) != '0') { + if (!FoundLeadingZero) { *Data = 0; return RETURN_SUCCESS; } @@ -2517,6 +2530,9 @@ AsciiStrHexToUint64S ( OUT UINT64 *Data ) { + BOOLEAN FoundLeadingZero; + + FoundLeadingZero = FALSE; // // 1. Neither String nor Data shall be a null pointer. // @@ -2544,12 +2560,13 @@ AsciiStrHexToUint64S ( // // Ignore leading Zeros after the spaces // + FoundLeadingZero = *String == '0'; while (*String == '0') { String++; } if (AsciiCharToUpper (*String) == 'X') { - if (*(String - 1) != '0') { + if (!FoundLeadingZero) { *Data = 0; return RETURN_SUCCESS; } From e7737045da0bd9d2b86a312056935de094f3f1a6 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Fri, 4 Nov 2022 20:02:14 +0800 Subject: [PATCH 0299/1529] CryptoPkg/Readme.md: typo and grammar fixes Commit 244ce33bdd2f ("CryptoPkg: Add Readme.md", 2022-10-24) had added the long-awaited documentation on the dynamic crypto services. Fix some of the typos and arguable grammar errors in "Readme.md". A few light clarifications are also snuck in. Cc: Christopher Zurcher Cc: Guomin Jiang Cc: Jian J Wang Cc: Jiewen Yao Cc: Michael D Kinney Cc: Xiaoyu Lu Signed-off-by: Laszlo Ersek Reviewed-by: Christopher Zurcher Reviewed-by: Michael D Kinney Acked-by: Jiewen Yao --- CryptoPkg/Readme.md | 46 ++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/CryptoPkg/Readme.md b/CryptoPkg/Readme.md index 946aa1e99e..067465b8eb 100644 --- a/CryptoPkg/Readme.md +++ b/CryptoPkg/Readme.md @@ -39,7 +39,7 @@ provides the smallest overall firmware overhead. ## Statically Linking Cryptographic Services -The figure below shows an example of a firmware modules that requires the use of +The figure below shows an example of a firmware module that requires the use of cryptographic services. The cryptographic services are provided by three library classes called BaseCryptLib, TlsLib, and HashApiLib. These library classes are implemented using APIs from the OpenSSL project that are abstracted by the @@ -49,7 +49,7 @@ full C runtime library for firmware components. Instead, the CryptoPkg includes the smallest subset of services required to build the OpenSSL project in the private library class called IntrinsicLib. -The CryptoPkg provides several instances if the BaseCryptLib and OpensslLib with +The CryptoPkg provides several instances of the BaseCryptLib and OpensslLib with different cryptographic service features and performance optimizations. The platform developer must select the correct instances based on cryptographic service requirements in each UEFI/PI firmware phase (SEC, PEI, DXE, UEFI, @@ -97,9 +97,9 @@ linking is not available for SEC or UEFI RT modules. The EDK II modules/libraries that require cryptographic services use the same BaseCryptLib/TlsLib/HashApiLib APIs. This means no source changes are required -to use static linking or dynamic linking. It is a platform configuration options -to select static linking or dynamic linking. This choice can be make globally, -per firmware module type, or individual modules. +to use static linking or dynamic linking. It is a platform configuration option +to select static linking or dynamic linking. This choice can be made globally, +per firmware module type, or for individual modules. ``` +===================+ +===================+ +===================+ @@ -159,7 +159,7 @@ The table below provides a summary of the supported cryptographic services. It indicates if the family or service is deprecated or recommended to not be used. It also shows which *CryptLib library instances support the family or service. If a cell is blank then the service or family is always disabled and the -`PcdCryptoServiceFamilyEnable` settings for that family or service is ignored. +`PcdCryptoServiceFamilyEnable` setting for that family or service is ignored. If the cell is not blank, then the service or family is configurable using `PcdCryptoServiceFamilyEnable` as long as the correct OpensslLib or TlsLib is also configured. @@ -234,10 +234,10 @@ phases (SEC, PEI, DXE, UEFI, SMM, UEFI RT). The following table can be used to help select the best OpensslLib instance for each phase. The Size column only shows the estimated size increase for a -compressed IA32/X64 modules that uses the cryptographic services with +compressed IA32/X64 module that uses the cryptographic services with `OpensslLib.inf` as the baseline size. The actual size increase depends on the specific set of enabled cryptographic services. If ECC services are not -required, then size can be reduced by using OpensslLib.inf instead of +required, then the size can be reduced by using OpensslLib.inf instead of `OpensslLibFull.inf`. Performance optimization requires a size increase. | OpensslLib Instance | SSL | ECC | Perf Opt | CPU Arch | Size | @@ -371,10 +371,10 @@ settings. ### UEFI Runtime Driver Library Mappings -UEFI Runtime Drivers only supports static linking of cryptographic services. -The following library mappings are recommended for UEFI Runtime Drivers. It uses -the runtime specific version of the BaseCryptLib and the null version of the -TlsLib because TLS services are not typically used in runtime. +UEFI Runtime Drivers only support static linking of cryptographic services. +The following library mappings are recommended for UEFI Runtime Drivers. They +use the runtime specific version of the BaseCryptLib and the null version of the +TlsLib because TLS services are not typically used at runtime. ``` [LibraryClasses.common.DXE_RUNTIME_DRIVER] @@ -394,7 +394,7 @@ configure the cryptographic services supported by the CryptoPei, CryptoDxe, and CryptoSmm modules. * `gEfiCryptoPkgTokenSpaceGuid.PcdHashApiLibPolicy` - This PCD indicates the - HASH algorithm to to use in the BaseHashApiLib to calculate hash of data. The + HASH algorithm to use in the BaseHashApiLib to calculate hash of data. The default hashing algorithm for BaseHashApiLib is set to HASH_ALG_SHA256. | Setting | Algorithm | |------------|------------------| @@ -407,8 +407,8 @@ and CryptoSmm modules. * `gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable` - Enable/Disable the families and individual services produced by the EDK II Crypto Protocols/PPIs. The default is all services disabled. This Structured PCD is - associated with `PCD_CRYPTO_SERVICE_FAMILY_ENABLE` structure that defined in - `Include/Pcd/PcdCryptoServiceFamilyEnable.h`. + associated with the `PCD_CRYPTO_SERVICE_FAMILY_ENABLE` structure that is + defined in `Include/Pcd/PcdCryptoServiceFamilyEnable.h`. There are three layers of priority that determine if a specific family or individual cryptographic service is actually enabled in the CryptoPei, @@ -420,15 +420,15 @@ and CryptoSmm modules. OpensslLib instance linked, then the service is always disabled. 2) BaseCryptLib instance selection. * CryptoPei is always linked with the PeiCryptLib instance of the - BaseCryptLib library class. The table above have a column for the + BaseCryptLib library class. The table above has a column for the PeiCryptLib. If the family or service is blank, then that family or service is always disabled. * CryptoDxe is always linked with the BaseCryptLib instance of the - BaseCryptLib library class. The table above have a column for the + BaseCryptLib library class. The table above has a column for the BaseCryptLib. If the family or service is blank, then that family or service is always disabled. * CryptoSmm is always linked with the SmmCryptLib instance of the - BaseCryptLib library class. The table above have a column for the + BaseCryptLib library class. The table above has a column for the SmmCryptLib. If the family or service is blank, then that family or service is always disabled. 3) If a family or service is enabled in the OpensslLib instance and it is @@ -438,11 +438,11 @@ and CryptoSmm modules. bit fields for each family of services. All of the families are disabled by default. An entire family of services can be enabled by setting the family field to the value `PCD_CRYPTO_SERVICE_ENABLE_FAMILY`. Individual - services can be enabled by setting a single service name to `TRUE`. - Settings listed later in the DSC file have priority over settings earlier - in the DSC file, so it is legal for an entire family to be enabled first - and then a few individual services disabled by setting the service name to - `FALSE`. + services can be enabled by setting a single service name (bit) to `TRUE`. + Settings listed later in the DSC file have priority over settings listed + earlier in the DSC file, so it is valid for an entire family to be enabled + first and then for a few individual services to be disabled by setting + those service names to `FALSE`. #### Common PEI PcdCryptoServiceFamilyEnable Settings From cf7bbb73392dd148ec7eb9bc9b96c557f61fa357 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 3 Nov 2022 20:07:49 -0400 Subject: [PATCH 0300/1529] UnitTestFrameworkPkg: Add UnitTestUefiBootServicesTableLib This library supports a Boot Services table library implementation that allows code dependent upon UefiBootServicesTableLib to operate in an isolated execution environment such as within the context of a host-based unit test framework. The unit test should initialize the Boot Services database with any required elements (e.g. protocols, events, handles, etc.) prior to the services being invoked by code under test. It is strongly recommended to clean any global databases (e.g. protocol, event, handles, etc.) after every unit test so the tests execute in a predictable manner from a clean state. This library is being moved here from PrmPkg so it can be made more generally available to other packages and improved upon for others use. Cc: Michael D Kinney Cc: Sean Brogan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .../UnitTestUefiBootServicesTableLib.c | 119 ++ .../UnitTestUefiBootServicesTableLib.h | 1042 +++++++++++ .../UnitTestUefiBootServicesTableLib.inf | 46 + .../UnitTestUefiBootServicesTableLib.uni | 12 + ...itTestUefiBootServicesTableLibEventTimer.c | 180 ++ .../UnitTestUefiBootServicesTableLibImage.c | 163 ++ .../UnitTestUefiBootServicesTableLibMemory.c | 145 ++ .../UnitTestUefiBootServicesTableLibMisc.c | 198 ++ ...UnitTestUefiBootServicesTableLibProtocol.c | 1650 +++++++++++++++++ ...UnitTestUefiBootServicesTableLibProtocol.h | 120 ++ .../UnitTestUefiBootServicesTableLibTpl.c | 43 + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 1 + .../UnitTestFrameworkPkgHost.dsc.inc | 1 + 13 files changed, 3720 insertions(+) create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.h create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibEventTimer.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibImage.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMemory.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMisc.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.h create mode 100644 UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibTpl.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.c new file mode 100644 index 0000000000..a6fc13e7d2 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.c @@ -0,0 +1,119 @@ +/** @file + This library supports a Boot Services table library implementation that allows code dependent + upon UefiBootServicesTableLib to operate in an isolated execution environment such as within + the context of a host-based unit test framework. + + The unit test should initialize the Boot Services database with any required elements + (e.g. protocols, events, handles, etc.) prior to the services being invoked by code under test. + + It is strongly recommended to clean any global databases (e.g. protocol, event, handles, etc.) after + every unit test so the tests execute in a predictable manner from a clean state. + + Copyright (c) Microsoft Corporation + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +EFI_HANDLE gImageHandle = NULL; +EFI_SYSTEM_TABLE *gST = NULL; + +STATIC EFI_BOOT_SERVICES mBootServices = { + { + EFI_BOOT_SERVICES_SIGNATURE, // Signature + EFI_BOOT_SERVICES_REVISION, // Revision + sizeof (EFI_BOOT_SERVICES), // HeaderSize + 0, // CRC32 + 0 // Reserved + }, + (EFI_RAISE_TPL)UnitTestRaiseTpl, // RaiseTPL + (EFI_RESTORE_TPL)UnitTestRestoreTpl, // RestoreTPL + (EFI_ALLOCATE_PAGES)UnitTestAllocatePages, // AllocatePages + (EFI_FREE_PAGES)UnitTestFreePages, // FreePages + (EFI_GET_MEMORY_MAP)UnitTestGetMemoryMap, // GetMemoryMap + (EFI_ALLOCATE_POOL)UnitTestAllocatePool, // AllocatePool + (EFI_FREE_POOL)UnitTestFreePool, // FreePool + (EFI_CREATE_EVENT)UnitTestCreateEvent, // CreateEvent + (EFI_SET_TIMER)UnitTestSetTimer, // SetTimer + (EFI_WAIT_FOR_EVENT)UnitTestWaitForEvent, // WaitForEvent + (EFI_SIGNAL_EVENT)UnitTestSignalEvent, // SignalEvent + (EFI_CLOSE_EVENT)UnitTestCloseEvent, // CloseEvent + (EFI_CHECK_EVENT)UnitTestCheckEvent, // CheckEvent + (EFI_INSTALL_PROTOCOL_INTERFACE)UnitTestInstallProtocolInterface, // InstallProtocolInterface + (EFI_REINSTALL_PROTOCOL_INTERFACE)UnitTestReinstallProtocolInterface, // ReinstallProtocolInterface + (EFI_UNINSTALL_PROTOCOL_INTERFACE)UnitTestUninstallProtocolInterface, // UninstallProtocolInterface + (EFI_HANDLE_PROTOCOL)UnitTestHandleProtocol, // HandleProtocol + (VOID *)NULL, // Reserved + (EFI_REGISTER_PROTOCOL_NOTIFY)UnitTestRegisterProtocolNotify, // RegisterProtocolNotify + (EFI_LOCATE_HANDLE)UnitTestLocateHandle, // LocateHandle + (EFI_LOCATE_DEVICE_PATH)UnitTestLocateDevicePath, // LocateDevicePath + (EFI_INSTALL_CONFIGURATION_TABLE)UnitTestInstallConfigurationTable, // InstallConfigurationTable + (EFI_IMAGE_LOAD)UnitTestLoadImage, // LoadImage + (EFI_IMAGE_START)UnitTestStartImage, // StartImage + (EFI_EXIT)UnitTestExit, // Exit + (EFI_IMAGE_UNLOAD)UnitTestUnloadImage, // UnloadImage + (EFI_EXIT_BOOT_SERVICES)UnitTestExitBootServices, // ExitBootServices + (EFI_GET_NEXT_MONOTONIC_COUNT)UnitTestGetNextMonotonicCount, // GetNextMonotonicCount + (EFI_STALL)UnitTestStall, // Stall + (EFI_SET_WATCHDOG_TIMER)UnitTestSetWatchdogTimer, // SetWatchdogTimer + (EFI_CONNECT_CONTROLLER)UnitTestConnectController, // ConnectController + (EFI_DISCONNECT_CONTROLLER)UnitTestDisconnectController, // DisconnectController + (EFI_OPEN_PROTOCOL)UnitTestOpenProtocol, // OpenProtocol + (EFI_CLOSE_PROTOCOL)UnitTestCloseProtocol, // CloseProtocol + (EFI_OPEN_PROTOCOL_INFORMATION)UnitTestOpenProtocolInformation, // OpenProtocolInformation + (EFI_PROTOCOLS_PER_HANDLE)UnitTestProtocolsPerHandle, // ProtocolsPerHandle + (EFI_LOCATE_HANDLE_BUFFER)UnitTestLocateHandleBuffer, // LocateHandleBuffer + (EFI_LOCATE_PROTOCOL)UnitTestLocateProtocol, // LocateProtocol + (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES)UnitTestInstallMultipleProtocolInterfaces, // InstallMultipleProtocolInterfaces + (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES)UnitTestUninstallMultipleProtocolInterfaces, // UninstallMultipleProtocolInterfaces + (EFI_CALCULATE_CRC32)UnitTestCalculateCrc32, // CalculateCrc32 + (EFI_COPY_MEM)CopyMem, // CopyMem + (EFI_SET_MEM)SetMem, // SetMem + (EFI_CREATE_EVENT_EX)UnitTestCreateEventEx // CreateEventEx +}; + +EFI_BOOT_SERVICES *gBS = &mBootServices; + +/** + The constructor function caches the pointer of Boot Services Table. + + The constructor function caches the pointer of Boot Services Table through System Table. + It will ASSERT() if the pointer of System Table is NULL. + It will ASSERT() if the pointer of Boot Services Table is NULL. + It will always return EFI_SUCCESS. + + @param ImageHandle The firmware allocated handle for the EFI image. + @param SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS. + +**/ +EFI_STATUS +EFIAPI +UnitTestUefiBootServicesTableLibConstructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + // + // Cache the Image Handle + // + gImageHandle = ImageHandle; + ASSERT (gImageHandle != NULL); + + // + // Cache pointer to the EFI System Table + // + + // Note: The system table is not implemented + gST = NULL; + + // + // Cache pointer to the EFI Boot Services Table + // + gBS = SystemTable->BootServices; + ASSERT (gBS != NULL); + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.h b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.h new file mode 100644 index 0000000000..82853bb61a --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.h @@ -0,0 +1,1042 @@ +/** @file + An internal header file for the Unit Test instance of the UEFI Boot Services Table Library. + + This file includes common header files, defines internal structure and functions used by + the library implementation. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_H_ +#define UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +/** + Raise the task priority level to the new level. + High level is implemented by disabling processor interrupts. + + @param NewTpl New task priority level + + @return The previous task priority level + +**/ +EFI_TPL +EFIAPI +UnitTestRaiseTpl ( + IN EFI_TPL NewTpl + ); + +/** + Lowers the task priority to the previous value. If the new + priority unmasks events at a higher priority, they are dispatched. + + @param NewTpl New, lower, task priority + +**/ +VOID +EFIAPI +UnitTestRestoreTpl ( + IN EFI_TPL NewTpl + ); + +/** + Allocates pages from the memory map. + + @param Type The type of allocation to perform + @param MemoryType The type of memory to turn the allocated pages + into + @param NumberOfPages The number of pages to allocate + @param Memory A pointer to receive the base allocated memory + address + + @return Status. On success, Memory is filled in with the base address allocated + @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in + spec. + @retval EFI_NOT_FOUND Could not allocate pages match the requirement. + @retval EFI_OUT_OF_RESOURCES No enough pages to allocate. + @retval EFI_SUCCESS Pages successfully allocated. + +**/ +EFI_STATUS +EFIAPI +UnitTestAllocatePages ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, + IN OUT EFI_PHYSICAL_ADDRESS *Memory + ); + +/** + Frees previous allocated pages. + + @param Memory Base address of memory being freed + @param NumberOfPages The number of pages to free + + @retval EFI_NOT_FOUND Could not find the entry that covers the range + @retval EFI_INVALID_PARAMETER Address not aligned + @return EFI_SUCCESS -Pages successfully freed. + +**/ +EFI_STATUS +EFIAPI +UnitTestFreePages ( + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages + ); + +/** + This function returns a copy of the current memory map. The map is an array of + memory descriptors, each of which describes a contiguous block of memory. + + @param MemoryMapSize A pointer to the size, in bytes, of the + MemoryMap buffer. On input, this is the size of + the buffer allocated by the caller. On output, + it is the size of the buffer returned by the + firmware if the buffer was large enough, or the + size of the buffer needed to contain the map if + the buffer was too small. + @param MemoryMap A pointer to the buffer in which firmware places + the current memory map. + @param MapKey A pointer to the location in which firmware + returns the key for the current memory map. + @param DescriptorSize A pointer to the location in which firmware + returns the size, in bytes, of an individual + EFI_MEMORY_DESCRIPTOR. + @param DescriptorVersion A pointer to the location in which firmware + returns the version number associated with the + EFI_MEMORY_DESCRIPTOR. + + @retval EFI_SUCCESS The memory map was returned in the MemoryMap + buffer. + @retval EFI_BUFFER_TOO_SMALL The MemoryMap buffer was too small. The current + buffer size needed to hold the memory map is + returned in MemoryMapSize. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + +**/ +EFI_STATUS +EFIAPI +UnitTestGetMemoryMap ( + IN OUT UINTN *MemoryMapSize, + IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, + OUT UINTN *MapKey, + OUT UINTN *DescriptorSize, + OUT UINT32 *DescriptorVersion + ); + +/** + Allocate pool of a particular type. + + @param PoolType Type of pool to allocate + @param Size The amount of pool to allocate + @param Buffer The address to return a pointer to the allocated + pool + + @retval EFI_INVALID_PARAMETER PoolType not valid or Buffer is NULL + @retval EFI_OUT_OF_RESOURCES Size exceeds max pool size or allocation failed. + @retval EFI_SUCCESS Pool successfully allocated. + +**/ +EFI_STATUS +EFIAPI +UnitTestAllocatePool ( + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer + ); + +/** + Frees pool. + + @param Buffer The allocated pool entry to free + + @retval EFI_INVALID_PARAMETER Buffer is not a valid value. + @retval EFI_SUCCESS Pool successfully freed. + +**/ +EFI_STATUS +EFIAPI +UnitTestFreePool ( + IN VOID *Buffer + ); + +/** + Frees pool. + + @param Buffer The allocated pool entry to free + @param PoolType Pointer to pool type + + @retval EFI_INVALID_PARAMETER Buffer is not a valid value. + @retval EFI_SUCCESS Pool successfully freed. + +**/ +EFI_STATUS +EFIAPI +UnitTestInternalFreePool ( + IN VOID *Buffer, + OUT EFI_MEMORY_TYPE *PoolType OPTIONAL + ); + +/** + Creates an event. + + @param Type The type of event to create and its mode and + attributes + @param NotifyTpl The task priority level of event notifications + @param NotifyFunction Pointer to the events notification function + @param NotifyContext Pointer to the notification functions context; + corresponds to parameter "Context" in the + notification function + @param Event Pointer to the newly created event if the call + succeeds; undefined otherwise + + @retval EFI_SUCCESS The event structure was created + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + @retval EFI_OUT_OF_RESOURCES The event could not be allocated + +**/ +EFI_STATUS +EFIAPI +UnitTestCreateEvent ( + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL + IN VOID *NotifyContext, OPTIONAL + OUT EFI_EVENT *Event + ); + +/** + Sets the type of timer and the trigger time for a timer event. + + @param UserEvent The timer event that is to be signaled at the + specified time + @param Type The type of time that is specified in + TriggerTime + @param TriggerTime The number of 100ns units until the timer + expires + + @retval EFI_SUCCESS The event has been set to be signaled at the + requested time + @retval EFI_INVALID_PARAMETER Event or Type is not valid + +**/ +EFI_STATUS +EFIAPI +UnitTestSetTimer ( + IN EFI_EVENT UserEvent, + IN EFI_TIMER_DELAY Type, + IN UINT64 TriggerTime + ); + +/** + Stops execution until an event is signaled. + + @param NumberOfEvents The number of events in the UserEvents array + @param UserEvents An array of EFI_EVENT + @param UserIndex Pointer to the index of the event which + satisfied the wait condition + + @retval EFI_SUCCESS The event indicated by Index was signaled. + @retval EFI_INVALID_PARAMETER The event indicated by Index has a notification + function or Event was not a valid type + @retval EFI_UNSUPPORTED The current TPL is not TPL_APPLICATION + +**/ +EFI_STATUS +EFIAPI +UnitTestWaitForEvent ( + IN UINTN NumberOfEvents, + IN EFI_EVENT *UserEvents, + OUT UINTN *UserIndex + ); + +/** + Signals the event. Queues the event to be notified if needed. + + @param UserEvent The event to signal . + + @retval EFI_INVALID_PARAMETER Parameters are not valid. + @retval EFI_SUCCESS The event was signaled. + +**/ +EFI_STATUS +EFIAPI +UnitTestSignalEvent ( + IN EFI_EVENT UserEvent + ); + +/** + Closes an event and frees the event structure. + + @param UserEvent Event to close + + @retval EFI_INVALID_PARAMETER Parameters are not valid. + @retval EFI_SUCCESS The event has been closed + +**/ +EFI_STATUS +EFIAPI +UnitTestCloseEvent ( + IN EFI_EVENT UserEvent + ); + +/** + Check the status of an event. + + @param UserEvent The event to check + + @retval EFI_SUCCESS The event is in the signaled state + @retval EFI_NOT_READY The event is not in the signaled state + @retval EFI_INVALID_PARAMETER Event is of type EVT_NOTIFY_SIGNAL + +**/ +EFI_STATUS +EFIAPI +UnitTestCheckEvent ( + IN EFI_EVENT UserEvent + ); + +/** + Wrapper function to UnitTestInstallProtocolInterfaceNotify. This is the public API which + Calls the private one which contains a BOOLEAN parameter for notifications + + @param UserHandle The handle to install the protocol handler on, + or NULL if a new handle is to be allocated + @param Protocol The protocol to add to the handle + @param InterfaceType Indicates whether Interface is supplied in + native form. + @param Interface The interface for the protocol being added + + @return Status code + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallProtocolInterface ( + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface + ); + +/** + Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. + + @param UserHandle Handle on which the interface is to be + reinstalled + @param Protocol The numeric ID of the interface + @param OldInterface A pointer to the old interface + @param NewInterface A pointer to the new interface + + @retval EFI_SUCCESS The protocol interface was installed + @retval EFI_NOT_FOUND The OldInterface on the handle was not found + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + +**/ +EFI_STATUS +EFIAPI +UnitTestReinstallProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *OldInterface, + IN VOID *NewInterface + ); + +/** + Uninstalls all instances of a protocol:interfacer from a handle. + If the last protocol interface is remove from the handle, the + handle is freed. + + @param UserHandle The handle to remove the protocol handler from + @param Protocol The protocol, of protocol:interface, to remove + @param Interface The interface, of protocol:interface, to remove + + @retval EFI_INVALID_PARAMETER Protocol is NULL. + @retval EFI_SUCCESS Protocol interface successfully uninstalled. + +**/ +EFI_STATUS +EFIAPI +UnitTestUninstallProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *Interface + ); + +/** + Queries a handle to determine if it supports a specified protocol. + + @param UserHandle The handle being queried. + @param Protocol The published unique identifier of the protocol. + @param Interface Supplies the address where a pointer to the + corresponding Protocol Interface is returned. + + @return The requested protocol interface for the handle + +**/ +EFI_STATUS +EFIAPI +UnitTestHandleProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface + ); + +/** + Add a new protocol notification record for the request protocol. + + @param Protocol The requested protocol to add the notify + registration + @param Event The event to signal + @param Registration Returns the registration record + + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_SUCCESS Successfully returned the registration record + that has been added + +**/ +EFI_STATUS +EFIAPI +UnitTestRegisterProtocolNotify ( + IN EFI_GUID *Protocol, + IN EFI_EVENT Event, + OUT VOID **Registration + ); + +/** + Locates the requested handle(s) and returns them in Buffer. + + @param SearchType The type of search to perform to locate the + handles + @param Protocol The protocol to search for + @param SearchKey Dependant on SearchType + @param BufferSize On input the size of Buffer. On output the + size of data returned. + @param Buffer The buffer to return the results in + + @retval EFI_BUFFER_TOO_SMALL Buffer too small, required buffer size is + returned in BufferSize. + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_SUCCESS Successfully found the requested handle(s) and + returns them in Buffer. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateHandle ( + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer + ); + +/** + Locates the handle to a device on the device path that best matches the specified protocol. + + @param Protocol The protocol to search for. + @param DevicePath On input, a pointer to a pointer to the device + path. On output, the device path pointer is + modified to point to the remaining part of the + devicepath. + @param Device A pointer to the returned device handle. + + @retval EFI_SUCCESS The resulting handle was returned. + @retval EFI_NOT_FOUND No handles matched the search. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateDevicePath ( + IN EFI_GUID *Protocol, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, + OUT EFI_HANDLE *Device + ); + +/** + Boot Service called to add, modify, or remove a system configuration table from + the EFI System Table. + + @param Guid Pointer to the GUID for the entry to add, update, or + remove + @param Table Pointer to the configuration table for the entry to add, + update, or remove, may be NULL. + + @return EFI_SUCCESS Guid, Table pair added, updated, or removed. + @return EFI_INVALID_PARAMETER Input GUID not valid. + @return EFI_NOT_FOUND Attempted to delete non-existant entry + @return EFI_OUT_OF_RESOURCES Not enough memory available + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallConfigurationTable ( + IN EFI_GUID *Guid, + IN VOID *Table + ); + +/** + Loads an EFI image into memory and returns a handle to the image. + + @param BootPolicy If TRUE, indicates that the request originates + from the boot manager, and that the boot + manager is attempting to load FilePath as a + boot selection. + @param ParentImageHandle The caller's image handle. + @param FilePath The specific file path from which the image is + loaded. + @param SourceBuffer If not NULL, a pointer to the memory location + containing a copy of the image to be loaded. + @param SourceSize The size in bytes of SourceBuffer. + @param ImageHandle Pointer to the returned image handle that is + created when the image is successfully loaded. + + @retval EFI_SUCCESS The image was loaded into memory. + @retval EFI_NOT_FOUND The FilePath was not found. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + @retval EFI_UNSUPPORTED The image type is not supported, or the device + path cannot be parsed to locate the proper + protocol for loading the file. + @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient + resources. + @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not + understood. + @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error. + @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the + image from being loaded. NULL is returned in *ImageHandle. + @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a + valid EFI_LOADED_IMAGE_PROTOCOL. However, the current + platform policy specifies that the image should not be started. + +**/ +EFI_STATUS +EFIAPI +UnitTestLoadImage ( + IN BOOLEAN BootPolicy, + IN EFI_HANDLE ParentImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN VOID *SourceBuffer OPTIONAL, + IN UINTN SourceSize, + OUT EFI_HANDLE *ImageHandle + ); + +/** + Transfer control to a loaded image's entry point. + + @param ImageHandle Handle of image to be started. + @param ExitDataSize Pointer of the size to ExitData + @param ExitData Pointer to a pointer to a data buffer that + includes a Null-terminated string, + optionally followed by additional binary data. + The string is a description that the caller may + use to further indicate the reason for the + image's exit. + + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate + @retval EFI_SECURITY_VIOLATION The current platform policy specifies that the image should not be started. + @retval EFI_SUCCESS Successfully transfer control to the image's + entry point. + +**/ +EFI_STATUS +EFIAPI +UnitTestStartImage ( + IN EFI_HANDLE ImageHandle, + OUT UINTN *ExitDataSize, + OUT CHAR16 **ExitData OPTIONAL + ); + +/** + Terminates the currently loaded EFI image and returns control to boot services. + + @param ImageHandle Handle that identifies the image. This + parameter is passed to the image on entry. + @param Status The image's exit code. + @param ExitDataSize The size, in bytes, of ExitData. Ignored if + ExitStatus is EFI_SUCCESS. + @param ExitData Pointer to a data buffer that includes a + Null-terminated Unicode string, optionally + followed by additional binary data. The string + is a description that the caller may use to + further indicate the reason for the image's + exit. + + @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current + image. + @retval EFI_SUCCESS Successfully terminates the currently loaded + EFI image. + @retval EFI_ACCESS_DENIED Should never reach there. + @retval EFI_OUT_OF_RESOURCES Could not allocate pool + +**/ +EFI_STATUS +EFIAPI +UnitTestExit ( + IN EFI_HANDLE ImageHandle, + IN EFI_STATUS Status, + IN UINTN ExitDataSize, + IN CHAR16 *ExitData OPTIONAL + ); + +/** + Unloads an image. + + @param ImageHandle Handle that identifies the image to be + unloaded. + + @retval EFI_SUCCESS The image has been unloaded. + @retval EFI_UNSUPPORTED The image has been started, and does not support + unload. + @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle. + +**/ +EFI_STATUS +EFIAPI +UnitTestUnloadImage ( + IN EFI_HANDLE ImageHandle + ); + +/** + Terminates all boot services. + + @param ImageHandle Handle that identifies the exiting image. + @param MapKey Key to the latest memory map. + + @retval EFI_SUCCESS Boot Services terminated + @retval EFI_INVALID_PARAMETER MapKey is incorrect. + +**/ +EFI_STATUS +EFIAPI +UnitTestExitBootServices ( + IN EFI_HANDLE ImageHandle, + IN UINTN MapKey + ); + +/** + Returns a monotonically increasing count for the platform. + + @param[out] Count The pointer to returned value. + + @retval EFI_SUCCESS The next monotonic count was returned. + @retval EFI_INVALID_PARAMETER Count is NULL. + @retval EFI_DEVICE_ERROR The device is not functioning properly. + +**/ +EFI_STATUS +EFIAPI +UnitTestGetNextMonotonicCount ( + OUT UINT64 *Count + ); + +/** + Introduces a fine-grained stall. + + @param Microseconds The number of microseconds to stall execution. + + @retval EFI_SUCCESS Execution was stalled for at least the requested + amount of microseconds. + @retval EFI_NOT_AVAILABLE_YET gMetronome is not available yet + +**/ +EFI_STATUS +EFIAPI +UnitTestStall ( + IN UINTN Microseconds + ); + +/** + Sets the system's watchdog timer. + + @param Timeout The number of seconds to set the watchdog timer to. + A value of zero disables the timer. + @param WatchdogCode The numeric code to log on a watchdog timer timeout + event. The firmware reserves codes 0x0000 to 0xFFFF. + Loaders and operating systems may use other timeout + codes. + @param DataSize The size, in bytes, of WatchdogData. + @param WatchdogData A data buffer that includes a Null-terminated Unicode + string, optionally followed by additional binary data. + The string is a description that the call may use to + further indicate the reason to be logged with a + watchdog event. + + @return EFI_SUCCESS Timeout has been set + @return EFI_NOT_AVAILABLE_YET WatchdogTimer is not available yet + @return EFI_UNSUPPORTED System does not have a timer (currently not used) + @return EFI_DEVICE_ERROR Could not complete due to hardware error + +**/ +EFI_STATUS +EFIAPI +UnitTestSetWatchdogTimer ( + IN UINTN Timeout, + IN UINT64 WatchdogCode, + IN UINTN DataSize, + IN CHAR16 *WatchdogData OPTIONAL + ); + +/** + Connects one or more drivers to a controller. + + @param ControllerHandle The handle of the controller to which driver(s) are to be connected. + @param DriverImageHandle A pointer to an ordered list handles that support the + EFI_DRIVER_BINDING_PROTOCOL. + @param RemainingDevicePath A pointer to the device path that specifies a child of the + controller specified by ControllerHandle. + @param Recursive If TRUE, then ConnectController() is called recursively + until the entire tree of controllers below the controller specified + by ControllerHandle have been created. If FALSE, then + the tree of controllers is only expanded one level. + + @retval EFI_SUCCESS 1) One or more drivers were connected to ControllerHandle. + 2) No drivers were connected to ControllerHandle, but + RemainingDevicePath is not NULL, and it is an End Device + Path Node. + @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. + @retval EFI_NOT_FOUND 1) There are no EFI_DRIVER_BINDING_PROTOCOL instances + present in the system. + 2) No drivers were connected to ControllerHandle. + @retval EFI_SECURITY_VIOLATION + The user has no permission to start UEFI device drivers on the device path + associated with the ControllerHandle or specified by the RemainingDevicePath. + +**/ +EFI_STATUS +EFIAPI +UnitTestConnectController ( + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE *DriverImageHandle OPTIONAL, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, + IN BOOLEAN Recursive + ); + +/** + Disconnects a controller from a driver + + @param ControllerHandle ControllerHandle The handle of + the controller from which + driver(s) are to be + disconnected. + @param DriverImageHandle DriverImageHandle The driver to + disconnect from ControllerHandle. + @param ChildHandle ChildHandle The handle of the + child to destroy. + + @retval EFI_SUCCESS One or more drivers were + disconnected from the controller. + @retval EFI_SUCCESS On entry, no drivers are managing + ControllerHandle. + @retval EFI_SUCCESS DriverImageHandle is not NULL, + and on entry DriverImageHandle is + not managing ControllerHandle. + @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. + @retval EFI_INVALID_PARAMETER DriverImageHandle is not NULL, + and it is not a valid EFI_HANDLE. + @retval EFI_INVALID_PARAMETER ChildHandle is not NULL, and it + is not a valid EFI_HANDLE. + @retval EFI_OUT_OF_RESOURCES There are not enough resources + available to disconnect any + drivers from ControllerHandle. + @retval EFI_DEVICE_ERROR The controller could not be + disconnected because of a device + error. + +**/ +EFI_STATUS +EFIAPI +UnitTestDisconnectController ( + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE DriverImageHandle OPTIONAL, + IN EFI_HANDLE ChildHandle OPTIONAL + ); + +/** + Locates the installed protocol handler for the handle, and + invokes it to obtain the protocol interface. Usage information + is registered in the protocol data base. + + @param UserHandle The handle to obtain the protocol interface on + @param Protocol The ID of the protocol + @param Interface The location to return the protocol interface + @param ImageHandle The handle of the Image that is opening the + protocol interface specified by Protocol and + Interface. + @param ControllerHandle The controller handle that is requiring this + interface. + @param Attributes The open mode of the protocol interface + specified by Handle and Protocol. + + @retval EFI_INVALID_PARAMETER Protocol is NULL. + @retval EFI_SUCCESS Get the protocol interface. + +**/ +EFI_STATUS +EFIAPI +UnitTestOpenProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface OPTIONAL, + IN EFI_HANDLE ImageHandle, + IN EFI_HANDLE ControllerHandle, + IN UINT32 Attributes + ); + +/** + Closes a protocol on a handle that was opened using OpenProtocol(). + + @param UserHandle The handle for the protocol interface that was + previously opened with OpenProtocol(), and is + now being closed. + @param Protocol The published unique identifier of the protocol. + It is the caller's responsibility to pass in a + valid GUID. + @param AgentHandle The handle of the agent that is closing the + protocol interface. + @param ControllerHandle If the agent that opened a protocol is a driver + that follows the EFI Driver Model, then this + parameter is the controller handle that required + the protocol interface. If the agent does not + follow the EFI Driver Model, then this parameter + is optional and may be NULL. + + @retval EFI_SUCCESS The protocol instance was closed. + @retval EFI_INVALID_PARAMETER Handle, AgentHandle or ControllerHandle is not a + valid EFI_HANDLE. + @retval EFI_NOT_FOUND Can not find the specified protocol or + AgentHandle. + +**/ +EFI_STATUS +EFIAPI +UnitTestCloseProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN EFI_HANDLE AgentHandle, + IN EFI_HANDLE ControllerHandle + ); + +/** + Return information about Opened protocols in the system + + @param UserHandle The handle to close the protocol interface on + @param Protocol The ID of the protocol + @param EntryBuffer A pointer to a buffer of open protocol + information in the form of + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures. + @param EntryCount Number of EntryBuffer entries + +**/ +EFI_STATUS +EFIAPI +UnitTestOpenProtocolInformation ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, + OUT UINTN *EntryCount + ); + +/** + Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated + from pool. + + @param UserHandle The handle from which to retrieve the list of + protocol interface GUIDs. + @param ProtocolBuffer A pointer to the list of protocol interface GUID + pointers that are installed on Handle. + @param ProtocolBufferCount A pointer to the number of GUID pointers present + in ProtocolBuffer. + + @retval EFI_SUCCESS The list of protocol interface GUIDs installed + on Handle was returned in ProtocolBuffer. The + number of protocol interface GUIDs was returned + in ProtocolBufferCount. + @retval EFI_INVALID_PARAMETER Handle is NULL. + @retval EFI_INVALID_PARAMETER Handle is not a valid EFI_HANDLE. + @retval EFI_INVALID_PARAMETER ProtocolBuffer is NULL. + @retval EFI_INVALID_PARAMETER ProtocolBufferCount is NULL. + @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the + results. + +**/ +EFI_STATUS +EFIAPI +UnitTestProtocolsPerHandle ( + IN EFI_HANDLE UserHandle, + OUT EFI_GUID ***ProtocolBuffer, + OUT UINTN *ProtocolBufferCount + ); + +/** + Function returns an array of handles that support the requested protocol + in a buffer allocated from pool. This is a version of UnitTestLocateHandle() + that allocates a buffer for the caller. + + @param SearchType Specifies which handle(s) are to be returned. + @param Protocol Provides the protocol to search by. This + parameter is only valid for SearchType + ByProtocol. + @param SearchKey Supplies the search key depending on the + SearchType. + @param NumberHandles The number of handles returned in Buffer. + @param Buffer A pointer to the buffer to return the requested + array of handles that support Protocol. + + @retval EFI_SUCCESS The result array of handles was returned. + @retval EFI_NOT_FOUND No handles match the search. + @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the + matching results. + @retval EFI_INVALID_PARAMETER One or more parameters are not valid. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateHandleBuffer ( + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *NumberHandles, + OUT EFI_HANDLE **Buffer + ); + +/** + Return the first Protocol Interface that matches the Protocol GUID. If + Registration is passed in, return a Protocol Instance that was just add + to the system. If Registration is NULL return the first Protocol Interface + you find. + + @param Protocol The protocol to search for + @param Registration Optional Registration Key returned from + RegisterProtocolNotify() + @param Interface Return the Protocol interface (instance). + + @retval EFI_SUCCESS If a valid Interface is returned + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_NOT_FOUND Protocol interface not found + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateProtocol ( + IN EFI_GUID *Protocol, + IN VOID *Registration OPTIONAL, + OUT VOID **Interface + ); + +/** + Installs a list of protocol interface into the boot services environment. + This function calls InstallProtocolInterface() in a loop. If any error + occurs all the protocols added by this function are removed. This is + basically a lib function to save space. + + @param Handle The handle to install the protocol handlers on, + or NULL if a new handle is to be allocated + @param ... EFI_GUID followed by protocol instance. A NULL + terminates the list. The pairs are the + arguments to InstallProtocolInterface(). All the + protocols are added to Handle. + + @retval EFI_SUCCESS All the protocol interface was installed. + @retval EFI_OUT_OF_RESOURCES There was not enough memory in pool to install all the protocols. + @retval EFI_ALREADY_STARTED A Device Path Protocol instance was passed in that is already present in + the handle database. + @retval EFI_INVALID_PARAMETER Handle is NULL. + @retval EFI_INVALID_PARAMETER Protocol is already installed on the handle specified by Handle. + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallMultipleProtocolInterfaces ( + IN OUT EFI_HANDLE *Handle, + ... + ); + +/** + Uninstalls a list of protocol interface in the boot services environment. + This function calls UninstallProtocolInterface() in a loop. This is + basically a lib function to save space. + + @param Handle The handle to uninstall the protocol + @param ... EFI_GUID followed by protocol instance. A NULL + terminates the list. The pairs are the + arguments to UninstallProtocolInterface(). All + the protocols are added to Handle. + + @return Status code + +**/ +EFI_STATUS +EFIAPI +UnitTestUninstallMultipleProtocolInterfaces ( + IN EFI_HANDLE Handle, + ... + ); + +/** + Computes and returns a 32-bit CRC for a data buffer. + + @param[in] Data A pointer to the buffer on which the 32-bit CRC is to be computed. + @param[in] DataSize The number of bytes in the buffer Data. + @param[out] Crc32 The 32-bit CRC that was computed for the data buffer specified by Data + and DataSize. + + @retval EFI_SUCCESS The 32-bit CRC was computed for the data buffer and returned in + Crc32. + @retval EFI_INVALID_PARAMETER Data is NULL. + @retval EFI_INVALID_PARAMETER Crc32 is NULL. + @retval EFI_INVALID_PARAMETER DataSize is 0. + +**/ +EFI_STATUS +EFIAPI +UnitTestCalculateCrc32 ( + IN VOID *Data, + IN UINTN DataSize, + OUT UINT32 *Crc32 + ); + +/** + Creates an event in a group. + + @param Type The type of event to create and its mode and + attributes + @param NotifyTpl The task priority level of event notifications + @param NotifyFunction Pointer to the events notification function + @param NotifyContext Pointer to the notification functions context; + corresponds to parameter "Context" in the + notification function + @param EventGroup GUID for EventGroup if NULL act the same as + gBS->CreateEvent(). + @param Event Pointer to the newly created event if the call + succeeds; undefined otherwise + + @retval EFI_SUCCESS The event structure was created + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + @retval EFI_OUT_OF_RESOURCES The event could not be allocated + +**/ +EFI_STATUS +EFIAPI +UnitTestCreateEventEx ( + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL + IN CONST VOID *NotifyContext, OPTIONAL + IN CONST EFI_GUID *EventGroup, OPTIONAL + OUT EFI_EVENT *Event + ); + +#endif diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf new file mode 100644 index 0000000000..b694dd0232 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf @@ -0,0 +1,46 @@ +## @file +# UEFI Boot Services Table Library for unit tests implementation. +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = UnitTestUefiBootServicesTableLib + MODULE_UNI_FILE = UefiBootServicesTableLibTest.uni + FILE_GUID = AA3A0651-89EB-4951-9D68-50F27360EBC2 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiBootServicesTableLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_APPLICATION UEFI_DRIVER SMM_CORE + + CONSTRUCTOR = UnitTestUefiBootServicesTableLibConstructor + +# +# VALID_ARCHITECTURES = IA32 X64 EBC +# + +[Sources] + UnitTestUefiBootServicesTableLib.h + UnitTestUefiBootServicesTableLib.c + UnitTestUefiBootServicesTableLibEventTimer.c + UnitTestUefiBootServicesTableLibImage.c + UnitTestUefiBootServicesTableLibMemory.c + UnitTestUefiBootServicesTableLibProtocol.h + UnitTestUefiBootServicesTableLibProtocol.c + UnitTestUefiBootServicesTableLibMisc.c + UnitTestUefiBootServicesTableLibTpl.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + MemoryAllocationLib + UnitTestLib + +[UserExtensions.TianoCore."ExtraFiles"] + TimerExtra.uni diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.uni b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.uni new file mode 100644 index 0000000000..1f742bb6d8 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.uni @@ -0,0 +1,12 @@ +// /** @file +// UEFI Boot Services Table Library for unit tests implementation. +// +// Copyright (c) Microsoft Corporation +// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "UEFI Boot Services Table Library for unit tests" + +#string STR_MODULE_DESCRIPTION #language en-US "UEFI Boot Services Table Library for unit tests." diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibEventTimer.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibEventTimer.c new file mode 100644 index 0000000000..dc02c4ef9a --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibEventTimer.c @@ -0,0 +1,180 @@ +/** @file + Implementation of event and timer related services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +/** + Creates an event. + + @param Type The type of event to create and its mode and + attributes + @param NotifyTpl The task priority level of event notifications + @param NotifyFunction Pointer to the events notification function + @param NotifyContext Pointer to the notification functions context + corresponds to parameter "Context" in the + notification function + @param Event Pointer to the newly created event if the call + succeeds undefined otherwise + + @retval EFI_SUCCESS The event structure was created + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + @retval EFI_OUT_OF_RESOURCES The event could not be allocated + +**/ +EFI_STATUS +EFIAPI +UnitTestCreateEvent ( + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL + IN VOID *NotifyContext, OPTIONAL + OUT EFI_EVENT *Event + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Sets the type of timer and the trigger time for a timer event. + + @param UserEvent The timer event that is to be signaled at the + specified time + @param Type The type of time that is specified in + TriggerTime + @param TriggerTime The number of 100ns units until the timer + expires + + @retval EFI_SUCCESS The event has been set to be signaled at the + requested time + @retval EFI_INVALID_PARAMETER Event or Type is not valid + +**/ +EFI_STATUS +EFIAPI +UnitTestSetTimer ( + IN EFI_EVENT UserEvent, + IN EFI_TIMER_DELAY Type, + IN UINT64 TriggerTime + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Stops execution until an event is signaled. + + @param NumberOfEvents The number of events in the UserEvents array + @param UserEvents An array of EFI_EVENT + @param UserIndex Pointer to the index of the event which + satisfied the wait condition + + @retval EFI_SUCCESS The event indicated by Index was signaled. + @retval EFI_INVALID_PARAMETER The event indicated by Index has a notification + function or Event was not a valid type + @retval EFI_UNSUPPORTED The current TPL is not TPL_APPLICATION + +**/ +EFI_STATUS +EFIAPI +UnitTestWaitForEvent ( + IN UINTN NumberOfEvents, + IN EFI_EVENT *UserEvents, + OUT UINTN *UserIndex + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Signals the event. Queues the event to be notified if needed. + + @param UserEvent The event to signal . + + @retval EFI_INVALID_PARAMETER Parameters are not valid. + @retval EFI_SUCCESS The event was signaled. + +**/ +EFI_STATUS +EFIAPI +UnitTestSignalEvent ( + IN EFI_EVENT UserEvent + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Closes an event and frees the event structure. + + @param UserEvent Event to close + + @retval EFI_INVALID_PARAMETER Parameters are not valid. + @retval EFI_SUCCESS The event has been closed + +**/ +EFI_STATUS +EFIAPI +UnitTestCloseEvent ( + IN EFI_EVENT UserEvent + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Check the status of an event. + + @param UserEvent The event to check + + @retval EFI_SUCCESS The event is in the signaled state + @retval EFI_NOT_READY The event is not in the signaled state + @retval EFI_INVALID_PARAMETER Event is of type EVT_NOTIFY_SIGNAL + +**/ +EFI_STATUS +EFIAPI +UnitTestCheckEvent ( + IN EFI_EVENT UserEvent + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Creates an event in a group. + + @param Type The type of event to create and its mode and + attributes + @param NotifyTpl The task priority level of event notifications + @param NotifyFunction Pointer to the events notification function + @param NotifyContext Pointer to the notification functions context + corresponds to parameter "Context" in the + notification function + @param EventGroup GUID for EventGroup if NULL act the same as + gBS->CreateEvent(). + @param Event Pointer to the newly created event if the call + succeeds undefined otherwise + + @retval EFI_SUCCESS The event structure was created + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + @retval EFI_OUT_OF_RESOURCES The event could not be allocated + +**/ +EFI_STATUS +EFIAPI +UnitTestCreateEventEx ( + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL + IN CONST VOID *NotifyContext, OPTIONAL + IN CONST EFI_GUID *EventGroup, OPTIONAL + OUT EFI_EVENT *Event + ) +{ + return EFI_NOT_AVAILABLE_YET; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibImage.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibImage.c new file mode 100644 index 0000000000..144cc33e25 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibImage.c @@ -0,0 +1,163 @@ +/** @file + Implementation of image related services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +/** + Loads an EFI image into memory and returns a handle to the image. + + @param BootPolicy If TRUE, indicates that the request originates + from the boot manager, and that the boot + manager is attempting to load FilePath as a + boot selection. + @param ParentImageHandle The caller's image handle. + @param FilePath The specific file path from which the image is + loaded. + @param SourceBuffer If not NULL, a pointer to the memory location + containing a copy of the image to be loaded. + @param SourceSize The size in bytes of SourceBuffer. + @param ImageHandle Pointer to the returned image handle that is + created when the image is successfully loaded. + + @retval EFI_SUCCESS The image was loaded into memory. + @retval EFI_NOT_FOUND The FilePath was not found. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + @retval EFI_UNSUPPORTED The image type is not supported, or the device + path cannot be parsed to locate the proper + protocol for loading the file. + @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient + resources. + @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not + understood. + @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error. + @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the + image from being loaded. NULL is returned in *ImageHandle. + @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a + valid EFI_LOADED_IMAGE_PROTOCOL. However, the current + platform policy specifies that the image should not be started. + +**/ +EFI_STATUS +EFIAPI +UnitTestLoadImage ( + IN BOOLEAN BootPolicy, + IN EFI_HANDLE ParentImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN VOID *SourceBuffer OPTIONAL, + IN UINTN SourceSize, + OUT EFI_HANDLE *ImageHandle + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Transfer control to a loaded image's entry point. + + @param ImageHandle Handle of image to be started. + @param ExitDataSize Pointer of the size to ExitData + @param ExitData Pointer to a pointer to a data buffer that + includes a Null-terminated string, + optionally followed by additional binary data. + The string is a description that the caller may + use to further indicate the reason for the + image's exit. + + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate + @retval EFI_SECURITY_VIOLATION The current platform policy specifies that the image should not be started. + @retval EFI_SUCCESS Successfully transfer control to the image's + entry point. + +**/ +EFI_STATUS +EFIAPI +UnitTestStartImage ( + IN EFI_HANDLE ImageHandle, + OUT UINTN *ExitDataSize, + OUT CHAR16 **ExitData OPTIONAL + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Terminates the currently loaded EFI image and returns control to boot services. + + @param ImageHandle Handle that identifies the image. This + parameter is passed to the image on entry. + @param Status The image's exit code. + @param ExitDataSize The size, in bytes, of ExitData. Ignored if + ExitStatus is EFI_SUCCESS. + @param ExitData Pointer to a data buffer that includes a + Null-terminated Unicode string, optionally + followed by additional binary data. The string + is a description that the caller may use to + further indicate the reason for the image's + exit. + + @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current + image. + @retval EFI_SUCCESS Successfully terminates the currently loaded + EFI image. + @retval EFI_ACCESS_DENIED Should never reach there. + @retval EFI_OUT_OF_RESOURCES Could not allocate pool + +**/ +EFI_STATUS +EFIAPI +UnitTestExit ( + IN EFI_HANDLE ImageHandle, + IN EFI_STATUS Status, + IN UINTN ExitDataSize, + IN CHAR16 *ExitData OPTIONAL + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Unloads an image. + + @param ImageHandle Handle that identifies the image to be + unloaded. + + @retval EFI_SUCCESS The image has been unloaded. + @retval EFI_UNSUPPORTED The image has been started, and does not support + unload. + @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle. + +**/ +EFI_STATUS +EFIAPI +UnitTestUnloadImage ( + IN EFI_HANDLE ImageHandle + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Terminates all boot services. + + @param ImageHandle Handle that identifies the exiting image. + @param MapKey Key to the latest memory map. + + @retval EFI_SUCCESS Boot Services terminated + @retval EFI_INVALID_PARAMETER MapKey is incorrect. + +**/ +EFI_STATUS +EFIAPI +UnitTestExitBootServices ( + IN EFI_HANDLE ImageHandle, + IN UINTN MapKey + ) +{ + return EFI_NOT_AVAILABLE_YET; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMemory.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMemory.c new file mode 100644 index 0000000000..abbb12974a --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMemory.c @@ -0,0 +1,145 @@ +/** @file + Implementation of memory related services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +/** + Allocates pages from the memory map. + + @param Type The type of allocation to perform + @param MemoryType The type of memory to turn the allocated pages + into + @param NumberOfPages The number of pages to allocate + @param Memory A pointer to receive the base allocated memory + address + + @return Status. On success, Memory is filled in with the base address allocated + @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in + spec. + @retval EFI_NOT_FOUND Could not allocate pages match the requirement. + @retval EFI_OUT_OF_RESOURCES No enough pages to allocate. + @retval EFI_SUCCESS Pages successfully allocated. + +**/ +EFI_STATUS +EFIAPI +UnitTestAllocatePages ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, + IN OUT EFI_PHYSICAL_ADDRESS *Memory + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Frees previous allocated pages. + + @param Memory Base address of memory being freed + @param NumberOfPages The number of pages to free + + @retval EFI_NOT_FOUND Could not find the entry that covers the range + @retval EFI_INVALID_PARAMETER Address not aligned + @return EFI_SUCCESS -Pages successfully freed. + +**/ +EFI_STATUS +EFIAPI +UnitTestFreePages ( + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + This function returns a copy of the current memory map. The map is an array of + memory descriptors, each of which describes a contiguous block of memory. + + @param MemoryMapSize A pointer to the size, in bytes, of the + MemoryMap buffer. On input, this is the size of + the buffer allocated by the caller. On output, + it is the size of the buffer returned by the + firmware if the buffer was large enough, or the + size of the buffer needed to contain the map if + the buffer was too small. + @param MemoryMap A pointer to the buffer in which firmware places + the current memory map. + @param MapKey A pointer to the location in which firmware + returns the key for the current memory map. + @param DescriptorSize A pointer to the location in which firmware + returns the size, in bytes, of an individual + EFI_MEMORY_DESCRIPTOR. + @param DescriptorVersion A pointer to the location in which firmware + returns the version number associated with the + EFI_MEMORY_DESCRIPTOR. + + @retval EFI_SUCCESS The memory map was returned in the MemoryMap + buffer. + @retval EFI_BUFFER_TOO_SMALL The MemoryMap buffer was too small. The current + buffer size needed to hold the memory map is + returned in MemoryMapSize. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + +**/ +EFI_STATUS +EFIAPI +UnitTestGetMemoryMap ( + IN OUT UINTN *MemoryMapSize, + IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, + OUT UINTN *MapKey, + OUT UINTN *DescriptorSize, + OUT UINT32 *DescriptorVersion + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Allocate pool of a particular type. + + @param PoolType Type of pool to allocate + @param Size The amount of pool to allocate + @param Buffer The address to return a pointer to the allocated + pool + + @retval EFI_INVALID_PARAMETER PoolType not valid or Buffer is NULL + @retval EFI_OUT_OF_RESOURCES Size exceeds max pool size or allocation failed. + @retval EFI_SUCCESS Pool successfully allocated. + +**/ +EFI_STATUS +EFIAPI +UnitTestAllocatePool ( + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Frees pool. + + @param Buffer The allocated pool entry to free + + @retval EFI_INVALID_PARAMETER Buffer is not a valid value. + @retval EFI_SUCCESS Pool successfully freed. + +**/ +EFI_STATUS +EFIAPI +UnitTestFreePool ( + IN VOID *Buffer + ) +{ + return EFI_NOT_AVAILABLE_YET; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMisc.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMisc.c new file mode 100644 index 0000000000..121496b3b9 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibMisc.c @@ -0,0 +1,198 @@ +/** @file + Implementation of miscellaneous services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +/** + Returns a monotonically increasing count for the platform. + + @param[out] Count The pointer to returned value. + + @retval EFI_SUCCESS The next monotonic count was returned. + @retval EFI_INVALID_PARAMETER Count is NULL. + @retval EFI_DEVICE_ERROR The device is not functioning properly. + +**/ +EFI_STATUS +EFIAPI +UnitTestGetNextMonotonicCount ( + OUT UINT64 *Count + ) +{ + STATIC UINT64 StaticCount = 0; + + *Count = StaticCount++; + + return EFI_SUCCESS; +} + +/** + Introduces a fine-grained stall. + + @param Microseconds The number of microseconds to stall execution. + + @retval EFI_SUCCESS Execution was stalled for at least the requested + amount of microseconds. + @retval EFI_NOT_AVAILABLE_YET gMetronome is not available yet + +**/ +EFI_STATUS +EFIAPI +UnitTestStall ( + IN UINTN Microseconds + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Sets the system's watchdog timer. + + @param Timeout The number of seconds to set the watchdog timer to. + A value of zero disables the timer. + @param WatchdogCode The numeric code to log on a watchdog timer timeout + event. The firmware reserves codes 0x0000 to 0xFFFF. + Loaders and operating systems may use other timeout + codes. + @param DataSize The size, in bytes, of WatchdogData. + @param WatchdogData A data buffer that includes a Null-terminated Unicode + string, optionally followed by additional binary data. + The string is a description that the call may use to + further indicate the reason to be logged with a + watchdog event. + + @return EFI_SUCCESS Timeout has been set + @return EFI_NOT_AVAILABLE_YET WatchdogTimer is not available yet + @return EFI_UNSUPPORTED System does not have a timer (currently not used) + @return EFI_DEVICE_ERROR Could not complete due to hardware error + +**/ +EFI_STATUS +EFIAPI +UnitTestSetWatchdogTimer ( + IN UINTN Timeout, + IN UINT64 WatchdogCode, + IN UINTN DataSize, + IN CHAR16 *WatchdogData OPTIONAL + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Connects one or more drivers to a controller. + + @param ControllerHandle The handle of the controller to which driver(s) are to be connected. + @param DriverImageHandle A pointer to an ordered list handles that support the + EFI_DRIVER_BINDING_PROTOCOL. + @param RemainingDevicePath A pointer to the device path that specifies a child of the + controller specified by ControllerHandle. + @param Recursive If TRUE, then ConnectController() is called recursively + until the entire tree of controllers below the controller specified + by ControllerHandle have been created. If FALSE, then + the tree of controllers is only expanded one level. + + @retval EFI_SUCCESS 1) One or more drivers were connected to ControllerHandle. + 2) No drivers were connected to ControllerHandle, but + RemainingDevicePath is not NULL, and it is an End Device + Path Node. + @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. + @retval EFI_NOT_FOUND 1) There are no EFI_DRIVER_BINDING_PROTOCOL instances + present in the system. + 2) No drivers were connected to ControllerHandle. + @retval EFI_SECURITY_VIOLATION + The user has no permission to start UEFI device drivers on the device path + associated with the ControllerHandle or specified by the RemainingDevicePath. + +**/ +EFI_STATUS +EFIAPI +UnitTestConnectController ( + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE *DriverImageHandle OPTIONAL, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, + IN BOOLEAN Recursive + ) +{ + return EFI_SUCCESS; // Return success for now +} + +/** + Disconnects a controller from a driver + + @param ControllerHandle ControllerHandle The handle of + the controller from which + driver(s) are to be + disconnected. + @param DriverImageHandle DriverImageHandle The driver to + disconnect from ControllerHandle. + @param ChildHandle ChildHandle The handle of the + child to destroy. + + @retval EFI_SUCCESS One or more drivers were + disconnected from the controller. + @retval EFI_SUCCESS On entry, no drivers are managing + ControllerHandle. + @retval EFI_SUCCESS DriverImageHandle is not NULL, + and on entry DriverImageHandle is + not managing ControllerHandle. + @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. + @retval EFI_INVALID_PARAMETER DriverImageHandle is not NULL, + and it is not a valid EFI_HANDLE. + @retval EFI_INVALID_PARAMETER ChildHandle is not NULL, and it + is not a valid EFI_HANDLE. + @retval EFI_OUT_OF_RESOURCES There are not enough resources + available to disconnect any + drivers from ControllerHandle. + @retval EFI_DEVICE_ERROR The controller could not be + disconnected because of a device + error. + +**/ +EFI_STATUS +EFIAPI +UnitTestDisconnectController ( + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE DriverImageHandle OPTIONAL, + IN EFI_HANDLE ChildHandle OPTIONAL + ) +{ + return EFI_SUCCESS; // Return success for now +} + +/** + Computes and returns a 32-bit CRC for a data buffer. + + @param[in] Data A pointer to the buffer on which the 32-bit CRC is to be computed. + @param[in] DataSize The number of bytes in the buffer Data. + @param[out] Crc32 The 32-bit CRC that was computed for the data buffer specified by Data + and DataSize. + + @retval EFI_SUCCESS The 32-bit CRC was computed for the data buffer and returned in + Crc32. + @retval EFI_INVALID_PARAMETER Data is NULL. + @retval EFI_INVALID_PARAMETER Crc32 is NULL. + @retval EFI_INVALID_PARAMETER DataSize is 0. + +**/ +EFI_STATUS +EFIAPI +UnitTestCalculateCrc32 ( + IN VOID *Data, + IN UINTN DataSize, + OUT UINT32 *Crc32 + ) +{ + if ((Data == NULL) || (Crc32 == NULL) || (DataSize == 0)) { + return EFI_INVALID_PARAMETER; + } + + *Crc32 = CalculateCrc32 (Data, DataSize); + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.c new file mode 100644 index 0000000000..437082d516 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.c @@ -0,0 +1,1650 @@ +/** @file + Implementation of protocol related services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLibProtocol.h" + +STATIC LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); +STATIC LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); +STATIC UINT64 gHandleDatabaseKey = 0; +STATIC UINTN mEfiLocateHandleRequest = 0; + +// +// Helper Functions +// + +/** + Check whether a handle is a valid EFI_HANDLE + + @param UserHandle The handle to check + + @retval EFI_INVALID_PARAMETER The handle is NULL or not a valid EFI_HANDLE. + @retval EFI_SUCCESS The handle is valid EFI_HANDLE. + +**/ +EFI_STATUS +UnitTestValidateHandle ( + IN EFI_HANDLE UserHandle + ) +{ + IHANDLE *Handle; + LIST_ENTRY *Link; + + if (UserHandle == NULL) { + return EFI_INVALID_PARAMETER; + } + + for (Link = gHandleList.BackLink; Link != &gHandleList; Link = Link->BackLink) { + Handle = CR (Link, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); + if (Handle == (IHANDLE *)UserHandle) { + return EFI_SUCCESS; + } + } + + return EFI_INVALID_PARAMETER; +} + +/** + Finds the protocol entry for the requested protocol. + + @param Protocol The ID of the protocol + @param Create Create a new entry if not found + + @return Protocol entry + +**/ +PROTOCOL_ENTRY * +UnitTestFindProtocolEntry ( + IN EFI_GUID *Protocol, + IN BOOLEAN Create + ) +{ + LIST_ENTRY *Link; + PROTOCOL_ENTRY *Item; + PROTOCOL_ENTRY *ProtEntry; + + // + // Search the database for the matching GUID + // + + ProtEntry = NULL; + for (Link = mProtocolDatabase.ForwardLink; + Link != &mProtocolDatabase; + Link = Link->ForwardLink) + { + Item = CR (Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); + if (CompareGuid (&Item->ProtocolID, Protocol)) { + // + // This is the protocol entry + // + + ProtEntry = Item; + break; + } + } + + // + // If the protocol entry was not found and Create is TRUE, then + // allocate a new entry + // + if ((ProtEntry == NULL) && Create) { + ProtEntry = AllocatePool (sizeof (PROTOCOL_ENTRY)); + + if (ProtEntry != NULL) { + // + // Initialize new protocol entry structure + // + ProtEntry->Signature = PROTOCOL_ENTRY_SIGNATURE; + CopyGuid ((VOID *)&ProtEntry->ProtocolID, Protocol); + InitializeListHead (&ProtEntry->Protocols); + InitializeListHead (&ProtEntry->Notify); + + // + // Add it to protocol database + // + InsertTailList (&mProtocolDatabase, &ProtEntry->AllEntries); + } + } + + return ProtEntry; +} + +/** + Finds the protocol instance for the requested handle and protocol. + Note: This function doesn't do parameters checking, it's caller's responsibility + to pass in valid parameters. + + @param Handle The handle to search the protocol on + @param Protocol GUID of the protocol + @param Interface The interface for the protocol being searched + + @return Protocol instance (NULL: Not found) + +**/ +PROTOCOL_INTERFACE * +UnitTestFindProtocolInterface ( + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface + ) +{ + PROTOCOL_INTERFACE *Prot; + PROTOCOL_ENTRY *ProtEntry; + LIST_ENTRY *Link; + + Prot = NULL; + + // + // Lookup the protocol entry for this protocol ID + // + + ProtEntry = UnitTestFindProtocolEntry (Protocol, FALSE); + if (ProtEntry != NULL) { + // + // Look at each protocol interface for any matches + // + for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { + // + // If this protocol interface matches, remove it + // + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + if ((Prot->Interface == Interface) && (Prot->Protocol == ProtEntry)) { + break; + } + + Prot = NULL; + } + } + + return Prot; +} + +/** + Signal event for every protocol in protocol entry. + + @param ProtEntry Protocol entry + +**/ +VOID +UnitTestNotifyProtocolEntry ( + IN PROTOCOL_ENTRY *ProtEntry + ) +{ + PROTOCOL_NOTIFY *ProtNotify; + LIST_ENTRY *Link; + + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + UnitTestSignalEvent (ProtNotify->Event); + } +} + +/** + Routine to get the next Handle, when you are searching for all handles. + + @param Position Information about which Handle to seach for. + @param Interface Return the interface structure for the matching + protocol. + + @return An pointer to IHANDLE if the next Position is not the end of the list. + Otherwise,NULL is returned. + +**/ +IHANDLE * +UnitTestGetNextLocateAllHandles ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface + ) +{ + IHANDLE *Handle; + + // + // Next handle + // + Position->Position = Position->Position->ForwardLink; + + // + // If not at the end of the list, get the handle + // + Handle = NULL; + *Interface = NULL; + if (Position->Position != &gHandleList) { + Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); + } + + return Handle; +} + +/** + Routine to get the next Handle, when you are searching for register protocol + notifies. + + @param Position Information about which Handle to seach for. + @param Interface Return the interface structure for the matching + protocol. + + @return An pointer to IHANDLE if the next Position is not the end of the list. + Otherwise,NULL is returned. + +**/ +IHANDLE * +UnitTestGetNextLocateByRegisterNotify ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface + ) +{ + IHANDLE *Handle; + PROTOCOL_NOTIFY *ProtNotify; + PROTOCOL_INTERFACE *Prot; + LIST_ENTRY *Link; + + Handle = NULL; + *Interface = NULL; + ProtNotify = Position->SearchKey; + + // + // If this is the first request, get the next handle + // + if (ProtNotify != NULL) { + ASSERT (ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); + Position->SearchKey = NULL; + + // + // If not at the end of the list, get the next handle + // + Link = ProtNotify->Position->ForwardLink; + if (Link != &ProtNotify->Protocol->Protocols) { + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; + *Interface = Prot->Interface; + } + } + + return Handle; +} + +/** + Routine to get the next Handle, when you are searching for a given protocol. + + @param Position Information about which Handle to seach for. + @param Interface Return the interface structure for the matching + protocol. + + @return An pointer to IHANDLE if the next Position is not the end of the list. + Otherwise,NULL is returned. + +**/ +IHANDLE * +UnitTestGetNextLocateByProtocol ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface + ) +{ + IHANDLE *Handle; + LIST_ENTRY *Link; + PROTOCOL_INTERFACE *Prot; + + Handle = NULL; + *Interface = NULL; + for ( ; ;) { + // + // Next entry + // + Link = Position->Position->ForwardLink; + Position->Position = Link; + + // + // If not at the end, return the handle + // + if (Link == &Position->ProtEntry->Protocols) { + Handle = NULL; + break; + } + + // + // Get the handle + // + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; + *Interface = Prot->Interface; + + // + // If this handle has not been returned this request, then + // return it now + // + if (Handle->LocateRequest != mEfiLocateHandleRequest) { + Handle->LocateRequest = mEfiLocateHandleRequest; + break; + } + } + + return Handle; +} + +/** + Attempts to disconnect all drivers that are using the protocol interface being queried. + If failed, reconnect all drivers disconnected. + Note: This function doesn't do parameters checking, it's caller's responsibility + to pass in valid parameters. + + @param UserHandle The handle on which the protocol is installed + @param Prot The protocol to disconnect drivers from + + @retval EFI_SUCCESS Drivers using the protocol interface are all + disconnected + @retval EFI_ACCESS_DENIED Failed to disconnect one or all of the drivers + +**/ +EFI_STATUS +UnitTestDisconnectControllersUsingProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN PROTOCOL_INTERFACE *Prot + ) +{ + EFI_STATUS Status; + BOOLEAN ItemFound; + LIST_ENTRY *Link; + OPEN_PROTOCOL_DATA *OpenData; + + Status = EFI_SUCCESS; + + // + // Attempt to disconnect all drivers from this protocol interface + // + do { + ItemFound = FALSE; + for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { + Status = UnitTestDisconnectController (UserHandle, OpenData->AgentHandle, NULL); + if (!EFI_ERROR (Status)) { + ItemFound = TRUE; + } + + break; + } + } + } while (ItemFound); + + if (!EFI_ERROR (Status)) { + // + // Attempt to remove BY_HANDLE_PROTOCOL and GET_PROTOCOL and TEST_PROTOCOL Open List items + // + for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList;) { + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + if ((OpenData->Attributes & + (EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL | EFI_OPEN_PROTOCOL_GET_PROTOCOL | EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) != 0) + { + Link = RemoveEntryList (&OpenData->Link); + Prot->OpenListCount--; + FreePool (OpenData); + } else { + Link = Link->ForwardLink; + } + } + } + + // + // If there are errors or still has open items in the list, then reconnect all the drivers and return an error + // + if (EFI_ERROR (Status) || (Prot->OpenListCount > 0)) { + UnitTestConnectController (UserHandle, NULL, NULL, TRUE); + Status = EFI_ACCESS_DENIED; + } + + return Status; +} + +/** + Removes Protocol from the protocol list (but not the handle list). + + @param Handle The handle to remove protocol on. + @param Protocol GUID of the protocol to be moved + @param Interface The interface of the protocol + + @return Protocol Entry + +**/ +PROTOCOL_INTERFACE * +UnitTestRemoveInterfaceFromProtocol ( + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface + ) +{ + PROTOCOL_INTERFACE *Prot; + PROTOCOL_NOTIFY *ProtNotify; + PROTOCOL_ENTRY *ProtEntry; + LIST_ENTRY *Link; + + Prot = UnitTestFindProtocolInterface (Handle, Protocol, Interface); + if (Prot != NULL) { + ProtEntry = Prot->Protocol; + + // + // If there's a protocol notify location pointing to this entry, back it up one + // + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + + if (ProtNotify->Position == &Prot->ByProtocol) { + ProtNotify->Position = Prot->ByProtocol.BackLink; + } + } + + // + // Remove the protocol interface entry + // + RemoveEntryList (&Prot->ByProtocol); + } + + return Prot; +} + +// +// Boot Services Function Implementation +// + +/** + Locate a certain GUID protocol interface in a Handle's protocols. + + @param UserHandle The handle to obtain the protocol interface on + @param Protocol The GUID of the protocol + + @return The requested protocol interface for the handle + +**/ +PROTOCOL_INTERFACE * +UnitTestGetProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol + ) +{ + EFI_STATUS Status; + PROTOCOL_ENTRY *ProtEntry; + PROTOCOL_INTERFACE *Prot; + IHANDLE *Handle; + LIST_ENTRY *Link; + + Status = UnitTestValidateHandle (UserHandle); + if (EFI_ERROR (Status)) { + return NULL; + } + + Handle = (IHANDLE *)UserHandle; + + // + // Look at each protocol interface for a match + // + for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + ProtEntry = Prot->Protocol; + if (CompareGuid (&ProtEntry->ProtocolID, Protocol)) { + return Prot; + } + } + + return NULL; +} + +/** + Installs a protocol interface into the boot services environment. + + @param UserHandle The handle to install the protocol handler on, + or NULL if a new handle is to be allocated + @param Protocol The protocol to add to the handle + @param InterfaceType Indicates whether Interface is supplied in + native form. + @param Interface The interface for the protocol being added + @param Notify indicates whether notify the notification list + for this protocol + + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate + @retval EFI_SUCCESS Protocol interface successfully installed + +**/ +EFI_STATUS +UnitTestInstallProtocolInterfaceNotify ( + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface, + IN BOOLEAN Notify + ) +{ + PROTOCOL_INTERFACE *Prot; + PROTOCOL_ENTRY *ProtEntry; + IHANDLE *Handle; + EFI_STATUS Status; + VOID *ExistingInterface; + + // + // returns EFI_INVALID_PARAMETER if InterfaceType is invalid. + // Also added check for invalid UserHandle and Protocol pointers. + // + if ((UserHandle == NULL) || (Protocol == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if (InterfaceType != EFI_NATIVE_INTERFACE) { + return EFI_INVALID_PARAMETER; + } + + // + // Print debug message + // + UT_LOG_INFO ("InstallProtocolInterface: %g %p\n", Protocol, Interface); + + Status = EFI_OUT_OF_RESOURCES; + Prot = NULL; + Handle = NULL; + + if (*UserHandle != NULL) { + Status = UnitTestHandleProtocol (*UserHandle, Protocol, (VOID **)&ExistingInterface); + if (!EFI_ERROR (Status)) { + return EFI_INVALID_PARAMETER; + } + } + + // + // Lookup the Protocol Entry for the requested protocol + // + ProtEntry = UnitTestFindProtocolEntry (Protocol, TRUE); + if (ProtEntry == NULL) { + goto Done; + } + + // + // Allocate a new protocol interface structure + // + Prot = AllocateZeroPool (sizeof (PROTOCOL_INTERFACE)); + if (Prot == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + // + // If caller didn't supply a handle, allocate a new one + // + Handle = (IHANDLE *)*UserHandle; + if (Handle == NULL) { + Handle = AllocateZeroPool (sizeof (IHANDLE)); + if (Handle == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + // + // Initialize new handler structure + // + Handle->Signature = EFI_HANDLE_SIGNATURE; + InitializeListHead (&Handle->Protocols); + + // + // Initialize the Key to show that the handle has been created/modified + // + gHandleDatabaseKey++; + Handle->Key = gHandleDatabaseKey; + + // + // Add this handle to the list global list of all handles + // in the system + // + InsertTailList (&gHandleList, &Handle->AllHandles); + } else { + Status = UnitTestValidateHandle (Handle); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); + goto Done; + } + } + + // + // Each interface that is added must be unique + // + ASSERT (UnitTestFindProtocolInterface (Handle, Protocol, Interface) == NULL); + + // + // Initialize the protocol interface structure + // + Prot->Signature = PROTOCOL_INTERFACE_SIGNATURE; + Prot->Handle = Handle; + Prot->Protocol = ProtEntry; + Prot->Interface = Interface; + + // + // Initialize OpenProtocol Data base + // + InitializeListHead (&Prot->OpenList); + Prot->OpenListCount = 0; + + // + // Add this protocol interface to the head of the supported + // protocol list for this handle + // + InsertHeadList (&Handle->Protocols, &Prot->Link); + + // + // Add this protocol interface to the tail of the + // protocol entry + // + InsertTailList (&ProtEntry->Protocols, &Prot->ByProtocol); + + // + // Notify the notification list for this protocol + // + if (Notify) { + UnitTestNotifyProtocolEntry (ProtEntry); + } + + Status = EFI_SUCCESS; + +Done: + if (!EFI_ERROR (Status)) { + // + // Return the new handle back to the caller + // + *UserHandle = Handle; + } else { + // + // There was an error, clean up + // + if (Prot != NULL) { + UnitTestFreePool (Prot); + } + + DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); + } + + return Status; +} + +/** + Wrapper function to UnitTestInstallProtocolInterfaceNotify. This is the public API which + Calls the private one which contains a BOOLEAN parameter for notifications + + @param UserHandle The handle to install the protocol handler on, + or NULL if a new handle is to be allocated + @param Protocol The protocol to add to the handle + @param InterfaceType Indicates whether Interface is supplied in + native form. + @param Interface The interface for the protocol being added + + @return Status code + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallProtocolInterface ( + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface + ) +{ + return UnitTestInstallProtocolInterfaceNotify ( + UserHandle, + Protocol, + InterfaceType, + Interface, + TRUE + ); +} + +/** + Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. + + @param UserHandle Handle on which the interface is to be + reinstalled + @param Protocol The numeric ID of the interface + @param OldInterface A pointer to the old interface + @param NewInterface A pointer to the new interface + + @retval EFI_SUCCESS The protocol interface was installed + @retval EFI_NOT_FOUND The OldInterface on the handle was not found + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value + +**/ +EFI_STATUS +EFIAPI +UnitTestReinstallProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *OldInterface, + IN VOID *NewInterface + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Uninstalls all instances of a protocol:interfacer from a handle. + If the last protocol interface is remove from the handle, the + handle is freed. + + @param UserHandle The handle to remove the protocol handler from + @param Protocol The protocol, of protocol:interface, to remove + @param Interface The interface, of protocol:interface, to remove + + @retval EFI_INVALID_PARAMETER Protocol is NULL. + @retval EFI_SUCCESS Protocol interface successfully uninstalled. + +**/ +EFI_STATUS +EFIAPI +UnitTestUninstallProtocolInterface ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *Interface + ) +{ + EFI_STATUS Status; + IHANDLE *Handle; + PROTOCOL_INTERFACE *Prot; + + // + // Check that Protocol is valid + // + if (Protocol == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Check that UserHandle is a valid handle + // + Status = UnitTestValidateHandle (UserHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + // + // Check that Protocol exists on UserHandle, and Interface matches the interface in the database + // + Prot = UnitTestFindProtocolInterface (UserHandle, Protocol, Interface); + if (Prot == NULL) { + Status = EFI_NOT_FOUND; + goto Done; + } + + // + // Attempt to disconnect all drivers that are using the protocol interface that is about to be removed + // + Status = UnitTestDisconnectControllersUsingProtocolInterface ( + UserHandle, + Prot + ); + if (EFI_ERROR (Status)) { + // + // One or more drivers refused to release, so return the error + // + goto Done; + } + + // + // Remove the protocol interface from the protocol + // + Status = EFI_NOT_FOUND; + Handle = (IHANDLE *)UserHandle; + Prot = UnitTestRemoveInterfaceFromProtocol (Handle, Protocol, Interface); + + if (Prot != NULL) { + // + // Update the Key to show that the handle has been created/modified + // + gHandleDatabaseKey++; + Handle->Key = gHandleDatabaseKey; + + // + // Remove the protocol interface from the handle + // + RemoveEntryList (&Prot->Link); + + // + // Free the memory + // + Prot->Signature = 0; + FreePool (Prot); + Status = EFI_SUCCESS; + } + + // + // If there are no more handlers for the handle, free the handle + // + if (IsListEmpty (&Handle->Protocols)) { + Handle->Signature = 0; + RemoveEntryList (&Handle->AllHandles); + FreePool (Handle); + } + +Done: + return Status; +} + +/** + Queries a handle to determine if it supports a specified protocol. + + @param UserHandle The handle being queried. + @param Protocol The published unique identifier of the protocol. + @param Interface Supplies the address where a pointer to the + corresponding Protocol Interface is returned. + + @return The requested protocol interface for the handle + +**/ +EFI_STATUS +EFIAPI +UnitTestHandleProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface + ) +{ + return UnitTestOpenProtocol ( + UserHandle, + Protocol, + Interface, + gImageHandle, + NULL, + EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL + ); +} + +/** + Add a new protocol notification record for the request protocol. + + @param Protocol The requested protocol to add the notify + registration + @param Event The event to signal + @param Registration Returns the registration record + + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_SUCCESS Successfully returned the registration record + that has been added + +**/ +EFI_STATUS +EFIAPI +UnitTestRegisterProtocolNotify ( + IN EFI_GUID *Protocol, + IN EFI_EVENT Event, + OUT VOID **Registration + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Locates the requested handle(s) and returns them in Buffer. + + @param SearchType The type of search to perform to locate the + handles + @param Protocol The protocol to search for + @param SearchKey Dependant on SearchType + @param BufferSize On input the size of Buffer. On output the + size of data returned. + @param Buffer The buffer to return the results in + + @retval EFI_BUFFER_TOO_SMALL Buffer too small, required buffer size is + returned in BufferSize. + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_SUCCESS Successfully found the requested handle(s) and + returns them in Buffer. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateHandle ( + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer + ) +{ + EFI_STATUS Status; + LOCATE_POSITION Position; + PROTOCOL_NOTIFY *ProtNotify; + UNIT_TEST_GET_NEXT GetNext; + UINTN ResultSize; + IHANDLE *Handle; + IHANDLE **ResultBuffer; + VOID *Interface; + + if (BufferSize == NULL) { + return EFI_INVALID_PARAMETER; + } + + if ((*BufferSize > 0) && (Buffer == NULL)) { + return EFI_INVALID_PARAMETER; + } + + GetNext = NULL; + + // + // Set initial position + // + Position.Protocol = Protocol; + Position.SearchKey = SearchKey; + Position.Position = &gHandleList; + + ResultSize = 0; + ResultBuffer = (IHANDLE **)Buffer; + Status = EFI_SUCCESS; + + // + // Get the search function based on type + // + switch (SearchType) { + case AllHandles: + GetNext = UnitTestGetNextLocateAllHandles; + break; + + case ByRegisterNotify: + // + // Must have SearchKey for locate ByRegisterNotify + // + if (SearchKey == NULL) { + Status = EFI_INVALID_PARAMETER; + break; + } + + GetNext = UnitTestGetNextLocateByRegisterNotify; + break; + + case ByProtocol: + GetNext = UnitTestGetNextLocateByProtocol; + if (Protocol == NULL) { + Status = EFI_INVALID_PARAMETER; + break; + } + + // + // Look up the protocol entry and set the head pointer + // + Position.ProtEntry = UnitTestFindProtocolEntry (Protocol, FALSE); + if (Position.ProtEntry == NULL) { + Status = EFI_NOT_FOUND; + break; + } + + Position.Position = &Position.ProtEntry->Protocols; + break; + + default: + Status = EFI_INVALID_PARAMETER; + break; + } + + if (EFI_ERROR (Status)) { + return Status; + } + + ASSERT (GetNext != NULL); + // + // Enumerate out the matching handles + // + mEfiLocateHandleRequest += 1; + for ( ; ;) { + // + // Get the next handle. If no more handles, stop + // + Handle = GetNext (&Position, &Interface); + if (NULL == Handle) { + break; + } + + // + // Increase the resulting buffer size, and if this handle + // fits return it + // + ResultSize += sizeof (Handle); + if (ResultSize <= *BufferSize) { + *ResultBuffer = Handle; + ResultBuffer += 1; + } + } + + // + // If the result is a zero length buffer, then there were no + // matching handles + // + if (ResultSize == 0) { + Status = EFI_NOT_FOUND; + } else { + // + // Return the resulting buffer size. If it's larger than what + // was passed, then set the error code + // + if (ResultSize > *BufferSize) { + Status = EFI_BUFFER_TOO_SMALL; + } + + *BufferSize = ResultSize; + + if ((SearchType == ByRegisterNotify) && !EFI_ERROR (Status)) { + // + // If this is a search by register notify and a handle was + // returned, update the register notification position + // + ASSERT (SearchKey != NULL); + ProtNotify = SearchKey; + ProtNotify->Position = ProtNotify->Position->ForwardLink; + } + } + + return Status; +} + +/** + Locates the handle to a device on the device path that best matches the specified protocol. + + @param Protocol The protocol to search for. + @param DevicePath On input, a pointer to a pointer to the device + path. On output, the device path pointer is + modified to point to the remaining part of the + devicepath. + @param Device A pointer to the returned device handle. + + @retval EFI_SUCCESS The resulting handle was returned. + @retval EFI_NOT_FOUND No handles matched the search. + @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateDevicePath ( + IN EFI_GUID *Protocol, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, + OUT EFI_HANDLE *Device + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Boot Service called to add, modify, or remove a system configuration table from + the EFI System Table. + + @param Guid Pointer to the GUID for the entry to add, update, or + remove + @param Table Pointer to the configuration table for the entry to add, + update, or remove, may be NULL. + + @return EFI_SUCCESS Guid, Table pair added, updated, or removed. + @return EFI_INVALID_PARAMETER Input GUID not valid. + @return EFI_NOT_FOUND Attempted to delete non-existant entry + @return EFI_OUT_OF_RESOURCES Not enough memory available + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallConfigurationTable ( + IN EFI_GUID *Guid, + IN VOID *Table + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Locates the installed protocol handler for the handle, and + invokes it to obtain the protocol interface. Usage information + is registered in the protocol data base. + + @param UserHandle The handle to obtain the protocol interface on + @param Protocol The ID of the protocol + @param Interface The location to return the protocol interface + @param ImageHandle The handle of the Image that is opening the + protocol interface specified by Protocol and + Interface. + @param ControllerHandle The controller handle that is requiring this + interface. + @param Attributes The open mode of the protocol interface + specified by Handle and Protocol. + + @retval EFI_INVALID_PARAMETER Protocol is NULL. + @retval EFI_SUCCESS Get the protocol interface. + +**/ +EFI_STATUS +EFIAPI +UnitTestOpenProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface OPTIONAL, + IN EFI_HANDLE ImageHandle, + IN EFI_HANDLE ControllerHandle, + IN UINT32 Attributes + ) +{ + EFI_STATUS Status; + PROTOCOL_INTERFACE *Prot; + LIST_ENTRY *Link; + OPEN_PROTOCOL_DATA *OpenData; + BOOLEAN ByDriver; + BOOLEAN Exclusive; + BOOLEAN Disconnect; + BOOLEAN ExactMatch; + + // + // Check for invalid Protocol + // + if (Protocol == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Check for invalid Interface + // + if ((Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) && (Interface == NULL)) { + return EFI_INVALID_PARAMETER; + } + + // + // Check for invalid UserHandle + // + Status = UnitTestValidateHandle (UserHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + // + // Check for invalid Attributes + // + switch (Attributes) { + case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: + Status = UnitTestValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + Status = UnitTestValidateHandle (ControllerHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + if (UserHandle == ControllerHandle) { + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_OPEN_PROTOCOL_BY_DRIVER: + case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: + Status = UnitTestValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + Status = UnitTestValidateHandle (ControllerHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + break; + case EFI_OPEN_PROTOCOL_EXCLUSIVE: + Status = UnitTestValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + break; + case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: + case EFI_OPEN_PROTOCOL_GET_PROTOCOL: + case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: + break; + default: + return EFI_INVALID_PARAMETER; + } + + // + // Look at each protocol interface for a match + // + Prot = UnitTestGetProtocolInterface (UserHandle, Protocol); + if (Prot == NULL) { + Status = EFI_UNSUPPORTED; + goto Done; + } + + Status = EFI_SUCCESS; + + ByDriver = FALSE; + Exclusive = FALSE; + for ( Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + ExactMatch = (BOOLEAN)((OpenData->AgentHandle == ImageHandle) && + (OpenData->Attributes == Attributes) && + (OpenData->ControllerHandle == ControllerHandle)); + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { + ByDriver = TRUE; + if (ExactMatch) { + Status = EFI_ALREADY_STARTED; + goto Done; + } + } + + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) != 0) { + Exclusive = TRUE; + } else if (ExactMatch) { + OpenData->OpenCount++; + Status = EFI_SUCCESS; + goto Done; + } + } + + // + // ByDriver TRUE -> A driver is managing (UserHandle, Protocol) + // ByDriver FALSE -> There are no drivers managing (UserHandle, Protocol) + // Exclusive TRUE -> Something has exclusive access to (UserHandle, Protocol) + // Exclusive FALSE -> Nothing has exclusive access to (UserHandle, Protocol) + // + + switch (Attributes) { + case EFI_OPEN_PROTOCOL_BY_DRIVER: + if (Exclusive || ByDriver) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + break; + case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: + case EFI_OPEN_PROTOCOL_EXCLUSIVE: + if (Exclusive) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + if (ByDriver) { + do { + Disconnect = FALSE; + for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { + Disconnect = TRUE; + Status = UnitTestDisconnectController (UserHandle, OpenData->AgentHandle, NULL); + if (EFI_ERROR (Status)) { + Status = EFI_ACCESS_DENIED; + goto Done; + } else { + break; + } + } + } + } while (Disconnect); + } + + break; + case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: + case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: + case EFI_OPEN_PROTOCOL_GET_PROTOCOL: + case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: + break; + } + + if (ImageHandle == NULL) { + Status = EFI_SUCCESS; + goto Done; + } + + // + // Create new entry + // + OpenData = AllocatePool (sizeof (OPEN_PROTOCOL_DATA)); + if (OpenData == NULL) { + Status = EFI_OUT_OF_RESOURCES; + } else { + OpenData->Signature = OPEN_PROTOCOL_DATA_SIGNATURE; + OpenData->AgentHandle = ImageHandle; + OpenData->ControllerHandle = ControllerHandle; + OpenData->Attributes = Attributes; + OpenData->OpenCount = 1; + InsertTailList (&Prot->OpenList, &OpenData->Link); + Prot->OpenListCount++; + Status = EFI_SUCCESS; + } + +Done: + + if (Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) { + // + // Keep Interface unmodified in case of any Error + // except EFI_ALREADY_STARTED and EFI_UNSUPPORTED. + // + if (!EFI_ERROR (Status) || (Status == EFI_ALREADY_STARTED)) { + // + // According to above logic, if 'Prot' is NULL, then the 'Status' must be + // EFI_UNSUPPORTED. Here the 'Status' is not EFI_UNSUPPORTED, so 'Prot' + // must be not NULL. + // + // The ASSERT here is for addressing a false positive NULL pointer + // dereference issue raised from static analysis. + // + ASSERT (Prot != NULL); + // + // EFI_ALREADY_STARTED is not an error for bus driver. + // Return the corresponding protocol interface. + // + *Interface = Prot->Interface; + } else if (Status == EFI_UNSUPPORTED) { + // + // Return NULL Interface if Unsupported Protocol. + // + *Interface = NULL; + } + } + + return Status; +} + +/** + Closes a protocol on a handle that was opened using OpenProtocol(). + + @param UserHandle The handle for the protocol interface that was + previously opened with OpenProtocol(), and is + now being closed. + @param Protocol The published unique identifier of the protocol. + It is the caller's responsibility to pass in a + valid GUID. + @param AgentHandle The handle of the agent that is closing the + protocol interface. + @param ControllerHandle If the agent that opened a protocol is a driver + that follows the EFI Driver Model, then this + parameter is the controller handle that required + the protocol interface. If the agent does not + follow the EFI Driver Model, then this parameter + is optional and may be NULL. + + @retval EFI_SUCCESS The protocol instance was closed. + @retval EFI_INVALID_PARAMETER Handle, AgentHandle or ControllerHandle is not a + valid EFI_HANDLE. + @retval EFI_NOT_FOUND Can not find the specified protocol or + AgentHandle. + +**/ +EFI_STATUS +EFIAPI +UnitTestCloseProtocol ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN EFI_HANDLE AgentHandle, + IN EFI_HANDLE ControllerHandle + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Return information about Opened protocols in the system + + @param UserHandle The handle to close the protocol interface on + @param Protocol The ID of the protocol + @param EntryBuffer A pointer to a buffer of open protocol + information in the form of + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures. + @param EntryCount Number of EntryBuffer entries + +**/ +EFI_STATUS +EFIAPI +UnitTestOpenProtocolInformation ( + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, + OUT UINTN *EntryCount + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated + from pool. + + @param UserHandle The handle from which to retrieve the list of + protocol interface GUIDs. + @param ProtocolBuffer A pointer to the list of protocol interface GUID + pointers that are installed on Handle. + @param ProtocolBufferCount A pointer to the number of GUID pointers present + in ProtocolBuffer. + + @retval EFI_SUCCESS The list of protocol interface GUIDs installed + on Handle was returned in ProtocolBuffer. The + number of protocol interface GUIDs was returned + in ProtocolBufferCount. + @retval EFI_INVALID_PARAMETER Handle is NULL. + @retval EFI_INVALID_PARAMETER Handle is not a valid EFI_HANDLE. + @retval EFI_INVALID_PARAMETER ProtocolBuffer is NULL. + @retval EFI_INVALID_PARAMETER ProtocolBufferCount is NULL. + @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the + results. + +**/ +EFI_STATUS +EFIAPI +UnitTestProtocolsPerHandle ( + IN EFI_HANDLE UserHandle, + OUT EFI_GUID ***ProtocolBuffer, + OUT UINTN *ProtocolBufferCount + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Function returns an array of handles that support the requested protocol + in a buffer allocated from pool. This is a version of UnitTestLocateHandle() + that allocates a buffer for the caller. + + @param SearchType Specifies which handle(s) are to be returned. + @param Protocol Provides the protocol to search by. This + parameter is only valid for SearchType + ByProtocol. + @param SearchKey Supplies the search key depending on the + SearchType. + @param NumberHandles The number of handles returned in Buffer. + @param Buffer A pointer to the buffer to return the requested + array of handles that support Protocol. + + @retval EFI_SUCCESS The result array of handles was returned. + @retval EFI_NOT_FOUND No handles match the search. + @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the + matching results. + @retval EFI_INVALID_PARAMETER One or more parameters are not valid. + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateHandleBuffer ( + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *NumberHandles, + OUT EFI_HANDLE **Buffer + ) +{ + EFI_STATUS Status; + UINTN BufferSize; + + if (NumberHandles == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (Buffer == NULL) { + return EFI_INVALID_PARAMETER; + } + + BufferSize = 0; + *NumberHandles = 0; + *Buffer = NULL; + Status = UnitTestLocateHandle ( + SearchType, + Protocol, + SearchKey, + &BufferSize, + *Buffer + ); + // + // LocateHandleBuffer() returns incorrect status code if SearchType is + // invalid. + // + // Add code to correctly handle expected errors from UnitTestLocateHandle(). + // + if (EFI_ERROR (Status) && (Status != EFI_BUFFER_TOO_SMALL)) { + if (Status != EFI_INVALID_PARAMETER) { + Status = EFI_NOT_FOUND; + } + + return Status; + } + + *Buffer = AllocatePool (BufferSize); + if (*Buffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + Status = UnitTestLocateHandle ( + SearchType, + Protocol, + SearchKey, + &BufferSize, + *Buffer + ); + + *NumberHandles = BufferSize / sizeof (EFI_HANDLE); + if (EFI_ERROR (Status)) { + *NumberHandles = 0; + } + + return Status; +} + +/** + Return the first Protocol Interface that matches the Protocol GUID. If + Registration is passed in, return a Protocol Instance that was just add + to the system. If Registration is NULL return the first Protocol Interface + you find. + + @param Protocol The protocol to search for + @param Registration Optional Registration Key returned from + RegisterProtocolNotify() + @param Interface Return the Protocol interface (instance). + + @retval EFI_SUCCESS If a valid Interface is returned + @retval EFI_INVALID_PARAMETER Invalid parameter + @retval EFI_NOT_FOUND Protocol interface not found + +**/ +EFI_STATUS +EFIAPI +UnitTestLocateProtocol ( + IN EFI_GUID *Protocol, + IN VOID *Registration OPTIONAL, + OUT VOID **Interface + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Installs a list of protocol interface into the boot services environment. + This function calls InstallProtocolInterface() in a loop. If any error + occurs all the protocols added by this function are removed. This is + basically a lib function to save space. + + @param Handle The handle to install the protocol handlers on, + or NULL if a new handle is to be allocated + @param ... EFI_GUID followed by protocol instance. A NULL + terminates the list. The pairs are the + arguments to InstallProtocolInterface(). All the + protocols are added to Handle. + + @retval EFI_SUCCESS All the protocol interface was installed. + @retval EFI_OUT_OF_RESOURCES There was not enough memory in pool to install all the protocols. + @retval EFI_ALREADY_STARTED A Device Path Protocol instance was passed in that is already present in + the handle database. + @retval EFI_INVALID_PARAMETER Handle is NULL. + @retval EFI_INVALID_PARAMETER Protocol is already installed on the handle specified by Handle. + +**/ +EFI_STATUS +EFIAPI +UnitTestInstallMultipleProtocolInterfaces ( + IN OUT EFI_HANDLE *Handle, + ... + ) +{ + return EFI_NOT_AVAILABLE_YET; +} + +/** + Uninstalls a list of protocol interface in the boot services environment. + This function calls UninstallProtocolInterface() in a loop. This is + basically a lib function to save space. + + @param Handle The handle to uninstall the protocol + @param ... EFI_GUID followed by protocol instance. A NULL + terminates the list. The pairs are the + arguments to UninstallProtocolInterface(). All + the protocols are added to Handle. + + @return Status code + +**/ +EFI_STATUS +EFIAPI +UnitTestUninstallMultipleProtocolInterfaces ( + IN EFI_HANDLE Handle, + ... + ) +{ + EFI_STATUS Status; + VA_LIST Args; + EFI_GUID *Protocol; + VOID *Interface; + UINTN Index; + + VA_START (Args, Handle); + for (Index = 0, Status = EFI_SUCCESS; !EFI_ERROR (Status); Index++) { + // + // If protocol is NULL, then it's the end of the list + // + Protocol = VA_ARG (Args, EFI_GUID *); + if (Protocol == NULL) { + break; + } + + Interface = VA_ARG (Args, VOID *); + + // + // Uninstall it + // + Status = UnitTestUninstallProtocolInterface (Handle, Protocol, Interface); + } + + VA_END (Args); + + // + // If there was an error, add all the interfaces that were + // uninstalled without any errors + // + if (EFI_ERROR (Status)) { + // + // Reset the va_arg back to the first argument. + // + VA_START (Args, Handle); + for ( ; Index > 1; Index--) { + Protocol = VA_ARG (Args, EFI_GUID *); + Interface = VA_ARG (Args, VOID *); + UnitTestInstallProtocolInterface (&Handle, Protocol, EFI_NATIVE_INTERFACE, Interface); + } + + VA_END (Args); + Status = EFI_INVALID_PARAMETER; + } + + return Status; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.h b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.h new file mode 100644 index 0000000000..fe91e0e396 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibProtocol.h @@ -0,0 +1,120 @@ +/** @file + An internal header file for the Unit Test instance of the UEFI Boot Services Table Library. + + This file includes common header files, defines internal structure and functions used by + the library implementation. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_PROTOCOL_H_ +#define UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_PROTOCOL_H_ + +#include "UnitTestUefiBootServicesTableLib.h" + +#define EFI_HANDLE_SIGNATURE SIGNATURE_32('h','n','d','l') + +/// +/// IHANDLE - contains a list of protocol handles +/// +typedef struct { + UINTN Signature; + /// All handles list of IHANDLE + LIST_ENTRY AllHandles; + /// List of PROTOCOL_INTERFACE's for this handle + LIST_ENTRY Protocols; + UINTN LocateRequest; + /// The Handle Database Key value when this handle was last created or modified + UINT64 Key; +} IHANDLE; + +#define ASSERT_IS_HANDLE(a) ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE) + +#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('p','r','t','e') + +/// +/// PROTOCOL_ENTRY - each different protocol has 1 entry in the protocol +/// database. Each handler that supports this protocol is listed, along +/// with a list of registered notifies. +/// +typedef struct { + UINTN Signature; + /// Link Entry inserted to mProtocolDatabase + LIST_ENTRY AllEntries; + /// ID of the protocol + EFI_GUID ProtocolID; + /// All protocol interfaces + LIST_ENTRY Protocols; + /// Registered notification handlers + LIST_ENTRY Notify; +} PROTOCOL_ENTRY; + +#define PROTOCOL_INTERFACE_SIGNATURE SIGNATURE_32('p','i','f','c') + +/// +/// PROTOCOL_INTERFACE - each protocol installed on a handle is tracked +/// with a protocol interface structure +/// +typedef struct { + UINTN Signature; + /// Link on IHANDLE.Protocols + LIST_ENTRY Link; + /// Back pointer + IHANDLE *Handle; + /// Link on PROTOCOL_ENTRY.Protocols + LIST_ENTRY ByProtocol; + /// The protocol ID + PROTOCOL_ENTRY *Protocol; + /// The interface value + VOID *Interface; + /// OPEN_PROTOCOL_DATA list + LIST_ENTRY OpenList; + UINTN OpenListCount; +} PROTOCOL_INTERFACE; + +#define OPEN_PROTOCOL_DATA_SIGNATURE SIGNATURE_32('p','o','d','l') + +typedef struct { + UINTN Signature; + /// Link on PROTOCOL_INTERFACE.OpenList + LIST_ENTRY Link; + + EFI_HANDLE AgentHandle; + EFI_HANDLE ControllerHandle; + UINT32 Attributes; + UINT32 OpenCount; +} OPEN_PROTOCOL_DATA; + +#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('p','r','t','n') + +/// +/// PROTOCOL_NOTIFY - used for each register notification for a protocol +/// +typedef struct { + UINTN Signature; + PROTOCOL_ENTRY *Protocol; + /// All notifications for this protocol + LIST_ENTRY Link; + /// Event to notify + EFI_EVENT Event; + /// Last position notified + LIST_ENTRY *Position; +} PROTOCOL_NOTIFY; + +typedef struct { + EFI_GUID *Protocol; + VOID *SearchKey; + LIST_ENTRY *Position; + PROTOCOL_ENTRY *ProtEntry; +} LOCATE_POSITION; + +typedef +IHANDLE * +(*UNIT_TEST_GET_NEXT) ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface + ); + +#endif diff --git a/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibTpl.c b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibTpl.c new file mode 100644 index 0000000000..2837a463aa --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLibTpl.c @@ -0,0 +1,43 @@ +/** @file + Implementation of Task Priority Level (TPL) related services in the UEFI Boot Services table for use in unit tests. + +Copyright (c) Microsoft Corporation +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "UnitTestUefiBootServicesTableLib.h" + +/** + Raise the task priority level to the new level. + High level is implemented by disabling processor interrupts. + + @param NewTpl New task priority level + + @return The previous task priority level + +**/ +EFI_TPL +EFIAPI +UnitTestRaiseTpl ( + IN EFI_TPL NewTpl + ) +{ + return TPL_APPLICATION; +} + +/** + Lowers the task priority to the previous value. If the new + priority unmasks events at a higher priority, they are dispatched. + + @param NewTpl New, lower, task priority + +**/ +VOID +EFIAPI +UnitTestRestoreTpl ( + IN EFI_TPL NewTpl + ) +{ + return; +} diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index e4f9fb6eb6..a76e31d97d 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -34,6 +34,7 @@ UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf UnitTestFrameworkPkg/Library/UnitTestDebugAssertLib/UnitTestDebugAssertLib.inf + UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index f249813713..9beeaef1ba 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -17,6 +17,7 @@ UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf + UefiBootServicesTableLib|UnitTestFrameworkPkg/Library/UnitTestUefiBootServicesTableLib/UnitTestUefiBootServicesTableLib.inf [BuildOptions] GCC:*_*_*_CC_FLAGS = -fno-pie From 351a67017793238ce4f11c0a82c3edf21cf19fb8 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 3 Nov 2022 20:11:39 -0400 Subject: [PATCH 0301/1529] PrmPkg: Use UnitTestFrameworkPkg UEFI BS library Updates PrmPkg to use UnitTestUefiBootServicesTableLib from UnitTestFrameworkPkg instead of UefiBootServicesTableLibUnitTest in PrmPkg. Cc: Michael D Kinney Cc: Sean Brogan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- PrmPkg/PrmPkg.dsc | 1 - PrmPkg/Test/PrmPkgHostTest.dsc | 6 - .../UefiBootServicesTableLibTest.uni | 12 - .../UefiBootServicesTableLibUnitTest.c | 119 -- .../UefiBootServicesTableLibUnitTest.h | 1042 ----------- .../UefiBootServicesTableLibUnitTest.inf | 46 - ...fiBootServicesTableLibUnitTestEventTimer.c | 180 -- .../UefiBootServicesTableLibUnitTestImage.c | 163 -- .../UefiBootServicesTableLibUnitTestMemory.c | 145 -- .../UefiBootServicesTableLibUnitTestMisc.c | 198 -- ...UefiBootServicesTableLibUnitTestProtocol.c | 1650 ----------------- ...UefiBootServicesTableLibUnitTestProtocol.h | 120 -- .../UefiBootServicesTableLibUnitTestTpl.c | 43 - 13 files changed, 3725 deletions(-) delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibTest.uni delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.h delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestEventTimer.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestImage.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMemory.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMisc.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.c delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.h delete mode 100644 PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestTpl.c diff --git a/PrmPkg/PrmPkg.dsc b/PrmPkg/PrmPkg.dsc index 3fb7490aca..6771005045 100644 --- a/PrmPkg/PrmPkg.dsc +++ b/PrmPkg/PrmPkg.dsc @@ -100,7 +100,6 @@ $(PLATFORM_PACKAGE)/Samples/PrmSampleAcpiParameterBufferModule/Library/DxeAcpiParameterBufferModuleConfigLib/DxeAcpiParameterBufferModuleConfigLib.inf $(PLATFORM_PACKAGE)/Samples/PrmSampleContextBufferModule/Library/DxeContextBufferModuleConfigLib/DxeContextBufferModuleConfigLib.inf $(PLATFORM_PACKAGE)/Samples/PrmSampleHardwareAccessModule/Library/DxeHardwareAccessModuleConfigLib/DxeHardwareAccessModuleConfigLib.inf - $(PLATFORM_PACKAGE)/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf # # PRM Module Discovery Library diff --git a/PrmPkg/Test/PrmPkgHostTest.dsc b/PrmPkg/Test/PrmPkgHostTest.dsc index 67fb4f5bd0..75d9046cc2 100644 --- a/PrmPkg/Test/PrmPkgHostTest.dsc +++ b/PrmPkg/Test/PrmPkgHostTest.dsc @@ -24,14 +24,8 @@ PrmContextBufferLib|PrmPkg/Library/DxePrmContextBufferLib/DxePrmContextBufferLib.inf PrmModuleDiscoveryLib|PrmPkg/Library/DxePrmModuleDiscoveryLib/DxePrmModuleDiscoveryLib.inf PrmPeCoffLib|PrmPkg/Library/DxePrmPeCoffLib/DxePrmPeCoffLib.inf - UefiBootServicesTableLib|PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf [Components] - # - # Unit test helper libraries - # - PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf - # # Unit test host applications # diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibTest.uni b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibTest.uni deleted file mode 100644 index 1f742bb6d8..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibTest.uni +++ /dev/null @@ -1,12 +0,0 @@ -// /** @file -// UEFI Boot Services Table Library for unit tests implementation. -// -// Copyright (c) Microsoft Corporation -// -// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - -#string STR_MODULE_ABSTRACT #language en-US "UEFI Boot Services Table Library for unit tests" - -#string STR_MODULE_DESCRIPTION #language en-US "UEFI Boot Services Table Library for unit tests." diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.c deleted file mode 100644 index ea3235e448..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.c +++ /dev/null @@ -1,119 +0,0 @@ -/** @file - This library supports a Boot Services table library implementation that allows code dependent - upon UefiBootServicesTableLib to operate in an isolated execution environment such as within - the context of a host-based unit test framework. - - The unit test should initialize the Boot Services database with any required elements - (e.g. protocols, events, handles, etc.) prior to the services being invoked by code under test. - - It is strongly recommended to clean any global databases (e.g. protocol, event, handles, etc.) after - every unit test so the tests execute in a predictable manner from a clean state. - - Copyright (c) Microsoft Corporation - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -EFI_HANDLE gImageHandle = NULL; -EFI_SYSTEM_TABLE *gST = NULL; - -STATIC EFI_BOOT_SERVICES mBootServices = { - { - EFI_BOOT_SERVICES_SIGNATURE, // Signature - EFI_BOOT_SERVICES_REVISION, // Revision - sizeof (EFI_BOOT_SERVICES), // HeaderSize - 0, // CRC32 - 0 // Reserved - }, - (EFI_RAISE_TPL)UnitTestRaiseTpl, // RaiseTPL - (EFI_RESTORE_TPL)UnitTestRestoreTpl, // RestoreTPL - (EFI_ALLOCATE_PAGES)UnitTestAllocatePages, // AllocatePages - (EFI_FREE_PAGES)UnitTestFreePages, // FreePages - (EFI_GET_MEMORY_MAP)UnitTestGetMemoryMap, // GetMemoryMap - (EFI_ALLOCATE_POOL)UnitTestAllocatePool, // AllocatePool - (EFI_FREE_POOL)UnitTestFreePool, // FreePool - (EFI_CREATE_EVENT)UnitTestCreateEvent, // CreateEvent - (EFI_SET_TIMER)UnitTestSetTimer, // SetTimer - (EFI_WAIT_FOR_EVENT)UnitTestWaitForEvent, // WaitForEvent - (EFI_SIGNAL_EVENT)UnitTestSignalEvent, // SignalEvent - (EFI_CLOSE_EVENT)UnitTestCloseEvent, // CloseEvent - (EFI_CHECK_EVENT)UnitTestCheckEvent, // CheckEvent - (EFI_INSTALL_PROTOCOL_INTERFACE)UnitTestInstallProtocolInterface, // InstallProtocolInterface - (EFI_REINSTALL_PROTOCOL_INTERFACE)UnitTestReinstallProtocolInterface, // ReinstallProtocolInterface - (EFI_UNINSTALL_PROTOCOL_INTERFACE)UnitTestUninstallProtocolInterface, // UninstallProtocolInterface - (EFI_HANDLE_PROTOCOL)UnitTestHandleProtocol, // HandleProtocol - (VOID *)NULL, // Reserved - (EFI_REGISTER_PROTOCOL_NOTIFY)UnitTestRegisterProtocolNotify, // RegisterProtocolNotify - (EFI_LOCATE_HANDLE)UnitTestLocateHandle, // LocateHandle - (EFI_LOCATE_DEVICE_PATH)UnitTestLocateDevicePath, // LocateDevicePath - (EFI_INSTALL_CONFIGURATION_TABLE)UnitTestInstallConfigurationTable, // InstallConfigurationTable - (EFI_IMAGE_LOAD)UnitTestLoadImage, // LoadImage - (EFI_IMAGE_START)UnitTestStartImage, // StartImage - (EFI_EXIT)UnitTestExit, // Exit - (EFI_IMAGE_UNLOAD)UnitTestUnloadImage, // UnloadImage - (EFI_EXIT_BOOT_SERVICES)UnitTestExitBootServices, // ExitBootServices - (EFI_GET_NEXT_MONOTONIC_COUNT)UnitTestGetNextMonotonicCount, // GetNextMonotonicCount - (EFI_STALL)UnitTestStall, // Stall - (EFI_SET_WATCHDOG_TIMER)UnitTestSetWatchdogTimer, // SetWatchdogTimer - (EFI_CONNECT_CONTROLLER)UnitTestConnectController, // ConnectController - (EFI_DISCONNECT_CONTROLLER)UnitTestDisconnectController, // DisconnectController - (EFI_OPEN_PROTOCOL)UnitTestOpenProtocol, // OpenProtocol - (EFI_CLOSE_PROTOCOL)UnitTestCloseProtocol, // CloseProtocol - (EFI_OPEN_PROTOCOL_INFORMATION)UnitTestOpenProtocolInformation, // OpenProtocolInformation - (EFI_PROTOCOLS_PER_HANDLE)UnitTestProtocolsPerHandle, // ProtocolsPerHandle - (EFI_LOCATE_HANDLE_BUFFER)UnitTestLocateHandleBuffer, // LocateHandleBuffer - (EFI_LOCATE_PROTOCOL)UnitTestLocateProtocol, // LocateProtocol - (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES)UnitTestInstallMultipleProtocolInterfaces, // InstallMultipleProtocolInterfaces - (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES)UnitTestUninstallMultipleProtocolInterfaces, // UninstallMultipleProtocolInterfaces - (EFI_CALCULATE_CRC32)UnitTestCalculateCrc32, // CalculateCrc32 - (EFI_COPY_MEM)CopyMem, // CopyMem - (EFI_SET_MEM)SetMem, // SetMem - (EFI_CREATE_EVENT_EX)UnitTestCreateEventEx // CreateEventEx -}; - -EFI_BOOT_SERVICES *gBS = &mBootServices; - -/** - The constructor function caches the pointer of Boot Services Table. - - The constructor function caches the pointer of Boot Services Table through System Table. - It will ASSERT() if the pointer of System Table is NULL. - It will ASSERT() if the pointer of Boot Services Table is NULL. - It will always return EFI_SUCCESS. - - @param ImageHandle The firmware allocated handle for the EFI image. - @param SystemTable A pointer to the EFI System Table. - - @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS. - -**/ -EFI_STATUS -EFIAPI -UefiBootServicesTableLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) -{ - // - // Cache the Image Handle - // - gImageHandle = ImageHandle; - ASSERT (gImageHandle != NULL); - - // - // Cache pointer to the EFI System Table - // - - // Note: The system table is not implemented - gST = NULL; - - // - // Cache pointer to the EFI Boot Services Table - // - gBS = SystemTable->BootServices; - ASSERT (gBS != NULL); - - return EFI_SUCCESS; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.h b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.h deleted file mode 100644 index 82853bb61a..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.h +++ /dev/null @@ -1,1042 +0,0 @@ -/** @file - An internal header file for the Unit Test instance of the UEFI Boot Services Table Library. - - This file includes common header files, defines internal structure and functions used by - the library implementation. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_H_ -#define UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include - -/** - Raise the task priority level to the new level. - High level is implemented by disabling processor interrupts. - - @param NewTpl New task priority level - - @return The previous task priority level - -**/ -EFI_TPL -EFIAPI -UnitTestRaiseTpl ( - IN EFI_TPL NewTpl - ); - -/** - Lowers the task priority to the previous value. If the new - priority unmasks events at a higher priority, they are dispatched. - - @param NewTpl New, lower, task priority - -**/ -VOID -EFIAPI -UnitTestRestoreTpl ( - IN EFI_TPL NewTpl - ); - -/** - Allocates pages from the memory map. - - @param Type The type of allocation to perform - @param MemoryType The type of memory to turn the allocated pages - into - @param NumberOfPages The number of pages to allocate - @param Memory A pointer to receive the base allocated memory - address - - @return Status. On success, Memory is filled in with the base address allocated - @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in - spec. - @retval EFI_NOT_FOUND Could not allocate pages match the requirement. - @retval EFI_OUT_OF_RESOURCES No enough pages to allocate. - @retval EFI_SUCCESS Pages successfully allocated. - -**/ -EFI_STATUS -EFIAPI -UnitTestAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, - IN OUT EFI_PHYSICAL_ADDRESS *Memory - ); - -/** - Frees previous allocated pages. - - @param Memory Base address of memory being freed - @param NumberOfPages The number of pages to free - - @retval EFI_NOT_FOUND Could not find the entry that covers the range - @retval EFI_INVALID_PARAMETER Address not aligned - @return EFI_SUCCESS -Pages successfully freed. - -**/ -EFI_STATUS -EFIAPI -UnitTestFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages - ); - -/** - This function returns a copy of the current memory map. The map is an array of - memory descriptors, each of which describes a contiguous block of memory. - - @param MemoryMapSize A pointer to the size, in bytes, of the - MemoryMap buffer. On input, this is the size of - the buffer allocated by the caller. On output, - it is the size of the buffer returned by the - firmware if the buffer was large enough, or the - size of the buffer needed to contain the map if - the buffer was too small. - @param MemoryMap A pointer to the buffer in which firmware places - the current memory map. - @param MapKey A pointer to the location in which firmware - returns the key for the current memory map. - @param DescriptorSize A pointer to the location in which firmware - returns the size, in bytes, of an individual - EFI_MEMORY_DESCRIPTOR. - @param DescriptorVersion A pointer to the location in which firmware - returns the version number associated with the - EFI_MEMORY_DESCRIPTOR. - - @retval EFI_SUCCESS The memory map was returned in the MemoryMap - buffer. - @retval EFI_BUFFER_TOO_SMALL The MemoryMap buffer was too small. The current - buffer size needed to hold the memory map is - returned in MemoryMapSize. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - -**/ -EFI_STATUS -EFIAPI -UnitTestGetMemoryMap ( - IN OUT UINTN *MemoryMapSize, - IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, - OUT UINTN *MapKey, - OUT UINTN *DescriptorSize, - OUT UINT32 *DescriptorVersion - ); - -/** - Allocate pool of a particular type. - - @param PoolType Type of pool to allocate - @param Size The amount of pool to allocate - @param Buffer The address to return a pointer to the allocated - pool - - @retval EFI_INVALID_PARAMETER PoolType not valid or Buffer is NULL - @retval EFI_OUT_OF_RESOURCES Size exceeds max pool size or allocation failed. - @retval EFI_SUCCESS Pool successfully allocated. - -**/ -EFI_STATUS -EFIAPI -UnitTestAllocatePool ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN Size, - OUT VOID **Buffer - ); - -/** - Frees pool. - - @param Buffer The allocated pool entry to free - - @retval EFI_INVALID_PARAMETER Buffer is not a valid value. - @retval EFI_SUCCESS Pool successfully freed. - -**/ -EFI_STATUS -EFIAPI -UnitTestFreePool ( - IN VOID *Buffer - ); - -/** - Frees pool. - - @param Buffer The allocated pool entry to free - @param PoolType Pointer to pool type - - @retval EFI_INVALID_PARAMETER Buffer is not a valid value. - @retval EFI_SUCCESS Pool successfully freed. - -**/ -EFI_STATUS -EFIAPI -UnitTestInternalFreePool ( - IN VOID *Buffer, - OUT EFI_MEMORY_TYPE *PoolType OPTIONAL - ); - -/** - Creates an event. - - @param Type The type of event to create and its mode and - attributes - @param NotifyTpl The task priority level of event notifications - @param NotifyFunction Pointer to the events notification function - @param NotifyContext Pointer to the notification functions context; - corresponds to parameter "Context" in the - notification function - @param Event Pointer to the newly created event if the call - succeeds; undefined otherwise - - @retval EFI_SUCCESS The event structure was created - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - @retval EFI_OUT_OF_RESOURCES The event could not be allocated - -**/ -EFI_STATUS -EFIAPI -UnitTestCreateEvent ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL - IN VOID *NotifyContext, OPTIONAL - OUT EFI_EVENT *Event - ); - -/** - Sets the type of timer and the trigger time for a timer event. - - @param UserEvent The timer event that is to be signaled at the - specified time - @param Type The type of time that is specified in - TriggerTime - @param TriggerTime The number of 100ns units until the timer - expires - - @retval EFI_SUCCESS The event has been set to be signaled at the - requested time - @retval EFI_INVALID_PARAMETER Event or Type is not valid - -**/ -EFI_STATUS -EFIAPI -UnitTestSetTimer ( - IN EFI_EVENT UserEvent, - IN EFI_TIMER_DELAY Type, - IN UINT64 TriggerTime - ); - -/** - Stops execution until an event is signaled. - - @param NumberOfEvents The number of events in the UserEvents array - @param UserEvents An array of EFI_EVENT - @param UserIndex Pointer to the index of the event which - satisfied the wait condition - - @retval EFI_SUCCESS The event indicated by Index was signaled. - @retval EFI_INVALID_PARAMETER The event indicated by Index has a notification - function or Event was not a valid type - @retval EFI_UNSUPPORTED The current TPL is not TPL_APPLICATION - -**/ -EFI_STATUS -EFIAPI -UnitTestWaitForEvent ( - IN UINTN NumberOfEvents, - IN EFI_EVENT *UserEvents, - OUT UINTN *UserIndex - ); - -/** - Signals the event. Queues the event to be notified if needed. - - @param UserEvent The event to signal . - - @retval EFI_INVALID_PARAMETER Parameters are not valid. - @retval EFI_SUCCESS The event was signaled. - -**/ -EFI_STATUS -EFIAPI -UnitTestSignalEvent ( - IN EFI_EVENT UserEvent - ); - -/** - Closes an event and frees the event structure. - - @param UserEvent Event to close - - @retval EFI_INVALID_PARAMETER Parameters are not valid. - @retval EFI_SUCCESS The event has been closed - -**/ -EFI_STATUS -EFIAPI -UnitTestCloseEvent ( - IN EFI_EVENT UserEvent - ); - -/** - Check the status of an event. - - @param UserEvent The event to check - - @retval EFI_SUCCESS The event is in the signaled state - @retval EFI_NOT_READY The event is not in the signaled state - @retval EFI_INVALID_PARAMETER Event is of type EVT_NOTIFY_SIGNAL - -**/ -EFI_STATUS -EFIAPI -UnitTestCheckEvent ( - IN EFI_EVENT UserEvent - ); - -/** - Wrapper function to UnitTestInstallProtocolInterfaceNotify. This is the public API which - Calls the private one which contains a BOOLEAN parameter for notifications - - @param UserHandle The handle to install the protocol handler on, - or NULL if a new handle is to be allocated - @param Protocol The protocol to add to the handle - @param InterfaceType Indicates whether Interface is supplied in - native form. - @param Interface The interface for the protocol being added - - @return Status code - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallProtocolInterface ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface - ); - -/** - Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. - - @param UserHandle Handle on which the interface is to be - reinstalled - @param Protocol The numeric ID of the interface - @param OldInterface A pointer to the old interface - @param NewInterface A pointer to the new interface - - @retval EFI_SUCCESS The protocol interface was installed - @retval EFI_NOT_FOUND The OldInterface on the handle was not found - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - -**/ -EFI_STATUS -EFIAPI -UnitTestReinstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *OldInterface, - IN VOID *NewInterface - ); - -/** - Uninstalls all instances of a protocol:interfacer from a handle. - If the last protocol interface is remove from the handle, the - handle is freed. - - @param UserHandle The handle to remove the protocol handler from - @param Protocol The protocol, of protocol:interface, to remove - @param Interface The interface, of protocol:interface, to remove - - @retval EFI_INVALID_PARAMETER Protocol is NULL. - @retval EFI_SUCCESS Protocol interface successfully uninstalled. - -**/ -EFI_STATUS -EFIAPI -UnitTestUninstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *Interface - ); - -/** - Queries a handle to determine if it supports a specified protocol. - - @param UserHandle The handle being queried. - @param Protocol The published unique identifier of the protocol. - @param Interface Supplies the address where a pointer to the - corresponding Protocol Interface is returned. - - @return The requested protocol interface for the handle - -**/ -EFI_STATUS -EFIAPI -UnitTestHandleProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface - ); - -/** - Add a new protocol notification record for the request protocol. - - @param Protocol The requested protocol to add the notify - registration - @param Event The event to signal - @param Registration Returns the registration record - - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_SUCCESS Successfully returned the registration record - that has been added - -**/ -EFI_STATUS -EFIAPI -UnitTestRegisterProtocolNotify ( - IN EFI_GUID *Protocol, - IN EFI_EVENT Event, - OUT VOID **Registration - ); - -/** - Locates the requested handle(s) and returns them in Buffer. - - @param SearchType The type of search to perform to locate the - handles - @param Protocol The protocol to search for - @param SearchKey Dependant on SearchType - @param BufferSize On input the size of Buffer. On output the - size of data returned. - @param Buffer The buffer to return the results in - - @retval EFI_BUFFER_TOO_SMALL Buffer too small, required buffer size is - returned in BufferSize. - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_SUCCESS Successfully found the requested handle(s) and - returns them in Buffer. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer - ); - -/** - Locates the handle to a device on the device path that best matches the specified protocol. - - @param Protocol The protocol to search for. - @param DevicePath On input, a pointer to a pointer to the device - path. On output, the device path pointer is - modified to point to the remaining part of the - devicepath. - @param Device A pointer to the returned device handle. - - @retval EFI_SUCCESS The resulting handle was returned. - @retval EFI_NOT_FOUND No handles matched the search. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateDevicePath ( - IN EFI_GUID *Protocol, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, - OUT EFI_HANDLE *Device - ); - -/** - Boot Service called to add, modify, or remove a system configuration table from - the EFI System Table. - - @param Guid Pointer to the GUID for the entry to add, update, or - remove - @param Table Pointer to the configuration table for the entry to add, - update, or remove, may be NULL. - - @return EFI_SUCCESS Guid, Table pair added, updated, or removed. - @return EFI_INVALID_PARAMETER Input GUID not valid. - @return EFI_NOT_FOUND Attempted to delete non-existant entry - @return EFI_OUT_OF_RESOURCES Not enough memory available - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallConfigurationTable ( - IN EFI_GUID *Guid, - IN VOID *Table - ); - -/** - Loads an EFI image into memory and returns a handle to the image. - - @param BootPolicy If TRUE, indicates that the request originates - from the boot manager, and that the boot - manager is attempting to load FilePath as a - boot selection. - @param ParentImageHandle The caller's image handle. - @param FilePath The specific file path from which the image is - loaded. - @param SourceBuffer If not NULL, a pointer to the memory location - containing a copy of the image to be loaded. - @param SourceSize The size in bytes of SourceBuffer. - @param ImageHandle Pointer to the returned image handle that is - created when the image is successfully loaded. - - @retval EFI_SUCCESS The image was loaded into memory. - @retval EFI_NOT_FOUND The FilePath was not found. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - @retval EFI_UNSUPPORTED The image type is not supported, or the device - path cannot be parsed to locate the proper - protocol for loading the file. - @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient - resources. - @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not - understood. - @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error. - @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the - image from being loaded. NULL is returned in *ImageHandle. - @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a - valid EFI_LOADED_IMAGE_PROTOCOL. However, the current - platform policy specifies that the image should not be started. - -**/ -EFI_STATUS -EFIAPI -UnitTestLoadImage ( - IN BOOLEAN BootPolicy, - IN EFI_HANDLE ParentImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN VOID *SourceBuffer OPTIONAL, - IN UINTN SourceSize, - OUT EFI_HANDLE *ImageHandle - ); - -/** - Transfer control to a loaded image's entry point. - - @param ImageHandle Handle of image to be started. - @param ExitDataSize Pointer of the size to ExitData - @param ExitData Pointer to a pointer to a data buffer that - includes a Null-terminated string, - optionally followed by additional binary data. - The string is a description that the caller may - use to further indicate the reason for the - image's exit. - - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate - @retval EFI_SECURITY_VIOLATION The current platform policy specifies that the image should not be started. - @retval EFI_SUCCESS Successfully transfer control to the image's - entry point. - -**/ -EFI_STATUS -EFIAPI -UnitTestStartImage ( - IN EFI_HANDLE ImageHandle, - OUT UINTN *ExitDataSize, - OUT CHAR16 **ExitData OPTIONAL - ); - -/** - Terminates the currently loaded EFI image and returns control to boot services. - - @param ImageHandle Handle that identifies the image. This - parameter is passed to the image on entry. - @param Status The image's exit code. - @param ExitDataSize The size, in bytes, of ExitData. Ignored if - ExitStatus is EFI_SUCCESS. - @param ExitData Pointer to a data buffer that includes a - Null-terminated Unicode string, optionally - followed by additional binary data. The string - is a description that the caller may use to - further indicate the reason for the image's - exit. - - @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current - image. - @retval EFI_SUCCESS Successfully terminates the currently loaded - EFI image. - @retval EFI_ACCESS_DENIED Should never reach there. - @retval EFI_OUT_OF_RESOURCES Could not allocate pool - -**/ -EFI_STATUS -EFIAPI -UnitTestExit ( - IN EFI_HANDLE ImageHandle, - IN EFI_STATUS Status, - IN UINTN ExitDataSize, - IN CHAR16 *ExitData OPTIONAL - ); - -/** - Unloads an image. - - @param ImageHandle Handle that identifies the image to be - unloaded. - - @retval EFI_SUCCESS The image has been unloaded. - @retval EFI_UNSUPPORTED The image has been started, and does not support - unload. - @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle. - -**/ -EFI_STATUS -EFIAPI -UnitTestUnloadImage ( - IN EFI_HANDLE ImageHandle - ); - -/** - Terminates all boot services. - - @param ImageHandle Handle that identifies the exiting image. - @param MapKey Key to the latest memory map. - - @retval EFI_SUCCESS Boot Services terminated - @retval EFI_INVALID_PARAMETER MapKey is incorrect. - -**/ -EFI_STATUS -EFIAPI -UnitTestExitBootServices ( - IN EFI_HANDLE ImageHandle, - IN UINTN MapKey - ); - -/** - Returns a monotonically increasing count for the platform. - - @param[out] Count The pointer to returned value. - - @retval EFI_SUCCESS The next monotonic count was returned. - @retval EFI_INVALID_PARAMETER Count is NULL. - @retval EFI_DEVICE_ERROR The device is not functioning properly. - -**/ -EFI_STATUS -EFIAPI -UnitTestGetNextMonotonicCount ( - OUT UINT64 *Count - ); - -/** - Introduces a fine-grained stall. - - @param Microseconds The number of microseconds to stall execution. - - @retval EFI_SUCCESS Execution was stalled for at least the requested - amount of microseconds. - @retval EFI_NOT_AVAILABLE_YET gMetronome is not available yet - -**/ -EFI_STATUS -EFIAPI -UnitTestStall ( - IN UINTN Microseconds - ); - -/** - Sets the system's watchdog timer. - - @param Timeout The number of seconds to set the watchdog timer to. - A value of zero disables the timer. - @param WatchdogCode The numeric code to log on a watchdog timer timeout - event. The firmware reserves codes 0x0000 to 0xFFFF. - Loaders and operating systems may use other timeout - codes. - @param DataSize The size, in bytes, of WatchdogData. - @param WatchdogData A data buffer that includes a Null-terminated Unicode - string, optionally followed by additional binary data. - The string is a description that the call may use to - further indicate the reason to be logged with a - watchdog event. - - @return EFI_SUCCESS Timeout has been set - @return EFI_NOT_AVAILABLE_YET WatchdogTimer is not available yet - @return EFI_UNSUPPORTED System does not have a timer (currently not used) - @return EFI_DEVICE_ERROR Could not complete due to hardware error - -**/ -EFI_STATUS -EFIAPI -UnitTestSetWatchdogTimer ( - IN UINTN Timeout, - IN UINT64 WatchdogCode, - IN UINTN DataSize, - IN CHAR16 *WatchdogData OPTIONAL - ); - -/** - Connects one or more drivers to a controller. - - @param ControllerHandle The handle of the controller to which driver(s) are to be connected. - @param DriverImageHandle A pointer to an ordered list handles that support the - EFI_DRIVER_BINDING_PROTOCOL. - @param RemainingDevicePath A pointer to the device path that specifies a child of the - controller specified by ControllerHandle. - @param Recursive If TRUE, then ConnectController() is called recursively - until the entire tree of controllers below the controller specified - by ControllerHandle have been created. If FALSE, then - the tree of controllers is only expanded one level. - - @retval EFI_SUCCESS 1) One or more drivers were connected to ControllerHandle. - 2) No drivers were connected to ControllerHandle, but - RemainingDevicePath is not NULL, and it is an End Device - Path Node. - @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. - @retval EFI_NOT_FOUND 1) There are no EFI_DRIVER_BINDING_PROTOCOL instances - present in the system. - 2) No drivers were connected to ControllerHandle. - @retval EFI_SECURITY_VIOLATION - The user has no permission to start UEFI device drivers on the device path - associated with the ControllerHandle or specified by the RemainingDevicePath. - -**/ -EFI_STATUS -EFIAPI -UnitTestConnectController ( - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE *DriverImageHandle OPTIONAL, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, - IN BOOLEAN Recursive - ); - -/** - Disconnects a controller from a driver - - @param ControllerHandle ControllerHandle The handle of - the controller from which - driver(s) are to be - disconnected. - @param DriverImageHandle DriverImageHandle The driver to - disconnect from ControllerHandle. - @param ChildHandle ChildHandle The handle of the - child to destroy. - - @retval EFI_SUCCESS One or more drivers were - disconnected from the controller. - @retval EFI_SUCCESS On entry, no drivers are managing - ControllerHandle. - @retval EFI_SUCCESS DriverImageHandle is not NULL, - and on entry DriverImageHandle is - not managing ControllerHandle. - @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. - @retval EFI_INVALID_PARAMETER DriverImageHandle is not NULL, - and it is not a valid EFI_HANDLE. - @retval EFI_INVALID_PARAMETER ChildHandle is not NULL, and it - is not a valid EFI_HANDLE. - @retval EFI_OUT_OF_RESOURCES There are not enough resources - available to disconnect any - drivers from ControllerHandle. - @retval EFI_DEVICE_ERROR The controller could not be - disconnected because of a device - error. - -**/ -EFI_STATUS -EFIAPI -UnitTestDisconnectController ( - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE DriverImageHandle OPTIONAL, - IN EFI_HANDLE ChildHandle OPTIONAL - ); - -/** - Locates the installed protocol handler for the handle, and - invokes it to obtain the protocol interface. Usage information - is registered in the protocol data base. - - @param UserHandle The handle to obtain the protocol interface on - @param Protocol The ID of the protocol - @param Interface The location to return the protocol interface - @param ImageHandle The handle of the Image that is opening the - protocol interface specified by Protocol and - Interface. - @param ControllerHandle The controller handle that is requiring this - interface. - @param Attributes The open mode of the protocol interface - specified by Handle and Protocol. - - @retval EFI_INVALID_PARAMETER Protocol is NULL. - @retval EFI_SUCCESS Get the protocol interface. - -**/ -EFI_STATUS -EFIAPI -UnitTestOpenProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface OPTIONAL, - IN EFI_HANDLE ImageHandle, - IN EFI_HANDLE ControllerHandle, - IN UINT32 Attributes - ); - -/** - Closes a protocol on a handle that was opened using OpenProtocol(). - - @param UserHandle The handle for the protocol interface that was - previously opened with OpenProtocol(), and is - now being closed. - @param Protocol The published unique identifier of the protocol. - It is the caller's responsibility to pass in a - valid GUID. - @param AgentHandle The handle of the agent that is closing the - protocol interface. - @param ControllerHandle If the agent that opened a protocol is a driver - that follows the EFI Driver Model, then this - parameter is the controller handle that required - the protocol interface. If the agent does not - follow the EFI Driver Model, then this parameter - is optional and may be NULL. - - @retval EFI_SUCCESS The protocol instance was closed. - @retval EFI_INVALID_PARAMETER Handle, AgentHandle or ControllerHandle is not a - valid EFI_HANDLE. - @retval EFI_NOT_FOUND Can not find the specified protocol or - AgentHandle. - -**/ -EFI_STATUS -EFIAPI -UnitTestCloseProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN EFI_HANDLE AgentHandle, - IN EFI_HANDLE ControllerHandle - ); - -/** - Return information about Opened protocols in the system - - @param UserHandle The handle to close the protocol interface on - @param Protocol The ID of the protocol - @param EntryBuffer A pointer to a buffer of open protocol - information in the form of - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures. - @param EntryCount Number of EntryBuffer entries - -**/ -EFI_STATUS -EFIAPI -UnitTestOpenProtocolInformation ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, - OUT UINTN *EntryCount - ); - -/** - Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated - from pool. - - @param UserHandle The handle from which to retrieve the list of - protocol interface GUIDs. - @param ProtocolBuffer A pointer to the list of protocol interface GUID - pointers that are installed on Handle. - @param ProtocolBufferCount A pointer to the number of GUID pointers present - in ProtocolBuffer. - - @retval EFI_SUCCESS The list of protocol interface GUIDs installed - on Handle was returned in ProtocolBuffer. The - number of protocol interface GUIDs was returned - in ProtocolBufferCount. - @retval EFI_INVALID_PARAMETER Handle is NULL. - @retval EFI_INVALID_PARAMETER Handle is not a valid EFI_HANDLE. - @retval EFI_INVALID_PARAMETER ProtocolBuffer is NULL. - @retval EFI_INVALID_PARAMETER ProtocolBufferCount is NULL. - @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the - results. - -**/ -EFI_STATUS -EFIAPI -UnitTestProtocolsPerHandle ( - IN EFI_HANDLE UserHandle, - OUT EFI_GUID ***ProtocolBuffer, - OUT UINTN *ProtocolBufferCount - ); - -/** - Function returns an array of handles that support the requested protocol - in a buffer allocated from pool. This is a version of UnitTestLocateHandle() - that allocates a buffer for the caller. - - @param SearchType Specifies which handle(s) are to be returned. - @param Protocol Provides the protocol to search by. This - parameter is only valid for SearchType - ByProtocol. - @param SearchKey Supplies the search key depending on the - SearchType. - @param NumberHandles The number of handles returned in Buffer. - @param Buffer A pointer to the buffer to return the requested - array of handles that support Protocol. - - @retval EFI_SUCCESS The result array of handles was returned. - @retval EFI_NOT_FOUND No handles match the search. - @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the - matching results. - @retval EFI_INVALID_PARAMETER One or more parameters are not valid. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateHandleBuffer ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *NumberHandles, - OUT EFI_HANDLE **Buffer - ); - -/** - Return the first Protocol Interface that matches the Protocol GUID. If - Registration is passed in, return a Protocol Instance that was just add - to the system. If Registration is NULL return the first Protocol Interface - you find. - - @param Protocol The protocol to search for - @param Registration Optional Registration Key returned from - RegisterProtocolNotify() - @param Interface Return the Protocol interface (instance). - - @retval EFI_SUCCESS If a valid Interface is returned - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_NOT_FOUND Protocol interface not found - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateProtocol ( - IN EFI_GUID *Protocol, - IN VOID *Registration OPTIONAL, - OUT VOID **Interface - ); - -/** - Installs a list of protocol interface into the boot services environment. - This function calls InstallProtocolInterface() in a loop. If any error - occurs all the protocols added by this function are removed. This is - basically a lib function to save space. - - @param Handle The handle to install the protocol handlers on, - or NULL if a new handle is to be allocated - @param ... EFI_GUID followed by protocol instance. A NULL - terminates the list. The pairs are the - arguments to InstallProtocolInterface(). All the - protocols are added to Handle. - - @retval EFI_SUCCESS All the protocol interface was installed. - @retval EFI_OUT_OF_RESOURCES There was not enough memory in pool to install all the protocols. - @retval EFI_ALREADY_STARTED A Device Path Protocol instance was passed in that is already present in - the handle database. - @retval EFI_INVALID_PARAMETER Handle is NULL. - @retval EFI_INVALID_PARAMETER Protocol is already installed on the handle specified by Handle. - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallMultipleProtocolInterfaces ( - IN OUT EFI_HANDLE *Handle, - ... - ); - -/** - Uninstalls a list of protocol interface in the boot services environment. - This function calls UninstallProtocolInterface() in a loop. This is - basically a lib function to save space. - - @param Handle The handle to uninstall the protocol - @param ... EFI_GUID followed by protocol instance. A NULL - terminates the list. The pairs are the - arguments to UninstallProtocolInterface(). All - the protocols are added to Handle. - - @return Status code - -**/ -EFI_STATUS -EFIAPI -UnitTestUninstallMultipleProtocolInterfaces ( - IN EFI_HANDLE Handle, - ... - ); - -/** - Computes and returns a 32-bit CRC for a data buffer. - - @param[in] Data A pointer to the buffer on which the 32-bit CRC is to be computed. - @param[in] DataSize The number of bytes in the buffer Data. - @param[out] Crc32 The 32-bit CRC that was computed for the data buffer specified by Data - and DataSize. - - @retval EFI_SUCCESS The 32-bit CRC was computed for the data buffer and returned in - Crc32. - @retval EFI_INVALID_PARAMETER Data is NULL. - @retval EFI_INVALID_PARAMETER Crc32 is NULL. - @retval EFI_INVALID_PARAMETER DataSize is 0. - -**/ -EFI_STATUS -EFIAPI -UnitTestCalculateCrc32 ( - IN VOID *Data, - IN UINTN DataSize, - OUT UINT32 *Crc32 - ); - -/** - Creates an event in a group. - - @param Type The type of event to create and its mode and - attributes - @param NotifyTpl The task priority level of event notifications - @param NotifyFunction Pointer to the events notification function - @param NotifyContext Pointer to the notification functions context; - corresponds to parameter "Context" in the - notification function - @param EventGroup GUID for EventGroup if NULL act the same as - gBS->CreateEvent(). - @param Event Pointer to the newly created event if the call - succeeds; undefined otherwise - - @retval EFI_SUCCESS The event structure was created - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - @retval EFI_OUT_OF_RESOURCES The event could not be allocated - -**/ -EFI_STATUS -EFIAPI -UnitTestCreateEventEx ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL - IN CONST VOID *NotifyContext, OPTIONAL - IN CONST EFI_GUID *EventGroup, OPTIONAL - OUT EFI_EVENT *Event - ); - -#endif diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf deleted file mode 100644 index 3b85dbb1b7..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTest.inf +++ /dev/null @@ -1,46 +0,0 @@ -## @file -# UEFI Boot Services Table Library for unit tests implementation. -# -# Copyright (c) Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = UefiBootServicesTableLibUnitTest - MODULE_UNI_FILE = UefiBootServicesTableLibTest.uni - FILE_GUID = 725E1CCD-07F1-4964-9A3E-9AA6DCC51DE6 - MODULE_TYPE = UEFI_DRIVER - VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiBootServicesTableLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_APPLICATION UEFI_DRIVER SMM_CORE - - CONSTRUCTOR = UefiBootServicesTableLibUnitTestConstructor - -# -# VALID_ARCHITECTURES = IA32 X64 EBC -# - -[Sources] - UefiBootServicesTableLibUnitTest.h - UefiBootServicesTableLibUnitTest.c - UefiBootServicesTableLibUnitTestEventTimer.c - UefiBootServicesTableLibUnitTestImage.c - UefiBootServicesTableLibUnitTestMemory.c - UefiBootServicesTableLibUnitTestProtocol.h - UefiBootServicesTableLibUnitTestProtocol.c - UefiBootServicesTableLibUnitTestMisc.c - UefiBootServicesTableLibUnitTestTpl.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - MemoryAllocationLib - UnitTestLib - -[UserExtensions.TianoCore."ExtraFiles"] - TimerExtra.uni diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestEventTimer.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestEventTimer.c deleted file mode 100644 index c1ec801bca..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestEventTimer.c +++ /dev/null @@ -1,180 +0,0 @@ -/** @file - Implementation of event and timer related services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -/** - Creates an event. - - @param Type The type of event to create and its mode and - attributes - @param NotifyTpl The task priority level of event notifications - @param NotifyFunction Pointer to the events notification function - @param NotifyContext Pointer to the notification functions context - corresponds to parameter "Context" in the - notification function - @param Event Pointer to the newly created event if the call - succeeds undefined otherwise - - @retval EFI_SUCCESS The event structure was created - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - @retval EFI_OUT_OF_RESOURCES The event could not be allocated - -**/ -EFI_STATUS -EFIAPI -UnitTestCreateEvent ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL - IN VOID *NotifyContext, OPTIONAL - OUT EFI_EVENT *Event - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Sets the type of timer and the trigger time for a timer event. - - @param UserEvent The timer event that is to be signaled at the - specified time - @param Type The type of time that is specified in - TriggerTime - @param TriggerTime The number of 100ns units until the timer - expires - - @retval EFI_SUCCESS The event has been set to be signaled at the - requested time - @retval EFI_INVALID_PARAMETER Event or Type is not valid - -**/ -EFI_STATUS -EFIAPI -UnitTestSetTimer ( - IN EFI_EVENT UserEvent, - IN EFI_TIMER_DELAY Type, - IN UINT64 TriggerTime - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Stops execution until an event is signaled. - - @param NumberOfEvents The number of events in the UserEvents array - @param UserEvents An array of EFI_EVENT - @param UserIndex Pointer to the index of the event which - satisfied the wait condition - - @retval EFI_SUCCESS The event indicated by Index was signaled. - @retval EFI_INVALID_PARAMETER The event indicated by Index has a notification - function or Event was not a valid type - @retval EFI_UNSUPPORTED The current TPL is not TPL_APPLICATION - -**/ -EFI_STATUS -EFIAPI -UnitTestWaitForEvent ( - IN UINTN NumberOfEvents, - IN EFI_EVENT *UserEvents, - OUT UINTN *UserIndex - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Signals the event. Queues the event to be notified if needed. - - @param UserEvent The event to signal . - - @retval EFI_INVALID_PARAMETER Parameters are not valid. - @retval EFI_SUCCESS The event was signaled. - -**/ -EFI_STATUS -EFIAPI -UnitTestSignalEvent ( - IN EFI_EVENT UserEvent - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Closes an event and frees the event structure. - - @param UserEvent Event to close - - @retval EFI_INVALID_PARAMETER Parameters are not valid. - @retval EFI_SUCCESS The event has been closed - -**/ -EFI_STATUS -EFIAPI -UnitTestCloseEvent ( - IN EFI_EVENT UserEvent - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Check the status of an event. - - @param UserEvent The event to check - - @retval EFI_SUCCESS The event is in the signaled state - @retval EFI_NOT_READY The event is not in the signaled state - @retval EFI_INVALID_PARAMETER Event is of type EVT_NOTIFY_SIGNAL - -**/ -EFI_STATUS -EFIAPI -UnitTestCheckEvent ( - IN EFI_EVENT UserEvent - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Creates an event in a group. - - @param Type The type of event to create and its mode and - attributes - @param NotifyTpl The task priority level of event notifications - @param NotifyFunction Pointer to the events notification function - @param NotifyContext Pointer to the notification functions context - corresponds to parameter "Context" in the - notification function - @param EventGroup GUID for EventGroup if NULL act the same as - gBS->CreateEvent(). - @param Event Pointer to the newly created event if the call - succeeds undefined otherwise - - @retval EFI_SUCCESS The event structure was created - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - @retval EFI_OUT_OF_RESOURCES The event could not be allocated - -**/ -EFI_STATUS -EFIAPI -UnitTestCreateEventEx ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL - IN CONST VOID *NotifyContext, OPTIONAL - IN CONST EFI_GUID *EventGroup, OPTIONAL - OUT EFI_EVENT *Event - ) -{ - return EFI_NOT_AVAILABLE_YET; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestImage.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestImage.c deleted file mode 100644 index a5799ff92d..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestImage.c +++ /dev/null @@ -1,163 +0,0 @@ -/** @file - Implementation of image related services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -/** - Loads an EFI image into memory and returns a handle to the image. - - @param BootPolicy If TRUE, indicates that the request originates - from the boot manager, and that the boot - manager is attempting to load FilePath as a - boot selection. - @param ParentImageHandle The caller's image handle. - @param FilePath The specific file path from which the image is - loaded. - @param SourceBuffer If not NULL, a pointer to the memory location - containing a copy of the image to be loaded. - @param SourceSize The size in bytes of SourceBuffer. - @param ImageHandle Pointer to the returned image handle that is - created when the image is successfully loaded. - - @retval EFI_SUCCESS The image was loaded into memory. - @retval EFI_NOT_FOUND The FilePath was not found. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - @retval EFI_UNSUPPORTED The image type is not supported, or the device - path cannot be parsed to locate the proper - protocol for loading the file. - @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient - resources. - @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not - understood. - @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error. - @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the - image from being loaded. NULL is returned in *ImageHandle. - @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a - valid EFI_LOADED_IMAGE_PROTOCOL. However, the current - platform policy specifies that the image should not be started. - -**/ -EFI_STATUS -EFIAPI -UnitTestLoadImage ( - IN BOOLEAN BootPolicy, - IN EFI_HANDLE ParentImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN VOID *SourceBuffer OPTIONAL, - IN UINTN SourceSize, - OUT EFI_HANDLE *ImageHandle - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Transfer control to a loaded image's entry point. - - @param ImageHandle Handle of image to be started. - @param ExitDataSize Pointer of the size to ExitData - @param ExitData Pointer to a pointer to a data buffer that - includes a Null-terminated string, - optionally followed by additional binary data. - The string is a description that the caller may - use to further indicate the reason for the - image's exit. - - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate - @retval EFI_SECURITY_VIOLATION The current platform policy specifies that the image should not be started. - @retval EFI_SUCCESS Successfully transfer control to the image's - entry point. - -**/ -EFI_STATUS -EFIAPI -UnitTestStartImage ( - IN EFI_HANDLE ImageHandle, - OUT UINTN *ExitDataSize, - OUT CHAR16 **ExitData OPTIONAL - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Terminates the currently loaded EFI image and returns control to boot services. - - @param ImageHandle Handle that identifies the image. This - parameter is passed to the image on entry. - @param Status The image's exit code. - @param ExitDataSize The size, in bytes, of ExitData. Ignored if - ExitStatus is EFI_SUCCESS. - @param ExitData Pointer to a data buffer that includes a - Null-terminated Unicode string, optionally - followed by additional binary data. The string - is a description that the caller may use to - further indicate the reason for the image's - exit. - - @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current - image. - @retval EFI_SUCCESS Successfully terminates the currently loaded - EFI image. - @retval EFI_ACCESS_DENIED Should never reach there. - @retval EFI_OUT_OF_RESOURCES Could not allocate pool - -**/ -EFI_STATUS -EFIAPI -UnitTestExit ( - IN EFI_HANDLE ImageHandle, - IN EFI_STATUS Status, - IN UINTN ExitDataSize, - IN CHAR16 *ExitData OPTIONAL - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Unloads an image. - - @param ImageHandle Handle that identifies the image to be - unloaded. - - @retval EFI_SUCCESS The image has been unloaded. - @retval EFI_UNSUPPORTED The image has been started, and does not support - unload. - @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle. - -**/ -EFI_STATUS -EFIAPI -UnitTestUnloadImage ( - IN EFI_HANDLE ImageHandle - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Terminates all boot services. - - @param ImageHandle Handle that identifies the exiting image. - @param MapKey Key to the latest memory map. - - @retval EFI_SUCCESS Boot Services terminated - @retval EFI_INVALID_PARAMETER MapKey is incorrect. - -**/ -EFI_STATUS -EFIAPI -UnitTestExitBootServices ( - IN EFI_HANDLE ImageHandle, - IN UINTN MapKey - ) -{ - return EFI_NOT_AVAILABLE_YET; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMemory.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMemory.c deleted file mode 100644 index 2c9a1989f2..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMemory.c +++ /dev/null @@ -1,145 +0,0 @@ -/** @file - Implementation of memory related services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -/** - Allocates pages from the memory map. - - @param Type The type of allocation to perform - @param MemoryType The type of memory to turn the allocated pages - into - @param NumberOfPages The number of pages to allocate - @param Memory A pointer to receive the base allocated memory - address - - @return Status. On success, Memory is filled in with the base address allocated - @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in - spec. - @retval EFI_NOT_FOUND Could not allocate pages match the requirement. - @retval EFI_OUT_OF_RESOURCES No enough pages to allocate. - @retval EFI_SUCCESS Pages successfully allocated. - -**/ -EFI_STATUS -EFIAPI -UnitTestAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, - IN OUT EFI_PHYSICAL_ADDRESS *Memory - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Frees previous allocated pages. - - @param Memory Base address of memory being freed - @param NumberOfPages The number of pages to free - - @retval EFI_NOT_FOUND Could not find the entry that covers the range - @retval EFI_INVALID_PARAMETER Address not aligned - @return EFI_SUCCESS -Pages successfully freed. - -**/ -EFI_STATUS -EFIAPI -UnitTestFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - This function returns a copy of the current memory map. The map is an array of - memory descriptors, each of which describes a contiguous block of memory. - - @param MemoryMapSize A pointer to the size, in bytes, of the - MemoryMap buffer. On input, this is the size of - the buffer allocated by the caller. On output, - it is the size of the buffer returned by the - firmware if the buffer was large enough, or the - size of the buffer needed to contain the map if - the buffer was too small. - @param MemoryMap A pointer to the buffer in which firmware places - the current memory map. - @param MapKey A pointer to the location in which firmware - returns the key for the current memory map. - @param DescriptorSize A pointer to the location in which firmware - returns the size, in bytes, of an individual - EFI_MEMORY_DESCRIPTOR. - @param DescriptorVersion A pointer to the location in which firmware - returns the version number associated with the - EFI_MEMORY_DESCRIPTOR. - - @retval EFI_SUCCESS The memory map was returned in the MemoryMap - buffer. - @retval EFI_BUFFER_TOO_SMALL The MemoryMap buffer was too small. The current - buffer size needed to hold the memory map is - returned in MemoryMapSize. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - -**/ -EFI_STATUS -EFIAPI -UnitTestGetMemoryMap ( - IN OUT UINTN *MemoryMapSize, - IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, - OUT UINTN *MapKey, - OUT UINTN *DescriptorSize, - OUT UINT32 *DescriptorVersion - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Allocate pool of a particular type. - - @param PoolType Type of pool to allocate - @param Size The amount of pool to allocate - @param Buffer The address to return a pointer to the allocated - pool - - @retval EFI_INVALID_PARAMETER PoolType not valid or Buffer is NULL - @retval EFI_OUT_OF_RESOURCES Size exceeds max pool size or allocation failed. - @retval EFI_SUCCESS Pool successfully allocated. - -**/ -EFI_STATUS -EFIAPI -UnitTestAllocatePool ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN Size, - OUT VOID **Buffer - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Frees pool. - - @param Buffer The allocated pool entry to free - - @retval EFI_INVALID_PARAMETER Buffer is not a valid value. - @retval EFI_SUCCESS Pool successfully freed. - -**/ -EFI_STATUS -EFIAPI -UnitTestFreePool ( - IN VOID *Buffer - ) -{ - return EFI_NOT_AVAILABLE_YET; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMisc.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMisc.c deleted file mode 100644 index ab79365448..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestMisc.c +++ /dev/null @@ -1,198 +0,0 @@ -/** @file - Implementation of miscellaneous services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -/** - Returns a monotonically increasing count for the platform. - - @param[out] Count The pointer to returned value. - - @retval EFI_SUCCESS The next monotonic count was returned. - @retval EFI_INVALID_PARAMETER Count is NULL. - @retval EFI_DEVICE_ERROR The device is not functioning properly. - -**/ -EFI_STATUS -EFIAPI -UnitTestGetNextMonotonicCount ( - OUT UINT64 *Count - ) -{ - STATIC UINT64 StaticCount = 0; - - *Count = StaticCount++; - - return EFI_SUCCESS; -} - -/** - Introduces a fine-grained stall. - - @param Microseconds The number of microseconds to stall execution. - - @retval EFI_SUCCESS Execution was stalled for at least the requested - amount of microseconds. - @retval EFI_NOT_AVAILABLE_YET gMetronome is not available yet - -**/ -EFI_STATUS -EFIAPI -UnitTestStall ( - IN UINTN Microseconds - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Sets the system's watchdog timer. - - @param Timeout The number of seconds to set the watchdog timer to. - A value of zero disables the timer. - @param WatchdogCode The numeric code to log on a watchdog timer timeout - event. The firmware reserves codes 0x0000 to 0xFFFF. - Loaders and operating systems may use other timeout - codes. - @param DataSize The size, in bytes, of WatchdogData. - @param WatchdogData A data buffer that includes a Null-terminated Unicode - string, optionally followed by additional binary data. - The string is a description that the call may use to - further indicate the reason to be logged with a - watchdog event. - - @return EFI_SUCCESS Timeout has been set - @return EFI_NOT_AVAILABLE_YET WatchdogTimer is not available yet - @return EFI_UNSUPPORTED System does not have a timer (currently not used) - @return EFI_DEVICE_ERROR Could not complete due to hardware error - -**/ -EFI_STATUS -EFIAPI -UnitTestSetWatchdogTimer ( - IN UINTN Timeout, - IN UINT64 WatchdogCode, - IN UINTN DataSize, - IN CHAR16 *WatchdogData OPTIONAL - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Connects one or more drivers to a controller. - - @param ControllerHandle The handle of the controller to which driver(s) are to be connected. - @param DriverImageHandle A pointer to an ordered list handles that support the - EFI_DRIVER_BINDING_PROTOCOL. - @param RemainingDevicePath A pointer to the device path that specifies a child of the - controller specified by ControllerHandle. - @param Recursive If TRUE, then ConnectController() is called recursively - until the entire tree of controllers below the controller specified - by ControllerHandle have been created. If FALSE, then - the tree of controllers is only expanded one level. - - @retval EFI_SUCCESS 1) One or more drivers were connected to ControllerHandle. - 2) No drivers were connected to ControllerHandle, but - RemainingDevicePath is not NULL, and it is an End Device - Path Node. - @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. - @retval EFI_NOT_FOUND 1) There are no EFI_DRIVER_BINDING_PROTOCOL instances - present in the system. - 2) No drivers were connected to ControllerHandle. - @retval EFI_SECURITY_VIOLATION - The user has no permission to start UEFI device drivers on the device path - associated with the ControllerHandle or specified by the RemainingDevicePath. - -**/ -EFI_STATUS -EFIAPI -UnitTestConnectController ( - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE *DriverImageHandle OPTIONAL, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, - IN BOOLEAN Recursive - ) -{ - return EFI_SUCCESS; // Return success for now -} - -/** - Disconnects a controller from a driver - - @param ControllerHandle ControllerHandle The handle of - the controller from which - driver(s) are to be - disconnected. - @param DriverImageHandle DriverImageHandle The driver to - disconnect from ControllerHandle. - @param ChildHandle ChildHandle The handle of the - child to destroy. - - @retval EFI_SUCCESS One or more drivers were - disconnected from the controller. - @retval EFI_SUCCESS On entry, no drivers are managing - ControllerHandle. - @retval EFI_SUCCESS DriverImageHandle is not NULL, - and on entry DriverImageHandle is - not managing ControllerHandle. - @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. - @retval EFI_INVALID_PARAMETER DriverImageHandle is not NULL, - and it is not a valid EFI_HANDLE. - @retval EFI_INVALID_PARAMETER ChildHandle is not NULL, and it - is not a valid EFI_HANDLE. - @retval EFI_OUT_OF_RESOURCES There are not enough resources - available to disconnect any - drivers from ControllerHandle. - @retval EFI_DEVICE_ERROR The controller could not be - disconnected because of a device - error. - -**/ -EFI_STATUS -EFIAPI -UnitTestDisconnectController ( - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE DriverImageHandle OPTIONAL, - IN EFI_HANDLE ChildHandle OPTIONAL - ) -{ - return EFI_SUCCESS; // Return success for now -} - -/** - Computes and returns a 32-bit CRC for a data buffer. - - @param[in] Data A pointer to the buffer on which the 32-bit CRC is to be computed. - @param[in] DataSize The number of bytes in the buffer Data. - @param[out] Crc32 The 32-bit CRC that was computed for the data buffer specified by Data - and DataSize. - - @retval EFI_SUCCESS The 32-bit CRC was computed for the data buffer and returned in - Crc32. - @retval EFI_INVALID_PARAMETER Data is NULL. - @retval EFI_INVALID_PARAMETER Crc32 is NULL. - @retval EFI_INVALID_PARAMETER DataSize is 0. - -**/ -EFI_STATUS -EFIAPI -UnitTestCalculateCrc32 ( - IN VOID *Data, - IN UINTN DataSize, - OUT UINT32 *Crc32 - ) -{ - if ((Data == NULL) || (Crc32 == NULL) || (DataSize == 0)) { - return EFI_INVALID_PARAMETER; - } - - *Crc32 = CalculateCrc32 (Data, DataSize); - - return EFI_SUCCESS; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.c deleted file mode 100644 index 799b153a44..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.c +++ /dev/null @@ -1,1650 +0,0 @@ -/** @file - Implementation of protocol related services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTestProtocol.h" - -STATIC LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); -STATIC LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); -STATIC UINT64 gHandleDatabaseKey = 0; -STATIC UINTN mEfiLocateHandleRequest = 0; - -// -// Helper Functions -// - -/** - Check whether a handle is a valid EFI_HANDLE - - @param UserHandle The handle to check - - @retval EFI_INVALID_PARAMETER The handle is NULL or not a valid EFI_HANDLE. - @retval EFI_SUCCESS The handle is valid EFI_HANDLE. - -**/ -EFI_STATUS -UnitTestValidateHandle ( - IN EFI_HANDLE UserHandle - ) -{ - IHANDLE *Handle; - LIST_ENTRY *Link; - - if (UserHandle == NULL) { - return EFI_INVALID_PARAMETER; - } - - for (Link = gHandleList.BackLink; Link != &gHandleList; Link = Link->BackLink) { - Handle = CR (Link, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); - if (Handle == (IHANDLE *)UserHandle) { - return EFI_SUCCESS; - } - } - - return EFI_INVALID_PARAMETER; -} - -/** - Finds the protocol entry for the requested protocol. - - @param Protocol The ID of the protocol - @param Create Create a new entry if not found - - @return Protocol entry - -**/ -PROTOCOL_ENTRY * -UnitTestFindProtocolEntry ( - IN EFI_GUID *Protocol, - IN BOOLEAN Create - ) -{ - LIST_ENTRY *Link; - PROTOCOL_ENTRY *Item; - PROTOCOL_ENTRY *ProtEntry; - - // - // Search the database for the matching GUID - // - - ProtEntry = NULL; - for (Link = mProtocolDatabase.ForwardLink; - Link != &mProtocolDatabase; - Link = Link->ForwardLink) - { - Item = CR (Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); - if (CompareGuid (&Item->ProtocolID, Protocol)) { - // - // This is the protocol entry - // - - ProtEntry = Item; - break; - } - } - - // - // If the protocol entry was not found and Create is TRUE, then - // allocate a new entry - // - if ((ProtEntry == NULL) && Create) { - ProtEntry = AllocatePool (sizeof (PROTOCOL_ENTRY)); - - if (ProtEntry != NULL) { - // - // Initialize new protocol entry structure - // - ProtEntry->Signature = PROTOCOL_ENTRY_SIGNATURE; - CopyGuid ((VOID *)&ProtEntry->ProtocolID, Protocol); - InitializeListHead (&ProtEntry->Protocols); - InitializeListHead (&ProtEntry->Notify); - - // - // Add it to protocol database - // - InsertTailList (&mProtocolDatabase, &ProtEntry->AllEntries); - } - } - - return ProtEntry; -} - -/** - Finds the protocol instance for the requested handle and protocol. - Note: This function doesn't do parameters checking, it's caller's responsibility - to pass in valid parameters. - - @param Handle The handle to search the protocol on - @param Protocol GUID of the protocol - @param Interface The interface for the protocol being searched - - @return Protocol instance (NULL: Not found) - -**/ -PROTOCOL_INTERFACE * -UnitTestFindProtocolInterface ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface - ) -{ - PROTOCOL_INTERFACE *Prot; - PROTOCOL_ENTRY *ProtEntry; - LIST_ENTRY *Link; - - Prot = NULL; - - // - // Lookup the protocol entry for this protocol ID - // - - ProtEntry = UnitTestFindProtocolEntry (Protocol, FALSE); - if (ProtEntry != NULL) { - // - // Look at each protocol interface for any matches - // - for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - // - // If this protocol interface matches, remove it - // - Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); - if ((Prot->Interface == Interface) && (Prot->Protocol == ProtEntry)) { - break; - } - - Prot = NULL; - } - } - - return Prot; -} - -/** - Signal event for every protocol in protocol entry. - - @param ProtEntry Protocol entry - -**/ -VOID -UnitTestNotifyProtocolEntry ( - IN PROTOCOL_ENTRY *ProtEntry - ) -{ - PROTOCOL_NOTIFY *ProtNotify; - LIST_ENTRY *Link; - - for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { - ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); - UnitTestSignalEvent (ProtNotify->Event); - } -} - -/** - Routine to get the next Handle, when you are searching for all handles. - - @param Position Information about which Handle to seach for. - @param Interface Return the interface structure for the matching - protocol. - - @return An pointer to IHANDLE if the next Position is not the end of the list. - Otherwise,NULL is returned. - -**/ -IHANDLE * -UnitTestGetNextLocateAllHandles ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface - ) -{ - IHANDLE *Handle; - - // - // Next handle - // - Position->Position = Position->Position->ForwardLink; - - // - // If not at the end of the list, get the handle - // - Handle = NULL; - *Interface = NULL; - if (Position->Position != &gHandleList) { - Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); - } - - return Handle; -} - -/** - Routine to get the next Handle, when you are searching for register protocol - notifies. - - @param Position Information about which Handle to seach for. - @param Interface Return the interface structure for the matching - protocol. - - @return An pointer to IHANDLE if the next Position is not the end of the list. - Otherwise,NULL is returned. - -**/ -IHANDLE * -UnitTestGetNextLocateByRegisterNotify ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface - ) -{ - IHANDLE *Handle; - PROTOCOL_NOTIFY *ProtNotify; - PROTOCOL_INTERFACE *Prot; - LIST_ENTRY *Link; - - Handle = NULL; - *Interface = NULL; - ProtNotify = Position->SearchKey; - - // - // If this is the first request, get the next handle - // - if (ProtNotify != NULL) { - ASSERT (ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); - Position->SearchKey = NULL; - - // - // If not at the end of the list, get the next handle - // - Link = ProtNotify->Position->ForwardLink; - if (Link != &ProtNotify->Protocol->Protocols) { - Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; - *Interface = Prot->Interface; - } - } - - return Handle; -} - -/** - Routine to get the next Handle, when you are searching for a given protocol. - - @param Position Information about which Handle to seach for. - @param Interface Return the interface structure for the matching - protocol. - - @return An pointer to IHANDLE if the next Position is not the end of the list. - Otherwise,NULL is returned. - -**/ -IHANDLE * -UnitTestGetNextLocateByProtocol ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface - ) -{ - IHANDLE *Handle; - LIST_ENTRY *Link; - PROTOCOL_INTERFACE *Prot; - - Handle = NULL; - *Interface = NULL; - for ( ; ;) { - // - // Next entry - // - Link = Position->Position->ForwardLink; - Position->Position = Link; - - // - // If not at the end, return the handle - // - if (Link == &Position->ProtEntry->Protocols) { - Handle = NULL; - break; - } - - // - // Get the handle - // - Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; - *Interface = Prot->Interface; - - // - // If this handle has not been returned this request, then - // return it now - // - if (Handle->LocateRequest != mEfiLocateHandleRequest) { - Handle->LocateRequest = mEfiLocateHandleRequest; - break; - } - } - - return Handle; -} - -/** - Attempts to disconnect all drivers that are using the protocol interface being queried. - If failed, reconnect all drivers disconnected. - Note: This function doesn't do parameters checking, it's caller's responsibility - to pass in valid parameters. - - @param UserHandle The handle on which the protocol is installed - @param Prot The protocol to disconnect drivers from - - @retval EFI_SUCCESS Drivers using the protocol interface are all - disconnected - @retval EFI_ACCESS_DENIED Failed to disconnect one or all of the drivers - -**/ -EFI_STATUS -UnitTestDisconnectControllersUsingProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN PROTOCOL_INTERFACE *Prot - ) -{ - EFI_STATUS Status; - BOOLEAN ItemFound; - LIST_ENTRY *Link; - OPEN_PROTOCOL_DATA *OpenData; - - Status = EFI_SUCCESS; - - // - // Attempt to disconnect all drivers from this protocol interface - // - do { - ItemFound = FALSE; - for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { - Status = UnitTestDisconnectController (UserHandle, OpenData->AgentHandle, NULL); - if (!EFI_ERROR (Status)) { - ItemFound = TRUE; - } - - break; - } - } - } while (ItemFound); - - if (!EFI_ERROR (Status)) { - // - // Attempt to remove BY_HANDLE_PROTOCOL and GET_PROTOCOL and TEST_PROTOCOL Open List items - // - for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList;) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - if ((OpenData->Attributes & - (EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL | EFI_OPEN_PROTOCOL_GET_PROTOCOL | EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) != 0) - { - Link = RemoveEntryList (&OpenData->Link); - Prot->OpenListCount--; - FreePool (OpenData); - } else { - Link = Link->ForwardLink; - } - } - } - - // - // If there are errors or still has open items in the list, then reconnect all the drivers and return an error - // - if (EFI_ERROR (Status) || (Prot->OpenListCount > 0)) { - UnitTestConnectController (UserHandle, NULL, NULL, TRUE); - Status = EFI_ACCESS_DENIED; - } - - return Status; -} - -/** - Removes Protocol from the protocol list (but not the handle list). - - @param Handle The handle to remove protocol on. - @param Protocol GUID of the protocol to be moved - @param Interface The interface of the protocol - - @return Protocol Entry - -**/ -PROTOCOL_INTERFACE * -UnitTestRemoveInterfaceFromProtocol ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface - ) -{ - PROTOCOL_INTERFACE *Prot; - PROTOCOL_NOTIFY *ProtNotify; - PROTOCOL_ENTRY *ProtEntry; - LIST_ENTRY *Link; - - Prot = UnitTestFindProtocolInterface (Handle, Protocol, Interface); - if (Prot != NULL) { - ProtEntry = Prot->Protocol; - - // - // If there's a protocol notify location pointing to this entry, back it up one - // - for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { - ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); - - if (ProtNotify->Position == &Prot->ByProtocol) { - ProtNotify->Position = Prot->ByProtocol.BackLink; - } - } - - // - // Remove the protocol interface entry - // - RemoveEntryList (&Prot->ByProtocol); - } - - return Prot; -} - -// -// Boot Services Function Implementation -// - -/** - Locate a certain GUID protocol interface in a Handle's protocols. - - @param UserHandle The handle to obtain the protocol interface on - @param Protocol The GUID of the protocol - - @return The requested protocol interface for the handle - -**/ -PROTOCOL_INTERFACE * -UnitTestGetProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol - ) -{ - EFI_STATUS Status; - PROTOCOL_ENTRY *ProtEntry; - PROTOCOL_INTERFACE *Prot; - IHANDLE *Handle; - LIST_ENTRY *Link; - - Status = UnitTestValidateHandle (UserHandle); - if (EFI_ERROR (Status)) { - return NULL; - } - - Handle = (IHANDLE *)UserHandle; - - // - // Look at each protocol interface for a match - // - for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); - ProtEntry = Prot->Protocol; - if (CompareGuid (&ProtEntry->ProtocolID, Protocol)) { - return Prot; - } - } - - return NULL; -} - -/** - Installs a protocol interface into the boot services environment. - - @param UserHandle The handle to install the protocol handler on, - or NULL if a new handle is to be allocated - @param Protocol The protocol to add to the handle - @param InterfaceType Indicates whether Interface is supplied in - native form. - @param Interface The interface for the protocol being added - @param Notify indicates whether notify the notification list - for this protocol - - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate - @retval EFI_SUCCESS Protocol interface successfully installed - -**/ -EFI_STATUS -UnitTestInstallProtocolInterfaceNotify ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface, - IN BOOLEAN Notify - ) -{ - PROTOCOL_INTERFACE *Prot; - PROTOCOL_ENTRY *ProtEntry; - IHANDLE *Handle; - EFI_STATUS Status; - VOID *ExistingInterface; - - // - // returns EFI_INVALID_PARAMETER if InterfaceType is invalid. - // Also added check for invalid UserHandle and Protocol pointers. - // - if ((UserHandle == NULL) || (Protocol == NULL)) { - return EFI_INVALID_PARAMETER; - } - - if (InterfaceType != EFI_NATIVE_INTERFACE) { - return EFI_INVALID_PARAMETER; - } - - // - // Print debug message - // - UT_LOG_INFO ("InstallProtocolInterface: %g %p\n", Protocol, Interface); - - Status = EFI_OUT_OF_RESOURCES; - Prot = NULL; - Handle = NULL; - - if (*UserHandle != NULL) { - Status = UnitTestHandleProtocol (*UserHandle, Protocol, (VOID **)&ExistingInterface); - if (!EFI_ERROR (Status)) { - return EFI_INVALID_PARAMETER; - } - } - - // - // Lookup the Protocol Entry for the requested protocol - // - ProtEntry = UnitTestFindProtocolEntry (Protocol, TRUE); - if (ProtEntry == NULL) { - goto Done; - } - - // - // Allocate a new protocol interface structure - // - Prot = AllocateZeroPool (sizeof (PROTOCOL_INTERFACE)); - if (Prot == NULL) { - Status = EFI_OUT_OF_RESOURCES; - goto Done; - } - - // - // If caller didn't supply a handle, allocate a new one - // - Handle = (IHANDLE *)*UserHandle; - if (Handle == NULL) { - Handle = AllocateZeroPool (sizeof (IHANDLE)); - if (Handle == NULL) { - Status = EFI_OUT_OF_RESOURCES; - goto Done; - } - - // - // Initialize new handler structure - // - Handle->Signature = EFI_HANDLE_SIGNATURE; - InitializeListHead (&Handle->Protocols); - - // - // Initialize the Key to show that the handle has been created/modified - // - gHandleDatabaseKey++; - Handle->Key = gHandleDatabaseKey; - - // - // Add this handle to the list global list of all handles - // in the system - // - InsertTailList (&gHandleList, &Handle->AllHandles); - } else { - Status = UnitTestValidateHandle (Handle); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); - goto Done; - } - } - - // - // Each interface that is added must be unique - // - ASSERT (UnitTestFindProtocolInterface (Handle, Protocol, Interface) == NULL); - - // - // Initialize the protocol interface structure - // - Prot->Signature = PROTOCOL_INTERFACE_SIGNATURE; - Prot->Handle = Handle; - Prot->Protocol = ProtEntry; - Prot->Interface = Interface; - - // - // Initialize OpenProtocol Data base - // - InitializeListHead (&Prot->OpenList); - Prot->OpenListCount = 0; - - // - // Add this protocol interface to the head of the supported - // protocol list for this handle - // - InsertHeadList (&Handle->Protocols, &Prot->Link); - - // - // Add this protocol interface to the tail of the - // protocol entry - // - InsertTailList (&ProtEntry->Protocols, &Prot->ByProtocol); - - // - // Notify the notification list for this protocol - // - if (Notify) { - UnitTestNotifyProtocolEntry (ProtEntry); - } - - Status = EFI_SUCCESS; - -Done: - if (!EFI_ERROR (Status)) { - // - // Return the new handle back to the caller - // - *UserHandle = Handle; - } else { - // - // There was an error, clean up - // - if (Prot != NULL) { - UnitTestFreePool (Prot); - } - - DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); - } - - return Status; -} - -/** - Wrapper function to UnitTestInstallProtocolInterfaceNotify. This is the public API which - Calls the private one which contains a BOOLEAN parameter for notifications - - @param UserHandle The handle to install the protocol handler on, - or NULL if a new handle is to be allocated - @param Protocol The protocol to add to the handle - @param InterfaceType Indicates whether Interface is supplied in - native form. - @param Interface The interface for the protocol being added - - @return Status code - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallProtocolInterface ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface - ) -{ - return UnitTestInstallProtocolInterfaceNotify ( - UserHandle, - Protocol, - InterfaceType, - Interface, - TRUE - ); -} - -/** - Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. - - @param UserHandle Handle on which the interface is to be - reinstalled - @param Protocol The numeric ID of the interface - @param OldInterface A pointer to the old interface - @param NewInterface A pointer to the new interface - - @retval EFI_SUCCESS The protocol interface was installed - @retval EFI_NOT_FOUND The OldInterface on the handle was not found - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value - -**/ -EFI_STATUS -EFIAPI -UnitTestReinstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *OldInterface, - IN VOID *NewInterface - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Uninstalls all instances of a protocol:interfacer from a handle. - If the last protocol interface is remove from the handle, the - handle is freed. - - @param UserHandle The handle to remove the protocol handler from - @param Protocol The protocol, of protocol:interface, to remove - @param Interface The interface, of protocol:interface, to remove - - @retval EFI_INVALID_PARAMETER Protocol is NULL. - @retval EFI_SUCCESS Protocol interface successfully uninstalled. - -**/ -EFI_STATUS -EFIAPI -UnitTestUninstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *Interface - ) -{ - EFI_STATUS Status; - IHANDLE *Handle; - PROTOCOL_INTERFACE *Prot; - - // - // Check that Protocol is valid - // - if (Protocol == NULL) { - return EFI_INVALID_PARAMETER; - } - - // - // Check that UserHandle is a valid handle - // - Status = UnitTestValidateHandle (UserHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - // - // Check that Protocol exists on UserHandle, and Interface matches the interface in the database - // - Prot = UnitTestFindProtocolInterface (UserHandle, Protocol, Interface); - if (Prot == NULL) { - Status = EFI_NOT_FOUND; - goto Done; - } - - // - // Attempt to disconnect all drivers that are using the protocol interface that is about to be removed - // - Status = UnitTestDisconnectControllersUsingProtocolInterface ( - UserHandle, - Prot - ); - if (EFI_ERROR (Status)) { - // - // One or more drivers refused to release, so return the error - // - goto Done; - } - - // - // Remove the protocol interface from the protocol - // - Status = EFI_NOT_FOUND; - Handle = (IHANDLE *)UserHandle; - Prot = UnitTestRemoveInterfaceFromProtocol (Handle, Protocol, Interface); - - if (Prot != NULL) { - // - // Update the Key to show that the handle has been created/modified - // - gHandleDatabaseKey++; - Handle->Key = gHandleDatabaseKey; - - // - // Remove the protocol interface from the handle - // - RemoveEntryList (&Prot->Link); - - // - // Free the memory - // - Prot->Signature = 0; - FreePool (Prot); - Status = EFI_SUCCESS; - } - - // - // If there are no more handlers for the handle, free the handle - // - if (IsListEmpty (&Handle->Protocols)) { - Handle->Signature = 0; - RemoveEntryList (&Handle->AllHandles); - FreePool (Handle); - } - -Done: - return Status; -} - -/** - Queries a handle to determine if it supports a specified protocol. - - @param UserHandle The handle being queried. - @param Protocol The published unique identifier of the protocol. - @param Interface Supplies the address where a pointer to the - corresponding Protocol Interface is returned. - - @return The requested protocol interface for the handle - -**/ -EFI_STATUS -EFIAPI -UnitTestHandleProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface - ) -{ - return UnitTestOpenProtocol ( - UserHandle, - Protocol, - Interface, - gImageHandle, - NULL, - EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL - ); -} - -/** - Add a new protocol notification record for the request protocol. - - @param Protocol The requested protocol to add the notify - registration - @param Event The event to signal - @param Registration Returns the registration record - - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_SUCCESS Successfully returned the registration record - that has been added - -**/ -EFI_STATUS -EFIAPI -UnitTestRegisterProtocolNotify ( - IN EFI_GUID *Protocol, - IN EFI_EVENT Event, - OUT VOID **Registration - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Locates the requested handle(s) and returns them in Buffer. - - @param SearchType The type of search to perform to locate the - handles - @param Protocol The protocol to search for - @param SearchKey Dependant on SearchType - @param BufferSize On input the size of Buffer. On output the - size of data returned. - @param Buffer The buffer to return the results in - - @retval EFI_BUFFER_TOO_SMALL Buffer too small, required buffer size is - returned in BufferSize. - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_SUCCESS Successfully found the requested handle(s) and - returns them in Buffer. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer - ) -{ - EFI_STATUS Status; - LOCATE_POSITION Position; - PROTOCOL_NOTIFY *ProtNotify; - UNIT_TEST_GET_NEXT GetNext; - UINTN ResultSize; - IHANDLE *Handle; - IHANDLE **ResultBuffer; - VOID *Interface; - - if (BufferSize == NULL) { - return EFI_INVALID_PARAMETER; - } - - if ((*BufferSize > 0) && (Buffer == NULL)) { - return EFI_INVALID_PARAMETER; - } - - GetNext = NULL; - - // - // Set initial position - // - Position.Protocol = Protocol; - Position.SearchKey = SearchKey; - Position.Position = &gHandleList; - - ResultSize = 0; - ResultBuffer = (IHANDLE **)Buffer; - Status = EFI_SUCCESS; - - // - // Get the search function based on type - // - switch (SearchType) { - case AllHandles: - GetNext = UnitTestGetNextLocateAllHandles; - break; - - case ByRegisterNotify: - // - // Must have SearchKey for locate ByRegisterNotify - // - if (SearchKey == NULL) { - Status = EFI_INVALID_PARAMETER; - break; - } - - GetNext = UnitTestGetNextLocateByRegisterNotify; - break; - - case ByProtocol: - GetNext = UnitTestGetNextLocateByProtocol; - if (Protocol == NULL) { - Status = EFI_INVALID_PARAMETER; - break; - } - - // - // Look up the protocol entry and set the head pointer - // - Position.ProtEntry = UnitTestFindProtocolEntry (Protocol, FALSE); - if (Position.ProtEntry == NULL) { - Status = EFI_NOT_FOUND; - break; - } - - Position.Position = &Position.ProtEntry->Protocols; - break; - - default: - Status = EFI_INVALID_PARAMETER; - break; - } - - if (EFI_ERROR (Status)) { - return Status; - } - - ASSERT (GetNext != NULL); - // - // Enumerate out the matching handles - // - mEfiLocateHandleRequest += 1; - for ( ; ;) { - // - // Get the next handle. If no more handles, stop - // - Handle = GetNext (&Position, &Interface); - if (NULL == Handle) { - break; - } - - // - // Increase the resulting buffer size, and if this handle - // fits return it - // - ResultSize += sizeof (Handle); - if (ResultSize <= *BufferSize) { - *ResultBuffer = Handle; - ResultBuffer += 1; - } - } - - // - // If the result is a zero length buffer, then there were no - // matching handles - // - if (ResultSize == 0) { - Status = EFI_NOT_FOUND; - } else { - // - // Return the resulting buffer size. If it's larger than what - // was passed, then set the error code - // - if (ResultSize > *BufferSize) { - Status = EFI_BUFFER_TOO_SMALL; - } - - *BufferSize = ResultSize; - - if ((SearchType == ByRegisterNotify) && !EFI_ERROR (Status)) { - // - // If this is a search by register notify and a handle was - // returned, update the register notification position - // - ASSERT (SearchKey != NULL); - ProtNotify = SearchKey; - ProtNotify->Position = ProtNotify->Position->ForwardLink; - } - } - - return Status; -} - -/** - Locates the handle to a device on the device path that best matches the specified protocol. - - @param Protocol The protocol to search for. - @param DevicePath On input, a pointer to a pointer to the device - path. On output, the device path pointer is - modified to point to the remaining part of the - devicepath. - @param Device A pointer to the returned device handle. - - @retval EFI_SUCCESS The resulting handle was returned. - @retval EFI_NOT_FOUND No handles matched the search. - @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateDevicePath ( - IN EFI_GUID *Protocol, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, - OUT EFI_HANDLE *Device - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Boot Service called to add, modify, or remove a system configuration table from - the EFI System Table. - - @param Guid Pointer to the GUID for the entry to add, update, or - remove - @param Table Pointer to the configuration table for the entry to add, - update, or remove, may be NULL. - - @return EFI_SUCCESS Guid, Table pair added, updated, or removed. - @return EFI_INVALID_PARAMETER Input GUID not valid. - @return EFI_NOT_FOUND Attempted to delete non-existant entry - @return EFI_OUT_OF_RESOURCES Not enough memory available - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallConfigurationTable ( - IN EFI_GUID *Guid, - IN VOID *Table - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Locates the installed protocol handler for the handle, and - invokes it to obtain the protocol interface. Usage information - is registered in the protocol data base. - - @param UserHandle The handle to obtain the protocol interface on - @param Protocol The ID of the protocol - @param Interface The location to return the protocol interface - @param ImageHandle The handle of the Image that is opening the - protocol interface specified by Protocol and - Interface. - @param ControllerHandle The controller handle that is requiring this - interface. - @param Attributes The open mode of the protocol interface - specified by Handle and Protocol. - - @retval EFI_INVALID_PARAMETER Protocol is NULL. - @retval EFI_SUCCESS Get the protocol interface. - -**/ -EFI_STATUS -EFIAPI -UnitTestOpenProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface OPTIONAL, - IN EFI_HANDLE ImageHandle, - IN EFI_HANDLE ControllerHandle, - IN UINT32 Attributes - ) -{ - EFI_STATUS Status; - PROTOCOL_INTERFACE *Prot; - LIST_ENTRY *Link; - OPEN_PROTOCOL_DATA *OpenData; - BOOLEAN ByDriver; - BOOLEAN Exclusive; - BOOLEAN Disconnect; - BOOLEAN ExactMatch; - - // - // Check for invalid Protocol - // - if (Protocol == NULL) { - return EFI_INVALID_PARAMETER; - } - - // - // Check for invalid Interface - // - if ((Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) && (Interface == NULL)) { - return EFI_INVALID_PARAMETER; - } - - // - // Check for invalid UserHandle - // - Status = UnitTestValidateHandle (UserHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - // - // Check for invalid Attributes - // - switch (Attributes) { - case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: - Status = UnitTestValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - Status = UnitTestValidateHandle (ControllerHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - if (UserHandle == ControllerHandle) { - return EFI_INVALID_PARAMETER; - } - - break; - case EFI_OPEN_PROTOCOL_BY_DRIVER: - case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: - Status = UnitTestValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - Status = UnitTestValidateHandle (ControllerHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - break; - case EFI_OPEN_PROTOCOL_EXCLUSIVE: - Status = UnitTestValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - return Status; - } - - break; - case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: - case EFI_OPEN_PROTOCOL_GET_PROTOCOL: - case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: - break; - default: - return EFI_INVALID_PARAMETER; - } - - // - // Look at each protocol interface for a match - // - Prot = UnitTestGetProtocolInterface (UserHandle, Protocol); - if (Prot == NULL) { - Status = EFI_UNSUPPORTED; - goto Done; - } - - Status = EFI_SUCCESS; - - ByDriver = FALSE; - Exclusive = FALSE; - for ( Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - ExactMatch = (BOOLEAN)((OpenData->AgentHandle == ImageHandle) && - (OpenData->Attributes == Attributes) && - (OpenData->ControllerHandle == ControllerHandle)); - if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { - ByDriver = TRUE; - if (ExactMatch) { - Status = EFI_ALREADY_STARTED; - goto Done; - } - } - - if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) != 0) { - Exclusive = TRUE; - } else if (ExactMatch) { - OpenData->OpenCount++; - Status = EFI_SUCCESS; - goto Done; - } - } - - // - // ByDriver TRUE -> A driver is managing (UserHandle, Protocol) - // ByDriver FALSE -> There are no drivers managing (UserHandle, Protocol) - // Exclusive TRUE -> Something has exclusive access to (UserHandle, Protocol) - // Exclusive FALSE -> Nothing has exclusive access to (UserHandle, Protocol) - // - - switch (Attributes) { - case EFI_OPEN_PROTOCOL_BY_DRIVER: - if (Exclusive || ByDriver) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - - break; - case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: - case EFI_OPEN_PROTOCOL_EXCLUSIVE: - if (Exclusive) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - - if (ByDriver) { - do { - Disconnect = FALSE; - for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { - Disconnect = TRUE; - Status = UnitTestDisconnectController (UserHandle, OpenData->AgentHandle, NULL); - if (EFI_ERROR (Status)) { - Status = EFI_ACCESS_DENIED; - goto Done; - } else { - break; - } - } - } - } while (Disconnect); - } - - break; - case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: - case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: - case EFI_OPEN_PROTOCOL_GET_PROTOCOL: - case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: - break; - } - - if (ImageHandle == NULL) { - Status = EFI_SUCCESS; - goto Done; - } - - // - // Create new entry - // - OpenData = AllocatePool (sizeof (OPEN_PROTOCOL_DATA)); - if (OpenData == NULL) { - Status = EFI_OUT_OF_RESOURCES; - } else { - OpenData->Signature = OPEN_PROTOCOL_DATA_SIGNATURE; - OpenData->AgentHandle = ImageHandle; - OpenData->ControllerHandle = ControllerHandle; - OpenData->Attributes = Attributes; - OpenData->OpenCount = 1; - InsertTailList (&Prot->OpenList, &OpenData->Link); - Prot->OpenListCount++; - Status = EFI_SUCCESS; - } - -Done: - - if (Attributes != EFI_OPEN_PROTOCOL_TEST_PROTOCOL) { - // - // Keep Interface unmodified in case of any Error - // except EFI_ALREADY_STARTED and EFI_UNSUPPORTED. - // - if (!EFI_ERROR (Status) || (Status == EFI_ALREADY_STARTED)) { - // - // According to above logic, if 'Prot' is NULL, then the 'Status' must be - // EFI_UNSUPPORTED. Here the 'Status' is not EFI_UNSUPPORTED, so 'Prot' - // must be not NULL. - // - // The ASSERT here is for addressing a false positive NULL pointer - // dereference issue raised from static analysis. - // - ASSERT (Prot != NULL); - // - // EFI_ALREADY_STARTED is not an error for bus driver. - // Return the corresponding protocol interface. - // - *Interface = Prot->Interface; - } else if (Status == EFI_UNSUPPORTED) { - // - // Return NULL Interface if Unsupported Protocol. - // - *Interface = NULL; - } - } - - return Status; -} - -/** - Closes a protocol on a handle that was opened using OpenProtocol(). - - @param UserHandle The handle for the protocol interface that was - previously opened with OpenProtocol(), and is - now being closed. - @param Protocol The published unique identifier of the protocol. - It is the caller's responsibility to pass in a - valid GUID. - @param AgentHandle The handle of the agent that is closing the - protocol interface. - @param ControllerHandle If the agent that opened a protocol is a driver - that follows the EFI Driver Model, then this - parameter is the controller handle that required - the protocol interface. If the agent does not - follow the EFI Driver Model, then this parameter - is optional and may be NULL. - - @retval EFI_SUCCESS The protocol instance was closed. - @retval EFI_INVALID_PARAMETER Handle, AgentHandle or ControllerHandle is not a - valid EFI_HANDLE. - @retval EFI_NOT_FOUND Can not find the specified protocol or - AgentHandle. - -**/ -EFI_STATUS -EFIAPI -UnitTestCloseProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN EFI_HANDLE AgentHandle, - IN EFI_HANDLE ControllerHandle - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Return information about Opened protocols in the system - - @param UserHandle The handle to close the protocol interface on - @param Protocol The ID of the protocol - @param EntryBuffer A pointer to a buffer of open protocol - information in the form of - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY structures. - @param EntryCount Number of EntryBuffer entries - -**/ -EFI_STATUS -EFIAPI -UnitTestOpenProtocolInformation ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, - OUT UINTN *EntryCount - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated - from pool. - - @param UserHandle The handle from which to retrieve the list of - protocol interface GUIDs. - @param ProtocolBuffer A pointer to the list of protocol interface GUID - pointers that are installed on Handle. - @param ProtocolBufferCount A pointer to the number of GUID pointers present - in ProtocolBuffer. - - @retval EFI_SUCCESS The list of protocol interface GUIDs installed - on Handle was returned in ProtocolBuffer. The - number of protocol interface GUIDs was returned - in ProtocolBufferCount. - @retval EFI_INVALID_PARAMETER Handle is NULL. - @retval EFI_INVALID_PARAMETER Handle is not a valid EFI_HANDLE. - @retval EFI_INVALID_PARAMETER ProtocolBuffer is NULL. - @retval EFI_INVALID_PARAMETER ProtocolBufferCount is NULL. - @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the - results. - -**/ -EFI_STATUS -EFIAPI -UnitTestProtocolsPerHandle ( - IN EFI_HANDLE UserHandle, - OUT EFI_GUID ***ProtocolBuffer, - OUT UINTN *ProtocolBufferCount - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Function returns an array of handles that support the requested protocol - in a buffer allocated from pool. This is a version of UnitTestLocateHandle() - that allocates a buffer for the caller. - - @param SearchType Specifies which handle(s) are to be returned. - @param Protocol Provides the protocol to search by. This - parameter is only valid for SearchType - ByProtocol. - @param SearchKey Supplies the search key depending on the - SearchType. - @param NumberHandles The number of handles returned in Buffer. - @param Buffer A pointer to the buffer to return the requested - array of handles that support Protocol. - - @retval EFI_SUCCESS The result array of handles was returned. - @retval EFI_NOT_FOUND No handles match the search. - @retval EFI_OUT_OF_RESOURCES There is not enough pool memory to store the - matching results. - @retval EFI_INVALID_PARAMETER One or more parameters are not valid. - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateHandleBuffer ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *NumberHandles, - OUT EFI_HANDLE **Buffer - ) -{ - EFI_STATUS Status; - UINTN BufferSize; - - if (NumberHandles == NULL) { - return EFI_INVALID_PARAMETER; - } - - if (Buffer == NULL) { - return EFI_INVALID_PARAMETER; - } - - BufferSize = 0; - *NumberHandles = 0; - *Buffer = NULL; - Status = UnitTestLocateHandle ( - SearchType, - Protocol, - SearchKey, - &BufferSize, - *Buffer - ); - // - // LocateHandleBuffer() returns incorrect status code if SearchType is - // invalid. - // - // Add code to correctly handle expected errors from UnitTestLocateHandle(). - // - if (EFI_ERROR (Status) && (Status != EFI_BUFFER_TOO_SMALL)) { - if (Status != EFI_INVALID_PARAMETER) { - Status = EFI_NOT_FOUND; - } - - return Status; - } - - *Buffer = AllocatePool (BufferSize); - if (*Buffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - Status = UnitTestLocateHandle ( - SearchType, - Protocol, - SearchKey, - &BufferSize, - *Buffer - ); - - *NumberHandles = BufferSize / sizeof (EFI_HANDLE); - if (EFI_ERROR (Status)) { - *NumberHandles = 0; - } - - return Status; -} - -/** - Return the first Protocol Interface that matches the Protocol GUID. If - Registration is passed in, return a Protocol Instance that was just add - to the system. If Registration is NULL return the first Protocol Interface - you find. - - @param Protocol The protocol to search for - @param Registration Optional Registration Key returned from - RegisterProtocolNotify() - @param Interface Return the Protocol interface (instance). - - @retval EFI_SUCCESS If a valid Interface is returned - @retval EFI_INVALID_PARAMETER Invalid parameter - @retval EFI_NOT_FOUND Protocol interface not found - -**/ -EFI_STATUS -EFIAPI -UnitTestLocateProtocol ( - IN EFI_GUID *Protocol, - IN VOID *Registration OPTIONAL, - OUT VOID **Interface - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Installs a list of protocol interface into the boot services environment. - This function calls InstallProtocolInterface() in a loop. If any error - occurs all the protocols added by this function are removed. This is - basically a lib function to save space. - - @param Handle The handle to install the protocol handlers on, - or NULL if a new handle is to be allocated - @param ... EFI_GUID followed by protocol instance. A NULL - terminates the list. The pairs are the - arguments to InstallProtocolInterface(). All the - protocols are added to Handle. - - @retval EFI_SUCCESS All the protocol interface was installed. - @retval EFI_OUT_OF_RESOURCES There was not enough memory in pool to install all the protocols. - @retval EFI_ALREADY_STARTED A Device Path Protocol instance was passed in that is already present in - the handle database. - @retval EFI_INVALID_PARAMETER Handle is NULL. - @retval EFI_INVALID_PARAMETER Protocol is already installed on the handle specified by Handle. - -**/ -EFI_STATUS -EFIAPI -UnitTestInstallMultipleProtocolInterfaces ( - IN OUT EFI_HANDLE *Handle, - ... - ) -{ - return EFI_NOT_AVAILABLE_YET; -} - -/** - Uninstalls a list of protocol interface in the boot services environment. - This function calls UninstallProtocolInterface() in a loop. This is - basically a lib function to save space. - - @param Handle The handle to uninstall the protocol - @param ... EFI_GUID followed by protocol instance. A NULL - terminates the list. The pairs are the - arguments to UninstallProtocolInterface(). All - the protocols are added to Handle. - - @return Status code - -**/ -EFI_STATUS -EFIAPI -UnitTestUninstallMultipleProtocolInterfaces ( - IN EFI_HANDLE Handle, - ... - ) -{ - EFI_STATUS Status; - VA_LIST Args; - EFI_GUID *Protocol; - VOID *Interface; - UINTN Index; - - VA_START (Args, Handle); - for (Index = 0, Status = EFI_SUCCESS; !EFI_ERROR (Status); Index++) { - // - // If protocol is NULL, then it's the end of the list - // - Protocol = VA_ARG (Args, EFI_GUID *); - if (Protocol == NULL) { - break; - } - - Interface = VA_ARG (Args, VOID *); - - // - // Uninstall it - // - Status = UnitTestUninstallProtocolInterface (Handle, Protocol, Interface); - } - - VA_END (Args); - - // - // If there was an error, add all the interfaces that were - // uninstalled without any errors - // - if (EFI_ERROR (Status)) { - // - // Reset the va_arg back to the first argument. - // - VA_START (Args, Handle); - for ( ; Index > 1; Index--) { - Protocol = VA_ARG (Args, EFI_GUID *); - Interface = VA_ARG (Args, VOID *); - UnitTestInstallProtocolInterface (&Handle, Protocol, EFI_NATIVE_INTERFACE, Interface); - } - - VA_END (Args); - Status = EFI_INVALID_PARAMETER; - } - - return Status; -} diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.h b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.h deleted file mode 100644 index 6428090071..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestProtocol.h +++ /dev/null @@ -1,120 +0,0 @@ -/** @file - An internal header file for the Unit Test instance of the UEFI Boot Services Table Library. - - This file includes common header files, defines internal structure and functions used by - the library implementation. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_PROTOCOL_H_ -#define UEFI_BOOT_SERVICES_TABLE_LIB_UNIT_TEST_PROTOCOL_H_ - -#include "UefiBootServicesTableLibUnitTest.h" - -#define EFI_HANDLE_SIGNATURE SIGNATURE_32('h','n','d','l') - -/// -/// IHANDLE - contains a list of protocol handles -/// -typedef struct { - UINTN Signature; - /// All handles list of IHANDLE - LIST_ENTRY AllHandles; - /// List of PROTOCOL_INTERFACE's for this handle - LIST_ENTRY Protocols; - UINTN LocateRequest; - /// The Handle Database Key value when this handle was last created or modified - UINT64 Key; -} IHANDLE; - -#define ASSERT_IS_HANDLE(a) ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE) - -#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('p','r','t','e') - -/// -/// PROTOCOL_ENTRY - each different protocol has 1 entry in the protocol -/// database. Each handler that supports this protocol is listed, along -/// with a list of registered notifies. -/// -typedef struct { - UINTN Signature; - /// Link Entry inserted to mProtocolDatabase - LIST_ENTRY AllEntries; - /// ID of the protocol - EFI_GUID ProtocolID; - /// All protocol interfaces - LIST_ENTRY Protocols; - /// Registered notification handlers - LIST_ENTRY Notify; -} PROTOCOL_ENTRY; - -#define PROTOCOL_INTERFACE_SIGNATURE SIGNATURE_32('p','i','f','c') - -/// -/// PROTOCOL_INTERFACE - each protocol installed on a handle is tracked -/// with a protocol interface structure -/// -typedef struct { - UINTN Signature; - /// Link on IHANDLE.Protocols - LIST_ENTRY Link; - /// Back pointer - IHANDLE *Handle; - /// Link on PROTOCOL_ENTRY.Protocols - LIST_ENTRY ByProtocol; - /// The protocol ID - PROTOCOL_ENTRY *Protocol; - /// The interface value - VOID *Interface; - /// OPEN_PROTOCOL_DATA list - LIST_ENTRY OpenList; - UINTN OpenListCount; -} PROTOCOL_INTERFACE; - -#define OPEN_PROTOCOL_DATA_SIGNATURE SIGNATURE_32('p','o','d','l') - -typedef struct { - UINTN Signature; - /// Link on PROTOCOL_INTERFACE.OpenList - LIST_ENTRY Link; - - EFI_HANDLE AgentHandle; - EFI_HANDLE ControllerHandle; - UINT32 Attributes; - UINT32 OpenCount; -} OPEN_PROTOCOL_DATA; - -#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('p','r','t','n') - -/// -/// PROTOCOL_NOTIFY - used for each register notification for a protocol -/// -typedef struct { - UINTN Signature; - PROTOCOL_ENTRY *Protocol; - /// All notifications for this protocol - LIST_ENTRY Link; - /// Event to notify - EFI_EVENT Event; - /// Last position notified - LIST_ENTRY *Position; -} PROTOCOL_NOTIFY; - -typedef struct { - EFI_GUID *Protocol; - VOID *SearchKey; - LIST_ENTRY *Position; - PROTOCOL_ENTRY *ProtEntry; -} LOCATE_POSITION; - -typedef -IHANDLE * -(*UNIT_TEST_GET_NEXT) ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface - ); - -#endif diff --git a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestTpl.c b/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestTpl.c deleted file mode 100644 index 5b7b6700f8..0000000000 --- a/PrmPkg/Test/UnitTest/Library/UefiBootServicesTableLibUnitTest/UefiBootServicesTableLibUnitTestTpl.c +++ /dev/null @@ -1,43 +0,0 @@ -/** @file - Implementation of Task Priority Level (TPL) related services in the UEFI Boot Services table for use in unit tests. - -Copyright (c) Microsoft Corporation -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "UefiBootServicesTableLibUnitTest.h" - -/** - Raise the task priority level to the new level. - High level is implemented by disabling processor interrupts. - - @param NewTpl New task priority level - - @return The previous task priority level - -**/ -EFI_TPL -EFIAPI -UnitTestRaiseTpl ( - IN EFI_TPL NewTpl - ) -{ - return TPL_APPLICATION; -} - -/** - Lowers the task priority to the previous value. If the new - priority unmasks events at a higher priority, they are dispatched. - - @param NewTpl New, lower, task priority - -**/ -VOID -EFIAPI -UnitTestRestoreTpl ( - IN EFI_TPL NewTpl - ) -{ - return; -} From 38f4209cc8b60bd3b129f4373e9ec89de72bcfe6 Mon Sep 17 00:00:00 2001 From: Judah Vang Date: Tue, 8 Nov 2022 04:02:25 +0800 Subject: [PATCH 0302/1529] CryptoPkg: Sha1 functions causing build errors REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3991 Fix build issue when DiSABLE_SHA1_DEPRECATED_INTERFACES is defined. Percolate the #ifndef DiSABLE_SHA1_DEPRECATED_INTERFACES to all the Sha1 functions. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Nishant C Mistry Signed-off-by: Jian J Wang Signed-off-by: Nishant C Mistry Signed-off-by: Judah Vang Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c b/CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c index f9796b2158..ede9fa8c09 100644 --- a/CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c +++ b/CryptoPkg/Library/BaseHashApiLib/BaseHashApiLib.c @@ -6,7 +6,7 @@ This API, when called, will calculate the Hash using the hashing algorithm specified by PcdHashApiLibPolicy. - Copyright (c) 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2020-2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -33,9 +33,11 @@ HashApiGetContextSize ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1GetContextSize (); break; + #endif case HASH_ALG_SHA256: return Sha256GetContextSize (); @@ -75,9 +77,11 @@ HashApiInit ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1Init (HashContext); break; + #endif case HASH_ALG_SHA256: return Sha256Init (HashContext); @@ -119,9 +123,11 @@ HashApiDuplicate ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1Duplicate (HashContext, NewHashContext); break; + #endif case HASH_ALG_SHA256: return Sha256Duplicate (HashContext, NewHashContext); @@ -165,9 +171,11 @@ HashApiUpdate ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1Update (HashContext, DataToHash, DataToHashLen); break; + #endif case HASH_ALG_SHA256: return Sha256Update (HashContext, DataToHash, DataToHashLen); @@ -209,9 +217,11 @@ HashApiFinal ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1Final (HashContext, Digest); break; + #endif case HASH_ALG_SHA256: return Sha256Final (HashContext, Digest); @@ -255,9 +265,11 @@ HashApiHashAll ( ) { switch (PcdGet32 (PcdHashApiLibPolicy)) { + #ifndef DISABLE_SHA1_DEPRECATED_INTERFACES case HASH_ALG_SHA1: return Sha1HashAll (DataToHash, DataToHashLen, Digest); break; + #endif case HASH_ALG_SHA256: return Sha256HashAll (DataToHash, DataToHashLen, Digest); From a83dc9c21db3e1518327ac395c346e99d4032b38 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 3 Aug 2022 16:28:38 -0400 Subject: [PATCH 0303/1529] Maintainers.txt: Add .github maintainers and reviewers Adds the maintainers and reviewers for the new .github directory being added to hold GitHub workflows files. Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Cc: Sean Brogan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- Maintainers.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Maintainers.txt b/Maintainers.txt index 889990fa56..a2727fa7bd 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -117,6 +117,12 @@ M: Michael Kubacki [makubacki] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] +.github/ +F: .github/ +M: Sean Brogan [spbrogan] +M: Michael Kubacki [makubacki] +R: Michael D Kinney [mdkinney] + .mergify/ F: .mergify/ M: Michael D Kinney [mdkinney] From ccc7fb1d764b5ceb329d94d6c2c52b83948aac57 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 3 Aug 2022 16:19:02 -0400 Subject: [PATCH 0304/1529] .github: Add initial CodeQL config and workflow files REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4115 Adds initial support for enabling CodeQL Code Scanning in this repository per the RFC: https://github.com/tianocore/edk2/discussions/3258 Adds the following new files: - .github/workflows/codql-analysis.yml - The main GitHub workflow file used to setup CodeQL in the repo. - .github/codeql/codeql-config.yml - The main CodeQL configuration file used to customize the queries and other resources the repo is using for CodeQL. - edk2.qls - A query set of queries to run for CodeQL. Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .github/codeql/codeql-config.yml | 30 +++++++++ .github/codeql/edk2.qls | 12 ++++ .github/workflows/codeql-analysis.yml | 91 +++++++++++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 .github/codeql/codeql-config.yml create mode 100644 .github/codeql/edk2.qls create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml new file mode 100644 index 0000000000..3e27c2fb0d --- /dev/null +++ b/.github/codeql/codeql-config.yml @@ -0,0 +1,30 @@ +## @file +# CodeQL configuration file for edk2. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +name: "CodeQL config" + +# The following line disables the default queries. This is used because we want to enable on query at a time by +# explicitly specifying each query in a "queries" array as they are enabled. +# +# See the following for more information about adding custom queries: +# https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-a-custom-configuration-file + +#disable-default-queries: true + +queries: + - name: EDK2 CodeQL Query List + uses: ./.github/codeql/edk2.qls + +# We must specify a query for CodeQL to run. Until the first query is enabled, enable the security query suite but +# exclude all problem levels from impacting the results. After the first query is enabled, this filter can be relaxed +# to find the level of problems desired from the query. +query-filters: +- exclude: + problem.severity: + - error + - warning + - recommendation diff --git a/.github/codeql/edk2.qls b/.github/codeql/edk2.qls new file mode 100644 index 0000000000..0efc7dca52 --- /dev/null +++ b/.github/codeql/edk2.qls @@ -0,0 +1,12 @@ +--- +- description: EDK2 (C++) queries + +# Bring in all queries from the official cpp-queries suite so individual queries can be explicitly enabled. + +- queries: '.' + from: codeql/cpp-queries + +# Enable individual queries below. + +- include: + id: cpp/conditionallyuninitializedvariable diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000000..2eacb9c9e1 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,91 @@ +# @file +# GitHub Workflow for CodeQL Analysis +# +# Copyright (c) Microsoft Corporation. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +name: "CodeQL" + +on: + push: + branches: + - master + pull_request: + branches: + - master + paths-ignore: + - '**/*.bat' + - '**/*.md' + - '**/*.py' + - '**/*.rst' + - '**/*.sh' + - '**/*.txt' + + schedule: + # https://crontab.guru/#20_23_*_*_4 + - cron: '20 23 * * 4' + +jobs: + analyze: + name: Analyze + runs-on: windows-2019 + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + package: [ + "ArmPkg", + "CryptoPkg", + "DynamicTablesPkg", + "FatPkg", + "FmpDevicePkg", + "IntelFsp2Pkg", + "IntelFsp2WrapperPkg", + "MdeModulePkg", + "MdePkg", + "PcAtChipsetPkg", + "PrmPkg", + "SecurityPkg", + "ShellPkg", + "SourceLevelDebugPkg", + "StandaloneMmPkg", + "UefiCpuPkg", + "UnitTestFrameworkPkg"] + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: 'cpp' + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://codeql.github.com/docs/codeql-overview/supported-languages-and-frameworks/ + config-file: ./.github/codeql/codeql-config.yml + # Note: Add new queries to codeql-config.yml file as they are enabled. + + - name: Install/Upgrade pip Modules + run: pip install -r pip-requirements.txt --upgrade + + - name: Setup + run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + + - name: Update + run: stuart_update -c .pytool/CISettings.py -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + + - name: Build Tools From Source + run: python BaseTools/Edk2ToolsBuild.py -t VS2019 + + - name: CI Build + run: stuart_ci_build -c .pytool/CISettings.py -p ${{ matrix.package }} -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 From 0bc4815a978ab978ab1410a32e6ee42c102c3c13 Mon Sep 17 00:00:00 2001 From: Wei6 Xu Date: Mon, 7 Nov 2022 16:29:39 +0800 Subject: [PATCH 0305/1529] PrmPkg/PrmSsdtInstallDxe: Update PRMT Device CID to PNP0C02. REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4141 PRMT device is an unknown device in Device Manager if there is no Windows Driver installed for it. It will cause WHQL Signed Driver test failure. To complete WHQL certification, update PRMT Device CID to PNP0C02. In this way, PRMT Device will be a Motherboard Resources when no real driver is loaded (default), but will be shown as the actual device name when a legitimate Windows Driver is loaded. Cc: Michael Kubacki Cc: Nate DeSimone Cc: Ankit Sinha Signed-off-by: Wei6 Xu Reviewed-by: Ankit Sinha Reviewed-by: Michael Kubacki --- PrmPkg/PrmSsdtInstallDxe/Prm.asl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PrmPkg/PrmSsdtInstallDxe/Prm.asl b/PrmPkg/PrmSsdtInstallDxe/Prm.asl index e34336b4ee..c4c406e93e 100644 --- a/PrmPkg/PrmSsdtInstallDxe/Prm.asl +++ b/PrmPkg/PrmSsdtInstallDxe/Prm.asl @@ -22,7 +22,7 @@ DefinitionBlock ( Device (PRMT) { Name (_HID, "80860223") - Name (_CID, "80860223") + Name (_CID, EisaId ("PNP0C02")) Name (_DDN, "PRM Test Device") //PRM operation region format From 2935809c7462e67289d6a003f73d266a0d82234d Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 5 Nov 2022 12:43:24 -0700 Subject: [PATCH 0306/1529] BaseTools/Source/C: Use /Z7 instead of /Zi for host tools REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4139 Update ms.common and *.mak files to use /Z7 instead of /Zi to embed symbol information in obj files for host tools built with VS compilers. This prevents vcxxx.pdb files from being generated in the root of the local edk2 repository or in BaseTools directories. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- BaseTools/Source/C/Makefiles/ms.common | 5 ++--- BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrDDK.mak | 4 ++-- BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrMS.mak | 6 +++--- BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgDDK.mak | 4 ++-- BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgMS.mak | 7 +++---- 5 files changed, 12 insertions(+), 14 deletions(-) diff --git a/BaseTools/Source/C/Makefiles/ms.common b/BaseTools/Source/C/Makefiles/ms.common index b2dbcf376c..8391f10d5d 100644 --- a/BaseTools/Source/C/Makefiles/ms.common +++ b/BaseTools/Source/C/Makefiles/ms.common @@ -57,6 +57,5 @@ LINKER = $(LD) INC = $(INC) -I . -I $(SOURCE_PATH)\Include -I $(ARCH_INCLUDE) -I $(SOURCE_PATH)\Common -CFLAGS = $(CFLAGS) /nologo /Zi /c /O2 /MT /W4 /WX /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE -CPPFLAGS = $(CPPFLAGS) /EHsc /nologo /Zi /c /O2 /MT /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE - +CFLAGS = $(CFLAGS) /nologo /Z7 /c /O2 /MT /W4 /WX /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE +CPPFLAGS = $(CPPFLAGS) /EHsc /nologo /Z7 /c /O2 /MT /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrDDK.mak b/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrDDK.mak index 71b7c6b0b1..cde91a4715 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrDDK.mak +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrDDK.mak @@ -16,7 +16,7 @@ SET=$(PCCTS_HOME)\support\set # Compiler stuff CC = cl CFLAGS = /nologo -I "." -I "$(PCCTS_H)" -I "$(SET)" -D "USER_ZZSYN" -D "PC" \ - -D "ZZLEXBUFSIZE=65536" -D "LONGFILENAMES" /Zi /W3 -D__USE_PROTOS /wd4700 + -D "ZZLEXBUFSIZE=65536" -D "LONGFILENAMES" /Z7 /W3 -D__USE_PROTOS /wd4700 ANTLR_OBJS = antlr.obj scan.obj err.obj bits.obj build.obj fset2.obj \ fset.obj gen.obj globals.obj hash.obj lex.obj main.obj \ @@ -225,7 +225,7 @@ set.obj: $(SET)\set.c \ $(CC) -c $(CFLAGS) $(SET)\set.c -clean: +clean: del *.obj distclean: diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrMS.mak b/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrMS.mak index b30a73bb74..6fc4d5c15d 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrMS.mak +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/AntlrMS.mak @@ -16,8 +16,8 @@ SET=$(PCCTS_HOME)\support\set # Compiler stuff CC = cl CFLAGS = /nologo -I "." -I "$(PCCTS_H)" -I "$(SET)" -D "USER_ZZSYN" -D "PC" \ - -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /Zi /W3 -D__USE_PROTOS /wd4700 \ - /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE + -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /Z7 /W3 -D__USE_PROTOS /wd4700 \ + /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE ANTLR_OBJS = antlr.obj scan.obj err.obj bits.obj build.obj fset2.obj \ fset.obj gen.obj globals.obj hash.obj lex.obj main.obj \ @@ -226,7 +226,7 @@ set.obj: $(SET)\set.c \ $(CC) -c $(CFLAGS) $(SET)\set.c -clean: +clean: -del *.obj -del *.ilk -del *.pdb diff --git a/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgDDK.mak b/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgDDK.mak index 156d524acc..dcc259543c 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgDDK.mak +++ b/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgDDK.mak @@ -16,7 +16,7 @@ SET=$(PCCTS_HOME)\support\set # Compiler stuff CC = cl CFLAGS = /nologo -I "." -I "$(PCCTS_H)" -I "$(SET)" -D "USER_ZZSYN" -D "PC" \ - -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /W3 /Zi + -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /W3 /Z7 DLG_OBJS = dlg_p.obj dlg_a.obj main.obj err.obj support.obj \ output.obj relabel.obj automata.obj @@ -113,7 +113,7 @@ set.obj: $(SET)\set.c \ $(CC) -c $(CFLAGS) $(SET)\set.c -clean: +clean: del *.obj distclean: diff --git a/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgMS.mak b/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgMS.mak index 2714308d4f..c2cac00f53 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgMS.mak +++ b/BaseTools/Source/C/VfrCompile/Pccts/dlg/DlgMS.mak @@ -16,8 +16,8 @@ SET=$(PCCTS_HOME)\support\set # Compiler stuff CC = cl CFLAGS = /nologo -I "." -I "$(PCCTS_H)" -I "$(SET)" -D "USER_ZZSYN" -D "PC" \ - -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /W3 /Zi \ - /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE + -D "ZZLEXBUFSIZE=65536" /D "LONGFILENAMES" /W3 /Z7 \ + /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE DLG_OBJS = dlg_p.obj dlg_a.obj main.obj err.obj support.obj \ output.obj relabel.obj automata.obj @@ -112,7 +112,7 @@ set.obj: $(SET)\set.c \ $(CC) -c $(CFLAGS) $(SET)\set.c -clean: +clean: -del *.obj -del *.ilk -del *.pdb @@ -123,4 +123,3 @@ cleanall: -del *.pdb -del *.exe -del $(EDK_TOOLS_PATH)\Bin\Win32\dlg.exe - From 6d8c30ee8438e0884aa9abf1741ef1e3110d3308 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 12:17:59 -0500 Subject: [PATCH 0307/1529] BaseTools: Fix wrong type of arguments to formatting functions Fixes issues found with the cpp/wrong-type-format-argument CodeQL rule in BaseTools. Reference: https://cwe.mitre.org/data/definitions/686.html The following CodeQL errors are resolved: 1. Check failure on line 1115 in BaseTools/Source/C/EfiRom/EfiRom.c - This argument should be of type 'int' but is of type 'char *'. - This argument should be of type 'int' but is of type 'signed char *'. 2. Check failure on line 359 in BaseTools/Source/C/GenFw/Elf32Convert.c - This argument should be of type 'CHAR8 *' but is of type 'unsigned int'. 3. Check failure on line 1841 in BaseTools/Source/C/GenFw/Elf64Convert.c - This argument should be of type 'unsigned int' but is of type 'unsigned long long'. 4. Check failure on line 1871 in BaseTools/Source/C/GenFw/Elf64Convert.c - This argument should be of type 'unsigned int' but is of type 'unsigned long long'. 5. Check failure on line 2400 in BaseTools/Source/C/GenFv/GenFvInternalLib.c - This argument should be of type 'unsigned long long' but is of type 'unsigned int'. 6. Check failure on line 1099 in BaseTools/Source/C/GenFw/Elf64Convert.c - This argument should be of type 'CHAR8 *' but is of type 'unsigned int'. 7. Check failure on line 1098 in BaseTools/Source/C/GenSec/GenSec.c - This argument should be of type 'CHAR8 *' but is of type 'char **'. 8. Check failure on line 911 in BaseTools/Source/C/GenSec/GenSec.c - This argument should be of type 'CHAR8 *' but is of type 'char **'. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan Reviewed-by: Michael D Kinney --- BaseTools/Source/C/EfiRom/EfiRom.c | 2 +- BaseTools/Source/C/GenFv/GenFvInternalLib.c | 2 +- BaseTools/Source/C/GenFw/Elf32Convert.c | 2 +- BaseTools/Source/C/GenFw/Elf64Convert.c | 6 +++--- BaseTools/Source/C/GenSec/GenSec.c | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/BaseTools/Source/C/EfiRom/EfiRom.c b/BaseTools/Source/C/EfiRom/EfiRom.c index 2506f559d5..fa7bf0e62e 100644 --- a/BaseTools/Source/C/EfiRom/EfiRom.c +++ b/BaseTools/Source/C/EfiRom/EfiRom.c @@ -1112,7 +1112,7 @@ Routine Description: goto Done; } if (DebugLevel > 9) { - Error (NULL, 0, 2000, "Invalid option value", "Debug Level range is 0-9, current input level is %d", Argv[1]); + Error (NULL, 0, 2000, "Invalid option value", "Debug Level range is 0-9, current input level is %llu", DebugLevel); ReturnStatus = 1; goto Done; } diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index b5b9425003..6bd59515b1 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -2397,7 +2397,7 @@ Routine Description: VerboseMsg("SecCore entry point Address = 0x%llX", (unsigned long long) SecCoreEntryAddress); VerboseMsg("BaseAddress = 0x%llX", (unsigned long long) FvInfo->BaseAddress); bSecCore = (UINT32)(SecCoreEntryAddress - FvInfo->BaseAddress); - VerboseMsg("offset = 0x%llX", bSecCore); + VerboseMsg("offset = 0x%X", bSecCore); if(bSecCore > 0x0fffff) { Error(NULL, 0, 3000, "Invalid", "SEC Entry point must be within 1MB of start of the FV"); diff --git a/BaseTools/Source/C/GenFw/Elf32Convert.c b/BaseTools/Source/C/GenFw/Elf32Convert.c index d917a444c8..87d7f133f1 100644 --- a/BaseTools/Source/C/GenFw/Elf32Convert.c +++ b/BaseTools/Source/C/GenFw/Elf32Convert.c @@ -356,7 +356,7 @@ ScanSections32 ( mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32); break; default: - VerboseMsg ("%s unknown e_machine type. Assume IA-32", (UINTN)mEhdr->e_machine); + VerboseMsg ("%u unknown e_machine type. Assume IA-32", (UINTN)mEhdr->e_machine); mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32); break; } diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index c6092269e2..8b50774beb 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -1096,7 +1096,7 @@ ScanSections64 ( break; default: - VerboseMsg ("%s unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine); + VerboseMsg ("%u unknown e_machine type. Assume X64", (UINTN)mEhdr->e_machine); NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_X64; NtHdr->Pe32Plus.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC; } @@ -1837,7 +1837,7 @@ WriteRelocations64 ( case R_X86_64_REX_GOTPCRELX: break; case R_X86_64_64: - VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08X", + VerboseMsg ("EFI_IMAGE_REL_BASED_DIR64 Offset: 0x%08llX", mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr)); CoffAddFixup( (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info] @@ -1867,7 +1867,7 @@ WriteRelocations64 ( // // case R_X86_64_32S: case R_X86_64_32: - VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08X", + VerboseMsg ("EFI_IMAGE_REL_BASED_HIGHLOW Offset: 0x%08llX", mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr)); CoffAddFixup( (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info] diff --git a/BaseTools/Source/C/GenSec/GenSec.c b/BaseTools/Source/C/GenSec/GenSec.c index a4c2d19aa6..cf24d821aa 100644 --- a/BaseTools/Source/C/GenSec/GenSec.c +++ b/BaseTools/Source/C/GenSec/GenSec.c @@ -908,7 +908,7 @@ Routine Description: if (FileBuffer != NULL) { free (FileBuffer); } - Error (NULL, 0, 2000, "Invalid parameter", "the size of input file %s can't be zero", InputFileName); + Error (NULL, 0, 2000, "Invalid parameter", "the size of input file %s can't be zero", *InputFileName); return EFI_NOT_FOUND; } @@ -1095,7 +1095,7 @@ Routine Description: if (FileBuffer != NULL) { free (FileBuffer); } - Error (NULL, 0, 2000, "Invalid parameter", "the size of input file %s can't be zero", InputFileName); + Error (NULL, 0, 2000, "Invalid parameter", "the size of input file %s can't be zero", *InputFileName); return EFI_NOT_FOUND; } From d082d991f663588ed126dbf0f57bb92e3aec7cee Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 10:19:17 -0500 Subject: [PATCH 0308/1529] edk2.qls: Allow error severity results and add new queries The query cpp/conditionallyuninitializedvariable was initially enabled with the CodeQL code because work was in progress on those changes. The results were filtered out so CodeQL passed so we could verify the CodeQL workflow without impacting CI results. This change allows error severity messages and substitutes that query with two queries that do not return failures. This allows these queries to find future problems and prepares the CodeQL workflow to catch future failures as queries are enabled. Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan Reviewed-by: Michael D Kinney --- .github/codeql/codeql-config.yml | 1 - .github/codeql/edk2.qls | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml index 3e27c2fb0d..a51db141eb 100644 --- a/.github/codeql/codeql-config.yml +++ b/.github/codeql/codeql-config.yml @@ -25,6 +25,5 @@ queries: query-filters: - exclude: problem.severity: - - error - warning - recommendation diff --git a/.github/codeql/edk2.qls b/.github/codeql/edk2.qls index 0efc7dca52..ef9aae790f 100644 --- a/.github/codeql/edk2.qls +++ b/.github/codeql/edk2.qls @@ -9,4 +9,6 @@ # Enable individual queries below. - include: - id: cpp/conditionallyuninitializedvariable + id: cpp/infinite-loop-with-unsatisfiable-exit-condition +- include: + id: cpp/overflow-buffer From 381a502170494b26705c0e93254912f4a921af7d Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Wed, 9 Nov 2022 20:21:16 -0800 Subject: [PATCH 0309/1529] pip-requirements.txt: Update edk2-pytool-library to 0.12.0 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4146 Update edk2-pytool-library to version 0.12.0 that adds support for the environment variable PYTOOL_TEMPORARILY_IGNORE_NESTED_EDK_PACKAGES that can be set to true to ignore nested packages instead of breaking the build with an exception. Nested packages are not allowed by the edk2 specifications. This environment variable allows pytools to run with reduced functionality if nested packages are present giving downstream consumers of edk2 that use pytools time to resolve the use of nested packages and restore all features of pytools. Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Cc: Andrew Fish Cc: Leif Lindholm Signed-off-by: Michael D Kinney --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 74d1bb35f2..d7e6b536f9 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -12,7 +12,7 @@ # https://www.python.org/dev/peps/pep-0440/#version-specifiers ## -edk2-pytool-library==0.11.6 +edk2-pytool-library==0.12.0 edk2-pytool-extensions~=0.19.1 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 From a3217fe15b4fa84963a05c461779fe89936c7606 Mon Sep 17 00:00:00 2001 From: Sainadh Nagolu Date: Fri, 4 Nov 2022 16:23:08 +0530 Subject: [PATCH 0310/1529] ShellPkg:Improved Smbios Type9 data under smbiosview REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4135 Added spec version check while publishing new Type9 fields, added Slot Pitch field which was missing and corrected the publishing order as per Smbios spec. Cc: Vasudevan S Cc: Sundaresan S Signed-off-by: Sainadh Nagolu Reviewed-by: Liming Gao --- .../SmbiosView/PrintInfo.c | 17 +++++++++++------ .../SmbiosView/SmbiosViewStrings.uni | 2 ++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c index bf5306205b..e936ee8ea9 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c @@ -638,12 +638,17 @@ SmbiosPrintStructure ( ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_DATA_BUS_WIDTH), gShellDebug1HiiHandle, PeerGroupPtr[Index].DataBusWidth); } - // Since PeerGroups has a variable number of entries, new fields added after PeerGroups are defined in - // a extended structure. Those fields can be referenced using SMBIOS_TABLE_TYPE9_EXTENDED structure. - Type9ExtendedStruct = (SMBIOS_TABLE_TYPE9_EXTENDED *)((UINT8 *)PeerGroupPtr + (PeerGroupCount * sizeof (MISC_SLOT_PEER_GROUP))); - DisplaySystemSlotHeight (Type9ExtendedStruct->SlotHeight, Option); - DisplaySystemSlotPhysicalWidth (Type9ExtendedStruct->SlotPhysicalWidth, Option); - DisplaySystemSlotInformation (Type9ExtendedStruct->SlotInformation, Option); + if (AE_SMBIOS_VERSION (0x3, 0x4)) { + // Since PeerGroups has a variable number of entries, new fields added after PeerGroups are defined in + // a extended structure. Those fields can be referenced using SMBIOS_TABLE_TYPE9_EXTENDED structure. + Type9ExtendedStruct = (SMBIOS_TABLE_TYPE9_EXTENDED *)((UINT8 *)PeerGroupPtr + (PeerGroupCount * sizeof (MISC_SLOT_PEER_GROUP))); + DisplaySystemSlotInformation (Type9ExtendedStruct->SlotInformation, Option); + DisplaySystemSlotPhysicalWidth (Type9ExtendedStruct->SlotPhysicalWidth, Option); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PITCH), gShellDebug1HiiHandle, Type9ExtendedStruct->SlotPitch); + if (AE_SMBIOS_VERSION (0x3, 0x5)) { + DisplaySystemSlotHeight (Type9ExtendedStruct->SlotHeight, Option); + } + } } } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni index 68211ce7ab..1ab0e3dd60 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni @@ -1,6 +1,7 @@ // /** // // Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved.
+// Copyright (c) 1985 - 2022, American Megatrends International LLC.
// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
// (C) Copyright 2015-2019 Hewlett Packard Enterprise Development LP
// SPDX-License-Identifier: BSD-2-Clause-Patent @@ -417,6 +418,7 @@ #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_INFORMATION #language en-US "System Slot Information: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_HEIGHT #language en-US "System Slot Height: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PHYSICAL_WIDTH #language en-US "System Slot Physical Width: " +#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PITCH #language en-US "System Slot Pitch: %d\r\n" #string STR_SMBIOSVIEW_QUERYTABLE_ONBOARD_DEVICE_TYPE #language en-US "Onboard Device Type: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_EVENT_LOG_TYPE #language en-US "System Event Log Type: " #string STR_SMBIOSVIEW_QUERYTABLE_EVENT_LOG_VAR_DATA_FORMAT #language en-US "Event Log Variable Data Format Types: " From 109fe3d13f190d1eaf0587c74882ca6d24785cc0 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 10 Nov 2022 17:44:53 -0800 Subject: [PATCH 0311/1529] .github/workflows: Update CodeQL to install Python 3.10.6 Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki --- .github/workflows/codeql-analysis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 2eacb9c9e1..791f79d1f0 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -62,6 +62,11 @@ jobs: - name: Checkout repository uses: actions/checkout@v3 + - name: Install Python + uses: actions/setup-python@v4 + with: + python-version: '3.10.6' + # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 From fda9ab6cd555780e40af892397471be09a9a7cad Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 10 Nov 2022 21:47:36 +0800 Subject: [PATCH 0312/1529] ArmPkg/ArmTrngLib: Fix incorrect GUID reference in DEBUG() output ArmTrngLib crashes when run in DEBUG mode due to the fact that it passed the [truncated] GUID value to a DEBUG() print statement instead of a pointer to the GUID which is what the %g conversion expects. Signed-off-by: Ard Biesheuvel Reviewed-by: Sami Mujawar --- ArmPkg/Library/ArmTrngLib/ArmTrngLib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c index b974a94238..fdabc02cd3 100644 --- a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c @@ -375,7 +375,7 @@ ArmTrngLibConstructor ( "FW-TRNG: Version %d.%d, GUID {%g}\n", MajorRev, MinorRev, - Guid + &Guid )); DEBUG_CODE_END (); From 2fdbec6d90fe273c02508a1ed75cb81cbc53d217 Mon Sep 17 00:00:00 2001 From: "Kuo, Ted" Date: Wed, 9 Nov 2022 03:30:57 -0800 Subject: [PATCH 0313/1529] IntelFsp2Pkg: Improvement of supporting null UPD pointer in FSP-T REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4114 1.Use xmm5 slot 1 and xmm6 slot 3 to save ucode status and UPD pointer respectively in TempRamInitApi in IA32 FspSecCoreT. 2.Correct inappropriate description in the return value of AsmGetFspInfoHeader. 3.Replace hardcoded offset value 0x1C with FSP_HEADER_IMGBASE_OFFSET in FspHeler.nasm. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Cc: Ashraf Ali S Cc: Chinni B Duggapu Signed-off-by: Ted Kuo Reviewed-by: Chasel Chiu Reviewed-by: Nate DeSimone --- .../FspSecCore/Ia32/FspApiEntryT.nasm | 17 +++-- IntelFsp2Pkg/FspSecCore/Ia32/FspHelper.nasm | 4 +- .../FspSecCore/Ia32/SaveRestoreSseNasm.inc | 74 ++++++++++--------- IntelFsp2Pkg/FspSecCore/SecFsp.h | 2 +- IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm | 4 +- 5 files changed, 55 insertions(+), 46 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm index 73821ad22a..2cff8b3643 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm @@ -594,37 +594,38 @@ ASM_PFX(TempRamInitApi): SAVE_EAX SAVE_EDX + CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param + SAVE_ECX ; save UPD param to slot 3 in xmm6 + ; ; Sec Platform Init ; - CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param CALL_MMX ASM_PFX(SecPlatformInit) cmp eax, 0 jnz TempRamInitExit ; Load microcode LOAD_ESP - CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param + LOAD_ECX CALL_MMX ASM_PFX(LoadMicrocodeDefault) - SXMMN xmm6, 3, eax ;Save microcode return status in ECX-SLOT 3 in xmm6. + SAVE_UCODE_STATUS ; Save microcode return status in slot 1 in xmm5. ;@note If return value eax is not 0, microcode did not load, but continue and attempt to boot. ; Call Sec CAR Init LOAD_ESP - CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param + LOAD_ECX CALL_MMX ASM_PFX(SecCarInit) cmp eax, 0 jnz TempRamInitExit LOAD_ESP - CALL_EBP ASM_PFX(LoadUpdPointerToECX) ; ECX for UPD param - mov edi, ecx ; Save UPD param to EDI for later code use + LOAD_ECX + mov edi, ecx ; Save UPD param to EDI for later code use CALL_MMX ASM_PFX(EstablishStackFsp) cmp eax, 0 jnz TempRamInitExit - LXMMN xmm6, eax, 3 ;Restore microcode status if no CAR init error from ECX-SLOT 3 in xmm6. - SXMMN xmm6, 3, edi ;Save FSP-T UPD parameter pointer in ECX-SLOT 3 in xmm6. + LOAD_UCODE_STATUS ; Restore microcode status if no CAR init error from slot 1 in xmm5. TempRamInitExit: mov bl, al ; save al data in bl diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/FspHelper.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/FspHelper.nasm index e3e1945473..3c63f6eea5 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/FspHelper.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/FspHelper.nasm @@ -7,6 +7,8 @@ SECTION .text +FSP_HEADER_IMGBASE_OFFSET EQU 1Ch + global ASM_PFX(FspInfoHeaderRelativeOff) ASM_PFX(FspInfoHeaderRelativeOff): DD 0x12345678 ; This value must be patched by the build script @@ -14,7 +16,7 @@ ASM_PFX(FspInfoHeaderRelativeOff): global ASM_PFX(AsmGetFspBaseAddress) ASM_PFX(AsmGetFspBaseAddress): call ASM_PFX(AsmGetFspInfoHeader) - add eax, 0x1C + add eax, FSP_HEADER_IMGBASE_OFFSET mov eax, dword [eax] ret diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc b/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc index 4c321cbece..a222f2e376 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc +++ b/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc @@ -1,6 +1,6 @@ ;------------------------------------------------------------------------------ ; -; Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+; Copyright (c) 2015 - 2022, Intel Corporation. All rights reserved.
; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Abstract: @@ -16,21 +16,21 @@ ; ; Define SSE macros using SSE 4.1 instructions ; args 1:XMM, 2:IDX, 3:REG -%macro SXMMN 3 +%macro SXMMN 3 pinsrd %1, %3, (%2 & 3) %endmacro ; ;args 1:XMM, 2:REG, 3:IDX ; -%macro LXMMN 3 +%macro LXMMN 3 pextrd %2, %1, (%3 & 3) %endmacro %else ; ; Define SSE macros using SSE 2 instructions ; args 1:XMM, 2:IDX, 3:REG -%macro SXMMN 3 +%macro SXMMN 3 pinsrw %1, %3, (%2 & 3) * 2 ror %3, 16 pinsrw %1, %3, (%2 & 3) * 2 + 1 @@ -38,19 +38,19 @@ %endmacro ; -;args 1:XMM, 2:REG, 3:IDX +;args 1:XMM, 2:REG, 3:IDX ; %macro LXMMN 3 - pshufd %1, %1, ((0E4E4E4h >> (%3 * 2)) & 0FFh) + pshufd %1, %1, ((0E4E4E4h >> (%3 * 2)) & 0FFh) movd %2, %1 - pshufd %1, %1, ((0E4E4E4h >> (%3 * 2 + (%3 & 1) * 4)) & 0FFh) + pshufd %1, %1, ((0E4E4E4h >> (%3 * 2 + (%3 & 1) * 4)) & 0FFh) %endmacro %endif ; -; XMM7 to save/restore EBP, EBX, ESI, EDI +; XMM7 to save/restore EBP - slot 0, EBX - slot 1, ESI - slot 2, EDI - slot 3 ; -%macro SAVE_REGS 0 +%macro SAVE_REGS 0 SXMMN xmm7, 0, ebp SXMMN xmm7, 1, ebx SXMMN xmm7, 2, esi @@ -67,63 +67,67 @@ %endmacro ; -; XMM6 to save/restore EAX, EDX, ECX, ESP +; XMM6 to save/restore ESP - slot 0, EAX - slot 1, EDX - slot 2, ECX - slot 3 ; -%macro LOAD_EAX 0 +%macro LOAD_ESP 0 + movd esp, xmm6 + %endmacro + +%macro SAVE_ESP 0 + SXMMN xmm6, 0, esp + %endmacro + +%macro LOAD_EAX 0 LXMMN xmm6, eax, 1 %endmacro -%macro SAVE_EAX 0 +%macro SAVE_EAX 0 SXMMN xmm6, 1, eax %endmacro -%macro LOAD_EDX 0 +%macro LOAD_EDX 0 LXMMN xmm6, edx, 2 %endmacro -%macro SAVE_EDX 0 +%macro SAVE_EDX 0 SXMMN xmm6, 2, edx %endmacro -%macro SAVE_ECX 0 - SXMMN xmm6, 3, ecx - %endmacro - -%macro LOAD_ECX 0 +%macro LOAD_ECX 0 LXMMN xmm6, ecx, 3 %endmacro -%macro SAVE_ESP 0 - SXMMN xmm6, 0, esp +%macro SAVE_ECX 0 + SXMMN xmm6, 3, ecx %endmacro -%macro LOAD_ESP 0 - movd esp, xmm6 - %endmacro ; -; XMM5 for calling stack +; XMM5 slot 0 for calling stack ; arg 1:Entry %macro CALL_XMM 1 mov esi, %%ReturnAddress - pslldq xmm5, 4 -%ifdef USE_SSE41_FLAG - pinsrd xmm5, esi, 0 -%else - pinsrw xmm5, esi, 0 - ror esi, 16 - pinsrw xmm5, esi, 1 -%endif + SXMMN xmm5, 0, esi mov esi, %1 jmp esi %%ReturnAddress: %endmacro %macro RET_XMM 0 - movd esi, xmm5 - psrldq xmm5, 4 + LXMMN xmm5, esi, 0 jmp esi %endmacro +; +; XMM5 slot 1 for uCode status +; +%macro LOAD_UCODE_STATUS 0 + LXMMN xmm5, eax, 1 + %endmacro + +%macro SAVE_UCODE_STATUS 0 + SXMMN xmm5, 1, eax + %endmacro + %macro ENABLE_SSE 0 ; ; Initialize floating point units diff --git a/IntelFsp2Pkg/FspSecCore/SecFsp.h b/IntelFsp2Pkg/FspSecCore/SecFsp.h index d7a5976c12..693af29f20 100644 --- a/IntelFsp2Pkg/FspSecCore/SecFsp.h +++ b/IntelFsp2Pkg/FspSecCore/SecFsp.h @@ -79,7 +79,7 @@ AsmGetFspBaseAddress ( /** This interface gets FspInfoHeader pointer - @return FSP binary base address. + @return FSP info header. **/ UINTN diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm index 122fa1d174..71624a3aad 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm @@ -7,10 +7,12 @@ DEFAULT REL SECTION .text +FSP_HEADER_IMGBASE_OFFSET EQU 1Ch + global ASM_PFX(AsmGetFspBaseAddress) ASM_PFX(AsmGetFspBaseAddress): call ASM_PFX(AsmGetFspInfoHeader) - add rax, 0x1C + add rax, FSP_HEADER_IMGBASE_OFFSET mov eax, [rax] ret From 0fa908e8467d2ece4767c2a1fa18f3711f5e9a1f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 21 Jun 2022 12:30:07 -0700 Subject: [PATCH 0314/1529] MdePkg/Include: Update Base.h to improve C++ compatibility REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 * Map NULL to nullptr or __null when c++ compiler is used. * Map STATIC_ASSERT to static_assert when a c++ compiler is used. * Typecast RETURN_SUCCESS to type RETURN_STATUS to match type used by all return error/warning status codes. C++ has stricter type checking and found this inconsistency. Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- MdePkg/Include/Base.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/Base.h b/MdePkg/Include/Base.h index d19ddfe4bb..d209e6de28 100644 --- a/MdePkg/Include/Base.h +++ b/MdePkg/Include/Base.h @@ -309,7 +309,15 @@ struct _LIST_ENTRY { /// /// NULL pointer (VOID *) /// +#if defined (__cplusplus) + #if defined (_MSC_EXTENSIONS) +#define NULL nullptr + #else +#define NULL __null + #endif +#else #define NULL ((VOID *) 0) +#endif // // Null character @@ -760,7 +768,7 @@ typedef UINTN *BASE_LIST; **/ #ifdef MDE_CPU_EBC #define STATIC_ASSERT(Expression, Message) -#elif defined (_MSC_EXTENSIONS) +#elif defined (_MSC_EXTENSIONS) || defined (__cplusplus) #define STATIC_ASSERT static_assert #else #define STATIC_ASSERT _Static_assert @@ -959,7 +967,7 @@ typedef UINTN RETURN_STATUS; /// /// The operation completed successfully. /// -#define RETURN_SUCCESS 0 +#define RETURN_SUCCESS (RETURN_STATUS)(0) /// /// The image failed to load. From 8f5cb0870b201dbf093782d993e6c32ae0daf26d Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 11 Oct 2022 12:03:48 -0700 Subject: [PATCH 0315/1529] MdePkg/Include/Library: Undefine _ASSERT() if already defined REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 When unit testing is enabled, make sure _ASSERT() is not already defined by the host environment before defining _ASSERT(). This avoids conflicts with VS20xx builds of GoogleTest based unit tests. Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- MdePkg/Include/Library/DebugLib.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MdePkg/Include/Library/DebugLib.h b/MdePkg/Include/Library/DebugLib.h index 8d3d08638d..9110be2f41 100644 --- a/MdePkg/Include/Library/DebugLib.h +++ b/MdePkg/Include/Library/DebugLib.h @@ -337,6 +337,9 @@ UnitTestDebugAssert ( IN CONST CHAR8 *Description ); + #if defined (_ASSERT) + #undef _ASSERT + #endif #if defined (__clang__) && defined (__FILE_NAME__) #define _ASSERT(Expression) UnitTestDebugAssert (__FILE_NAME__, DEBUG_LINE_NUMBER, DEBUG_EXPRESSION_STRING (Expression)) #else From afcf580a4f08c94e96c7faabc1fbcfcea6bd8430 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 20 Jun 2022 19:52:03 -0700 Subject: [PATCH 0316/1529] UnitTestFrameworkPkg: Add googletest submodule and GoogleTestLib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 Add submodule for googletest and add GoogleTestLib that is required for GoogleTest based unit tests. Add GoogleTest documentation to Readme.md along with a port of the sample unit test to the GoogleTest style. A few typos in Readme.md are also fixed. Cc: Michael Kubacki Cc: Sean Brogan Cc: Andrew Fish Cc: Leif Lindholm Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki Acked-by: Leif Lindholm --- .gitmodules | 3 + ReadMe.rst | 1 + .../Include/Library/GoogleTestLib.h | 14 + .../Library/GoogleTestLib/GoogleTestLib.inf | 36 +++ .../Library/GoogleTestLib/GoogleTestLib.uni | 14 + .../Library/GoogleTestLib/googletest | 1 + UnitTestFrameworkPkg/ReadMe.md | 255 +++++++++++++++-- .../SampleGoogleTest/SampleGoogleTest.cpp | 263 ++++++++++++++++++ .../SampleGoogleTest/SampleGoogleTestHost.inf | 35 +++ .../Test/UnitTestFrameworkPkgHostTest.dsc | 4 +- .../UnitTestFrameworkPkg.ci.yaml | 4 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 8 + .../UnitTestFrameworkPkgHost.dsc.inc | 4 +- 13 files changed, 611 insertions(+), 31 deletions(-) create mode 100644 UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h create mode 100644 UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf create mode 100644 UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni create mode 160000 UnitTestFrameworkPkg/Library/GoogleTestLib/googletest create mode 100644 UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTest.cpp create mode 100644 UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf diff --git a/.gitmodules b/.gitmodules index b845c9ee3f..8011a88d9d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -20,3 +20,6 @@ [submodule "RedfishPkg/Library/JsonLib/jansson"] path = RedfishPkg/Library/JsonLib/jansson url = https://github.com/akheron/jansson +[submodule "UnitTestFrameworkPkg/Library/GoogleTestLib/googletest"] + path = UnitTestFrameworkPkg/Library/GoogleTestLib/googletest + url = https://github.com/google/googletest.git diff --git a/ReadMe.rst b/ReadMe.rst index 8f5db11281..497d963559 100644 --- a/ReadMe.rst +++ b/ReadMe.rst @@ -93,6 +93,7 @@ that are covered by additional licenses. - `MdeModulePkg/Library/BrotliCustomDecompressLib/brotli `__ - `MdeModulePkg/Universal/RegularExpressionDxe/oniguruma `__ - `UnitTestFrameworkPkg/Library/CmockaLib/cmocka `__ +- `UnitTestFrameworkPkg/Library/GoogleTestLib/googletest `__ - `RedfishPkg/Library/JsonLib/jansson `__ The EDK II Project is composed of packages. The maintainers for each package diff --git a/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h b/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h new file mode 100644 index 0000000000..ebec766d4c --- /dev/null +++ b/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h @@ -0,0 +1,14 @@ +/** @file + GoogleTestLib class with APIs from the googletest project + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef GOOGLE_TEST_LIB_H_ +#define GOOGLE_TEST_LIB_H_ + +#include + +#endif diff --git a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf new file mode 100644 index 0000000000..68db75d702 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf @@ -0,0 +1,36 @@ +## @file +# This module provides GoogleTest Library implementation. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = GoogleTestLib + MODULE_UNI_FILE = GoogleTestLib.uni + FILE_GUID = A90E4751-AD30-43CC-980B-01E356B49ADF + MODULE_TYPE = BASE + VERSION_STRING = 0.1 + LIBRARY_CLASS = GoogleTestLib|HOST_APPLICATION + +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + googletest/googletest/src/gtest-all.cc + +[Packages] + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS == /c /EHsc /Zi + MSFT:NOOPT_*_*_CC_FLAGS = /Od + + GCC:*_*_*_CC_FLAGS == -g -c + + GCC:NOOPT_*_*_CC_FLAGS = -O0 + GCC:*_*_IA32_CC_FLAGS = -m32 + GCC:*_*_X64_CC_FLAGS = -m64 diff --git a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni new file mode 100644 index 0000000000..14c862a237 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni @@ -0,0 +1,14 @@ +// /** @file +// This module provides GoogleTest Library implementation. +// +// This module provides GoogleTest Library implementation. +// +// Copyright (c) 2022, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "GoogleTest Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides GoogleTest Library implementation." diff --git a/UnitTestFrameworkPkg/Library/GoogleTestLib/googletest b/UnitTestFrameworkPkg/Library/GoogleTestLib/googletest new file mode 160000 index 0000000000..86add13493 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/GoogleTestLib/googletest @@ -0,0 +1 @@ +Subproject commit 86add13493e5c881d7e4ba77fb91c1f57752b3a4 diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index e696412cb3..9ce04b7f3e 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -2,12 +2,67 @@ ## About -This package adds a unit test framework capable of building tests for multiple contexts including +This package provides unit test frameworks capable of building tests for multiple contexts including the UEFI shell environment and host-based environments. It allows for unit test development to focus -on the tests and leave error logging, result formatting, context persistance, and test running to the framework. +on the tests and leave error logging, result formatting, context persistence, and test running to the framework. The unit test framework works well for low level unit tests as well as system level tests and fits easily in automation frameworks. +### Framework + +The first unit test framework is called **Framework** and is implemented as a set of EDK II libraries. +The Framework supports both host-based unit tests and target-based unit tests that share the same +source style, macros, and APIs. In some scenarios, the same unit test case sources can be built +for both host-based unit test execution and target-based unit test execution. Host-based unit tests +that require mocked interfaces can use the mocking infrastructure provided by +[cmocka](https://api.cmocka.org/) that is included in the UnitTestFrameworkPkg as a submodule. + +### GoogleTest + +The second unit test framework supported by the UnitTestFrameworkPkg is +[GoogleTest](http://google.github.io/googletest/) that can be used to implement host-based unit tests. +Use of GoogleTest for target-based unit tests of EDK II components is not supported. If a +host-based unit test requires mocked interfaces, then the Framework with cmocka support should be +used instead. Enabling support for mocked interfaces with GoogleTest is being actively investigated. +[GoogleTest on GitHub](https://github.com/google/googletest) is included in the UnitTestFrameworkPkg +as a submodule. + +GoogleTest requires less overhead to register test suites and test cases compared to the Framework. +There are also a number of tools that layer on top of GoogleTest that improve developer productivity. +One example is the VS Code extension +[C++ TestMate](https://marketplace.visualstudio.com/items?itemName=matepek.vscode-catch2-test-adapter) +that may be used to implement, run, and debug unit tests implemented using GoogleTest. + +If a component can be tested with host-based unit tests without support for mocked interfaces, +then GoogleTest is recommended. The MdePkg contains a port of the BaseSafeIntLib unit tests in +the GoogleTest style so the differences between GoogleTest and Framework unit tests can be reviewed. +The paths to the BaseSafeIntLib unit tests are: + +* MdePkg\Test\UnitTest\Library\BaseSafeIntLib +* MdePkg\Test\GoogleTest\Library\BaseSafeIntLib + +## Framework and GoogleTest Feature Comparison + +| Feature | Framework | GoogleTest | +|:----------------------------|:---------:|:----------:| +| Host Based Unit Tests | YES | YES | +| Target Based Unit Tests | YES | NO | +| Unit Test Source Language | C | C++ | +| Register Test Suite | YES | Auto | +| Register Test Case | YES | Auto | +| Death/Expected Assert Tests | YES | YES | +| Setup/Teardown Hooks | YES | YES | +| Value-Parameterized Tests | NO | YES | +| Typed Tests | NO | YES | +| Type-Parameterized Tests | NO | YES | +| Timeout Support | NO | YES | +| Mocking Support | Cmocka | NO | +| JUNIT XML Reports | YES | YES | +| Execute subset of tests | NO | YES | +| VS Code Extensions | NO | YES | + +## Framework Libraries + ### UnitTestLib The main "framework" library. The core of the framework is the Framework object, which can have any number @@ -31,10 +86,10 @@ in supporting a system reboot in the middle of a test run. Library provides function to run at the end of a framework test run and handles formatting the report. This is a common customization point and allows the unit test framework to fit its output reports into -other test infrastructure. In this package a simple library instances has been supplied to output test +other test infrastructure. In this package simple library instances have been supplied to output test results to the console as plain text. -## Samples +## Framework Samples There is a sample unit test provided as both an example of how to write a unit test and leverage many of the features of the framework. This sample can be found in the `Test/UnitTest/Sample/SampleUnitTest` @@ -43,7 +98,7 @@ directory. The sample is provided in PEI, SMM, DXE, and UEFI App flavors. It also has a flavor for the HOST_APPLICATION build type, which can be run on a host system without needing a target. -## Usage +## Framework Usage This section is built a lot like a "Getting Started". We'll go through some of the components that are needed when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe @@ -51,7 +106,7 @@ how to check for expected conditions in test cases and a bit of the logging char Most of these examples will refer to the SampleUnitTestUefiShell app found in this package. -### Requirements - INF +### Framework Requirements - INF In our INF file, we'll need to bring in the `UnitTestLib` library. Conveniently, the interface header for the `UnitTestLib` is located in `MdePkg`, so you shouldn't need to depend on any other @@ -80,7 +135,7 @@ to make sure that the module `BASE_NAME` contains the word `Test`... BASE_NAME = SampleUnitTestUefiShell ``` -### Requirements - Code +### Framework Requirements - Code Not to state the obvious, but let's make sure we have the following include before getting too far along... @@ -90,9 +145,9 @@ Not to state the obvious, but let's make sure we have the following include befo Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). -### Configuring the Framework +### Framework Configuration -Everything in the UnitTestPkg framework is built around an object called -- conveniently -- the Framework. +Everything in the UnitTestFrameworkPkg framework is built around an object called -- conveniently -- the Framework. This Framework object will contain all the information about our test, the test suites and test cases associated with it, the current location within the test pass, and any results that have been recorded so far. @@ -102,7 +157,7 @@ The long name and version strings are just for user presentation and relatively will be used to name any cache files and/or test results, so should be a name that makes sense in that context. These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. -In the 'SampleUnitTestUefiShell' app, the module name is used as the short name, so the init looks like this. +In the 'SampleUnitTestUefiShell' app, the module name is used as the short name, so the initialization looks like this. ```c DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); @@ -144,11 +199,11 @@ will be used when adding test cases. Great! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; a `CHAR8` string for the description and class name; a function pointer for the test case itself; additional, optional -function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. +function pointers for prerequisite check and cleanup routines; and an optional pointer to a context structure. Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in usage to the suite title and package name strings in the test suites. The former is for user presentation and the -latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the +latter is for xUnit parsing. The test case function pointer is what is executed as the "test" and the prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining. The prerequisite check function has a prototype of `UNIT_TEST_PREREQUISITE` and -- if provided -- will be called @@ -180,7 +235,7 @@ Once all the suites and cases are added, it's time to run the Framework. Status = RunAllTestSuites( Framework ); ``` -### A Simple Test Case +### Framework - A Simple Test Case We'll take a look at the below test case from 'SampleUnitTestApp'... @@ -217,9 +272,9 @@ _Note_ that this early return can have implications for memory leakage. At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. -### More Complex Cases +### Framework - More Complex Cases -To write more advanced tests, first take a look at all the Assertion and Logging macros provided in the framework. +To write more advanced tests, first look at all the Assertion and Logging macros provided in the framework. Beyond that, if you're writing host-based tests and want to take a dependency on the UnitTestFrameworkPkg, you can leverage the `cmocka.h` interface and write tests with all the features of the Cmocka framework. @@ -227,6 +282,125 @@ leverage the `cmocka.h` interface and write tests with all the features of the C Documentation for Cmocka can be found here: https://api.cmocka.org/ +## GoogleTest Samples + +There is a sample unit test provided as both an example of how to write a unit test and leverage +many of the GoogleTest features. This sample can be found in the `Test/GoogleTest/Sample/SampleGoogleTest` +directory. + +The sample is provided for the HOST_APPLICATION build type, which can be run on a host system without +needing a target. + +## GoogleTest Usage + +This section is built a lot like a "Getting Started". We'll go through some of the components that are needed +when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe +how to check for expected conditions in test cases and a bit of the logging characteristics. + +Most of these examples will refer to the SampleGoogleTestHost app found in this package. + +### GoogleTest Requirements - INF + +In our INF file, we'll need to bring in the `GoogleTest` library. Conveniently, the interface +header for the `GoogleTest` is in `UnitTestFrameworkPkg`, so you shouldn't need to depend on any other +packages. As long as your DSC file knows where to find the lib implementation that you want to use, +you should be good to go. + +See this example in 'SampleGoogleTestHost.inf'... + +``` +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + BaseLib + DebugLib +``` + +Also, if you want you test to automatically be picked up by the Test Runner plugin, you will need +to make sure that the module `BASE_NAME` contains the word `Test`... + +``` +[Defines] + BASE_NAME = SampleGoogleTestHost +``` + +### GoogleTest Requirements - Code + +Not to state the obvious, but let's make sure we have the following include before getting too far along... + +``` +#include +extern "C" { + #include + #include + #include +} +``` + +GoogleTest applications are implemented in C++. The first include brings in the +GoogleTest definitions. Other EDK II related include files must be wrapped in +`extern "C" {}` because they are C include files. Link failures will occur if +this is not done. + +Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). + +### GoogleTest Configuration + +Unlike the Framework, GoogleTest does not require test suites or test cases to +be registered. Instead, the test cases declare the test suite name and test +case name as part of their implementation. The only requirement for GoogleTest +is to have a `main()` function that initialize the GoogleTest infrastructure and +call the service `RUN_ALL_TESTS()` to run all the unit tests. + +```c +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +### GoogleTest - A Simple Test Case + +We'll look at the below test case from 'SampleGoogleTestHost'... + +```c +TEST(SimpleMathTests, OnePlusOneShouldEqualTwo) { + UINTN A; + UINTN B; + UINTN C; + + A = 1; + B = 1; + C = A + B; + + ASSERT_EQ (C, 2); +} +``` + +This uses the simplest form of a GoogleTest unit test using `TEST()` that +declares the test suite name and the unit test name within that test suite. +The unit test performs actions and typically makes calls to the code under test +and contains test assertions to verify that the code under test behaves as +expected for the given inputs. + +In this test case, the `ASSERT_EQ` assertion is being used to establish that the business logic has functioned +correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your +intended test criterium as possible, because the logging is specific to the macro and more specific macros have more +detailed logs. When in doubt, there are always `ASSERT_TRUE` and `ASSERT_FALSE`. Assertion macros that fail their +test criterium will immediately return from the test case with a failed status and log an error string. +_Note_ that this early return can have implications for memory leakage. + +There is no return status from a GooglTest unit test. If no assertions are +triggered then the unit test has a passing status. + +### GoogleTest - More Complex Cases + +To write more advanced tests, take a look at the +[GoogleTest User's Guide](http://google.github.io/googletest/). + ## Development ### Iterating on a Single Test @@ -243,11 +417,11 @@ stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOP ### Hooking BaseLib -Most unit test mocking can be performed by the functions provided in the UnitTestFramework libraries, but since +Most unit test mocking can be performed by the functions provided in the UnitTestFrameworkPkg libraries, but since BaseLib is consumed by the Framework itself, it requires different techniques to substitute parts of the functionality. -To solve some of this, the UnitTestFramework consumes a special implementation of BaseLib for host-based tests. +To solve some of this, the UnitTestFrameworkPkg consumes a special implementation of BaseLib for host-based tests. This implementation contains a [hook table](https://github.com/tianocore/edk2/blob/e188ecc8b4aed8fdd26b731d43883861f5e5e7b4/MdePkg/Test/UnitTest/Include/Library/UnitTestHostBaseLib.h#L507) that can be used to substitute test functionality for any of the BaseLib functions. By default, this implementation will use the underlying BaseLib implementation, so the unit test writer only has to supply minimal code to test a @@ -255,7 +429,7 @@ particular case. ### Debugging the Framework Itself -While most of the tests that are produced by the UnitTestFramework are easy to step through in a debugger, the Framework +While most of the tests that are produced by the UnitTestFrameworkPkg are easy to step through in a debugger, the Framework itself consumes code (mostly Cmocka) that sets its own build flags. These flags cause parts of the Framework to not export symbols and captures exceptions, and as such are harder to debug. We have provided a Stuart parameter to force symbolic debugging to be enabled. @@ -269,15 +443,17 @@ stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2019 -p MdePkg -t NOOP ## Building and Running Host-Based Tests The EDK2 CI infrastructure provides a convenient way to run all host-based tests -- in the the entire tree or just -selected packages -- and aggregate all the the reports, including highlighting any failures. This functionality is -provided through the Stuart build system (published by EDK2-PyTools) and the `NOOPT` build target. +selected packages -- and aggregate all the reports, including highlighting any failures. This functionality is +provided through the Stuart build system (published by EDK2-PyTools) and the `NOOPT` build target. The sections that +follow use Framework examples. Unit tests based on GoogleTest are built and run the same way. The text output and +JUNIT XML output format have small differences. ### Building Locally First, to make sure you're working with the latest PyTools, run the following command: ```bash -# Would recommend to run this in a Python venv, but that's out of scope for this doc. +# Would recommend running this in a Python venv, but that's out of scope for this doc. python -m pip install --upgrade -r ./pip-requirements.txt ``` @@ -361,7 +537,7 @@ RUNNING TEST SUITE: Int Safe Conversions Test Suite ``` You can also, if you are so inclined, read the output from the exact instance of the test that was run during -`stuart_ci_build`. The ouput file can be found on a path that looks like: +`stuart_ci_build`. The output file can be found on a path that looks like: `Build//HostTest//...result.xml` @@ -389,22 +565,30 @@ c:\_uefi\MdePkg\Test\UnitTest\Library\BaseSafeIntLib\TestBaseSafeIntLib.c:35: er ### XML Reporting Mode -Since these applications are built using the CMocka framework, they can also use the following env variables to output -in a structured XML rather than text: +Unit test applications using Framework are built using Cmocka that requires the +following environment variables to be set to generate structured XML output +rather than text: -```text +``` CMOCKA_MESSAGE_OUTPUT=xml CMOCKA_XML_FILE= ``` +Unit test applications using GoogleTest require the following environment +variable to be set to generate structured XML output rather than text: + +``` +GTEST_OUTPUT=xml: +``` + This mode is used by the test running plugin to aggregate the results for CI test status reporting in the web view. ### Important Note -This works on both Windows and Linux, but is currently limited to x64 architectures. Working on getting others, but we +This works on both Windows and Linux but is currently limited to x64 architectures. Working on getting others, but we also welcome contributions. -## Known Limitations +## Framework Known Limitations ### PEI, DXE, SMM @@ -418,7 +602,7 @@ PEI, DXE, and SMM is forthcoming, but should be considered beta/staging for now. The host-based test framework is powered internally by the Cmocka framework. As such, it has abilities that the target-based tests don't (yet). It would be awesome if this meant that it was a super set of the target-based tests, and it worked just like the target-based tests but with more features. Unfortunately, -this is not the case. While care has been taken to keep them as close a possible, there are a few known +this is not the case. While care has been taken to keep them as close as possible, there are a few known inconsistencies that we're still ironing out. For example, the logging messages in the target-based tests are cached internally and associated with the running test case. They can be saved later as part of the reporting lib. This isn't currently possible with host-based. Only the assertion failures are logged. @@ -441,6 +625,9 @@ Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a Functionality or Feature | Simi ComponentY/ ComponentY.inf ComponentY.c + GoogleTest/ + ComponentYHostGoogleTest.inf # Host-Based Test for Driver Module + ComponentYGoogleTest.cpp UnitTest/ ComponentYHostUnitTest.inf # Host-Based Test for Driver Module ComponentYUnitTest.c @@ -455,11 +642,23 @@ Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a Functionality or Feature | Simi SpecificLibDxe/ SpecificLibDxe.c SpecificLibDxe.inf + GoogleTest/ # Host-Based Test for Specific Library Implementation + SpecificLibDxeHostGoogleTest.cpp + SpecificLibDxeHostGoogleTest.inf UnitTest/ # Host-Based Test for Specific Library Implementation SpecificLibDxeHostUnitTest.c SpecificLibDxeHostUnitTest.inf Test/ HostTest.dsc # Host-Based Test Apps + GoogleTest/ + InterfaceX + InterfaceXHostGoogleTest.inf # Host-Based App (should be in Test/HostTest.dsc) + InterfaceXUnitTest.cpp # Test Logic + + GeneralPurposeLib/ # Host-Based Test for any implementation of GeneralPurposeLib + GeneralPurposeLibTest.cpp + GeneralPurposeLibHostUnitTest.inf + UnitTest/ InterfaceX InterfaceXHostUnitTest.inf # Host-Based App (should be in Test/HostTest.dsc) diff --git a/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTest.cpp b/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTest.cpp new file mode 100644 index 0000000000..c83e58596a --- /dev/null +++ b/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTest.cpp @@ -0,0 +1,263 @@ +/** @file + This is a sample to demonstrates the use of GoogleTest that supports host + execution environments. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +extern "C" { + #include + #include + #include +} + +/** + Sample unit test that verifies the expected result of an unsigned integer + addition operation. +**/ +TEST(SimpleMathTests, OnePlusOneShouldEqualTwo) { + UINTN A; + UINTN B; + UINTN C; + + A = 1; + B = 1; + C = A + B; + + ASSERT_EQ (C, (UINTN)2); +} + +/** + Sample unit test that verifies that a global BOOLEAN is updatable. +**/ +class GlobalBooleanVarTests : public ::testing::Test { + public: + BOOLEAN SampleGlobalTestBoolean = FALSE; +}; + +TEST_F(GlobalBooleanVarTests, GlobalBooleanShouldBeChangeable) { + SampleGlobalTestBoolean = TRUE; + ASSERT_TRUE (SampleGlobalTestBoolean); + + SampleGlobalTestBoolean = FALSE; + ASSERT_FALSE (SampleGlobalTestBoolean); +} + +/** + Sample unit test that logs a warning message and verifies that a global + pointer is updatable. +**/ +class GlobalVarTests : public ::testing::Test { + public: + VOID *SampleGlobalTestPointer = NULL; + + protected: + void SetUp() override { + ASSERT_EQ ((UINTN)SampleGlobalTestPointer, (UINTN)NULL); + } + void TearDown() { + SampleGlobalTestPointer = NULL; + } +}; + +TEST_F(GlobalVarTests, GlobalPointerShouldBeChangeable) { + SampleGlobalTestPointer = (VOID *)-1; + ASSERT_EQ ((UINTN)SampleGlobalTestPointer, (UINTN)((VOID *)-1)); +} + + +/** + Set PcdDebugPropertyMask for each MacroTestsAssertsEnabledDisabled test +**/ +class MacroTestsAssertsEnabledDisabled : public testing::TestWithParam { + void SetUp() { + PatchPcdSet8 (PcdDebugPropertyMask, GetParam()); + } +}; + +/** + Sample unit test using the ASSERT_TRUE() macro. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertTrue) { + UINT64 Result; + + // + // This test passes because expression always evaluated to TRUE. + // + ASSERT_TRUE (TRUE); + + // + // This test passes because expression always evaluates to TRUE. + // + Result = LShiftU64 (BIT0, 1); + ASSERT_TRUE (Result == BIT1); +} + +/** + Sample unit test using the ASSERT_FALSE() macro. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertFalse) { + UINT64 Result; + + // + // This test passes because expression always evaluated to FALSE. + // + ASSERT_FALSE (FALSE); + + // + // This test passes because expression always evaluates to FALSE. + // + Result = LShiftU64 (BIT0, 1); + ASSERT_FALSE (Result == BIT0); +} + +/** + Sample unit test using the ASSERT_EQ() macro. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertEqual) { + UINT64 Result; + + // + // This test passes because both values are always equal. + // + ASSERT_EQ (1, 1); + + // + // This test passes because both values are always equal. + // + Result = LShiftU64 (BIT0, 1); + ASSERT_EQ (Result, (UINT64)BIT1); +} + +/** + Sample unit test using the ASSERT_STREQ() macro. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertMemEqual) { + CHAR8 *String1; + CHAR8 *String2; + + // + // This test passes because String1 and String2 are the same. + // + String1 = (CHAR8 *)"Hello"; + String2 = (CHAR8 *)"Hello"; + ASSERT_STREQ (String1, String2); +} + +/** + Sample unit test using the ASSERT_NE() macro. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertNotEqual) { + UINT64 Result; + + // + // This test passes because both values are never equal. + // + ASSERT_NE (0, 1); + + // + // This test passes because both values are never equal. + // + Result = LShiftU64 (BIT0, 1); + ASSERT_NE (Result, (UINT64)BIT0); +} + +/** + Sample unit test using the ASSERT_TRUE() and ASSERT(FALSE) + and EFI_EFFOR() macros to check status +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertNotEfiError) { + // + // This test passes because the status is not an EFI error. + // + ASSERT_FALSE (EFI_ERROR (EFI_SUCCESS)); + + // + // This test passes because the status is not an EFI error. + // + ASSERT_FALSE (EFI_ERROR (EFI_WARN_BUFFER_TOO_SMALL)); +} + +/** + Sample unit test using the ASSERT_EQ() macro to compare EFI_STATUS values. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertStatusEqual) { + // + // This test passes because the status value are always equal. + // + ASSERT_EQ (EFI_SUCCESS, EFI_SUCCESS); +} + +/** + Sample unit test using ASSERT_NE() macro to make sure a pointer is not NULL. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroAssertNotNull) { + UINT64 Result; + + // + // This test passes because the pointer is never NULL. + // + ASSERT_NE (&Result, (UINT64 *)NULL); +} + +/** + Sample unit test using that should not generate any ASSERTs() +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroExpectNoAssertFailure) { + // + // This test passes because it never triggers an ASSERT(). + // + ASSERT (TRUE); + + // + // This test passes because DecimalToBcd() does not ASSERT() if the + // value passed in is <= 99. + // + DecimalToBcd8 (99); +} + +/** + Sample unit test using the ASSERT_DEATH() macro to test expected ASSERT()s. +**/ +TEST_P(MacroTestsAssertsEnabledDisabled, MacroExpectAssertFailure) { + // + // Skip tests that verify an ASSERT() is triggered if ASSERT()s are disabled. + // + if ((PcdGet8 (PcdDebugPropertyMask) & BIT0) == 0x00) { + return; + } + + // + // This test passes because it directly triggers an ASSERT(). + // + ASSERT_DEATH (ASSERT (FALSE), ""); + + // + // This test passes because DecimalToBcd() generates an ASSERT() if the + // value passed in is >= 100. The expected ASSERT() is caught by the unit + // test framework and ASSERT_DEATH() returns without an error. + // + ASSERT_DEATH (DecimalToBcd8 (101), ""); +} + +INSTANTIATE_TEST_SUITE_P(ValidInput, + MacroTestsAssertsEnabledDisabled, + ::testing::Values(PcdGet8 (PcdDebugPropertyMask) | BIT0, PcdGet8 (PcdDebugPropertyMask) & (~BIT0))); + +/** + Sample unit test using the SCOPED_TRACE() macro for trace messages. +**/ +TEST(MacroTestsMessages, MacroTraceMessage) { + // + // Example of logging. + // + SCOPED_TRACE ("SCOPED_TRACE message\n"); +} + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf b/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf new file mode 100644 index 0000000000..37e7c86910 --- /dev/null +++ b/UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf @@ -0,0 +1,35 @@ +## @file +# This is a sample to demonstrates the use of GoogleTest that supports host +# execution environments. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SampleGoogleTestHost + FILE_GUID = 7D8BBFBB-7977-4AEE-A59F-257BF5C2F87C + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SampleGoogleTest.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + BaseLib + DebugLib + +[Pcd] + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 184fdec87a..708ef7f9ab 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -23,14 +23,16 @@ [Components] # - # Build HOST_APPLICATION that tests the SampleUnitTest + # Build HOST_APPLICATIONs that test the SampleUnitTest # UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf + UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf # # Build HOST_APPLICATION Libraries # UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 77d51e1348..072df6208c 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -78,7 +78,8 @@ "SpellCheck": { "AuditOnly": False, # Fails test but run in AuditOnly mode to collect log "IgnoreFiles": [ # use gitignore syntax to ignore errors in matching files - "Library/CmockaLib/cmocka/**/*.*" # not going to spell check a submodule + "Library/CmockaLib/cmocka/**/*.*", # not going to spell check a submodule + "Library/GoogleTestLib/googletest/**/*.*" # not going to spell check a submodule ], "ExtendWords": [ # words to extend to the dictionary for this package "testcase", @@ -91,6 +92,7 @@ "NOFAILURE", "cmockery", "DHAVE", # build flag for cmocka in the INF + "gtest", # file name in GoogleTestLib.inf "corthon", # Contact GitHub account in Readme "mdkinney", # Contact GitHub account in Readme "spbrogan" # Contact GitHub account in Readme diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 069289f009..ed12f32009 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -16,11 +16,15 @@ PACKAGE_VERSION = 1.00 [Includes] + Include Library/CmockaLib/cmocka/include + Library/GoogleTestLib/googletest/googletest/include + Library/GoogleTestLib/googletest/googlemock/include [Includes.Common.Private] PrivateInclude Library/CmockaLib/cmocka/include/cmockery + Library/GoogleTestLib/googletest/googletest [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state @@ -35,6 +39,10 @@ # UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h + ## @libraryclass GoogleTest infrastructure + # + GoogleTestLib|Include/Library/GoogleTestLib.h + [Guids] gUnitTestFrameworkPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 9beeaef1ba..8009337552 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -14,6 +14,7 @@ CpuLib|MdePkg/Library/BaseCpuLibNull/BaseCpuLibNull.inf CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLibNull/BaseCacheMaintenanceLibNull.inf CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + GoogleTestLib|UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf @@ -31,6 +32,7 @@ # # MSFT # + MSFT:*_*_*_CC_FLAGS = /EHsc MSFT:*_*_*_DLINK_FLAGS == /out:"$(BIN_DIR)\$(MODULE_NAME_GUID).exe" /pdb:"$(BIN_DIR)\$(MODULE_NAME_GUID).pdb" /IGNORE:4001 /NOLOGO /SUBSYSTEM:CONSOLE /DEBUG /STACK:0x40000,0x40000 /NODEFAULTLIB:libcmt.lib libcmtd.lib MSFT:*_*_IA32_DLINK_FLAGS = /MACHINE:I386 MSFT:*_*_X64_DLINK_FLAGS = /MACHINE:AMD64 @@ -50,7 +52,7 @@ # GCC:*_*_IA32_DLINK_FLAGS == -o $(BIN_DIR)/$(MODULE_NAME_GUID) -m32 -no-pie GCC:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(MODULE_NAME_GUID) -m64 -no-pie - GCC:*_*_*_DLINK2_FLAGS == -lgcov + GCC:*_*_*_DLINK2_FLAGS == -lgcov -lpthread -lstdc++ -lm # # Need to do this link via gcc and not ld as the pathing to libraries changes from OS version to OS version From 107cd71480831c3410bac3b90d2714595b39f829 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 3 Nov 2022 15:38:25 -0700 Subject: [PATCH 0317/1529] UnitTestFrameworkPkg/Library/CmockaLib: Generate symbol information Add /Zi to CC_FLAGS in CmockaLib.inf to enable symbol information Cc: Michael Kubacki Cc: Sean Brogan Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki --- UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf index 07da7a88e9..052c7f5572 100644 --- a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf @@ -26,7 +26,7 @@ UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [BuildOptions] - MSFT:*_*_*_CC_FLAGS == /c -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + MSFT:*_*_*_CC_FLAGS == /c -DHAVE_VSNPRINTF -DHAVE_SNPRINTF /Zi MSFT:NOOPT_*_*_CC_FLAGS = /Od GCC:*_*_*_CC_FLAGS == -g -DHAVE_SIGNAL_H From 9663a751b7d4e6526b0d2d3a2fac66c8ef0e0762 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 28 Jun 2022 10:33:02 -0700 Subject: [PATCH 0318/1529] .pytool: Add googletest submodule to CISettings.py REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki --- .pytool/CISettings.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index cc2214071c..76ac2b09db 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -192,6 +192,8 @@ def GetRequiredSubmodules(self): "CryptoPkg/Library/OpensslLib/openssl", False)) rs.append(RequiredSubmodule( "UnitTestFrameworkPkg/Library/CmockaLib/cmocka", False)) + rs.append(RequiredSubmodule( + "UnitTestFrameworkPkg/Library/GoogleTestLib/googletest", False)) rs.append(RequiredSubmodule( "MdeModulePkg/Universal/RegularExpressionDxe/oniguruma", False)) rs.append(RequiredSubmodule( From f01457a27fb475ed4a767d673e6ba7188d6caf90 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 31 Oct 2022 10:09:09 -0700 Subject: [PATCH 0319/1529] BaseTools/Plugin/HostBaseUnitTestRunner: Enable gtest xml output REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 Set environment variable GTEST_OUTPUT to specify the output format of XML and the output file name. Both CMOCKA_XML_FILE and GTEST_OUTPUT are set for each host based unit test to support both cmocka unit tests and gtest unit tests. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Signed-off-by: Michael D Kinney Reviewed-by: Bob Feng --- .../HostBasedUnitTestRunner/HostBasedUnitTestRunner.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index c1eeaf2625..a8220aacd3 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -85,9 +85,12 @@ def do_post_build(self, thebuilder): raise NotImplementedError("Unsupported Operating System") for test in testList: - # Configure output name. + # Configure output name if test uses cmocka. shell_env.set_shell_var( - 'CMOCKA_XML_FILE', test + ".%g." + arch + ".result.xml") + 'CMOCKA_XML_FILE', test + ".CMOCKA.%g." + arch + ".result.xml") + # Configure output name if test uses gtest. + shell_env.set_shell_var( + 'GTEST_OUTPUT', "xml:" + test + ".GTEST." + arch + ".result.xml") # Run the test. ret = RunCmd('"' + test + '"', "", workingdir=cp) From 544fab7528c0b785982296d007cc148226102792 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 20 Jun 2022 19:52:31 -0700 Subject: [PATCH 0320/1529] MdePkg/Test: Add port of BaseSafeIntLib unit tests to GoogleTest REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4134 Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .../GoogleTestBaseSafeIntLib.inf | 37 + .../GoogleTestBaseSafeIntLib.uni | 13 + .../SafeIntLibUintnIntnUnitTests32.cpp | 425 +++ .../SafeIntLibUintnIntnUnitTests64.cpp | 429 ++++ .../BaseSafeIntLib/TestBaseSafeIntLib.cpp | 2274 +++++++++++++++++ MdePkg/Test/MdePkgHostTest.dsc | 1 + 6 files changed, 3179 insertions(+) create mode 100644 MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.inf create mode 100644 MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.uni create mode 100644 MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests32.cpp create mode 100644 MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests64.cpp create mode 100644 MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.cpp diff --git a/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.inf b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.inf new file mode 100644 index 0000000000..f609bfa57f --- /dev/null +++ b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.inf @@ -0,0 +1,37 @@ +## @file +# Host OS based Application that Unit Tests the SafeIntLib using Google Test +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = GoogleTestBaseSafeIntLib + MODULE_UNI_FILE = GoogleTestBaseSafeIntLib.uni + FILE_GUID = 2D9C1796-B0D2-4DA7-9529-1F8D9CCC11D3 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.cpp + +[Sources.IA32] + SafeIntLibUintnIntnUnitTests32.cpp + +[Sources.X64] + SafeIntLibUintnIntnUnitTests64.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + SafeIntLib diff --git a/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.uni b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.uni new file mode 100644 index 0000000000..1c11b9e052 --- /dev/null +++ b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.uni @@ -0,0 +1,13 @@ +// /** @file +// Application that Unit Tests the SafeIntLib using Google Test +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Application that Unit Tests the SafeIntLib using Google Test" + +#string STR_MODULE_DESCRIPTION #language en-US "Application that Unit Tests the SafeIntLib using Google Test." + diff --git a/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests32.cpp b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests32.cpp new file mode 100644 index 0000000000..6fbf302c1c --- /dev/null +++ b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests32.cpp @@ -0,0 +1,425 @@ +/** @file + IA32-specific functions for unit-testing INTN and UINTN functions in + SafeIntLib. + + Copyright (c) Microsoft Corporation.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +extern "C" { + #include + #include +} + +TEST(ConversionTestSuite, TestSafeInt32ToUintn) { + RETURN_STATUS Status; + INT32 Operand; + UINTN Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt32ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToIntn) { + RETURN_STATUS Status; + UINT32 Operand; + INTN Result; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUint32ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToInt32) { + RETURN_STATUS Status; + INTN Operand; + INT32 Result; + + // + // INTN is same as INT32 in IA32, so this is just a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeIntnToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); +} + +TEST(ConversionTestSuite, TestSafeIntnToUint32) { + RETURN_STATUS Status; + INTN Operand; + UINT32 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeIntnToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToUint32) { + RETURN_STATUS Status; + UINTN Operand; + UINT32 Result; + + // + // UINTN is same as UINT32 in IA32, so this is just a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUintnToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); +} + +TEST(ConversionTestSuite, TestSafeUintnToIntn) { + RETURN_STATUS Status; + UINTN Operand; + INTN Result; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUintnToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToInt64) { + RETURN_STATUS Status; + UINTN Operand; + INT64 Result; + + // + // UINTN is same as UINT32 in IA32, and UINT32 is a subset of + // INT64, so this is just a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUintnToInt64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); +} + +TEST(ConversionTestSuite, TestSafeInt64ToIntn) { + RETURN_STATUS Status; + INT64 Operand; + INTN Result; + + // + // If Operand is between MIN_INTN and MAX_INTN2 inclusive, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt64ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeInt64ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUintn) { + RETURN_STATUS Status; + INT64 Operand; + UINTN Result; + + // + // If Operand is between 0 and MAX_UINTN inclusive, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeInt64ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToIntn) { + RETURN_STATUS Status; + UINT64 Operand; + INTN Result; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUint64ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToUintn) { + RETURN_STATUS Status; + UINT64 Operand; + UINTN Result; + + // + // If Operand is <= MAX_UINTN, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUint64ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUintnAdd) { + RETURN_STATUS Status; + UINTN Augend; + UINTN Addend; + UINTN Result; + + // + // If the result of addition doesn't overflow MAX_UINTN, then it's addition + // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; + Status = SafeUintnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x74747474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabababab; + Addend = 0xbcbcbcbc; + Status = SafeUintnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeIntnAdd) { + RETURN_STATUS Status; + INTN Augend; + INTN Addend; + INTN Result; + + // + // If the result of addition doesn't overflow MAX_INTN + // and doesn't underflow MIN_INTN, then it's addition + // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x74747474, Result); + + Augend = (-976894522); + Addend = (-976894522); + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-1953789044), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a; + Addend = 0x5a5a5a5a; + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-1515870810); + Addend = (-1515870810); + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUintnSub) { + RETURN_STATUS Status; + UINTN Minuend; + UINTN Subtrahend; + UINTN Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3b3b3b3b; + Result = 0; + Status = SafeUintnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x6d6d6d6d; + Status = SafeUintnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeIntnSub) { + RETURN_STATUS Status; + INTN Minuend; + INTN Subtrahend; + INTN Result; + + // + // If the result of subtractions doesn't overflow MAX_INTN or + // underflow MIN_INTN, then it's subtraction + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3a3a3a3a; + Result = 0; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x20202020, Result); + + Minuend = 0x3a3a3a3a; + Subtrahend = 0x5a5a5a5a; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-538976288), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-2054847098); + Subtrahend = 2054847098; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (2054847098); + Subtrahend = (-2054847098); + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeUintnMult) { + RETURN_STATUS Status; + UINTN Multiplicand; + UINTN Multiplier; + UINTN Result; + + // + // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed + // + Multiplicand = 0xa122a; + Multiplier = 0xd23; + Result = 0; + Status = SafeUintnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x844c9dbe, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0xa122a; + Multiplier = 0xed23; + Status = SafeUintnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeIntnMult) { + RETURN_STATUS Status; + INTN Multiplicand; + INTN Multiplier; + INTN Result; + + // + // If the result of multiplication doesn't overflow MAX_INTN and doesn't + // underflow MIN_UINTN, it will succeed + // + Multiplicand = 0x123456; + Multiplier = 0x678; + Result = 0; + Status = SafeIntnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x75c28c50, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456; + Multiplier = 0xabc; + Status = SafeIntnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} diff --git a/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests64.cpp b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests64.cpp new file mode 100644 index 0000000000..6fb0710cfe --- /dev/null +++ b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/SafeIntLibUintnIntnUnitTests64.cpp @@ -0,0 +1,429 @@ +/** @file + x64-specific functions for unit-testing INTN and UINTN functions in + SafeIntLib. + + Copyright (c) Microsoft Corporation.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +extern "C" { + #include + #include +} + +TEST(ConversionTestSuite, TestSafeInt32ToUintn) { + RETURN_STATUS Status; + INT32 Operand; + UINTN Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt32ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToIntn) { + RETURN_STATUS Status; + UINT32 Operand; + INTN Result; + + // + // For x64, INTN is same as INT64 which is a superset of INT32 + // This is just a cast then, and it'll never fail + // + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUint32ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); +} + +TEST(ConversionTestSuite, TestSafeIntnToInt32) { + RETURN_STATUS Status; + INTN Operand; + INT32 Result; + + // + // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeIntnToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeIntnToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeIntnToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeIntnToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToUint32) { + RETURN_STATUS Status; + INTN Operand; + UINT32 Result; + + // + // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeIntnToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeIntnToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeIntnToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToUint32) { + RETURN_STATUS Status; + UINTN Operand; + UINT32 Result; + + // + // If Operand is <= MAX_UINT32, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUintnToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToIntn) { + RETURN_STATUS Status; + UINTN Operand; + INTN Result; + + // + // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeUintnToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToInt64) { + RETURN_STATUS Status; + UINTN Operand; + INT64 Result; + + // + // If Operand is <= MAX_INT64, then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeUintnToInt64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToInt64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToIntn) { + RETURN_STATUS Status; + INT64 Operand; + INTN Result; + + // + // INTN is same as INT64 in x64, so this is just a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeInt64ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5babababefefefef, Result); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUintn) { + RETURN_STATUS Status; + INT64 Operand; + UINTN Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeInt64ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (-6605562033422200815); + Status = SafeInt64ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToIntn) { + RETURN_STATUS Status; + UINT64 Operand; + INTN Result; + + // + // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeUint64ToIntn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToIntn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToUintn) { + RETURN_STATUS Status; + UINT64 Operand; + UINTN Result; + + // + // UINTN is same as UINT64 in x64, so this is just a cast + // + Operand = 0xababababefefefef; + Result = 0; + Status = SafeUint64ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xababababefefefef, Result); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUintnAdd) { + RETURN_STATUS Status; + UINTN Augend; + UINTN Addend; + UINTN Result; + + // + // If the result of addition doesn't overflow MAX_UINTN, then it's addition + // + Augend = 0x3a3a3a3a12121212; + Addend = 0x3a3a3a3a12121212; + Result = 0; + Status = SafeUintnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x7474747424242424, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xababababefefefef; + Addend = 0xbcbcbcbcdededede; + Status = SafeUintnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeIntnAdd) { + RETURN_STATUS Status; + INTN Augend; + INTN Addend; + INTN Result; + + // + // If the result of addition doesn't overflow MAX_INTN + // and doesn't underflow MIN_INTN, then it's addition + // + Augend = 0x3a3a3a3a3a3a3a3a; + Addend = 0x3a3a3a3a3a3a3a3a; + Result = 0; + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7474747474747474, Result); + + Augend = (-4195730024608447034); + Addend = (-4195730024608447034); + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-8391460049216894068), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a5a5a5a5a; + Addend = 0x5a5a5a5a5a5a5a5a; + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-6510615555426900570); + Addend = (-6510615555426900570); + Status = SafeIntnAdd (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUintnSub) { + RETURN_STATUS Status; + UINTN Minuend; + UINTN Subtrahend; + UINTN Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3b3b3b3b3b3b3b3b; + Result = 0; + Status = SafeUintnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x1f1f1f1f1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x6d6d6d6d6d6d6d6d; + Status = SafeUintnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeIntnSub) { + RETURN_STATUS Status; + INTN Minuend; + INTN Subtrahend; + INTN Result; + + // + // If the result of subtractions doesn't overflow MAX_INTN or + // underflow MIN_INTN, then it's subtraction + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3a3a3a3a3a3a3a3a; + Result = 0; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x2020202020202020, Result); + + Minuend = 0x3a3a3a3a3a3a3a3a; + Subtrahend = 0x5a5a5a5a5a5a5a5a; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-2314885530818453536), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-8825501086245354106); + Subtrahend = 8825501086245354106; + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (8825501086245354106); + Subtrahend = (-8825501086245354106); + Status = SafeIntnSub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeUintnMult) { + RETURN_STATUS Status; + UINTN Multiplicand; + UINTN Multiplier; + UINTN Result; + + // + // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed + // + Multiplicand = 0x123456789a; + Multiplier = 0x1234567; + Result = 0; + Status = SafeUintnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x14b66db9745a07f6, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789a; + Multiplier = 0x12345678; + Status = SafeUintnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeIntnMult) { + RETURN_STATUS Status; + INTN Multiplicand; + INTN Multiplier; + INTN Result; + + // + // If the result of multiplication doesn't overflow MAX_INTN and doesn't + // underflow MIN_UINTN, it will succeed + // + Multiplicand = 0x123456789; + Multiplier = 0x6789abcd; + Result = 0; + Status = SafeIntnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x75cd9045220d6bb5, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789; + Multiplier = 0xa789abcd; + Status = SafeIntnMult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} diff --git a/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.cpp b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.cpp new file mode 100644 index 0000000000..1fd51067a1 --- /dev/null +++ b/MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.cpp @@ -0,0 +1,2274 @@ +/** @file + UEFI OS based application for unit testing the SafeIntLib. + + Copyright (c) Microsoft Corporation.
+ Copyright (c) 2018 - 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +extern "C" { + #include + #include +} + +// +// Conversion function tests: +// +TEST(ConversionTestSuite, TestSafeInt8ToUint8) { + RETURN_STATUS Status; + INT8 Operand; + UINT8 Result; + + // + // Positive UINT8 should result in just a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt8ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt8ToUint16) { + RETURN_STATUS Status; + INT8 Operand; + UINT16 Result; + + // + // Positive UINT8 should result in just a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt8ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt8ToUint32) { + RETURN_STATUS Status; + INT8 Operand; + UINT32 Result; + + // + // Positive UINT8 should result in just a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt8ToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt8ToUintn) { + RETURN_STATUS Status; + INT8 Operand; + UINTN Result; + + // + // Positive UINT8 should result in just a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt8ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt8ToUint64) { + RETURN_STATUS Status; + INT8 Operand; + UINT64 Result; + + // + // Positive UINT8 should result in just a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt8ToUint64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint8ToInt8) { + RETURN_STATUS Status; + UINT8 Operand; + INT8 Result; + + // + // Operand <= 0x7F (MAX_INT8) should result in a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint8ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Operand larger than 0x7f should result in an error status + // + Operand = 0xaf; + Status = SafeUint8ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint8ToChar8) { + RETURN_STATUS Status; + UINT8 Operand; + CHAR8 Result; + + // + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + // + + // + // Operand <= 0x7F (MAX_INT8) should result in a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint8ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Operand larger than 0x7f should result in an error status + // + Operand = 0xaf; + Status = SafeUint8ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToInt8) { + RETURN_STATUS Status; + INT16 Operand; + INT8 Result; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt16ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = (-35); + Status = SafeInt16ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-35), Result); + + // + // Otherwise should result in an error status + // + Operand = 0x1234; + Status = SafeInt16ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToChar8) { + RETURN_STATUS Status; + INT16 Operand; + CHAR8 Result; + + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = 0; + Result = 0; + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (MAX_INT8, Result); + + // + // Otherwise should result in an error status + // + Operand = (-35); + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = 0x1234; + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToUint8) { + RETURN_STATUS Status; + INT16 Operand; + UINT8 Result; + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt16ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = 0x1234; + Status = SafeInt16ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToUint16) { + RETURN_STATUS Status; + INT16 Operand = 0x5b5b; + UINT16 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt16ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToUint32) { + RETURN_STATUS Status; + INT16 Operand; + UINT32 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5b5b; + Result = 0; + Status = SafeInt16ToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToUintn) { + RETURN_STATUS Status; + INT16 Operand; + UINTN Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5b5b; + Result = 0; + Status = SafeInt16ToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt16ToUint64) { + RETURN_STATUS Status; + INT16 Operand; + UINT64 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5b5b; + Result = 0; + Status = SafeInt16ToUint64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint16ToInt8) { + RETURN_STATUS Status; + UINT16 Operand; + INT8 Result; + + // + // If Operand is <= MAX_INT8, it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint16ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint16ToChar8) { + RETURN_STATUS Status; + UINT16 Operand; + CHAR8 Result; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint16ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint16ToUint8) { + RETURN_STATUS Status; + UINT16 Operand; + UINT8 Result; + + // + // If Operand is <= MAX_UINT8 (0xff), it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeUint16ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint16ToInt16) { + RETURN_STATUS Status; + UINT16 Operand; + INT16 Result; + + // + // If Operand is <= MAX_INT16 (0x7fff), it's a cast + // + Operand = 0x5b5b; + Result = 0; + Status = SafeUint16ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUint16ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToInt8) { + RETURN_STATUS Status; + INT32 Operand; + INT8 Result; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt32ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = (-57); + Status = SafeInt32ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-57), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeInt32ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToChar8) { + RETURN_STATUS Status; + INT32 Operand; + CHAR8 Result; + + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = 0; + Result = 0; + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (MAX_INT8, Result); + + // + // Otherwise should result in an error status + // + Operand = (-57); + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToUint8) { + RETURN_STATUS Status; + INT32 Operand; + UINT8 Result; + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt32ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-57); + Status = SafeInt32ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeInt32ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToInt16) { + RETURN_STATUS Status; + INT32 Operand; + INT16 Result; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Operand = 0x5b5b; + Result = 0; + Status = SafeInt32ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b5b, Result); + + Operand = (-17857); + Status = SafeInt32ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-17857), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeInt32ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToUint16) { + RETURN_STATUS Status; + INT32 Operand; + UINT16 Result; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeInt32ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17857); + Status = SafeInt32ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeInt32ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToUint32) { + RETURN_STATUS Status; + INT32 Operand; + UINT32 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt32ToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt32ToUint64) { + RETURN_STATUS Status; + INT32 Operand; + UINT64 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt32ToUint64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUint64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToInt8) { + RETURN_STATUS Status; + UINT32 Operand; + INT8 Result; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint32ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeUint32ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToChar8) { + RETURN_STATUS Status; + UINT32 Operand; + CHAR8 Result; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint32ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeUint32ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToUint8) { + RETURN_STATUS Status; + UINT32 Operand; + UINT8 Result; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeUint32ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToInt16) { + RETURN_STATUS Status; + UINT32 Operand; + INT16 Result; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Operand = 0x5bab; + Result = 0; + Status = SafeUint32ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToUint16) { + RETURN_STATUS Status; + UINT32 Operand; + UINT16 Result; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeUint32ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint32ToInt32) { + RETURN_STATUS Status; + UINT32 Operand; + INT32 Result; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUint32ToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToInt8) { + RETURN_STATUS Status; + INTN Operand; + INT8 Result; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeIntnToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = (-53); + Status = SafeIntnToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-53), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToChar8) { + RETURN_STATUS Status; + INTN Operand; + CHAR8 Result; + + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = 0; + Result = 0; + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (MAX_INT8, Result); + + // + // Otherwise should result in an error status + // + Operand = (-53); + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToUint8) { + RETURN_STATUS Status; + INTN Operand; + UINT8 Result; + + // + // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeIntnToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToInt16) { + RETURN_STATUS Status; + INTN Operand; + INT16 Result; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Operand = 0x5bab; + Result = 0; + Status = SafeIntnToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bab, Result); + + Operand = (-23467); + Status = SafeIntnToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-23467), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToUint16) { + RETURN_STATUS Status; + INTN Operand; + UINT16 Result; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeIntnToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToUintn) { + RETURN_STATUS Status; + INTN Operand; + UINTN Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeIntnToUintn (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINTN)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUintn (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeIntnToUint64) { + RETURN_STATUS Status; + INTN Operand; + UINT64 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeIntnToUint64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUint64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToInt8) { + RETURN_STATUS Status; + UINTN Operand; + INT8 Result; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUintnToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToChar8) { + RETURN_STATUS Status; + UINTN Operand; + CHAR8 Result; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUintnToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToUint8) { + RETURN_STATUS Status; + UINTN Operand; + UINT8 Result; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeUintnToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToInt16) { + RETURN_STATUS Status; + UINTN Operand; + INT16 Result; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Operand = 0x5bab; + Result = 0; + Status = SafeUintnToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToUint16) { + RETURN_STATUS Status; + UINTN Operand; + UINT16 Result; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeUintnToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUintnToInt32) { + RETURN_STATUS Status; + UINTN Operand; + INT32 Result; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUintnToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToInt8) { + RETURN_STATUS Status; + INT64 Operand; + INT8 Result; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt64ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = (-37); + Status = SafeInt64ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-37), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToChar8) { + RETURN_STATUS Status; + INT64 Operand; + CHAR8 Result; + + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + Operand = 0; + Result = 0; + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (MAX_INT8, Result); + + // + // Otherwise should result in an error status + // + Operand = (-37); + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5babababefefefef); + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUint8) { + RETURN_STATUS Status; + INT64 Operand; + UINT8 Result; + + // + // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeInt64ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToInt16) { + RETURN_STATUS Status; + INT64 Operand; + INT16 Result; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Operand = 0x5bab; + Result = 0; + Status = SafeInt64ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bab, Result); + + Operand = (-23467); + Status = SafeInt64ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-23467), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUint16) { + RETURN_STATUS Status; + INT64 Operand; + UINT16 Result; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeInt64ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToInt32) { + RETURN_STATUS Status; + INT64 Operand; + INT32 Result; + + // + // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeInt64ToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeInt64ToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUint32) { + RETURN_STATUS Status; + INT64 Operand; + UINT32 Result; + + // + // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeInt64ToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeInt64ToUint64) { + RETURN_STATUS Status; + INT64 Operand; + UINT64 Result; + + // + // If Operand is non-negative, then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeInt64ToUint64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (-6605562033422200815); + Status = SafeInt64ToUint64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToInt8) { + RETURN_STATUS Status; + UINT64 Operand; + INT8 Result; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint64ToInt8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToChar8) { + RETURN_STATUS Status; + UINT64 Operand; + CHAR8 Result; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Operand = 0x5b; + Result = 0; + Status = SafeUint64ToChar8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToChar8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToUint8) { + RETURN_STATUS Status; + UINT64 Operand; + UINT8 Result; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Operand = 0xab; + Result = 0; + Status = SafeUint64ToUint8 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint8 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToInt16) { + RETURN_STATUS Status; + UINT64 Operand; + INT16 Result; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Operand = 0x5bab; + Result = 0; + Status = SafeUint64ToInt16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToUint16) { + RETURN_STATUS Status; + UINT64 Operand; + UINT16 Result; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Operand = 0xabab; + Result = 0; + Status = SafeUint64ToUint16 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint16 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToInt32) { + RETURN_STATUS Status; + UINT64 Operand; + INT32 Result; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Operand = 0x5bababab; + Result = 0; + Status = SafeUint64ToInt32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToUint32) { + RETURN_STATUS Status; + UINT64 Operand; + UINT32 Result; + + // + // If Operand is <= MAX_UINT32, then it's a cast + // + Operand = 0xabababab; + Result = 0; + Status = SafeUint64ToUint32 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint32 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(ConversionTestSuite, TestSafeUint64ToInt64) { + RETURN_STATUS Status; + UINT64 Operand; + INT64 Result; + + // + // If Operand is <= MAX_INT64, then it's a cast + // + Operand = 0x5babababefefefef; + Result = 0; + Status = SafeUint64ToInt64 (Operand, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt64 (Operand, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +// +// Addition function tests: +// +TEST(AdditionSubtractionTestSuite, TestSafeUint8Add) { + RETURN_STATUS Status; + UINT8 Augend; + UINT8 Addend; + UINT8 Result; + + // + // If the result of addition doesn't overflow MAX_UINT8, then it's addition + // + Augend = 0x3a; + Addend = 0x3a; + Result = 0; + Status = SafeUint8Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x74, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xab; + Addend = 0xbc; + Status = SafeUint8Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint16Add) { + RETURN_STATUS Status; + UINT16 Augend = 0x3a3a; + UINT16 Addend = 0x3a3a; + UINT16 Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINT16, then it's addition + // + Status = SafeUint16Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabab; + Addend = 0xbcbc; + Status = SafeUint16Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint32Add) { + RETURN_STATUS Status; + UINT32 Augend; + UINT32 Addend; + UINT32 Result; + + // + // If the result of addition doesn't overflow MAX_UINT32, then it's addition + // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; + Status = SafeUint32Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x74747474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabababab; + Addend = 0xbcbcbcbc; + Status = SafeUint32Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint64Add) { + RETURN_STATUS Status; + UINT64 Augend; + UINT64 Addend; + UINT64 Result; + + // + // If the result of addition doesn't overflow MAX_UINT64, then it's addition + // + Augend = 0x3a3a3a3a12121212; + Addend = 0x3a3a3a3a12121212; + Result = 0; + Status = SafeUint64Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x7474747424242424, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xababababefefefef; + Addend = 0xbcbcbcbcdededede; + Status = SafeUint64Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt8Add) { + RETURN_STATUS Status; + INT8 Augend; + INT8 Addend; + INT8 Result; + + // + // If the result of addition doesn't overflow MAX_INT8 + // and doesn't underflow MIN_INT8, then it's addition + // + Augend = 0x3a; + Addend = 0x3a; + Result = 0; + Status = SafeInt8Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x74, Result); + + Augend = (-58); + Addend = (-58); + Status = SafeInt8Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-116), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a; + Addend = 0x5a; + Status = SafeInt8Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-90); + Addend = (-90); + Status = SafeInt8Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt16Add) { + RETURN_STATUS Status; + INT16 Augend; + INT16 Addend; + INT16 Result; + + // + // If the result of addition doesn't overflow MAX_INT16 + // and doesn't underflow MIN_INT16, then it's addition + // + Augend = 0x3a3a; + Addend = 0x3a3a; + Result = 0; + Status = SafeInt16Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7474, Result); + + Augend = (-14906); + Addend = (-14906); + Status = SafeInt16Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-29812), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a; + Addend = 0x5a5a; + Status = SafeInt16Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-23130); + Addend = (-23130); + Status = SafeInt16Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt32Add) { + RETURN_STATUS Status; + INT32 Augend; + INT32 Addend; + INT32 Result; + + // + // If the result of addition doesn't overflow MAX_INT32 + // and doesn't underflow MIN_INT32, then it's addition + // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; + Status = SafeInt32Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x74747474, Result); + + Augend = (-976894522); + Addend = (-976894522); + Status = SafeInt32Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-1953789044), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a; + Addend = 0x5a5a5a5a; + Status = SafeInt32Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-1515870810); + Addend = (-1515870810); + Status = SafeInt32Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt64Add) { + RETURN_STATUS Status; + INT64 Augend; + INT64 Addend; + INT64 Result; + + // + // If the result of addition doesn't overflow MAX_INT64 + // and doesn't underflow MIN_INT64, then it's addition + // + Augend = 0x3a3a3a3a3a3a3a3a; + Addend = 0x3a3a3a3a3a3a3a3a; + Result = 0; + Status = SafeInt64Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7474747474747474, Result); + + Augend = (-4195730024608447034); + Addend = (-4195730024608447034); + Status = SafeInt64Add (Augend, Addend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-8391460049216894068), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a5a5a5a5a; + Addend = 0x5a5a5a5a5a5a5a5a; + Status = SafeInt64Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-6510615555426900570); + Addend = (-6510615555426900570); + Status = SafeInt64Add (Augend, Addend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +// +// Subtraction function tests: +// +TEST(AdditionSubtractionTestSuite, TestSafeUint8Sub) { + RETURN_STATUS Status; + UINT8 Minuend; + UINT8 Subtrahend; + UINT8 Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a; + Subtrahend = 0x3b; + Result = 0; + Status = SafeUint8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a; + Subtrahend = 0x6d; + Status = SafeUint8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint16Sub) { + RETURN_STATUS Status; + UINT16 Minuend; + UINT16 Subtrahend; + UINT16 Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a5a; + Subtrahend = 0x3b3b; + Result = 0; + Status = SafeUint16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a; + Subtrahend = 0x6d6d; + Status = SafeUint16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint32Sub) { + RETURN_STATUS Status; + UINT32 Minuend; + UINT32 Subtrahend; + UINT32 Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3b3b3b3b; + Result = 0; + Status = SafeUint32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT32)0x1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x6d6d6d6d; + Status = SafeUint32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeUint64Sub) { + RETURN_STATUS Status; + UINT64 Minuend; + UINT64 Subtrahend; + UINT64 Result; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3b3b3b3b3b3b3b3b; + Result = 0; + Status = SafeUint64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x1f1f1f1f1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x6d6d6d6d6d6d6d6d; + Status = SafeUint64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt8Sub) { + RETURN_STATUS Status; + INT8 Minuend; + INT8 Subtrahend; + INT8 Result; + + // + // If the result of subtractions doesn't overflow MAX_INT8 or + // underflow MIN_INT8, then it's subtraction + // + Minuend = 0x5a; + Subtrahend = 0x3a; + Result = 0; + Status = SafeInt8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x20, Result); + + Minuend = 58; + Subtrahend = 78; + Status = SafeInt8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-20), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-80); + Subtrahend = 80; + Status = SafeInt8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (80); + Subtrahend = (-80); + Status = SafeInt8Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt16Sub) { + RETURN_STATUS Status; + INT16 Minuend; + INT16 Subtrahend; + INT16 Result; + + // + // If the result of subtractions doesn't overflow MAX_INT16 or + // underflow MIN_INT16, then it's subtraction + // + Minuend = 0x5a5a; + Subtrahend = 0x3a3a; + Result = 0; + Status = SafeInt16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x2020, Result); + + Minuend = 0x3a3a; + Subtrahend = 0x5a5a; + Status = SafeInt16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-8224), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-31354); + Subtrahend = 31354; + Status = SafeInt16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (31354); + Subtrahend = (-31354); + Status = SafeInt16Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt32Sub) { + RETURN_STATUS Status; + INT32 Minuend; + INT32 Subtrahend; + INT32 Result; + + // + // If the result of subtractions doesn't overflow MAX_INT32 or + // underflow MIN_INT32, then it's subtraction + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3a3a3a3a; + Result = 0; + Status = SafeInt32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x20202020, Result); + + Minuend = 0x3a3a3a3a; + Subtrahend = 0x5a5a5a5a; + Status = SafeInt32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-538976288), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-2054847098); + Subtrahend = 2054847098; + Status = SafeInt32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (2054847098); + Subtrahend = (-2054847098); + Status = SafeInt32Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(AdditionSubtractionTestSuite, TestSafeInt64Sub) { + RETURN_STATUS Status; + INT64 Minuend; + INT64 Subtrahend; + INT64 Result; + + // + // If the result of subtractions doesn't overflow MAX_INT64 or + // underflow MIN_INT64, then it's subtraction + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3a3a3a3a3a3a3a3a; + Result = 0; + Status = SafeInt64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x2020202020202020, Result); + + Minuend = 0x3a3a3a3a3a3a3a3a; + Subtrahend = 0x5a5a5a5a5a5a5a5a; + Status = SafeInt64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((-2314885530818453536), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-8825501086245354106); + Subtrahend = 8825501086245354106; + Status = SafeInt64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (8825501086245354106); + Subtrahend = (-8825501086245354106); + Status = SafeInt64Sub (Minuend, Subtrahend, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +// +// Multiplication function tests: +// +TEST(MultiplicationTestSuite, TestSafeUint8Mult) { + RETURN_STATUS Status; + UINT8 Multiplicand; + UINT8 Multiplier; + UINT8 Result; + + // + // If the result of multiplication doesn't overflow MAX_UINT8, it will succeed + // + Multiplicand = 0x12; + Multiplier = 0xa; + Result = 0; + Status = SafeUint8Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xb4, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x12; + Multiplier = 0x23; + Status = SafeUint8Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeUint16Mult) { + RETURN_STATUS Status; + UINT16 Multiplicand; + UINT16 Multiplier; + UINT16 Result; + + // + // If the result of multiplication doesn't overflow MAX_UINT16, it will succeed + // + Multiplicand = 0x212; + Multiplier = 0x7a; + Result = 0; + Status = SafeUint16Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0xfc94, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x1234; + Multiplier = 0x213; + Status = SafeUint16Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeUint32Mult) { + RETURN_STATUS Status; + UINT32 Multiplicand; + UINT32 Multiplier; + UINT32 Result; + + // + // If the result of multiplication doesn't overflow MAX_UINT32, it will succeed + // + Multiplicand = 0xa122a; + Multiplier = 0xd23; + Result = 0; + Status = SafeUint32Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x844c9dbe, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0xa122a; + Multiplier = 0xed23; + Status = SafeUint32Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeUint64Mult) { + RETURN_STATUS Status; + UINT64 Multiplicand; + UINT64 Multiplier; + UINT64 Result; + + // + // If the result of multiplication doesn't overflow MAX_UINT64, it will succeed + // + Multiplicand = 0x123456789a; + Multiplier = 0x1234567; + Result = 0; + Status = SafeUint64Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ ((UINT64)0x14b66db9745a07f6, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789a; + Multiplier = 0x12345678; + Status = SafeUint64Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeInt8Mult) { + RETURN_STATUS Status; + INT8 Multiplicand; + INT8 Multiplier; + INT8 Result; + + // + // If the result of multiplication doesn't overflow MAX_INT8 and doesn't + // underflow MIN_UINT8, it will succeed + // + Multiplicand = 0x12; + Multiplier = 0x7; + Result = 0; + Status = SafeInt8Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7e, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x12; + Multiplier = 0xa; + Status = SafeInt8Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeInt16Mult) { + RETURN_STATUS Status; + INT16 Multiplicand; + INT16 Multiplier; + INT16 Result; + + // + // If the result of multiplication doesn't overflow MAX_INT16 and doesn't + // underflow MIN_UINT16, it will succeed + // + Multiplicand = 0x123; + Multiplier = 0x67; + Result = 0; + Status = SafeInt16Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x7515, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123; + Multiplier = 0xab; + Status = SafeInt16Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeInt32Mult) { + RETURN_STATUS Status; + INT32 Multiplicand; + INT32 Multiplier; + INT32 Result; + + // + // If the result of multiplication doesn't overflow MAX_INT32 and doesn't + // underflow MIN_UINT32, it will succeed + // + Multiplicand = 0x123456; + Multiplier = 0x678; + Result = 0; + Status = SafeInt32Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x75c28c50, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456; + Multiplier = 0xabc; + Status = SafeInt32Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +TEST(MultiplicationTestSuite, TestSafeInt64Mult) { + RETURN_STATUS Status; + INT64 Multiplicand; + INT64 Multiplier; + INT64 Result; + + // + // If the result of multiplication doesn't overflow MAX_INT64 and doesn't + // underflow MIN_UINT64, it will succeed + // + Multiplicand = 0x123456789; + Multiplier = 0x6789abcd; + Result = 0; + Status = SafeInt64Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (Status, RETURN_SUCCESS); + ASSERT_EQ (0x75cd9045220d6bb5, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789; + Multiplier = 0xa789abcd; + Status = SafeInt64Mult (Multiplicand, Multiplier, &Result); + ASSERT_EQ (RETURN_BUFFER_TOO_SMALL, Status); +} + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc index 0cac14f0e5..b8b186dd8b 100644 --- a/MdePkg/Test/MdePkgHostTest.dsc +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -28,6 +28,7 @@ # MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf + MdePkg/Test/GoogleTest/Library/BaseSafeIntLib/GoogleTestBaseSafeIntLib.inf # # Build HOST_APPLICATION Libraries From b76f6962170d48eb91ad2ce299af9433519c537c Mon Sep 17 00:00:00 2001 From: "Duggapu, Chinni B" Date: Mon, 7 Nov 2022 14:47:31 +0800 Subject: [PATCH 0321/1529] UefiCpuPkg/ResetVector:Add Option to reserve 4K region at 4GB REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4140 Some implementations may need to keep the initial Reset code to be separated out from rest of the code.This request is to add padding at lower 4K region below 4 GB which will result having only few jmp instructions and data at that region. Reviewed-by: Ray Ni Signed-off-by: Duggapu Chinni B --- UefiCpuPkg/ResetVector/Vtf0/Ia16/ResetVectorVtf0.asm | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/ResetVector/Vtf0/Ia16/ResetVectorVtf0.asm b/UefiCpuPkg/ResetVector/Vtf0/Ia16/ResetVectorVtf0.asm index 7538192876..fe5bbea803 100644 --- a/UefiCpuPkg/ResetVector/Vtf0/Ia16/ResetVectorVtf0.asm +++ b/UefiCpuPkg/ResetVector/Vtf0/Ia16/ResetVectorVtf0.asm @@ -21,7 +21,15 @@ ALIGN 16 ; located just below 0x100000000 (4GB) in the firmware device. ; %ifdef ALIGN_TOP_TO_4K_FOR_PAGING - TIMES (0x1000 - ($ - EndOfPageTables) - 0x20) DB 0 + TIMES (0x1000 - ($ - EndOfPageTables)) DB 0 +; +; Pad the VTF0 Reset code for Bsp & Ap to 4k aligned block. +; Some implementations may need to keep the initial Reset code +; to be separated out from rest of the code. +; This padding will make sure lower 4K region below 4 GB may +; only contains few jmp instructions and data. +; + TIMES (0x1000 - 0x20) DB 0 %endif applicationProcessorEntryPoint: From 943d54fc23aa0d326801565c4f5428a6c91c1f38 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Mon, 7 Nov 2022 14:30:26 +0800 Subject: [PATCH 0322/1529] OvmfPkg/UefiCpuPkg/UefiPayloadPkg: Rename VmgExitLib to CcExitLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4123 VmgExitLib once was designed to provide interfaces to support #VC handler and issue VMGEXIT instruction. After TDVF (enable TDX feature in OVMF) is introduced, this library is updated to support #VE as well. Now the name of VmgExitLib cannot reflect what the lib does. This patch renames VmgExitLib to CcExitLib (Cc means Confidential Computing). This is a simple renaming and there is no logic changes. After renaming all the VmgExitLib related codes are updated with CcExitLib. These changes are in OvmfPkg/UefiCpuPkg/UefiPayloadPkg. Cc: Guo Dong Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Cc: Eric Dong Cc: Ray Ni Cc: Brijesh Singh Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: James Lu Reviewed-by: Gua Guo Reviewed-by: Jiewen Yao Reviewed-by: Ray Ni Signed-off-by: Min Xu --- OvmfPkg/AmdSev/AmdSevX64.dsc | 4 +- OvmfPkg/Bhyve/BhyveX64.dsc | 2 +- OvmfPkg/CloudHv/CloudHvX64.dsc | 6 +-- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 4 +- .../DxeMemEncryptSevLib.inf | 2 +- .../PeiMemEncryptSevLib.inf | 2 +- .../SecMemEncryptSevLib.inf | 2 +- .../X64/SnpPageStateChangeInternal.c | 2 +- .../VmgExitLib.c => CcExitLib/CcExitLib.c} | 5 ++- .../CcExitLib.inf} | 17 +++++---- .../CcExitTd.h} | 4 +- .../CcExitVcHandler.c} | 5 +-- .../CcExitVcHandler.h} | 6 +-- .../CcExitVeHandler.c} | 4 +- .../PeiDxeCcExitVcHandler.c} | 4 +- .../SecCcExitLib.inf} | 14 +++---- .../SecCcExitVcHandler.c} | 4 +- .../X64/TdVmcallCpuid.nasm | 0 OvmfPkg/Microvm/MicrovmX64.dsc | 4 +- OvmfPkg/OvmfPkgIa32.dsc | 4 +- OvmfPkg/OvmfPkgIa32X64.dsc | 4 +- OvmfPkg/OvmfPkgX64.dsc | 6 +-- OvmfPkg/OvmfXen.dsc | 2 +- OvmfPkg/PlatformPei/AmdSev.c | 2 +- OvmfPkg/PlatformPei/PlatformPei.inf | 2 +- .../FvbServicesRuntimeDxe.inf | 2 +- .../QemuFlashDxe.c | 2 +- .../Library/{VmgExitLib.h => CcExitLib.h} | 13 ++++--- .../CcExitLibNull.c} | 33 +++++++++++++++- .../CcExitLibNull.inf} | 12 +++--- .../Library/CcExitLibNull/CcExitLibNull.uni | 14 +++++++ .../DxeCpuExceptionHandlerLib.inf | 2 +- .../PeiCpuExceptionHandlerLib.inf | 2 +- .../PeiDxeSmmCpuException.c | 2 +- .../SecPeiCpuException.c | 2 +- .../SecPeiCpuExceptionHandlerLib.inf | 2 +- .../SmmCpuExceptionHandlerLib.inf | 2 +- .../Xcode5SecPeiCpuExceptionHandlerLib.inf | 2 +- UefiCpuPkg/Library/MpInitLib/AmdSev.c | 2 +- UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 2 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 2 +- UefiCpuPkg/Library/MpInitLib/MpLib.c | 2 +- UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 2 +- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c | 2 +- .../Library/VmgExitLibNull/VmTdExitNull.c | 38 ------------------- .../Library/VmgExitLibNull/VmgExitLibNull.uni | 15 -------- UefiCpuPkg/UefiCpuPkg.dec | 4 +- UefiCpuPkg/UefiCpuPkg.dsc | 4 +- UefiPayloadPkg/UefiPayloadPkg.dsc | 2 +- 49 files changed, 135 insertions(+), 141 deletions(-) rename OvmfPkg/Library/{VmgExitLib/VmgExitLib.c => CcExitLib/CcExitLib.c} (94%) rename OvmfPkg/Library/{VmgExitLib/VmgExitLib.inf => CcExitLib/CcExitLib.inf} (66%) rename OvmfPkg/Library/{VmgExitLib/VmTdExitHandler.h => CcExitLib/CcExitTd.h} (86%) rename OvmfPkg/Library/{VmgExitLib/VmgExitVcHandler.c => CcExitLib/CcExitVcHandler.c} (95%) rename OvmfPkg/Library/{VmgExitLib/VmgExitVcHandler.h => CcExitLib/CcExitVcHandler.h} (89%) rename OvmfPkg/Library/{VmgExitLib/VmTdExitVeHandler.c => CcExitLib/CcExitVeHandler.c} (95%) rename OvmfPkg/Library/{VmgExitLib/PeiDxeVmgExitVcHandler.c => CcExitLib/PeiDxeCcExitVcHandler.c} (94%) rename OvmfPkg/Library/{VmgExitLib/SecVmgExitLib.inf => CcExitLib/SecCcExitLib.inf} (79%) rename OvmfPkg/Library/{VmgExitLib/SecVmgExitVcHandler.c => CcExitLib/SecCcExitVcHandler.c} (94%) rename OvmfPkg/Library/{VmgExitLib => CcExitLib}/X64/TdVmcallCpuid.nasm (100%) rename UefiCpuPkg/Include/Library/{VmgExitLib.h => CcExitLib.h} (89%) rename UefiCpuPkg/Library/{VmgExitLibNull/VmgExitLibNull.c => CcExitLibNull/CcExitLibNull.c} (79%) rename UefiCpuPkg/Library/{VmgExitLibNull/VmgExitLibNull.inf => CcExitLibNull/CcExitLibNull.inf} (60%) create mode 100644 UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.uni delete mode 100644 UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c delete mode 100644 UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.uni diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 90e8a213ef..8f7cae787e 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -204,7 +204,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf [LibraryClasses.common.SEC] @@ -229,7 +229,7 @@ !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf !endif - VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc index 475b88b21a..e3bb367b6b 100644 --- a/OvmfPkg/Bhyve/BhyveX64.dsc +++ b/OvmfPkg/Bhyve/BhyveX64.dsc @@ -232,7 +232,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf [LibraryClasses.common.SEC] diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 10b16104ac..ce277cb239 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -251,7 +251,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf [LibraryClasses.common.SEC] @@ -275,7 +275,7 @@ !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf !endif - VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] @@ -915,7 +915,7 @@ # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf { - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf } MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index c0c1a15b09..3458926515 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -215,7 +215,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf PlatformInitLib|OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf @@ -237,7 +237,7 @@ !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf !endif - VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf PrePiHobListPointerLib|OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf index 35b7d519d9..cc24961c92 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf @@ -51,7 +51,7 @@ DebugLib MemoryAllocationLib PcdLib - VmgExitLib + CcExitLib [FeaturePcd] gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLib.inf index 714da33237..8f56783da5 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLib.inf +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLib.inf @@ -51,7 +51,7 @@ DebugLib MemoryAllocationLib PcdLib - VmgExitLib + CcExitLib [FeaturePcd] gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf index 284e5acc11..b6d76e7e63 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf @@ -48,7 +48,7 @@ CpuLib DebugLib PcdLib - VmgExitLib + CcExitLib [FixedPcd] gUefiCpuPkgTokenSpaceGuid.PcdSevEsWorkAreaBase diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c index d11aafae84..73698a7b9d 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include diff --git a/OvmfPkg/Library/VmgExitLib/VmgExitLib.c b/OvmfPkg/Library/CcExitLib/CcExitLib.c similarity index 94% rename from OvmfPkg/Library/VmgExitLib/VmgExitLib.c rename to OvmfPkg/Library/CcExitLib/CcExitLib.c index c205521870..477064cde2 100644 --- a/OvmfPkg/Library/VmgExitLib/VmgExitLib.c +++ b/OvmfPkg/Library/CcExitLib/CcExitLib.c @@ -1,7 +1,8 @@ /** @file - VMGEXIT Support Library. + CcExitLib Support Library. Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (C) 2020 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -9,7 +10,7 @@ #include #include #include -#include +#include #include /** diff --git a/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf b/OvmfPkg/Library/CcExitLib/CcExitLib.inf similarity index 66% rename from OvmfPkg/Library/VmgExitLib/VmgExitLib.inf rename to OvmfPkg/Library/CcExitLib/CcExitLib.inf index 255b0c1a2f..131fa62675 100644 --- a/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf +++ b/OvmfPkg/Library/CcExitLib/CcExitLib.inf @@ -1,18 +1,19 @@ ## @file -# VMGEXIT Support Library. +# CcExitLib Library. # # Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+# Copyright (C) 2020 - 2022, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## [Defines] INF_VERSION = 0x00010005 - BASE_NAME = VmgExitLib + BASE_NAME = CcExitLib FILE_GUID = 0e923c25-13cd-430b-8714-ffe85652a97b MODULE_TYPE = BASE VERSION_STRING = 1.0 - LIBRARY_CLASS = VmgExitLib|PEIM DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER + LIBRARY_CLASS = CcExitLib|PEIM DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_DRIVER # # The following information is for reference only and not required by the build tools. @@ -21,11 +22,11 @@ # [Sources.common] - VmgExitLib.c - VmgExitVcHandler.c - VmgExitVcHandler.h - PeiDxeVmgExitVcHandler.c - VmTdExitVeHandler.c + CcExitLib.c + CcExitVcHandler.c + CcExitVcHandler.h + PeiDxeCcExitVcHandler.c + CcExitVeHandler.c X64/TdVmcallCpuid.nasm [Packages] diff --git a/OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h b/OvmfPkg/Library/CcExitLib/CcExitTd.h similarity index 86% rename from OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h rename to OvmfPkg/Library/CcExitLib/CcExitTd.h index 7eacd0872f..013a55e207 100644 --- a/OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h +++ b/OvmfPkg/Library/CcExitLib/CcExitTd.h @@ -5,8 +5,8 @@ **/ -#ifndef VMTD_EXIT_HANDLER_H_ -#define VMTD_EXIT_HANDLER_H_ +#ifndef CC_EXIT_TD_H_ +#define CC_EXIT_TD_H_ #include #include diff --git a/OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c similarity index 95% rename from OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.c rename to OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index a4393dffbd..ad2a922c9f 100644 --- a/OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -11,13 +11,12 @@ #include #include #include -#include +#include #include #include #include -#include "VmgExitVcHandler.h" -// #include +#include "CcExitVcHandler.h" // // Instruction execution mode definition diff --git a/OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.h b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.h similarity index 89% rename from OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.h rename to OvmfPkg/Library/CcExitLib/CcExitVcHandler.h index 3a37cb04f6..464591fcb7 100644 --- a/OvmfPkg/Library/VmgExitLib/VmgExitVcHandler.h +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.h @@ -6,12 +6,12 @@ **/ -#ifndef __VMG_EXIT_VC_HANDLER_H__ -#define __VMG_EXIT_VC_HANDLER_H__ +#ifndef CC_EXIT_VC_HANDLER_H_ +#define CC_EXIT_VC_HANDLER_H_ #include #include -#include +#include /** Handle a #VC exception. diff --git a/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c similarity index 95% rename from OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c rename to OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index c89268c5d8..08e92c66ce 100644 --- a/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -8,8 +8,8 @@ #include #include -#include "VmTdExitHandler.h" -#include +#include "CcExitTd.h" +#include #include #include #include diff --git a/OvmfPkg/Library/VmgExitLib/PeiDxeVmgExitVcHandler.c b/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c similarity index 94% rename from OvmfPkg/Library/VmgExitLib/PeiDxeVmgExitVcHandler.c rename to OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c index e3d0715837..bb718161f5 100644 --- a/OvmfPkg/Library/VmgExitLib/PeiDxeVmgExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c @@ -10,10 +10,10 @@ #include #include #include -#include +#include #include -#include "VmgExitVcHandler.h" +#include "CcExitVcHandler.h" /** Handle a #VC exception. diff --git a/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf b/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf similarity index 79% rename from OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf rename to OvmfPkg/Library/CcExitLib/SecCcExitLib.inf index f9bd4974f6..1ee22ce0ae 100644 --- a/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf +++ b/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf @@ -8,11 +8,11 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = SecVmgExitLib + BASE_NAME = SecCcExitLib FILE_GUID = dafff819-f86c-4cff-a70e-83161e5bcf9a MODULE_TYPE = BASE VERSION_STRING = 1.0 - LIBRARY_CLASS = VmgExitLib|SEC + LIBRARY_CLASS = CcExitLib|SEC # # The following information is for reference only and not required by the build tools. @@ -21,11 +21,11 @@ # [Sources.common] - VmgExitLib.c - VmgExitVcHandler.c - VmgExitVcHandler.h - SecVmgExitVcHandler.c - VmTdExitVeHandler.c + CcExitLib.c + CcExitVcHandler.c + CcExitVcHandler.h + SecCcExitVcHandler.c + CcExitVeHandler.c X64/TdVmcallCpuid.nasm [Packages] diff --git a/OvmfPkg/Library/VmgExitLib/SecVmgExitVcHandler.c b/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c similarity index 94% rename from OvmfPkg/Library/VmgExitLib/SecVmgExitVcHandler.c rename to OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c index fe8680f831..769e0b5b74 100644 --- a/OvmfPkg/Library/VmgExitLib/SecVmgExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c @@ -10,10 +10,10 @@ #include #include #include -#include +#include #include -#include "VmgExitVcHandler.h" +#include "CcExitVcHandler.h" /** Handle a #VC exception. diff --git a/OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm b/OvmfPkg/Library/CcExitLib/X64/TdVmcallCpuid.nasm similarity index 100% rename from OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm rename to OvmfPkg/Library/CcExitLib/X64/TdVmcallCpuid.nasm diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 7eff8e2a88..994a02d301 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -249,7 +249,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf @@ -277,7 +277,7 @@ !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf !endif - VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index e9ba491237..6f774baf90 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -256,7 +256,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf @@ -984,7 +984,7 @@ # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf { - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf } MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index af566b953f..c851764dec 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -260,7 +260,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf @@ -1002,7 +1002,7 @@ # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf { - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf } MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index f39d9cd117..63c3a47aea 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -276,7 +276,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf @@ -302,7 +302,7 @@ !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf !endif - VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf + CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf CcProbeLib|OvmfPkg/Library/CcProbeLib/SecPeiCcProbeLib.inf @@ -1072,7 +1072,7 @@ # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf { - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf } MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index 58a7c97cdd..8bb497088b 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -231,7 +231,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf [LibraryClasses.common.SEC] diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index 385562b44c..80a1194ffc 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include "Platform.h" diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf index 3cd83e6ec3..1fadadeb55 100644 --- a/OvmfPkg/PlatformPei/PlatformPei.inf +++ b/OvmfPkg/PlatformPei/PlatformPei.inf @@ -63,7 +63,7 @@ MtrrLib MemEncryptSevLib PcdLib - VmgExitLib + CcExitLib PlatformInitLib [Pcd] diff --git a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf index 8bb2325157..f471704789 100644 --- a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf +++ b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf @@ -53,7 +53,7 @@ UefiBootServicesTableLib UefiDriverEntryPoint UefiRuntimeLib - VmgExitLib + CcExitLib [Guids] gEfiEventVirtualAddressChangeGuid # ALWAYS_CONSUMED diff --git a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c index 172d6a4267..58bcad825d 100644 --- a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c +++ b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include "QemuFlash.h" diff --git a/UefiCpuPkg/Include/Library/VmgExitLib.h b/UefiCpuPkg/Include/Library/CcExitLib.h similarity index 89% rename from UefiCpuPkg/Include/Library/VmgExitLib.h rename to UefiCpuPkg/Include/Library/CcExitLib.h index f9f911099a..1ae618c19b 100644 --- a/UefiCpuPkg/Include/Library/VmgExitLib.h +++ b/UefiCpuPkg/Include/Library/CcExitLib.h @@ -1,16 +1,19 @@ /** @file - Public header file for the VMGEXIT Support library class. + Public header file for the CcExitLib. - This library class defines some routines used when invoking the VMGEXIT - instruction in support of SEV-ES and to handle #VC exceptions. + This library class defines some routines used for below CcExit handler. + - Invoking the VMGEXIT instruction in support of SEV-ES and to handle + #VC exceptions. + - Handle #VE exception in TDX. Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#ifndef __VMG_EXIT_LIB_H__ -#define __VMG_EXIT_LIB_H__ +#ifndef CC_EXIT_LIB_H_ +#define CC_EXIT_LIB_H_ #include #include diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.c b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c similarity index 79% rename from UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.c rename to UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c index d661d85974..79eca74e13 100644 --- a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.c +++ b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c @@ -1,14 +1,15 @@ /** @file - VMGEXIT Base Support Library. + CcExit Base Support Library. Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include #include -#include +#include /** Perform VMGEXIT. @@ -163,3 +164,31 @@ VmgExitHandleVc ( return EFI_UNSUPPORTED; } + +/** + Handle a #VE exception. + + Performs the necessary processing to handle a #VE exception. + + @param[in, out] ExceptionType Pointer to an EFI_EXCEPTION_TYPE to be set + as value to use on error. + @param[in, out] SystemContext Pointer to EFI_SYSTEM_CONTEXT + + @retval EFI_SUCCESS Exception handled + @retval EFI_UNSUPPORTED #VE not supported, (new) exception value to + propagate provided + @retval EFI_PROTOCOL_ERROR #VE handling failed, (new) exception value to + propagate provided + +**/ +EFI_STATUS +EFIAPI +VmTdExitHandleVe ( + IN OUT EFI_EXCEPTION_TYPE *ExceptionType, + IN OUT EFI_SYSTEM_CONTEXT SystemContext + ) +{ + *ExceptionType = VE_EXCEPTION; + + return EFI_UNSUPPORTED; +} diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf similarity index 60% rename from UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf rename to UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf index 4aab601939..ed7f611cbc 100644 --- a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf +++ b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf @@ -1,23 +1,23 @@ ## @file -# VMGEXIT Support Library. +# CcExit Base Support Library. # # Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+# Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## [Defines] INF_VERSION = 0x00010005 - BASE_NAME = VmgExitLibNull - MODULE_UNI_FILE = VmgExitLibNull.uni + BASE_NAME = CcExitLibNull + MODULE_UNI_FILE = CcExitLibNull.uni FILE_GUID = 3cd7368f-ef9b-4a9b-9571-2ed93813677e MODULE_TYPE = BASE VERSION_STRING = 1.0 - LIBRARY_CLASS = VmgExitLib + LIBRARY_CLASS = CcExitLib [Sources.common] - VmgExitLibNull.c - VmTdExitNull.c + CcExitLibNull.c [Packages] MdePkg/MdePkg.dec diff --git a/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.uni b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.uni new file mode 100644 index 0000000000..b18ae8792e --- /dev/null +++ b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.uni @@ -0,0 +1,14 @@ +// /** @file +// CcExitLib instance. +// +// Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+// Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "CcExitLib NULL instance" + +#string STR_MODULE_DESCRIPTION #language en-US "CcExitLib NULL instance." + diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf index e7a81bebdb..d0f82095cf 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf @@ -60,4 +60,4 @@ PeCoffGetEntryPointLib MemoryAllocationLib DebugLib - VmgExitLib + CcExitLib diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf index 7c2ec3b2db..5339f8e604 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf @@ -52,7 +52,7 @@ HobLib MemoryAllocationLib SynchronizationLib - VmgExitLib + CcExitLib [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard # CONSUMES diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c index a7d0897ef1..2b6d9da5c7 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c @@ -7,7 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include -#include +#include #include "CpuExceptionCommon.h" /** diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c index ad5e0e9ed4..0a9ea79f52 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c @@ -7,7 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include -#include +#include #include "CpuExceptionCommon.h" CONST UINTN mDoFarReturnFlag = 0; diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf index 6a170286c8..df44371fe0 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf @@ -48,7 +48,7 @@ PrintLib LocalApicLib PeCoffGetEntryPointLib - VmgExitLib + CcExitLib [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf index 9dde07612a..8f8a5dab79 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf @@ -51,7 +51,7 @@ LocalApicLib PeCoffGetEntryPointLib DebugLib - VmgExitLib + CcExitLib [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf index 6d2f66504a..619b39d7f1 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf @@ -53,7 +53,7 @@ PrintLib LocalApicLib PeCoffGetEntryPointLib - VmgExitLib + CcExitLib [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard diff --git a/UefiCpuPkg/Library/MpInitLib/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/AmdSev.c index 4e4c63a52d..2dd8f4d746 100644 --- a/UefiCpuPkg/Library/MpInitLib/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/AmdSev.c @@ -8,7 +8,7 @@ **/ #include "MpLib.h" -#include +#include /** Get Protected mode code segment with 16-bit default addressing diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index e1cd0b3500..cd07de3a3c 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -54,7 +54,7 @@ DebugAgentLib SynchronizationLib PcdLib - VmgExitLib + CcExitLib MicrocodeLib [Protocols] diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index 78cc3e2b93..ef56af1f73 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index 1c053f87a4..e5dc852ed9 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -9,7 +9,7 @@ **/ #include "MpLib.h" -#include +#include #include #include diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf index 5facf4db94..afd551bb0f 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf @@ -53,7 +53,7 @@ SynchronizationLib PeiServicesLib PcdLib - VmgExitLib + CcExitLib MicrocodeLib [Pcd] diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c index a3cd377ef6..4c4f81af7c 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c @@ -9,7 +9,7 @@ **/ #include "MpLib.h" -#include +#include #include #include diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c b/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c deleted file mode 100644 index 6a4e8087cb..0000000000 --- a/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c +++ /dev/null @@ -1,38 +0,0 @@ -/** @file - - Copyright (c) 2021, Intel Corporation. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ -#include -#include -#include - -/** - Handle a #VE exception. - - Performs the necessary processing to handle a #VE exception. - - @param[in, out] ExceptionType Pointer to an EFI_EXCEPTION_TYPE to be set - as value to use on error. - @param[in, out] SystemContext Pointer to EFI_SYSTEM_CONTEXT - - @retval EFI_SUCCESS Exception handled - @retval EFI_UNSUPPORTED #VE not supported, (new) exception value to - propagate provided - @retval EFI_PROTOCOL_ERROR #VE handling failed, (new) exception value to - propagate provided - -**/ -EFI_STATUS -EFIAPI -VmTdExitHandleVe ( - IN OUT EFI_EXCEPTION_TYPE *ExceptionType, - IN OUT EFI_SYSTEM_CONTEXT SystemContext - ) -{ - *ExceptionType = VE_EXCEPTION; - - return EFI_UNSUPPORTED; -} diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.uni b/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.uni deleted file mode 100644 index 8639bc0e8c..0000000000 --- a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.uni +++ /dev/null @@ -1,15 +0,0 @@ -// /** @file -// VMGEXIT support library instance. -// -// VMGEXIT support library instance. -// -// Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
-// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "VMGEXIT support NULL library instance" - -#string STR_MODULE_DESCRIPTION #language en-US "VMGEXIT support NULL library instance." - diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 718323d904..cff239d528 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -53,8 +53,8 @@ ## MpInitLib|Include/Library/MpInitLib.h - ## @libraryclass Provides function to support VMGEXIT processing. - VmgExitLib|Include/Library/VmgExitLib.h + ## @libraryclass Provides function to support CcExit processing. + CcExitLib|Include/Library/CcExitLib.h ## @libraryclass Provides function to get CPU cache information. CpuCacheInfoLib|Include/Library/CpuCacheInfoLib.h diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index 0e1a99ddc0..67b0ce46e4 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -59,7 +59,7 @@ PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf SmmCpuRendezvousLib|UefiCpuPkg/Library/SmmCpuRendezvousLib/SmmCpuRendezvousLib.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf @@ -163,7 +163,7 @@ UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf - UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf UefiCpuPkg/PiSmmCommunication/PiSmmCommunicationPei.inf UefiCpuPkg/PiSmmCommunication/PiSmmCommunicationSmm.inf UefiCpuPkg/SecCore/SecCore.inf diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 1150be6acd..723a50a422 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -301,7 +301,7 @@ VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf - VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf + CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf [LibraryClasses.common] From 5d98fe28a607093edc367ca03c9f90bc4c125be8 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Mon, 7 Nov 2022 15:50:11 +0800 Subject: [PATCH 0323/1529] OvmfPkg/UefiCpuPkg: Add CcExit prefix to the APIs of CcExitLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4123 APIs which are defined in CcExitLib.h are added with the CcExit prefix. This is to make the APIs' name more meaningful. This change impacts OvmfPkg/UefiCpuPkg. Cc: Eric Dong Cc: Ray Ni Cc: Brijesh Singh Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Jiewen Yao Reviewed-by: Ray Ni Signed-off-by: Min Xu --- .../X64/SnpPageStateChangeInternal.c | 8 +- OvmfPkg/Library/CcExitLib/CcExitLib.c | 18 +-- OvmfPkg/Library/CcExitLib/CcExitVcHandler.c | 124 +++++++++--------- OvmfPkg/Library/CcExitLib/CcExitVeHandler.c | 2 +- .../Library/CcExitLib/PeiDxeCcExitVcHandler.c | 2 +- .../Library/CcExitLib/SecCcExitVcHandler.c | 2 +- OvmfPkg/PlatformPei/AmdSev.c | 8 +- .../QemuFlashDxe.c | 8 +- UefiCpuPkg/Include/Library/CcExitLib.h | 16 +-- .../Library/CcExitLibNull/CcExitLibNull.c | 16 +-- .../PeiDxeSmmCpuException.c | 4 +- .../SecPeiCpuException.c | 4 +- UefiCpuPkg/Library/MpInitLib/AmdSev.c | 8 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 6 +- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c | 8 +- 15 files changed, 117 insertions(+), 117 deletions(-) diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c index 73698a7b9d..4d684964d8 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c @@ -193,9 +193,9 @@ PageStateChangeVmgExit ( // while (Info->Header.CurrentEntry <= Info->Header.EndEntry) { Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_SNP_PAGE_STATE_CHANGE, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_SNP_PAGE_STATE_CHANGE, 0, 0); // // The Page State Change VMGEXIT can pass the failure through the @@ -251,7 +251,7 @@ InternalSetPageState ( // // Initialize the GHCB // - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); // // Build the page state structure @@ -293,7 +293,7 @@ InternalSetPageState ( PvalidateRange (Info, CurrentEntry, EndEntry, TRUE); } - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); BaseAddress = NextAddress; } diff --git a/OvmfPkg/Library/CcExitLib/CcExitLib.c b/OvmfPkg/Library/CcExitLib/CcExitLib.c index 477064cde2..e256000fb2 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitLib.c +++ b/OvmfPkg/Library/CcExitLib/CcExitLib.c @@ -103,7 +103,7 @@ VmgExitErrorCheck ( **/ UINT64 EFIAPI -VmgExit ( +CcExitVmgExit ( IN OUT GHCB *Ghcb, IN UINT64 ExitCode, IN UINT64 ExitInfo1, @@ -114,9 +114,9 @@ VmgExit ( Ghcb->SaveArea.SwExitInfo1 = ExitInfo1; Ghcb->SaveArea.SwExitInfo2 = ExitInfo2; - VmgSetOffsetValid (Ghcb, GhcbSwExitCode); - VmgSetOffsetValid (Ghcb, GhcbSwExitInfo1); - VmgSetOffsetValid (Ghcb, GhcbSwExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwExitCode); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwExitInfo1); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwExitInfo2); // // Guest memory is used for the guest-hypervisor communication, so fence @@ -138,12 +138,12 @@ VmgExit ( @param[in, out] Ghcb A pointer to the GHCB @param[in, out] InterruptState A pointer to hold the current interrupt - state, used for restoring in VmgDone () + state, used for restoring in CcExitVmgDone () **/ VOID EFIAPI -VmgInit ( +CcExitVmgInit ( IN OUT GHCB *Ghcb, IN OUT BOOLEAN *InterruptState ) @@ -173,7 +173,7 @@ VmgInit ( **/ VOID EFIAPI -VmgDone ( +CcExitVmgDone ( IN OUT GHCB *Ghcb, IN BOOLEAN InterruptState ) @@ -195,7 +195,7 @@ VmgDone ( **/ VOID EFIAPI -VmgSetOffsetValid ( +CcExitVmgSetOffsetValid ( IN OUT GHCB *Ghcb, IN GHCB_REGISTER Offset ) @@ -224,7 +224,7 @@ VmgSetOffsetValid ( **/ BOOLEAN EFIAPI -VmgIsOffsetValid ( +CcExitVmgIsOffsetValid ( IN GHCB *Ghcb, IN GHCB_REGISTER Offset ) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index ad2a922c9f..985e547977 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -611,7 +611,7 @@ UnsupportedExit ( { UINT64 Status; - Status = VmgExit (Ghcb, SVM_EXIT_UNSUPPORTED, Regs->ExceptionData, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_UNSUPPORTED, Regs->ExceptionData, 0); if (Status == 0) { GHCB_EVENT_INJECTION Event; @@ -755,8 +755,8 @@ MmioExit ( CopyMem (Ghcb->SharedBuffer, &InstructionData->Ext.RegData, Bytes); Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -807,8 +807,8 @@ MmioExit ( CopyMem (Ghcb->SharedBuffer, &Regs->Rax, Bytes); Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -843,8 +843,8 @@ MmioExit ( CopyMem (Ghcb->SharedBuffer, InstructionData->Immediate, Bytes); Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -882,8 +882,8 @@ MmioExit ( ExitInfo2 = Bytes; Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -942,8 +942,8 @@ MmioExit ( ExitInfo2 = Bytes; Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -979,8 +979,8 @@ MmioExit ( ExitInfo2 = Bytes; Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -1011,8 +1011,8 @@ MmioExit ( ExitInfo2 = Bytes; Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_READ, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -1068,11 +1068,11 @@ MwaitExit ( DecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); Ghcb->SaveArea.Rcx = Regs->Rcx; - VmgSetOffsetValid (Ghcb, GhcbRcx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRcx); - return VmgExit (Ghcb, SVM_EXIT_MWAIT, 0, 0); + return CcExitVmgExit (Ghcb, SVM_EXIT_MWAIT, 0, 0); } /** @@ -1100,13 +1100,13 @@ MonitorExit ( DecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; // Identity mapped, so VA = PA - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); Ghcb->SaveArea.Rcx = Regs->Rcx; - VmgSetOffsetValid (Ghcb, GhcbRcx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRcx); Ghcb->SaveArea.Rdx = Regs->Rdx; - VmgSetOffsetValid (Ghcb, GhcbRdx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRdx); - return VmgExit (Ghcb, SVM_EXIT_MONITOR, 0, 0); + return CcExitVmgExit (Ghcb, SVM_EXIT_MONITOR, 0, 0); } /** @@ -1131,7 +1131,7 @@ WbinvdExit ( IN SEV_ES_INSTRUCTION_DATA *InstructionData ) { - return VmgExit (Ghcb, SVM_EXIT_WBINVD, 0, 0); + return CcExitVmgExit (Ghcb, SVM_EXIT_WBINVD, 0, 0); } /** @@ -1160,14 +1160,14 @@ RdtscpExit ( DecodeModRm (Regs, InstructionData); - Status = VmgExit (Ghcb, SVM_EXIT_RDTSCP, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_RDTSCP, 0, 0); if (Status != 0) { return Status; } - if (!VmgIsOffsetValid (Ghcb, GhcbRax) || - !VmgIsOffsetValid (Ghcb, GhcbRcx) || - !VmgIsOffsetValid (Ghcb, GhcbRdx)) + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRcx) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRdx)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -1206,16 +1206,16 @@ VmmCallExit ( DecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); Ghcb->SaveArea.Cpl = (UINT8)(Regs->Cs & 0x3); - VmgSetOffsetValid (Ghcb, GhcbCpl); + CcExitVmgSetOffsetValid (Ghcb, GhcbCpl); - Status = VmgExit (Ghcb, SVM_EXIT_VMMCALL, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_VMMCALL, 0, 0); if (Status != 0) { return Status; } - if (!VmgIsOffsetValid (Ghcb, GhcbRax)) { + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -1254,28 +1254,28 @@ MsrExit ( case 0x30: // WRMSR ExitInfo1 = 1; Ghcb->SaveArea.Rax = Regs->Rax; - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); Ghcb->SaveArea.Rdx = Regs->Rdx; - VmgSetOffsetValid (Ghcb, GhcbRdx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRdx); // // fall through // case 0x32: // RDMSR Ghcb->SaveArea.Rcx = Regs->Rcx; - VmgSetOffsetValid (Ghcb, GhcbRcx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRcx); break; default: return UnsupportedExit (Ghcb, Regs, InstructionData); } - Status = VmgExit (Ghcb, SVM_EXIT_MSR, ExitInfo1, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_MSR, ExitInfo1, 0); if (Status != 0) { return Status; } if (ExitInfo1 == 0) { - if (!VmgIsOffsetValid (Ghcb, GhcbRax) || - !VmgIsOffsetValid (Ghcb, GhcbRdx)) + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRdx)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -1471,8 +1471,8 @@ IoioExit ( } Ghcb->SaveArea.SwScratch = (UINT64)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - Status = VmgExit (Ghcb, SVM_EXIT_IOIO_PROT, ExitInfo1, ExitInfo2); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_IOIO_PROT, ExitInfo1, ExitInfo2); if (Status != 0) { return Status; } @@ -1495,15 +1495,15 @@ IoioExit ( CopyMem (&Ghcb->SaveArea.Rax, &Regs->Rax, IOIO_DATA_BYTES (ExitInfo1)); } - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); - Status = VmgExit (Ghcb, SVM_EXIT_IOIO_PROT, ExitInfo1, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_IOIO_PROT, ExitInfo1, 0); if (Status != 0) { return Status; } if ((ExitInfo1 & IOIO_TYPE_IN) != 0) { - if (!VmgIsOffsetValid (Ghcb, GhcbRax)) { + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -1536,7 +1536,7 @@ InvdExit ( IN SEV_ES_INSTRUCTION_DATA *InstructionData ) { - return VmgExit (Ghcb, SVM_EXIT_INVD, 0, 0); + return CcExitVmgExit (Ghcb, SVM_EXIT_INVD, 0, 0); } /** @@ -1581,23 +1581,23 @@ GetCpuidHyp ( { *UnsupportedExit = FALSE; Ghcb->SaveArea.Rax = EaxIn; - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); Ghcb->SaveArea.Rcx = EcxIn; - VmgSetOffsetValid (Ghcb, GhcbRcx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRcx); if (EaxIn == CPUID_EXTENDED_STATE) { Ghcb->SaveArea.XCr0 = XCr0; - VmgSetOffsetValid (Ghcb, GhcbXCr0); + CcExitVmgSetOffsetValid (Ghcb, GhcbXCr0); } - *Status = VmgExit (Ghcb, SVM_EXIT_CPUID, 0, 0); + *Status = CcExitVmgExit (Ghcb, SVM_EXIT_CPUID, 0, 0); if (*Status != 0) { return FALSE; } - if (!VmgIsOffsetValid (Ghcb, GhcbRax) || - !VmgIsOffsetValid (Ghcb, GhcbRbx) || - !VmgIsOffsetValid (Ghcb, GhcbRcx) || - !VmgIsOffsetValid (Ghcb, GhcbRdx)) + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRbx) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRcx) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRdx)) { *UnsupportedExit = TRUE; return FALSE; @@ -2049,15 +2049,15 @@ RdpmcExit ( UINT64 Status; Ghcb->SaveArea.Rcx = Regs->Rcx; - VmgSetOffsetValid (Ghcb, GhcbRcx); + CcExitVmgSetOffsetValid (Ghcb, GhcbRcx); - Status = VmgExit (Ghcb, SVM_EXIT_RDPMC, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_RDPMC, 0, 0); if (Status != 0) { return Status; } - if (!VmgIsOffsetValid (Ghcb, GhcbRax) || - !VmgIsOffsetValid (Ghcb, GhcbRdx)) + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRdx)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -2092,13 +2092,13 @@ RdtscExit ( { UINT64 Status; - Status = VmgExit (Ghcb, SVM_EXIT_RDTSC, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_RDTSC, 0, 0); if (Status != 0) { return Status; } - if (!VmgIsOffsetValid (Ghcb, GhcbRax) || - !VmgIsOffsetValid (Ghcb, GhcbRdx)) + if (!CcExitVmgIsOffsetValid (Ghcb, GhcbRax) || + !CcExitVmgIsOffsetValid (Ghcb, GhcbRdx)) { return UnsupportedExit (Ghcb, Regs, InstructionData); } @@ -2150,9 +2150,9 @@ Dr7WriteExit ( // Using a value of 0 for ExitInfo1 means RAX holds the value // Ghcb->SaveArea.Rax = *Register; - VmgSetOffsetValid (Ghcb, GhcbRax); + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); - Status = VmgExit (Ghcb, SVM_EXIT_DR7_WRITE, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_DR7_WRITE, 0, 0); if (Status != 0) { return Status; } @@ -2243,7 +2243,7 @@ InternalVmgExitHandleVc ( Regs = SystemContext.SystemContextX64; - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); ExitCode = Regs->ExceptionData; switch (ExitCode) { @@ -2327,7 +2327,7 @@ InternalVmgExitHandleVc ( VcRet = EFI_PROTOCOL_ERROR; } - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); return VcRet; } diff --git a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index 08e92c66ce..081af7e12a 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -464,7 +464,7 @@ MmioExit ( **/ EFI_STATUS EFIAPI -VmTdExitHandleVe ( +CcExitHandleVe ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) diff --git a/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c index bb718161f5..522f747f08 100644 --- a/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/PeiDxeCcExitVcHandler.c @@ -33,7 +33,7 @@ **/ EFI_STATUS EFIAPI -VmgExitHandleVc ( +CcExitHandleVc ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) diff --git a/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c index 769e0b5b74..da70581af8 100644 --- a/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/SecCcExitVcHandler.c @@ -33,7 +33,7 @@ **/ EFI_STATUS EFIAPI -VmgExitHandleVc ( +CcExitHandleVc ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index 80a1194ffc..e1b9fd9b7f 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -50,7 +50,7 @@ AmdSevSnpInitialize ( } // - // Query the hypervisor feature using the VmgExit and set the value in the + // Query the hypervisor feature using the CcExitVmgExit and set the value in the // hypervisor features PCD. // HvFeatures = GetHypervisorFeature (); @@ -129,19 +129,19 @@ GetHypervisorFeature ( // // Initialize the GHCB // - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); // // Query the Hypervisor Features. // - Status = VmgExit (Ghcb, SVM_EXIT_HYPERVISOR_FEATURES, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_HYPERVISOR_FEATURES, 0, 0); if ((Status != 0)) { SevEsProtocolFailure (GHCB_TERMINATE_GHCB_GENERAL); } Features = Ghcb->SaveArea.SwExitInfo2; - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); return Features; } diff --git a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c index 58bcad825d..d57f7ca25c 100644 --- a/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c +++ b/OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlashDxe.c @@ -82,12 +82,12 @@ QemuFlashPtrWrite ( // #VC exception. Instead, use the VMGEXIT MMIO write support directly // to perform the update. // - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); Ghcb->SharedBuffer[0] = Value; Ghcb->SaveArea.SwScratch = (UINT64)(UINTN)Ghcb->SharedBuffer; - VmgSetOffsetValid (Ghcb, GhcbSwScratch); - VmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, PhysAddr, 1); - VmgDone (Ghcb, InterruptState); + CcExitVmgSetOffsetValid (Ghcb, GhcbSwScratch); + CcExitVmgExit (Ghcb, SVM_EXIT_MMIO_WRITE, PhysAddr, 1); + CcExitVmgDone (Ghcb, InterruptState); } else { *Ptr = Value; } diff --git a/UefiCpuPkg/Include/Library/CcExitLib.h b/UefiCpuPkg/Include/Library/CcExitLib.h index 1ae618c19b..3381d58369 100644 --- a/UefiCpuPkg/Include/Library/CcExitLib.h +++ b/UefiCpuPkg/Include/Library/CcExitLib.h @@ -41,7 +41,7 @@ **/ UINT64 EFIAPI -VmgExit ( +CcExitVmgExit ( IN OUT GHCB *Ghcb, IN UINT64 ExitCode, IN UINT64 ExitInfo1, @@ -56,12 +56,12 @@ VmgExit ( @param[in, out] Ghcb A pointer to the GHCB @param[in, out] InterruptState A pointer to hold the current interrupt - state, used for restoring in VmgDone () + state, used for restoring in CcExitVmgDone () **/ VOID EFIAPI -VmgInit ( +CcExitVmgInit ( IN OUT GHCB *Ghcb, IN OUT BOOLEAN *InterruptState ); @@ -79,7 +79,7 @@ VmgInit ( **/ VOID EFIAPI -VmgDone ( +CcExitVmgDone ( IN OUT GHCB *Ghcb, IN BOOLEAN InterruptState ); @@ -96,7 +96,7 @@ VmgDone ( **/ VOID EFIAPI -VmgSetOffsetValid ( +CcExitVmgSetOffsetValid ( IN OUT GHCB *Ghcb, IN GHCB_REGISTER Offset ); @@ -116,7 +116,7 @@ VmgSetOffsetValid ( **/ BOOLEAN EFIAPI -VmgIsOffsetValid ( +CcExitVmgIsOffsetValid ( IN GHCB *Ghcb, IN GHCB_REGISTER Offset ); @@ -142,7 +142,7 @@ VmgIsOffsetValid ( **/ EFI_STATUS EFIAPI -VmgExitHandleVc ( +CcExitHandleVc ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ); @@ -168,7 +168,7 @@ VmgExitHandleVc ( **/ EFI_STATUS EFIAPI -VmTdExitHandleVe ( +CcExitHandleVe ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ); diff --git a/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c index 79eca74e13..230e50705b 100644 --- a/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c +++ b/UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.c @@ -35,7 +35,7 @@ **/ UINT64 EFIAPI -VmgExit ( +CcExitVmgExit ( IN OUT GHCB *Ghcb, IN UINT64 ExitCode, IN UINT64 ExitInfo1, @@ -60,12 +60,12 @@ VmgExit ( @param[in, out] Ghcb A pointer to the GHCB @param[in, out] InterruptState A pointer to hold the current interrupt - state, used for restoring in VmgDone () + state, used for restoring in CcExitVmgDone () **/ VOID EFIAPI -VmgInit ( +CcExitVmgInit ( IN OUT GHCB *Ghcb, IN OUT BOOLEAN *InterruptState ) @@ -85,7 +85,7 @@ VmgInit ( **/ VOID EFIAPI -VmgDone ( +CcExitVmgDone ( IN OUT GHCB *Ghcb, IN BOOLEAN InterruptState ) @@ -104,7 +104,7 @@ VmgDone ( **/ VOID EFIAPI -VmgSetOffsetValid ( +CcExitVmgSetOffsetValid ( IN OUT GHCB *Ghcb, IN GHCB_REGISTER Offset ) @@ -126,7 +126,7 @@ VmgSetOffsetValid ( **/ BOOLEAN EFIAPI -VmgIsOffsetValid ( +CcExitVmgIsOffsetValid ( IN GHCB *Ghcb, IN GHCB_REGISTER Offset ) @@ -155,7 +155,7 @@ VmgIsOffsetValid ( **/ EFI_STATUS EFIAPI -VmgExitHandleVc ( +CcExitHandleVc ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) @@ -183,7 +183,7 @@ VmgExitHandleVc ( **/ EFI_STATUS EFIAPI -VmTdExitHandleVe ( +CcExitHandleVe ( IN OUT EFI_EXCEPTION_TYPE *ExceptionType, IN OUT EFI_SYSTEM_CONTEXT SystemContext ) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c index 2b6d9da5c7..748cf8d3bf 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c @@ -40,7 +40,7 @@ CommonExceptionHandlerWorker ( // On other - ExceptionType contains (possibly new) exception // value // - Status = VmgExitHandleVc (&ExceptionType, SystemContext); + Status = CcExitHandleVc (&ExceptionType, SystemContext); if (!EFI_ERROR (Status)) { return; } @@ -57,7 +57,7 @@ CommonExceptionHandlerWorker ( // On other - ExceptionType contains (possibly new) exception // value // - Status = VmTdExitHandleVe (&ExceptionType, SystemContext); + Status = CcExitHandleVe (&ExceptionType, SystemContext); if (!EFI_ERROR (Status)) { return; } diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c index 0a9ea79f52..497cd16499 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c @@ -39,7 +39,7 @@ CommonExceptionHandler ( // On other - ExceptionType contains (possibly new) exception // value // - Status = VmgExitHandleVc (&ExceptionType, SystemContext); + Status = CcExitHandleVc (&ExceptionType, SystemContext); if (!EFI_ERROR (Status)) { return; } @@ -57,7 +57,7 @@ CommonExceptionHandler ( // On other - ExceptionType contains (possibly new) exception // value // - Status = VmTdExitHandleVe (&ExceptionType, SystemContext); + Status = CcExitHandleVe (&ExceptionType, SystemContext); if (!EFI_ERROR (Status)) { return; } diff --git a/UefiCpuPkg/Library/MpInitLib/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/AmdSev.c index 2dd8f4d746..ca9bfed7f3 100644 --- a/UefiCpuPkg/Library/MpInitLib/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/AmdSev.c @@ -209,7 +209,7 @@ SevEsPlaceApHlt ( Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB); Ghcb = Msr.Ghcb; - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); if (DoDecrement) { DoDecrement = FALSE; @@ -221,13 +221,13 @@ SevEsPlaceApHlt ( InterlockedDecrement ((UINT32 *)&CpuMpData->MpCpuExchangeInfo->NumApsExecuting); } - Status = VmgExit (Ghcb, SVM_EXIT_AP_RESET_HOLD, 0, 0); + Status = CcExitVmgExit (Ghcb, SVM_EXIT_AP_RESET_HOLD, 0, 0); if ((Status == 0) && (Ghcb->SaveArea.SwExitInfo2 != 0)) { - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); break; } - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); } // diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index ef56af1f73..a84e9e33ba 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -222,9 +222,9 @@ GetSevEsAPMemory ( Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB); Ghcb = Msr.Ghcb; - VmgInit (Ghcb, &InterruptState); - VmgExit (Ghcb, SVM_EXIT_AP_JUMP_TABLE, 0, (UINT64)(UINTN)StartAddress); - VmgDone (Ghcb, InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); + CcExitVmgExit (Ghcb, SVM_EXIT_AP_JUMP_TABLE, 0, (UINT64)(UINTN)StartAddress); + CcExitVmgDone (Ghcb, InterruptState); return (UINTN)StartAddress; } diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c index 4c4f81af7c..bfda1e1903 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c @@ -150,16 +150,16 @@ SevSnpCreateSaveArea ( Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB); Ghcb = Msr.Ghcb; - VmgInit (Ghcb, &InterruptState); + CcExitVmgInit (Ghcb, &InterruptState); Ghcb->SaveArea.Rax = SaveArea->SevFeatures; - VmgSetOffsetValid (Ghcb, GhcbRax); - VmgExitStatus = VmgExit ( + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); + VmgExitStatus = CcExitVmgExit ( Ghcb, SVM_EXIT_SNP_AP_CREATION, ExitInfo1, ExitInfo2 ); - VmgDone (Ghcb, InterruptState); + CcExitVmgDone (Ghcb, InterruptState); ASSERT (VmgExitStatus == 0); if (VmgExitStatus != 0) { From a6d40598350c63ef80fff907672b989a71598c71 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 28 Oct 2022 08:57:41 +0800 Subject: [PATCH 0324/1529] Maintainers: Update the VmgExitLib to CcExitLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4123 VmgExitLib is renamed as CcExitLib. The related section in Maintainers.txt should be updated as well. Cc: Michael D Kinney Cc: Liming Gao Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Michael D Kinney Signed-off-by: Min Xu --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index a2727fa7bd..7e98083685 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -481,7 +481,7 @@ F: OvmfPkg/Include/Library/MemEncryptSevLib.h F: OvmfPkg/IoMmuDxe/AmdSevIoMmu.* F: OvmfPkg/Library/BaseMemEncryptSevLib/ F: OvmfPkg/Library/PlatformBootManagerLibGrub/ -F: OvmfPkg/Library/VmgExitLib/ +F: OvmfPkg/Library/CcExitLib/ F: OvmfPkg/PlatformPei/AmdSev.c F: OvmfPkg/ResetVector/ F: OvmfPkg/Sec/ From 55974df47b78274e148d6e81ac34693990fb02d1 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Mon, 14 Nov 2022 22:43:47 +0800 Subject: [PATCH 0325/1529] ArmPkg/ArmTrngLib: Remove ASSERT in GetArmTrngVersion() BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4150 GetArmTrngVersion() is used to check the presence of an Arm Trng. If not found, an ASSERT prevents from booting in DEBUG builds. Remove this ASSERT. Reported-by: Sami Mujawar Signed-off-by: Pierre Gondois Acked-by: Ard Biesheuvel Reviewed-by: Sami Mujawar --- ArmPkg/Library/ArmTrngLib/ArmTrngLib.c | 1 - 1 file changed, 1 deletion(-) diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c index fdabc02cd3..3278722320 100644 --- a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c @@ -344,7 +344,6 @@ ArmTrngLibConstructor ( Status = GetArmTrngVersion (&MajorRev, &MinorRev); if (RETURN_ERROR (Status)) { - ASSERT_RETURN_ERROR (Status); goto ErrorHandler; } From 725ed535b2ef20d0161fc15d222d35b1cd705e5b Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 11 Nov 2022 16:01:09 -0500 Subject: [PATCH 0326/1529] pip-requirements.txt: Update to edk2-pytool-library 0.12.1 Updates edk2-pytool-library to pick up a minor bug fix release: 0.12.0 to 0.12.1 changes: - path_utilities.py: Prevent path case modification in GetContainingModules() That change prevents the case of paths from being set to lower case when returned from the function to avoid impacting case-sensitive callers. Release notes: https://github.com/tianocore/edk2-pytool-library/releases/tag/v0.12.1 Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Cc: Andrew Fish Cc: Leif Lindholm Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan Reviewed-by: Michael D Kinney --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index d7e6b536f9..4393bf1d1c 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -12,7 +12,7 @@ # https://www.python.org/dev/peps/pep-0440/#version-specifiers ## -edk2-pytool-library==0.12.0 +edk2-pytool-library==0.12.1 edk2-pytool-extensions~=0.19.1 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 From 945d003355babb9834bf9bd3f08f48a5637af7c2 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 11 Nov 2022 16:04:39 -0500 Subject: [PATCH 0327/1529] pip-requirements.txt: Update to edk2-pytool-extensions 0.20.0 Updates edk2-pytool-extensions to pick up a major version release: 0.19.1 to 0.20.0 changes: - .vscode/settings.json: Enable flake8 linting - Add Pydocstyle - Move dependabot.yml location - Fix typos in robot files - Pydocstyle Updates - Plugin Loader Updates - edk2_stuart_pr_eval: Improve robustness of path comparisons - edk2_pr_eval.py: Build all packages on file change outside package - Allow build wrappers Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Cc: Andrew Fish Cc: Leif Lindholm Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan Reviewed-by: Michael D Kinney --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 4393bf1d1c..be8c7a1c37 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -13,6 +13,6 @@ ## edk2-pytool-library==0.12.1 -edk2-pytool-extensions~=0.19.1 +edk2-pytool-extensions~=0.20.0 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 From 7ba1ceee62636b85f024d2c7ac0b3e1813f24454 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Thu, 24 Nov 2022 17:17:53 +0100 Subject: [PATCH 0328/1529] ArmPkg/ArmTrngLib: Remove ASSERTs in ArmTrngLibConstructor() Remove ASSERTs in ArmTrngLibConstructor() that prevent from booting on DEBUG builds. Signed-off-by: Pierre Gondois Reviewed-by: Ard Biesheuvel --- ArmPkg/Library/ArmTrngLib/ArmTrngLib.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c index 3278722320..c2555f3ea6 100644 --- a/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c +++ b/ArmPkg/Library/ArmTrngLib/ArmTrngLib.c @@ -331,14 +331,12 @@ ArmTrngLibConstructor ( ArmMonitorCall (&Parameters); Status = TrngStatusToReturnStatus ((INT32)Parameters.Arg0); if (RETURN_ERROR (Status)) { - ASSERT_RETURN_ERROR (Status); goto ErrorHandler; } // Cf [1] s2.1.3 'Caller responsibilities', // SMCCC version must be greater or equal than 1.1 if ((INT32)Parameters.Arg0 < 0x10001) { - ASSERT_RETURN_ERROR (RETURN_UNSUPPORTED); goto ErrorHandler; } @@ -350,14 +348,12 @@ ArmTrngLibConstructor ( // Check that the required features are present. Status = GetArmTrngFeatures (ARM_SMC_ID_TRNG_RND, NULL); if (RETURN_ERROR (Status)) { - ASSERT_RETURN_ERROR (Status); goto ErrorHandler; } // Check if TRNG UUID is supported and if so trace the GUID. Status = GetArmTrngFeatures (ARM_SMC_ID_TRNG_GET_UUID, NULL); if (RETURN_ERROR (Status)) { - ASSERT_RETURN_ERROR (Status); goto ErrorHandler; } @@ -365,7 +361,6 @@ ArmTrngLibConstructor ( Status = GetArmTrngUuid (&Guid); if (RETURN_ERROR (Status)) { - ASSERT_RETURN_ERROR (Status); goto ErrorHandler; } From b098b4e8bffd41fd85d0e29a5c9f5cd2b9508b1d Mon Sep 17 00:00:00 2001 From: VictorX Hsu Date: Tue, 15 Nov 2022 17:55:16 +0800 Subject: [PATCH 0329/1529] UefiPayloadPkg: The UPL info section is not aligned at 4-byte boundary REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4153 1.Upgrade spec revision to 0.9 2.Align .upld_info with 4-byte boundary by spec Reviewed-by: Guo Dong Cc: Ray Ni Reviewed-by: James Lu Cc: Gua Guo Signed-off-by: VictorX Hsu --- UefiPayloadPkg/UniversalPayloadBuild.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 6003de36d1..50a5950e7c 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -31,7 +31,7 @@ class UPLD_INFO_HEADER(LittleEndianStructure): def __init__(self): self.Identifier = b'PLDH' self.HeaderLength = sizeof(UPLD_INFO_HEADER) - self.SpecRevision = 0x0007 + self.SpecRevision = 0x0009 self.Revision = 0x0000010105 self.ImageId = b'UEFI' self.ProducerId = b'INTEL' @@ -133,7 +133,7 @@ def BuildUniversalPayload(Args, MacroList): FvOutputDir, EntryOutputDir ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld.upld_info=16 --set-section-alignment .upld.uefi_fv=16 {}'.format ( + set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 {}'.format ( LlvmObjcopyPath, ObjCopyFlag, ObjCopyFlag, From 8d2ad92ecaf1d616191c0c5171aabdac019e9be8 Mon Sep 17 00:00:00 2001 From: "Zhang, JuX" Date: Wed, 16 Nov 2022 15:12:57 +0800 Subject: [PATCH 0330/1529] ShellPkg/SmbiosView: Update ProcessorUpgradeTable REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4156 Refer to the latest SMBIOS v3.6, SMBIOS Socket not completely defined. SMBIOS v3.6: https://www.dmtf.org/sites/default/files/standards/documents/ DSP0134_3.6.0.pdf Signed-off-by: JuX Zhang Cc: Zhichao Gao Cc: Jiaxin Wu Reviewed-by: Zhichao Gao Reviewed-by: Jiaxin Wu --- .../SmbiosView/QueryTable.c | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c index 2e62ae3a34..edb46817e4 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c @@ -601,6 +601,42 @@ TABLE_ITEM ProcessorUpgradeTable[] = { { 0x3F, L"Socket LGA4677" + }, + { + 0x40, + L"Socket LGA1700" + }, + { + 0x41, + L"Socket BGA1744" + }, + { + 0x42, + L"Socket BGA1781" + }, + { + 0x43, + L"Socket BGA1211" + }, + { + 0x44, + L"Socket BGA2422" + }, + { + 0x45, + L"Socket LGA1211" + }, + { + 0x46, + L"Socket LGA2422" + }, + { + 0x47, + L"Socket LGA5773" + }, + { + 0x48, + L"Socket BGA5773" } }; From c6752bcfe4ceec12a3cda99639cc285a7ba476ca Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 10 Nov 2022 07:26:23 -0500 Subject: [PATCH 0331/1529] .github/dependabot.yml: Enable dependabot Enables dependabot in this repo so we can better alerted when dependency updates are available. This GitHub action will automatically create pull requests and summarize the dependency details. Because it is a pull request, the CI system will validate the dependency update in the pull request. Configures dependabot for: 1. PIP module updates 2. GitHub action updates The maintainers/reviewers of the .github directory were added as pull request reviewers so they can be notified when the pull request is available. Note to Maintainers: After this change is committed, PRs from dependabot will be automatically created in the edk2 repo. Never set the 'push' label directly on these PRs. If a dependency identified by dependedabot looks like one that should be updated in the edk2 repo, then copy the PR generated by dependabot to your personal fork and update the commit message to follow the edk2 commit message requirements and send as a normal code review. Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Sean Brogan --- .github/dependabot.yml | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..b4e0b93b16 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,34 @@ +## @file +# Dependabot configuration file to enable GitHub services for managing and updating +# dependencies. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +## +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "daily" + commit-message: + prefix: "pip" + reviewers: + - "makubacki" + - "mdkinney" + - "spbrogan" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + commit-message: + prefix: "GitHub Action" + reviewers: + - "makubacki" + - "mdkinney" + - "spbrogan" From 94553b0c542093e74dcfcac0dad887ea03355006 Mon Sep 17 00:00:00 2001 From: zhenhuay Date: Mon, 21 Nov 2022 17:34:56 +0800 Subject: [PATCH 0332/1529] ShellPkg/DpDynamicCommand: Add ResetEnd support in DP command DP command should be able to parse the FPDT ACPI table and dump the ResetEnd which was logged at the beginning of the firmware image execution. So that DP can calculate SEC phase time duration start from the beginning of firmware image execution. Cc: Ray Ni Cc: Zhichao Gao Cc: Star Zeng Signed-off-by: zhenhuay Reviewed-by: Zhichao Gao --- ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c | 14 ++++++++++++++ ShellPkg/DynamicCommand/DpDynamicCommand/Dp.uni | 1 + .../DynamicCommand/DpDynamicCommand/DpInternal.h | 1 + ShellPkg/DynamicCommand/DpDynamicCommand/DpTrace.c | 9 +++++++++ 4 files changed, 25 insertions(+) diff --git a/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c b/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c index 1799ab176a..512a146da6 100644 --- a/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c +++ b/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c @@ -57,6 +57,7 @@ UINT8 *mBootPerformanceTable; UINTN mBootPerformanceTableSize; BOOLEAN mPeiPhase = FALSE; BOOLEAN mDxePhase = FALSE; +UINT64 mResetEnd = 0; PERF_SUMMARY_DATA SummaryData = { 0 }; ///< Create the SummaryData structure and init. to ZERO. MEASUREMENT_RECORD *mMeasurementList = NULL; @@ -542,6 +543,8 @@ BuildMeasurementList ( { EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *RecordHeader; UINT8 *PerformanceTablePtr; + UINT8 *BasicBootTablePtr; + UINT64 ResetEnd; UINT16 StartProgressId; UINTN TableLength; UINT8 *StartRecordEvent; @@ -552,6 +555,17 @@ BuildMeasurementList ( return EFI_OUT_OF_RESOURCES; } + // + // Update the ResetEnd which was logged at the beginning of firmware image execution + // + TableLength = sizeof (EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER); + BasicBootTablePtr = (mBootPerformanceTable + TableLength); + ResetEnd = ((EFI_ACPI_5_0_FPDT_FIRMWARE_BASIC_BOOT_RECORD *)BasicBootTablePtr)->ResetEnd; + + if (ResetEnd > 0) { + mResetEnd = ResetEnd; + } + TableLength = sizeof (BOOT_PERFORMANCE_TABLE); PerformanceTablePtr = (mBootPerformanceTable + TableLength); diff --git a/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.uni b/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.uni index 8d8700573e..ef2e7708b8 100644 --- a/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.uni +++ b/ShellPkg/DynamicCommand/DpDynamicCommand/Dp.uni @@ -41,6 +41,7 @@ #string STR_DP_TIMER_PROPERTIES #language en-US "System Performance Timer counts %s from 0x%Lx to 0x%Lx\n" #string STR_DP_VERBOSE_THRESHOLD #language en-US "Measurements less than %,Ld microseconds are not displayed.\n" #string STR_DP_SECTION_PHASES #language en-US "Major Phases" +#string STR_DP_RESET_END #language en-US " Reset End: %L8d (us)\n" #string STR_DP_SEC_PHASE #language en-US " SEC Phase Duration: %L8d (us)\n" #string STR_DP_PHASE_BDSTO #language en-US " BDS Timeout: %L8d (ms) included in BDS Duration\n" #string STR_DP_PHASE_DURATION #language en-US "%5a Phase Duration: %L8d (ms)\n" diff --git a/ShellPkg/DynamicCommand/DpDynamicCommand/DpInternal.h b/ShellPkg/DynamicCommand/DpDynamicCommand/DpInternal.h index 39878c6085..97f47f2960 100644 --- a/ShellPkg/DynamicCommand/DpDynamicCommand/DpInternal.h +++ b/ShellPkg/DynamicCommand/DpDynamicCommand/DpInternal.h @@ -28,6 +28,7 @@ extern UINT8 *mBootPerformanceTable; extern UINTN mBootPerformanceTableLength; extern MEASUREMENT_RECORD *mMeasurementList; extern UINTN mMeasurementNum; +extern UINT64 mResetEnd; extern PERF_SUMMARY_DATA SummaryData; ///< Create the SummaryData structure and init. to ZERO. diff --git a/ShellPkg/DynamicCommand/DpDynamicCommand/DpTrace.c b/ShellPkg/DynamicCommand/DpDynamicCommand/DpTrace.c index 0abb8797ec..9c0a9a06a1 100644 --- a/ShellPkg/DynamicCommand/DpDynamicCommand/DpTrace.c +++ b/ShellPkg/DynamicCommand/DpDynamicCommand/DpTrace.c @@ -548,6 +548,15 @@ ProcessPhases ( Total = 0; + // print Reset End if it's valid + // + if (SecTime > mResetEnd) { + SecTime = SecTime - mResetEnd; // Calculate sec time duration start from the beginning of firmware image execution + ElapsedTime = DurationInMicroSeconds (mResetEnd); // Calculate elapsed time in microseconds + Total += DivU64x32 (ElapsedTime, 1000); // Accumulate time in milliseconds + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_RESET_END), mDpHiiHandle, ElapsedTime); + } + // print SEC phase duration time // if (SecTime > 0) { From 0b29384349a17e4e931140cba1a897699b01f48d Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Fri, 11 Nov 2022 19:21:06 +0800 Subject: [PATCH 0333/1529] BaseSynchronizationLib: Fix RISC-V helper name REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4143 Fix the name of InternalSyncCompareExchange64() function. Signed-off-by: Sunil V L Reported-by: Zhihao Li Tested-by: Zhihao Li Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Daniel Schaefer Reviewed-by: Liming Gao --- .../Library/BaseSynchronizationLib/BaseSynchronizationLib.inf | 2 +- .../Library/BaseSynchronizationLib/RiscV64/Synchronization.S | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf b/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf index dd66ec1d03..88dfb880fe 100755 --- a/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf +++ b/MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf @@ -81,7 +81,7 @@ [Sources.RISCV64] Synchronization.c - RiscV64/Synchronization.S + RiscV64/Synchronization.S | GCC [Sources.LOONGARCH64] Synchronization.c diff --git a/MdePkg/Library/BaseSynchronizationLib/RiscV64/Synchronization.S b/MdePkg/Library/BaseSynchronizationLib/RiscV64/Synchronization.S index bac80d6871..f287ef38f6 100644 --- a/MdePkg/Library/BaseSynchronizationLib/RiscV64/Synchronization.S +++ b/MdePkg/Library/BaseSynchronizationLib/RiscV64/Synchronization.S @@ -36,8 +36,6 @@ exit: mv a0, a3 ret -.global ASM_PFX(InternalSyncCompareExchange64) - // // Compare and xchange a 64-bit value. // @@ -45,7 +43,7 @@ exit: // @param a1 : Compare value. // @param a2 : Exchange value. // -ASM_PFX (SyncCompareExchange64): +ASM_PFX (InternalSyncCompareExchange64): lr.d a3, (a0) // Load the value from a0 and make // the reservation of address. bne a3, a1, exit From ee53b4a175d0201921da6deeed889ea7944b619a Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 29 Nov 2022 05:40:56 -0700 Subject: [PATCH 0334/1529] EmbeddedPkg/MetronomeDxe: Update outdated lower bound comment There was previously a lower bound on the value of TickPeriod such that it couldn't be less than 10 us. However, that was removed from the PI Specification in the 1.0 errata released in 2007. From the revision history: "M171 Remove 10 us lower bound restriction for the TickPeriod in the Metronome" Update the documentation of TickPeriod in MetronomeDxe/Metronome.c to remove mention of the lower bound. Signed-off-by: Rebecca Cran Reviewed-by: Leif Lindholm --- EmbeddedPkg/MetronomeDxe/Metronome.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/EmbeddedPkg/MetronomeDxe/Metronome.c b/EmbeddedPkg/MetronomeDxe/Metronome.c index a089231582..63db6d5139 100644 --- a/EmbeddedPkg/MetronomeDxe/Metronome.c +++ b/EmbeddedPkg/MetronomeDxe/Metronome.c @@ -43,10 +43,9 @@ WaitForTick ( @param TickPeriod The period of platform's known time source in 100 nS units. - This value on any platform must be at least 10 uS, and must not - exceed 200 uS. The value in this field is a constant that must - not be modified after the Metronome architectural protocol is - installed. All consumers must treat this as a read-only field. + This value on any platform must not exceed 200 uS. The value in this field + is a constant that must not be modified after the Metronome architectural + protocol is installed. All consumers must treat this as a read-only field. **/ EFI_METRONOME_ARCH_PROTOCOL gMetronome = { From 169ae45e5bc904219bc59ffbaa01863e7ae8d77d Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 10 Nov 2022 10:03:08 -0500 Subject: [PATCH 0335/1529] .github/ISSUE_TEMPLATE/config.yml: Add initial issue template Adds a GitHub issue template to direct contributors familiar with GitHub's issue tracker to the external resources used by TianoCore. Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan --- .github/ISSUE_TEMPLATE/config.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/config.yml diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..7866c2197a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,24 @@ +## @file +# GitHub issue configuration file. +# +# This file is meant to direct contributors familiar with GitHub's issue tracker +# to the external resources used by TianoCore. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +blank_issues_enabled: false +contact_links: + - name: Bugs and Feature Requests + url: https://bugzilla.tianocore.org/ + about: Submit bug reports and feature requests here + - name: Reporting Security Issues + url: https://github.com/tianocore/tianocore.github.io/wiki/Reporting-Security-Issues + about: Read the wiki page that describes the process here + - name: EDK II Development Mailing List + url: https://edk2.groups.io/g/devel + about: Submit code patches and ask questions on the mailing list (devel@edk2.groups.io) + - name: EDK II Discussions + url: https://github.com/tianocore/edk2/discussions + about: You can also reach out on the Discussion section of this repository From 351fd7dc57ecc8fc7d6abadea737e18d7d74239b Mon Sep 17 00:00:00 2001 From: Dongyan Qian Date: Thu, 17 Nov 2022 10:57:11 +0800 Subject: [PATCH 0336/1529] MdeModulePkg: Disable PciDegrade support for LoongArch64 LoongArch64: Pcie devices that come with OPROM may require large Mem Space, and downgrading all 64 Bit Bars may result in insufficient space. REF:https://bugzilla.tianocore.org/show_bug.cgi?id=4157 Cc: Jian J Wang Cc: Liming Gao Cc: Ray Ni Cc: Chao Li Signed-off-by: Dongyan Qian Co-authored-by: Bo Zhu Reviewed-by: Chao Li Reviewed-by: Liming Gao --- MdeModulePkg/MdeModulePkg.dec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 58e6ab0048..be5e829ca9 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -917,7 +917,7 @@ # @Prompt Enable process non-reset capsule image at runtime. gEfiMdeModulePkgTokenSpaceGuid.PcdSupportProcessCapsuleAtRuntime|FALSE|BOOLEAN|0x00010079 -[PcdsFeatureFlag.IA32, PcdsFeatureFlag.ARM, PcdsFeatureFlag.AARCH64] +[PcdsFeatureFlag.IA32, PcdsFeatureFlag.ARM, PcdsFeatureFlag.AARCH64, PcdsFeatureFlag.LOONGARCH64] gEfiMdeModulePkgTokenSpaceGuid.PcdPciDegradeResourceForOptionRom|FALSE|BOOLEAN|0x0001003a [PcdsFeatureFlag.IA32, PcdsFeatureFlag.X64] From 68c50df41422197206a10d628322a361df82d57d Mon Sep 17 00:00:00 2001 From: Gang Chen Date: Thu, 17 Nov 2022 16:39:37 +0800 Subject: [PATCH 0337/1529] CryptoPkg/OpensslLib: Upgrade OpenSSL to 1.1.1s Upgrade openssl to 1.1.1s. Pick up bugfixes from the latest openssl release, which include some GCC build warnings cleaning up. Cc: Jian J Wang Cc: Jiewen Yao Signed-off-by: Gang Chen Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/openssl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CryptoPkg/Library/OpensslLib/openssl b/CryptoPkg/Library/OpensslLib/openssl index d82e959e62..129058165d 160000 --- a/CryptoPkg/Library/OpensslLib/openssl +++ b/CryptoPkg/Library/OpensslLib/openssl @@ -1 +1 @@ -Subproject commit d82e959e621a3d597f1e0d50ff8c2d8b96915fd7 +Subproject commit 129058165d195e43a0ad10111b0c2e29bdf65980 From ffeb8f41f9802b9cd00c17b4a0d39f8214ae77d0 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Wed, 30 Nov 2022 13:14:09 -0800 Subject: [PATCH 0338/1529] UnitTestFrameworkPkg: Library classes private to public REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4178 * Change GoogleTestLib class from private to public. * Change UnitTestPersistenceLib class from private to public. Cc: Michael Kubacki Cc: Sean Brogan Cc: Ray Ni Cc: Zhiguang Liu Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki Reviewed-by: Ray Ni --- .../Library/UnitTestPersistenceLib.h | 0 UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 13 +++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) rename UnitTestFrameworkPkg/{PrivateInclude => Include}/Library/UnitTestPersistenceLib.h (100%) diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h similarity index 100% rename from UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index ed12f32009..14e387d63a 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -26,11 +26,16 @@ Library/CmockaLib/cmocka/include/cmockery Library/GoogleTestLib/googletest/googletest -[LibraryClasses.Common.Private] +[LibraryClasses] ## @libraryclass Allows save and restore unit test internal state # - UnitTestPersistenceLib|PrivateInclude/Library/UnitTestPersistenceLib.h + UnitTestPersistenceLib|Include/Library/UnitTestPersistenceLib.h + + ## @libraryclass GoogleTest infrastructure + # + GoogleTestLib|Include/Library/GoogleTestLib.h +[LibraryClasses.Common.Private] ## @libraryclass Provides a unit test result report # UnitTestResultReportLib|PrivateInclude/Library/UnitTestResultReportLib.h @@ -39,10 +44,6 @@ # UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h - ## @libraryclass GoogleTest infrastructure - # - GoogleTestLib|Include/Library/GoogleTestLib.h - [Guids] gUnitTestFrameworkPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } From 4ead765d83a74e29cd8902eedd7bfc1ac52c6df9 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Sun, 27 Nov 2022 15:00:14 +0800 Subject: [PATCH 0339/1529] OvmfPkg/PlatformInitLib: Add check to NvVarStoreFV HeaderLength There should be a check that the FV HeaderLength cannot be an odd number. Otherwise in the following CalculateSum16 there would be an ASSERT. In ValidateFvHeader@QemuFlashFvbServicesRuntimeDxe/FwBlockServices.c there a is similar check to the FwVolHeader->HeaderLength. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/Platform.c | 1 + 1 file changed, 1 insertion(+) diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 2582689ffe..77f22de046 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -653,6 +653,7 @@ PlatformValidateNvVarStore ( (!CompareGuid (&FvHdrGUID, &NvVarStoreFvHeader->FileSystemGuid)) || (NvVarStoreFvHeader->Signature != EFI_FVH_SIGNATURE) || (NvVarStoreFvHeader->Attributes != 0x4feff) || + ((NvVarStoreFvHeader->HeaderLength & 0x01) != 0) || (NvVarStoreFvHeader->Revision != EFI_FVH_REVISION) || (NvVarStoreFvHeader->FvLength != NvVarStoreSize) ) From a04236484882b892dc0d1196899771afae29d51a Mon Sep 17 00:00:00 2001 From: Zhihao Li Date: Wed, 30 Nov 2022 22:21:02 +0800 Subject: [PATCH 0340/1529] CryptPkg: Enable CryptoPkg BaseCryptLib ParallelHash for PEI and DXE REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4097 The BaseCryptLib in the CryptoPkg currently supports ParallelHash algorithm for SMM. The MP Services PPI and MP Services Protocol could be used to enable ParallelHash in PEI and DXE versions of the BaseCryptLib. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Zhihao Li Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/BaseCryptLib.inf | 11 +++- .../BaseCryptLib/Hash/CryptDispatchApDxe.c | 49 +++++++++++++++++ .../BaseCryptLib/Hash/CryptDispatchApMm.c | 35 ++++++++++++ .../BaseCryptLib/Hash/CryptDispatchApPei.c | 54 +++++++++++++++++++ .../BaseCryptLib/Hash/CryptParallelHash.c | 26 +-------- .../BaseCryptLib/Hash/CryptParallelHash.h | 23 ++++++++ .../Library/BaseCryptLib/PeiCryptLib.inf | 11 +++- .../Library/BaseCryptLib/SmmCryptLib.inf | 1 + 8 files changed, 183 insertions(+), 27 deletions(-) create mode 100644 CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApDxe.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApMm.c create mode 100644 CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApPei.c diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index 213813cad9..5be1724f08 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -35,7 +35,11 @@ Hash/CryptSha256.c Hash/CryptSha512.c Hash/CryptSm3.c - Hash/CryptParallelHashNull.c + Hash/CryptSha3.c + Hash/CryptXkcp.c + Hash/CryptCShake256.c + Hash/CryptParallelHash.c + Hash/CryptDispatchApDxe.c Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAes.c @@ -93,6 +97,11 @@ OpensslLib IntrinsicLib PrintLib + UefiBootServicesTableLib + SynchronizationLib + +[Protocols] + gEfiMpServiceProtocolGuid # # Remove these [BuildOptions] after this library is cleaned up diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApDxe.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApDxe.c new file mode 100644 index 0000000000..607aa7cd48 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApDxe.c @@ -0,0 +1,49 @@ +/** @file + Dispatch Block to Aps in Dxe phase for parallelhash algorithm. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CryptParallelHash.h" +#include +#include + +/** + Dispatch the block task to each AP in PEI phase. + +**/ +VOID +EFIAPI +DispatchBlockToAp ( + VOID + ) +{ + EFI_STATUS Status; + EFI_MP_SERVICES_PROTOCOL *MpServices; + + Status = gBS->LocateProtocol ( + &gEfiMpServiceProtocolGuid, + NULL, + (VOID **)&MpServices + ); + if (EFI_ERROR (Status)) { + // + // Failed to locate MpServices Protocol, do parallel hash by one core. + // + DEBUG ((DEBUG_ERROR, "[DispatchBlockToApDxe] Failed to locate MpServices Protocol. Status = %r\n", Status)); + return; + } + + Status = MpServices->StartupAllAPs ( + MpServices, + ParallelHashApExecute, + FALSE, + NULL, + 0, + NULL, + NULL + ); + return; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApMm.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApMm.c new file mode 100644 index 0000000000..0237fb38bc --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApMm.c @@ -0,0 +1,35 @@ +/** @file + Dispatch the block task to each AP in Smm mode for parallelhash algorithm. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CryptParallelHash.h" +#include + +/** + Dispatch the block task to each AP in SMM mode. + +**/ +VOID +EFIAPI +DispatchBlockToAp ( + VOID + ) +{ + UINTN Index; + + if (gMmst == NULL) { + return; + } + + for (Index = 0; Index < gMmst->NumberOfCpus; Index++) { + if (Index != gMmst->CurrentlyExecutingCpu) { + gMmst->MmStartupThisAp (ParallelHashApExecute, Index, NULL); + } + } + + return; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApPei.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApPei.c new file mode 100644 index 0000000000..9ddd23d320 --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptDispatchApPei.c @@ -0,0 +1,54 @@ +/** @file + Dispatch Block to Aps in Pei phase for parallelhash algorithm. + +Copyright (c) 2022, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CryptParallelHash.h" +#include +#include +#include +#include + +/** + Dispatch the block task to each AP in PEI phase. + +**/ +VOID +EFIAPI +DispatchBlockToAp ( + VOID + ) +{ + EFI_STATUS Status; + CONST EFI_PEI_SERVICES **PeiServices; + EFI_PEI_MP_SERVICES_PPI *MpServicesPpi; + + PeiServices = GetPeiServicesTablePointer (); + Status = (*PeiServices)->LocatePpi ( + PeiServices, + &gEfiPeiMpServicesPpiGuid, + 0, + NULL, + (VOID **)&MpServicesPpi + ); + if (EFI_ERROR (Status)) { + // + // Failed to locate MpServices Ppi, do parallel hash by one core. + // + DEBUG ((DEBUG_ERROR, "[DispatchBlockToApPei] Failed to locate MpServices Ppi. Status = %r\n", Status)); + return; + } + + Status = MpServicesPpi->StartupAllAPs ( + (CONST EFI_PEI_SERVICES **)PeiServices, + MpServicesPpi, + ParallelHashApExecute, + FALSE, + 0, + NULL + ); + return; +} diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.c index f7ce9dbf52..2931123736 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.c +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.c @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "CryptParallelHash.h" -#include #include #define PARALLELHASH_CUSTOMIZATION "ParallelHash" @@ -69,27 +68,6 @@ ParallelHashApExecute ( } } -/** - Dispatch the block task to each AP in SMM mode. - -**/ -VOID -EFIAPI -MmDispatchBlockToAP ( - VOID - ) -{ - UINTN Index; - - for (Index = 0; Index < gMmst->NumberOfCpus; Index++) { - if (Index != gMmst->CurrentlyExecutingCpu) { - gMmst->MmStartupThisAp (ParallelHashApExecute, Index, NULL); - } - } - - return; -} - /** Parallel hash function ParallelHash256, as defined in NIST's Special Publication 800-185, published December 2016. @@ -197,9 +175,7 @@ ParallelHash256HashAll ( // // Dispatch blocklist to each AP. // - if (gMmst != NULL) { - MmDispatchBlockToAP (); - } + DispatchBlockToAp (); // // Wait until all block hash completed. diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.h b/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.h index dcfe200e58..03a1a58cb8 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.h +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptParallelHash.h @@ -201,3 +201,26 @@ CShake256HashAll ( IN UINTN CustomizationLen, OUT UINT8 *HashValue ); + +/** + Complete computation of digest of each block. + + Each AP perform the function called by BSP. + + @param[in] ProcedureArgument Argument of the procedure. +**/ +VOID +EFIAPI +ParallelHashApExecute ( + IN VOID *ProcedureArgument + ); + +/** + Dispatch the block task to each AP. + +**/ +VOID +EFIAPI +DispatchBlockToAp ( + VOID + ); diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index b1629647f9..2aafa5f0ac 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -40,7 +40,11 @@ Hash/CryptSha256.c Hash/CryptSm3.c Hash/CryptSha512.c - Hash/CryptParallelHashNull.c + Hash/CryptSha3.c + Hash/CryptXkcp.c + Hash/CryptCShake256.c + Hash/CryptParallelHash.c + Hash/CryptDispatchApPei.c Hmac/CryptHmac.c Kdf/CryptHkdf.c Cipher/CryptAesNull.c @@ -80,7 +84,12 @@ OpensslLib IntrinsicLib PrintLib + PeiServicesTablePointerLib + PeiServicesLib + SynchronizationLib +[Ppis] + gEfiPeiMpServicesPpiGuid # # Remove these [BuildOptions] after this library is cleaned up # diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 0af7a3f96e..00ea7bf4c5 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -42,6 +42,7 @@ Hash/CryptXkcp.c Hash/CryptCShake256.c Hash/CryptParallelHash.c + Hash/CryptDispatchApMm.c Hmac/CryptHmac.c Kdf/CryptHkdfNull.c Cipher/CryptAes.c From c4ae207debc6bfb8cc6bad077879ac3467f919d0 Mon Sep 17 00:00:00 2001 From: Zihong Yi Date: Fri, 2 Dec 2022 13:51:50 +0800 Subject: [PATCH 0341/1529] CryptoPkg/BaseCryptLib:time overflow REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4167 In CrtLibSupport.h, time_t is defined as INT32, and its maximum value is 2147483647. That is, the corresponding maximum timestamp is 2038-01-19 11:14:07. Therefore, overflow occurs when the test time exceeds 2038-01-19 11:14:07. So change the type of time_t to INT64 and also change the type of variables in function gmtime which calculated with time_t. Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Zihong Yi Reviewed-by: Jiewen Yao --- .../BaseCryptLib/SysCall/TimerWrapper.c | 51 ++++++++++++++----- CryptoPkg/Library/Include/CrtLibSupport.h | 2 +- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c index bf8a532581..2dfc6fe6c5 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/TimerWrapper.c @@ -15,7 +15,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // -- Time Management Routines -- // -#define IsLeap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) #define SECSPERMIN (60) #define SECSPERHOUR (60 * 60) #define SECSPERDAY (24 * SECSPERHOUR) @@ -60,6 +59,26 @@ UINTN CumulativeDays[2][14] = { } }; +/* Check the year is leap or not. */ +// BOOLEAN IsLeap( +// INTN timer +// ) +BOOLEAN +IsLeap ( + time_t timer + ) +{ + INT64 Remainder1; + INT64 Remainder2; + INT64 Remainder3; + + DivS64x64Remainder (timer, 4, &Remainder1); + DivS64x64Remainder (timer, 100, &Remainder2); + DivS64x64Remainder (timer, 400, &Remainder3); + + return (Remainder1 == 0 && (Remainder2 != 0 || Remainder3 == 0)); +} + /* Get the system time as seconds elapsed since midnight, January 1, 1970. */ // INTN time( // INTN *timer @@ -117,12 +136,13 @@ gmtime ( ) { struct tm *GmTime; - UINT16 DayNo; - UINT32 DayRemainder; + UINT64 DayNo; + UINT64 DayRemainder; time_t Year; time_t YearNo; - UINT16 TotalDays; - UINT16 MonthNo; + UINT32 TotalDays; + UINT32 MonthNo; + INT64 Remainder; if (timer == NULL) { return NULL; @@ -135,18 +155,21 @@ gmtime ( ZeroMem ((VOID *)GmTime, (UINTN)sizeof (struct tm)); - DayNo = (UINT16)(*timer / SECSPERDAY); - DayRemainder = (UINT32)(*timer % SECSPERDAY); + DayNo = (UINT64)DivS64x64Remainder (*timer, SECSPERDAY, &Remainder); + DayRemainder = (UINT64)Remainder; - GmTime->tm_sec = (int)(DayRemainder % SECSPERMIN); - GmTime->tm_min = (int)((DayRemainder % SECSPERHOUR) / SECSPERMIN); - GmTime->tm_hour = (int)(DayRemainder / SECSPERHOUR); - GmTime->tm_wday = (int)((DayNo + 4) % 7); + DivS64x64Remainder (DayRemainder, SECSPERMIN, &Remainder); + GmTime->tm_sec = (int)Remainder; + DivS64x64Remainder (DayRemainder, SECSPERHOUR, &Remainder); + GmTime->tm_min = (int)DivS64x64Remainder (Remainder, SECSPERMIN, NULL); + GmTime->tm_hour = (int)DivS64x64Remainder (DayRemainder, SECSPERHOUR, NULL); + DivS64x64Remainder ((DayNo + 4), 7, &Remainder); + GmTime->tm_wday = (int)Remainder; for (Year = 1970, YearNo = 0; DayNo > 0; Year++) { - TotalDays = (UINT16)(IsLeap (Year) ? 366 : 365); + TotalDays = (UINT32)(IsLeap (Year) ? 366 : 365); if (DayNo >= TotalDays) { - DayNo = (UINT16)(DayNo - TotalDays); + DayNo = (UINT64)(DayNo - TotalDays); YearNo++; } else { break; @@ -158,7 +181,7 @@ gmtime ( for (MonthNo = 12; MonthNo > 1; MonthNo--) { if (DayNo >= CumulativeDays[IsLeap (Year)][MonthNo]) { - DayNo = (UINT16)(DayNo - (UINT16)(CumulativeDays[IsLeap (Year)][MonthNo])); + DayNo = (UINT64)(DayNo - (UINT32)(CumulativeDays[IsLeap (Year)][MonthNo])); break; } } diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index 5072c343da..94b0e6b601 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -109,7 +109,7 @@ typedef UINTN off_t; typedef UINTN u_int; typedef INTN ptrdiff_t; typedef INTN ssize_t; -typedef INT32 time_t; +typedef INT64 time_t; typedef UINT8 __uint8_t; typedef UINT8 sa_family_t; typedef UINT8 u_char; From 48c2d878bb6f3fc581610a30bda61ae618f63ce2 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 1 Dec 2022 08:20:53 -0700 Subject: [PATCH 0342/1529] RedfishPkg: Fix typos of the .inc filenames Fix a typo of "RedfishLibs.dsc.inc" in RedfishLibs.dsc.inc, and correct the name of the .fdf.inc filename in Redfish.fdf.inc. Signed-off-by: Rebecca Cran Reviewed-by: Nickle Wang Reviewed-by: Abner Chang --- RedfishPkg/Redfish.fdf.inc | 2 +- RedfishPkg/RedfishLibs.dsc.inc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/RedfishPkg/Redfish.fdf.inc b/RedfishPkg/Redfish.fdf.inc index 60f31cfcee..67e0469914 100644 --- a/RedfishPkg/Redfish.fdf.inc +++ b/RedfishPkg/Redfish.fdf.inc @@ -2,7 +2,7 @@ # Redfish FDF include file for [FV*] section of all Architectures. # # This file can be included to the [FV*] section(s) of a platform FDF file -# by using "!include RedfishPkg/RedfisLibs.fdf.inc" to specify the module instances +# by using "!include RedfishPkg/Redfish.fdf.inc" to specify the module instances # to be built in the firmware volume. # # (C) Copyright 2020-2021 Hewlett Packard Enterprise Development LP
diff --git a/RedfishPkg/RedfishLibs.dsc.inc b/RedfishPkg/RedfishLibs.dsc.inc index 50e5dda773..56950b711f 100644 --- a/RedfishPkg/RedfishLibs.dsc.inc +++ b/RedfishPkg/RedfishLibs.dsc.inc @@ -2,7 +2,7 @@ # Redfish DSC include file for [LibraryClasses*] section of all Architectures. # # This file can be included to the [LibraryClasses*] section(s) of a platform DSC file -# by using "!include RedfishPkg/RedfisLibs.dsc.inc" to specify the library instances +# by using "!include RedfishPkg/RedfishLibs.dsc.inc" to specify the library instances # of EDKII network library classes. # # (C) Copyright 2021 Hewlett Packard Enterprise Development LP
From 6bcd7f78c8a4ab8722d8583877a0d5a57ea2c919 Mon Sep 17 00:00:00 2001 From: "Ni, Ray" Date: Sat, 12 Nov 2022 12:00:40 +0800 Subject: [PATCH 0343/1529] EmulatorPkg/WinHost: pre-allocate "physical" RAM Move the "physical" RAM allocation from WinPeiAutoScan to main() entrypoint. This is to prepare the changes for "reset" support. Signed-off-by: Ray Ni Cc: Andrew Fish Reviewed-by: Zhiguang Liu --- EmulatorPkg/Win/Host/WinHost.c | 60 ++++++++++++++-------------------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 93247c5043..5b780ca8af 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -8,7 +8,7 @@ This code produces 128 K of temporary memory for the SEC stack by directly allocate memory space with ReadWrite and Execute attribute. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
(C) Copyright 2016-2020 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -87,14 +87,6 @@ WinPeiAutoScan ( return EFI_UNSUPPORTED; } - // - // Allocate enough memory space for emulator - // - gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS)(UINTN)VirtualAlloc (NULL, (SIZE_T)(gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE); - if (gSystemMemory[Index].Memory == 0) { - return EFI_OUT_OF_RESOURCES; - } - *MemoryBase = gSystemMemory[Index].Memory; *MemorySize = gSystemMemory[Index].Size; @@ -457,6 +449,30 @@ Routine Description: exit (1); } + // + // Allocate "physical" memory space for emulator. It will be reported out later throuth MemoryAutoScan() + // + for (Index = 0, Done = FALSE; !Done; Index++) { + ASSERT (Index < gSystemMemoryCount); + gSystemMemory[Index].Size = ((UINT64)_wtoi (MemorySizeStr)) * ((UINT64)SIZE_1MB); + gSystemMemory[Index].Memory = (EFI_PHYSICAL_ADDRESS)(UINTN)VirtualAlloc (NULL, (SIZE_T)(gSystemMemory[Index].Size), MEM_COMMIT, PAGE_EXECUTE_READWRITE); + if (gSystemMemory[Index].Memory == 0) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Find the next region + // + for (Index1 = 0; MemorySizeStr[Index1] != '!' && MemorySizeStr[Index1] != 0; Index1++) { + } + + if (MemorySizeStr[Index1] == 0) { + Done = TRUE; + } + + MemorySizeStr = MemorySizeStr + Index1 + 1; + } + // // Allocate space for gSystemMemory Array // @@ -575,32 +591,6 @@ Routine Description: SecPrint ("\n\r"); } - // - // Calculate memory regions and store the information in the gSystemMemory - // global for later use. The autosizing code will use this data to - // map this memory into the SEC process memory space. - // - for (Index = 0, Done = FALSE; !Done; Index++) { - // - // Save the size of the memory and make a Unicode filename SystemMemory00, ... - // - gSystemMemory[Index].Size = ((UINT64)_wtoi (MemorySizeStr)) * ((UINT64)SIZE_1MB); - - // - // Find the next region - // - for (Index1 = 0; MemorySizeStr[Index1] != '!' && MemorySizeStr[Index1] != 0; Index1++) { - } - - if (MemorySizeStr[Index1] == 0) { - Done = TRUE; - } - - MemorySizeStr = MemorySizeStr + Index1 + 1; - } - - SecPrint ("\n\r"); - // // Hand off to SEC Core // From 422dedb22aeeb4e79c05382ca19b2b099a51edb9 Mon Sep 17 00:00:00 2001 From: "Ni, Ray" Date: Sat, 12 Nov 2022 12:00:41 +0800 Subject: [PATCH 0344/1529] EmulatorPkg/WinHost: XIP for SEC and PEI_CORE In EmulatorPkg/Win, SEC and PEI_CORE are loaded to memory allocated through VirtualAlloc. Though the corresponding DLL files are loaded and the entry points in DLL files are executed. The loading to memory allocated through VirtualAlloc is for the case when the DLL files can not be loaded. Actually some PEIMs like PcdPeim which are loaded before "physical" RAM is discovered, they are executing in the original location (FV) like XIP module in real platform. The SEC and PEI_CORE can follow the same mechanism. So, the VirtualAlloc call is removed. This is to prepare the "reset" support to avoid additional OS memory consumption when reset happens. Signed-off-by: Ray Ni Reviewed-by: Zhiguang Liu Cc: Andrew Fish Date: Sat, 12 Nov 2022 12:00:42 +0800 Subject: [PATCH 0345/1529] EmulatorPkg/WinHost: Add Reset2 PPI When shutdown is requested, WinHost exits. Otherwise, WinHost re-runs from SEC. Tested no extra memory consumption with multiple resets in PEI. Signed-off-by: Ray Ni Cc: Andrew Fish Reviewed-by: Zhiguang Liu --- EmulatorPkg/Win/Host/WinHost.c | 75 ++++++++++++++++++++++++++++---- EmulatorPkg/Win/Host/WinHost.h | 3 +- EmulatorPkg/Win/Host/WinHost.inf | 3 +- 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 9b10290ff3..096292f95a 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -56,6 +56,14 @@ NT_FD_INFO *gFdInfo; UINTN gSystemMemoryCount = 0; NT_SYSTEM_MEMORY *gSystemMemory; +BASE_LIBRARY_JUMP_BUFFER mResetJumpBuffer; +CHAR8 *mResetTypeStr[] = { + "EfiResetCold", + "EfiResetWarm", + "EfiResetShutdown", + "EfiResetPlatformSpecific" +}; + /*++ Routine Description: @@ -196,6 +204,45 @@ SecPrint ( ); } +/** + Resets the entire platform. + + @param[in] ResetType The type of reset to perform. + @param[in] ResetStatus The status code for the reset. + @param[in] DataSize The size, in bytes, of ResetData. + @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or EfiResetShutdown + the data buffer starts with a Null-terminated string, optionally + followed by additional binary data. The string is a description + that the caller may use to further indicate the reason for the + system reset. + +**/ +VOID +EFIAPI +WinReset ( + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL + ) +{ + ASSERT (ResetType <= EfiResetPlatformSpecific); + SecPrint (" Emu ResetSystem is called: ResetType = %s\n", mResetTypeStr[ResetType]); + + if (ResetType == EfiResetShutdown) { + exit (0); + } else { + // + // Jump back to SetJump with jump code = ResetType + 1 + // + LongJump (&mResetJumpBuffer, ResetType + 1); + } +} + +EFI_PEI_RESET2_PPI mEmuReset2Ppi = { + WinReset +}; + /*++ Routine Description: @@ -388,6 +435,7 @@ Routine Description: UINTN ProcessAffinityMask; UINTN SystemAffinityMask; INT32 LowBit; + UINTN ResetJumpCode; // // Enable the privilege so that RTC driver can successfully run SetTime() @@ -430,6 +478,7 @@ Routine Description: // PPIs pased into PEI_CORE // AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, &mSecEmuThunkPpi); + AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEfiPeiReset2PpiGuid, &mEmuReset2Ppi); // // Emulator Bus Driver Thunks @@ -500,14 +549,6 @@ Routine Description: exit (1); } - SetMem32 (TemporaryRam, TemporaryRamSize, PcdGet32 (PcdInitValueInTempStack)); - - SecPrint ( - " OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n\r", - TemporaryRamSize / SIZE_1KB, - TemporaryRam - ); - // // If enabled use the magic page to communicate between modules // This replaces the PI PeiServicesTable pointer mechanism that @@ -591,6 +632,24 @@ Routine Description: SecPrint ("\n\r"); } + ResetJumpCode = SetJump (&mResetJumpBuffer); + + // + // Do not clear memory content for warm reset. + // + if (ResetJumpCode != EfiResetWarm + 1) { + SecPrint (" OS Emulator clearing temp RAM and physical RAM (to be discovered later)......\n\r"); + SetMem32 (TemporaryRam, TemporaryRamSize, PcdGet32 (PcdInitValueInTempStack)); + for (Index = 0; Index < gSystemMemoryCount; Index++) { + SetMem32 ((VOID *)(UINTN)gSystemMemory[Index].Memory, (UINTN)gSystemMemory[Index].Size, PcdGet32 (PcdInitValueInTempStack)); + } + } + + SecPrint ( + " OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n\r", + TemporaryRamSize / SIZE_1KB, + TemporaryRam + ); // // Hand off to SEC Core // diff --git a/EmulatorPkg/Win/Host/WinHost.h b/EmulatorPkg/Win/Host/WinHost.h index 49d42d1ad8..a9a21007e3 100644 --- a/EmulatorPkg/Win/Host/WinHost.h +++ b/EmulatorPkg/Win/Host/WinHost.h @@ -1,6 +1,6 @@ /**@file -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -26,6 +26,7 @@ Module Name: #include #include #include +#include #include #include diff --git a/EmulatorPkg/Win/Host/WinHost.inf b/EmulatorPkg/Win/Host/WinHost.inf index 2030ac0847..b61901fae2 100644 --- a/EmulatorPkg/Win/Host/WinHost.inf +++ b/EmulatorPkg/Win/Host/WinHost.inf @@ -2,7 +2,7 @@ # Entry Point of Win Emulator # # Main executable file of Win Emulator that loads Sec core after initialization finished. -# Copyright (c) 2008 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2011, Apple Inc. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
# @@ -58,6 +58,7 @@ [Ppis] gEmuThunkPpiGuid + gEfiPeiReset2PpiGuid [Protocols] gEmuIoThunkProtocolGuid From 1d60f53cf3df5eea058e71201b11bbe429956af3 Mon Sep 17 00:00:00 2001 From: MarsX Lin Date: Wed, 23 Nov 2022 15:50:06 +0800 Subject: [PATCH 0346/1529] UefiPayloadPkg: Support multiple firmware volume REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4164 To support multiple FVs provided by UPL Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: MarsX Lin --- .../UefiPayloadEntry/UniversalPayloadEntry.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c index 09aee89680..46ee27c905 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c +++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c @@ -310,6 +310,7 @@ BuildHobs ( UNIVERSAL_PAYLOAD_ACPI_TABLE *AcpiTable; ACPI_BOARD_INFO *AcpiBoardInfo; EFI_HOB_HANDOFF_INFO_TABLE *HobInfo; + UINT8 Idx; Hob.Raw = (UINT8 *)BootloaderParameter; MinimalNeededSize = FixedPcdGet32 (PcdSystemMemoryUefiRegionSize); @@ -397,11 +398,24 @@ BuildHobs ( GuidHob = GetFirstGuidHob (&gUniversalPayloadExtraDataGuid); ASSERT (GuidHob != NULL); ExtraData = (UNIVERSAL_PAYLOAD_EXTRA_DATA *)GET_GUID_HOB_DATA (GuidHob); - ASSERT (ExtraData->Count == 1); + DEBUG ((DEBUG_INFO, "Multiple Fv Count=%d\n", ExtraData->Count)); ASSERT (AsciiStrCmp (ExtraData->Entry[0].Identifier, "uefi_fv") == 0); *DxeFv = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)ExtraData->Entry[0].Base; ASSERT ((*DxeFv)->FvLength == ExtraData->Entry[0].Size); + // + // support multiple FVs provided by UPL + // + for (Idx = 1; Idx < ExtraData->Count; Idx++) { + BuildFvHob (ExtraData->Entry[Idx].Base, ExtraData->Entry[Idx].Size); + DEBUG (( + DEBUG_INFO, + "UPL Multiple fv[%d], Base=0x%x, size=0x%x\n", + Idx, + ExtraData->Entry[Idx].Base, + ExtraData->Entry[Idx].Size + )); + } // // Create guid hob for acpi board information From 45deca104fbad0fcfb03627fb70b685cc61d4188 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 5 Dec 2022 11:49:45 -0800 Subject: [PATCH 0347/1529] RedfishPkg: Remove overlapping private include path in DEC file Update ReadfishPkg.dec to remove PrivateInclude from the [Includes.Common.Private] section. The PrivateInclude directory does not contain any include files, and the PrivateInclude/Crt include path remaining in the [Includes.Common.Private] section providing the include path required to access the CRT related include files by components within the RedfishPkg. Without this update, there are two forms of #include statements that can be used to include the CRT related include files. Include files should only be available using one form of #include statements. Cc: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Signed-off-by: Michael D Kinney Reviewed-by: Abner Chang Reviewed-by: Igor Kulchytskyy --- RedfishPkg/RedfishPkg.dec | 1 - 1 file changed, 1 deletion(-) diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index 0aa26883e2..d2b189b13d 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -17,7 +17,6 @@ Include [Includes.Common.Private] - PrivateInclude # Private header files for C RTL. PrivateInclude/Crt # Private header files for C RTL. Library/JsonLib # Private header files for jansson # configuration files. From d09d12a3a11522f5ee9b3833847b6fb165f2d252 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 6 Dec 2022 22:30:39 +0800 Subject: [PATCH 0348/1529] MdeModulePkg: Put USB DEBUGs that occur for bulk timeouts under VERBOSE With the pending commit of UsbNetworkPkg, it will become common for UsbBulkTransfer calls to timeout, given that the drivers are called from MnpSystemPoll every MNP_SYS_POLL_INTERVAL milliseconds: the drivers check for network packets by calling UsbBulkTransfer with a timeout of 1ms. Avoid console spam by moving DEBUG messages that occur each time a bulk transfer request times out from DEBUG_ERROR to DEBUG_VERBOSE, for both EHCI and XHCI drivers. Signed-off-by: Rebecca Cran Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c | 9 ++++++++- MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c | 2 +- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 9 ++++++++- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 6 +++--- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c index 0b7270f4e9..e903593b01 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c @@ -848,6 +848,7 @@ EhcBulkTransfer ( URB *Urb; EFI_TPL OldTpl; EFI_STATUS Status; + UINTN DebugErrorLevel; // // Validate the parameters @@ -932,7 +933,13 @@ EhcBulkTransfer ( gBS->RestoreTPL (OldTpl); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "EhcBulkTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); + if (Status == EFI_TIMEOUT) { + DebugErrorLevel = DEBUG_VERBOSE; + } else { + DebugErrorLevel = DEBUG_ERROR; + } + + DEBUG ((DebugErrorLevel, "EhcBulkTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); } return Status; diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c index 5da26afbe1..6967aabceb 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c @@ -702,7 +702,7 @@ EhcExecTransfer ( } if (!Finished) { - DEBUG ((DEBUG_ERROR, "EhcExecTransfer: transfer not finished in %dms\n", (UINT32)TimeOut)); + DEBUG ((DEBUG_VERBOSE, "EhcExecTransfer: transfer not finished in %dms\n", (UINT32)TimeOut)); EhcDumpQh (Urb->Qh, NULL, FALSE); Status = EFI_TIMEOUT; diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index c05431ff30..15fb49f28f 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -1242,6 +1242,7 @@ XhcBulkTransfer ( UINT8 SlotId; EFI_STATUS Status; EFI_TPL OldTpl; + UINTN DebugErrorLevel; // // Validate the parameters @@ -1304,7 +1305,13 @@ XhcBulkTransfer ( ON_EXIT: if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "XhcBulkTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); + if (Status == EFI_TIMEOUT) { + DebugErrorLevel = DEBUG_VERBOSE; + } else { + DebugErrorLevel = DEBUG_ERROR; + } + + DEBUG ((DebugErrorLevel, "XhcBulkTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); } gBS->RestoreTPL (OldTpl); diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index 13b0400e83..13247f7b0d 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -734,7 +734,7 @@ XhcDequeueTrbFromEndpoint ( Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); ASSERT (Dci < 32); - DEBUG ((DEBUG_INFO, "Stop Slot = %x,Dci = %x\n", SlotId, Dci)); + DEBUG ((DEBUG_VERBOSE, "Stop Slot = %x,Dci = %x\n", SlotId, Dci)); // // 1) Send Stop endpoint command to stop xHC from executing of the TDs on the endpoint @@ -3376,7 +3376,7 @@ XhcStopEndpoint ( EVT_TRB_COMMAND_COMPLETION *EvtTrb; CMD_TRB_STOP_ENDPOINT CmdTrbStopED; - DEBUG ((DEBUG_INFO, "XhcStopEndpoint: Slot = 0x%x, Dci = 0x%x\n", SlotId, Dci)); + DEBUG ((DEBUG_VERBOSE, "XhcStopEndpoint: Slot = 0x%x, Dci = 0x%x\n", SlotId, Dci)); // // When XhcCheckUrbResult waits for the Stop_Endpoint completion, it also checks @@ -3497,7 +3497,7 @@ XhcSetTrDequeuePointer ( CMD_SET_TR_DEQ_POINTER CmdSetTRDeq; EFI_PHYSICAL_ADDRESS PhyAddr; - DEBUG ((DEBUG_INFO, "XhcSetTrDequeuePointer: Slot = 0x%x, Dci = 0x%x, Urb = 0x%x\n", SlotId, Dci, Urb)); + DEBUG ((DEBUG_VERBOSE, "XhcSetTrDequeuePointer: Slot = 0x%x, Dci = 0x%x, Urb = 0x%x\n", SlotId, Dci, Urb)); // // Send stop endpoint command to transit Endpoint from running to stop state From 041a4f8f6174599113714697e12d5960fd06b2b5 Mon Sep 17 00:00:00 2001 From: Jason Lou Date: Thu, 24 Nov 2022 20:11:57 +0800 Subject: [PATCH 0349/1529] UefiCpuPkg/Test: Move EfiMpServiceProtocol UT in a separate function Move the implementation of EfiMpServiceProtocol unit tests in a separate function in preparation for developing the UEFI application and dynamic command for the same unit tests. Signed-off-by: Jason Lou Reviewed-by: Ray Ni Cc: Eric Dong Cc: Laszlo Ersek Cc: Rahul Kumar Reviewed-by: Zhiguang Liu Reviewed-by: Dun Tan --- .../EfiMpServiceProtocolUnitTest.c | 30 ++++++++++++++----- .../EfiMpServicesUnitTestCommom.h | 2 +- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c index 57f8ba3c06..5fe6369960 100644 --- a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolUnitTest.c @@ -187,18 +187,16 @@ MpServicesUnitTestWhoAmI ( } /** - Standard DXE driver or UEFI application entry point for unit test execution from DXE or UEFI Shell. - Initialize the unit test framework, suite, and unit tests for the EfiMpServiceProtocol and run the unit test. + Initialize the unit test framework, suite and unit tests for the EfiMpServiceProtocol and run the unit tests. - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. + @retval EFI_SUCCESS Initialize the unit test framework, suite, unit tests and run the unit tests successfully. + @retval Others Initialize the unit test framework, suite, unit tests or run the unit tests unsuccessfully. **/ EFI_STATUS EFIAPI -DxeEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +EfiMpServiceProtocolUnitTest ( + VOID ) { EFI_STATUS Status; @@ -242,3 +240,21 @@ DxeEntryPoint ( return Status; } + +/** + Standard DXE driver or UEFI application entry point for unit test execution from DXE or UEFI Shell. + Initialize the unit test framework, suite, and unit tests for the EfiMpServiceProtocol and run the unit test. + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + +**/ +EFI_STATUS +EFIAPI +DxeEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return EfiMpServiceProtocolUnitTest (); +} diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h index abbbd2faba..d2b1633b4d 100644 --- a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.h @@ -1,5 +1,5 @@ /** @file - Common header file for EfiMpServiceProtocolUnitTest DXE driver. + Common header file for EdkiiPeiMpServices2Ppi and EfiMpServiceProtocol unit test. Copyright (c) 2022, Intel Corporation. All rights reserved.
From 6664f212c59d4ea014afa5a2ab045f6b72691d5f Mon Sep 17 00:00:00 2001 From: Jason Lou Date: Thu, 24 Nov 2022 20:11:58 +0800 Subject: [PATCH 0350/1529] UefiCpuPkg/Test: develop UEFI App and dynamic cmd for MP services UT The code changes develop UEFI application and dynamic command for EfiMpServiceProtocol unit tests based on current UnitTestFramework. Signed-off-by: Jason Lou Reviewed-by: Ray Ni Cc: Eric Dong Cc: Laszlo Ersek Cc: Rahul Kumar Reviewed-by: Zhiguang Liu Reviewed-by: Dun Tan --- .../EfiMpServiceProtocolDynamicCmdUnitTest.c | 129 ++++++++++++++++++ ...EfiMpServiceProtocolDynamicCmdUnitTest.inf | 45 ++++++ .../EfiMpServiceProtocolShellUnitTest.inf | 43 ++++++ UefiCpuPkg/UefiCpuPkg.dsc | 8 ++ 4 files changed, 225 insertions(+) create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.c create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.inf create mode 100644 UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolShellUnitTest.inf diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.c new file mode 100644 index 0000000000..be65c3d678 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.c @@ -0,0 +1,129 @@ +/** @file + Produce "MpProtocolUnitTest" shell dynamic command. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include "EfiMpServicesUnitTestCommom.h" + +CHAR16 *mMpProtocolUnitTestCommandHelp = L".TH MpProtocolUnitTest 0\r\n.SH NAME\r\nDisplay unit test results of EFI MP services protocol.\r\n"; + +EFI_STATUS +EFIAPI +EfiMpServiceProtocolUnitTest ( + VOID + ); + +/** + This is the shell command handler function pointer callback type. This + function handles the command when it is invoked in the shell. + + @param[in] This The instance of the EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL. + @param[in] SystemTable The pointer to the system table. + @param[in] ShellParameters The parameters associated with the command. + @param[in] Shell The instance of the shell protocol used in the context + of processing this command. + + @return EFI_SUCCESS the operation was successful + @return other the operation failed. +**/ +SHELL_STATUS +EFIAPI +MpProtocolUnitTestCommandHandler ( + IN EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL *This, + IN EFI_SYSTEM_TABLE *SystemTable, + IN EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters, + IN EFI_SHELL_PROTOCOL *Shell + ) +{ + return EfiMpServiceProtocolUnitTest (); +} + +/** + This is the command help handler function pointer callback type. This + function is responsible for displaying help information for the associated + command. + + @param[in] This The instance of the EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL. + @param[in] Language The pointer to the language string to use. + + @return string Pool allocated help string, must be freed by caller +**/ +CHAR16 * +EFIAPI +MpProtocolUnitTestCommandGetHelp ( + IN EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL *This, + IN CONST CHAR8 *Language + ) +{ + return AllocateCopyPool (StrSize (mMpProtocolUnitTestCommandHelp), mMpProtocolUnitTestCommandHelp); +} + +EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL mMpProtocolUnitTestDynamicCommand = { + L"MpProtocolUnitTest", + MpProtocolUnitTestCommandHandler, + MpProtocolUnitTestCommandGetHelp +}; + +/** + Entry point of MpProtocolUnitTest Dynamic Command. + + Produce the DynamicCommand protocol to handle "MpProtocolUnitTest" command. + + @param ImageHandle The image handle of the process. + @param SystemTable The EFI System Table pointer. + + @retval EFI_SUCCESS Tftp command is executed successfully. + @retval EFI_ABORTED HII package was failed to initialize. + @retval others Other errors when executing MpProtocolUnitTest command. +**/ +EFI_STATUS +EFIAPI +MpProtocolUnitTestCommandInitialize ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + Status = gBS->InstallProtocolInterface ( + &ImageHandle, + &gEfiShellDynamicCommandProtocolGuid, + EFI_NATIVE_INTERFACE, + &mMpProtocolUnitTestDynamicCommand + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} + +/** + Driver unload handler. + + @param ImageHandle The image handle of the process. + + @retval EFI_SUCCESS The image is unloaded. + @retval Others Failed to unload the image. +**/ +EFI_STATUS +EFIAPI +MpProtocolUnitTestUnload ( + IN EFI_HANDLE ImageHandle + ) +{ + EFI_STATUS Status; + + Status = gBS->UninstallProtocolInterface ( + ImageHandle, + &gEfiShellDynamicCommandProtocolGuid, + &mMpProtocolUnitTestDynamicCommand + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.inf b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.inf new file mode 100644 index 0000000000..3fa287d1ae --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.inf @@ -0,0 +1,45 @@ +## @file +# DXE driver that provides Shell 'MpProtocolUnitTest' dynamic command to test EfiMpServiceProtocol. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = EfiMpServiceProtocolDynamicCmdUnitTest + FILE_GUID = 8C4624B1-58CC-4DF6-9E6D-09B38D67DFA6 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = MpProtocolUnitTestCommandInitialize + UNLOAD_IMAGE = MpProtocolUnitTestUnload + +[Sources] + EfiMpServicesUnitTestCommom.c + EfiMpServicesUnitTestCommom.h + EfiMpServiceProtocolUnitTest.c + EfiMpServiceProtocolDynamicCmdUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + BaseMemoryLib + MemoryAllocationLib + UefiDriverEntryPoint + UefiBootServicesTableLib + UefiLib + UnitTestPersistenceLib + UnitTestLib + +[Protocols] + gEfiMpServiceProtocolGuid ## CONSUMES + gEfiShellDynamicCommandProtocolGuid ## PRODUCES + +[Depex] + TRUE diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolShellUnitTest.inf b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolShellUnitTest.inf new file mode 100644 index 0000000000..34c1ea96a6 --- /dev/null +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolShellUnitTest.inf @@ -0,0 +1,43 @@ +## @file +# UEFI application that tests EfiMpServiceProtocol in Shell. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MpProtocolUnitTest + FILE_GUID = 4CEE6399-A22C-4FFD-B148-3A56B1DD83F1 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + EfiMpServicesUnitTestCommom.c + EfiMpServicesUnitTestCommom.h + EfiMpServiceProtocolUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + BaseMemoryLib + MemoryAllocationLib + UefiApplicationEntryPoint + UefiBootServicesTableLib + UnitTestPersistenceLib + UnitTestLib + +[Protocols] + gEfiMpServiceProtocolGuid ## CONSUMES diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index 67b0ce46e4..f9a46089d2 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -183,6 +183,14 @@ UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EdkiiPeiMpServices2PpiPeiUnitTest.inf UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDxeUnitTest.inf + UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolDynamicCmdUnitTest.inf { + + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf + } + UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServiceProtocolShellUnitTest.inf { + + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf + } [Components.X64] UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf From f2516c3e8e6688748cd4fa9be9cd94aa6a7b4f71 Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 5 Dec 2022 14:51:18 +0800 Subject: [PATCH 0351/1529] EmulatorPkg/Win: Unload DLLs before reset EmulatorPkg/Win calls LoadLibraryEx() when the corresponding DLL file is found for each PEIM or DXE driver. The module entry point is changed to point to the entry point from the DLL. This helps to notify Visual Studio that a new windows module is loaded and corresponding symbol parsing is performed for source level debugging. But entry point from the DLL is only executed when the module is not loaded by AddModHandle(). When reset happens, we need to clear the DLL loading so that in next boot the module can be loaded again by AddModHandle(). Without this patch, source level debugging doesn't work after reset. Signed-off-by: Ray Ni Reviewed-by: Zhiguang Liu Cc: Andrew Fish --- EmulatorPkg/Win/Host/WinHost.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 096292f95a..084cd4cbd7 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -226,12 +226,26 @@ WinReset ( IN VOID *ResetData OPTIONAL ) { + UINTN Index; + ASSERT (ResetType <= EfiResetPlatformSpecific); SecPrint (" Emu ResetSystem is called: ResetType = %s\n", mResetTypeStr[ResetType]); if (ResetType == EfiResetShutdown) { exit (0); } else { + // + // Unload all DLLs + // + for (Index = 0; Index < mPdbNameModHandleArraySize; Index++) { + if (mPdbNameModHandleArray[Index].PdbPointer != NULL) { + SecPrint (" Emu Unload DLL: %s\n", mPdbNameModHandleArray[Index].PdbPointer); + FreeLibrary (mPdbNameModHandleArray[Index].ModHandle); + HeapFree (GetProcessHeap (), 0, mPdbNameModHandleArray[Index].PdbPointer); + mPdbNameModHandleArray[Index].PdbPointer = NULL; + } + } + // // Jump back to SetJump with jump code = ResetType + 1 // From af96508bf631095bf999423dbeaadd9704626f85 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Wed, 30 Nov 2022 13:13:56 +0800 Subject: [PATCH 0352/1529] UefiCpuPkg: Check SMM Delayed/Blocked AP Count REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4173 Due to more core count increasement, it's hard to reflect all APs state via AP bitvector support in the register. Actually, SMM CPU driver doesn't need to check each AP state to know all CPUs in SMI or not, one alternative method is to check the SMM Delayed & Blocked AP Count number: APs in SMI + Blocked Count + Disabled Count >= All supported Aps (code comments explained why can be > All supported Aps) With above change, the returned value of "SmmRegSmmEnable" & "SmmRegSmmDelayed" & "SmmRegSmmBlocked" from SmmCpuFeaturesLib should be the AP count number within the existing CPU package. For register that return the bitvector state, require SmmCpuFeaturesGetSmmRegister() returns count number of all bit per logical processor within the same package. For register that return the AP count, require SmmCpuFeaturesGetSmmRegister() returns the register value directly. v3: - Refine the coding style v2: - Rename "mPackageBspInfo" to "mPackageFirstThreadIndex" - Clarify the expected value of "SmmRegSmmEnable" & "SmmRegSmmDelayed" & "SmmRegSmmBlocked" returned from SmmCpuFeaturesLib. - Thread: https://edk2.groups.io/g/devel/message/96722 v1: - Thread: https://edk2.groups.io/g/devel/message/96671 Cc: Eric Dong Reviewed-by: Ray Ni Cc: Zeng Star Signed-off-by: Jiaxin Wu --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 195 ++++++++++++++++++--- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 5 + UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 16 +- 3 files changed, 184 insertions(+), 32 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index c79da418e3..a0967eb69c 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -24,6 +24,11 @@ SMM_CPU_SYNC_MODE mCpuSmmSyncMode; BOOLEAN mMachineCheckSupported = FALSE; MM_COMPLETION mSmmStartupThisApToken; +// +// Processor specified by mPackageFirstThreadIndex[PackageIndex] will do the package-scope register check. +// +UINT32 *mPackageFirstThreadIndex = NULL; + extern UINTN mSmmShadowStackSize; /** @@ -157,50 +162,125 @@ ReleaseAllAPs ( } /** - Checks if all CPUs (with certain exceptions) have checked in for this SMI run + Check whether the index of CPU perform the package level register + programming during System Management Mode initialization. - @param Exceptions CPU Arrival exception flags. + The index of Processor specified by mPackageFirstThreadIndex[PackageIndex] + will do the package-scope register programming. - @retval TRUE if all CPUs the have checked in. - @retval FALSE if at least one Normal AP hasn't checked in. + @param[in] CpuIndex Processor Index. + + @retval TRUE Perform the package level register programming. + @retval FALSE Don't perform the package level register programming. **/ BOOLEAN -AllCpusInSmmWithExceptions ( - SMM_CPU_ARRIVAL_EXCEPTIONS Exceptions +IsPackageFirstThread ( + IN UINTN CpuIndex ) { - UINTN Index; - SMM_CPU_DATA_BLOCK *CpuData; - EFI_PROCESSOR_INFORMATION *ProcessorInfo; + UINT32 PackageIndex; - ASSERT (*mSmmMpSyncData->Counter <= mNumberOfCpus); + PackageIndex = gSmmCpuPrivate->ProcessorInfo[CpuIndex].Location.Package; - if (*mSmmMpSyncData->Counter == mNumberOfCpus) { - return TRUE; + ASSERT (mPackageFirstThreadIndex != NULL); + + // + // Set the value of mPackageFirstThreadIndex[PackageIndex]. + // The package-scope register are checked by the first processor (CpuIndex) in Package. + // + // If mPackageFirstThreadIndex[PackageIndex] equals to (UINT32)-1, then update + // to current CpuIndex. If it doesn't equal to (UINT32)-1, don't change it. + // + if (mPackageFirstThreadIndex[PackageIndex] == (UINT32)-1) { + mPackageFirstThreadIndex[PackageIndex] = (UINT32)CpuIndex; } - CpuData = mSmmMpSyncData->CpuData; - ProcessorInfo = gSmmCpuPrivate->ProcessorInfo; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { - if (!(*(CpuData[Index].Present)) && (ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID)) { - if (((Exceptions & ARRIVAL_EXCEPTION_DELAYED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed) != 0)) { - continue; - } + return (BOOLEAN)(mPackageFirstThreadIndex[PackageIndex] == CpuIndex); +} + +/** + Returns the Number of SMM Delayed & Blocked & Disabled Thread Count. + + @param[in,out] DelayedCount The Number of SMM Delayed Thread Count. + @param[in,out] BlockedCount The Number of SMM Blocked Thread Count. + @param[in,out] DisabledCount The Number of SMM Disabled Thread Count. + +**/ +VOID +GetSmmDelayedBlockedDisabledCount ( + IN OUT UINT32 *DelayedCount, + IN OUT UINT32 *BlockedCount, + IN OUT UINT32 *DisabledCount + ) +{ + UINTN Index; - if (((Exceptions & ARRIVAL_EXCEPTION_BLOCKED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmBlocked) != 0)) { - continue; + for (Index = 0; Index < mNumberOfCpus; Index++) { + if (IsPackageFirstThread (Index)) { + if (DelayedCount != NULL) { + *DelayedCount += (UINT32)SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed); } - if (((Exceptions & ARRIVAL_EXCEPTION_SMI_DISABLED) != 0) && (SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmEnable) != 0)) { - continue; + if (BlockedCount != NULL) { + *BlockedCount += (UINT32)SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmBlocked); } - return FALSE; + if (DisabledCount != NULL) { + *DisabledCount += (UINT32)SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmEnable); + } } } +} - return TRUE; +/** + Checks if all CPUs (except Blocked & Disabled) have checked in for this SMI run + + @retval TRUE if all CPUs the have checked in. + @retval FALSE if at least one Normal AP hasn't checked in. + +**/ +BOOLEAN +AllCpusInSmmExceptBlockedDisabled ( + VOID + ) +{ + UINT32 BlockedCount; + UINT32 DisabledCount; + + BlockedCount = 0; + DisabledCount = 0; + + // + // Check to make sure mSmmMpSyncData->Counter is valid and not locked. + // + ASSERT (*mSmmMpSyncData->Counter <= mNumberOfCpus); + + // + // Check whether all CPUs in SMM. + // + if (*mSmmMpSyncData->Counter == mNumberOfCpus) { + return TRUE; + } + + // + // Check for the Blocked & Disabled Exceptions Case. + // + GetSmmDelayedBlockedDisabledCount (NULL, &BlockedCount, &DisabledCount); + + // + // *mSmmMpSyncData->Counter might be updated by all APs concurrently. The value + // can be dynamic changed. If some Aps enter the SMI after the BlockedCount & + // DisabledCount check, then the *mSmmMpSyncData->Counter will be increased, thus + // leading the *mSmmMpSyncData->Counter + BlockedCount + DisabledCount > mNumberOfCpus. + // since the BlockedCount & DisabledCount are local variable, it's ok here only for + // the checking of all CPUs In Smm. + // + if (*mSmmMpSyncData->Counter + BlockedCount + DisabledCount >= mNumberOfCpus) { + return TRUE; + } + + return FALSE; } /** @@ -268,6 +348,11 @@ SmmWaitForApArrival ( UINTN Index; BOOLEAN LmceEn; BOOLEAN LmceSignal; + UINT32 DelayedCount; + UINT32 BlockedCount; + + DelayedCount = 0; + BlockedCount = 0; ASSERT (*mSmmMpSyncData->Counter <= mNumberOfCpus); @@ -296,7 +381,7 @@ SmmWaitForApArrival ( !IsSyncTimerTimeout (Timer) && !(LmceEn && LmceSignal); ) { - mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmWithExceptions (ARRIVAL_EXCEPTION_BLOCKED | ARRIVAL_EXCEPTION_SMI_DISABLED); + mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); if (mSmmMpSyncData->AllApArrivedWithException) { break; } @@ -337,7 +422,7 @@ SmmWaitForApArrival ( !IsSyncTimerTimeout (Timer); ) { - mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmWithExceptions (ARRIVAL_EXCEPTION_BLOCKED | ARRIVAL_EXCEPTION_SMI_DISABLED); + mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); if (mSmmMpSyncData->AllApArrivedWithException) { break; } @@ -346,6 +431,14 @@ SmmWaitForApArrival ( } } + if (!mSmmMpSyncData->AllApArrivedWithException) { + // + // Check for the Blocked & Delayed Case. + // + GetSmmDelayedBlockedDisabledCount (&DelayedCount, &BlockedCount, NULL); + DEBUG ((DEBUG_INFO, "SmmWaitForApArrival: Delayed AP Count = %d, Blocked AP Count = %d\n", DelayedCount, BlockedCount)); + } + return; } @@ -739,6 +832,7 @@ APHandler ( if (mSmmMpSyncData->BspIndex != -1) { // // BSP Index is known + // Existing AP is in SMI now but BSP not in, so, try bring BSP in SMM. // BspIndex = mSmmMpSyncData->BspIndex; ASSERT (CpuIndex != BspIndex); @@ -763,12 +857,15 @@ APHandler ( // // Give up since BSP is unable to enter SMM // and signal the completion of this AP + // Reduce the mSmmMpSyncData->Counter! + // WaitForSemaphore (mSmmMpSyncData->Counter); return; } } else { // // Don't know BSP index. Give up without sending IPI to BSP. + // Reduce the mSmmMpSyncData->Counter! // WaitForSemaphore (mSmmMpSyncData->Counter); return; @@ -1668,10 +1765,13 @@ SmiRendezvous ( } else { // // Signal presence of this processor + // mSmmMpSyncData->Counter is increased here! + // "ReleaseSemaphore (mSmmMpSyncData->Counter) == 0" means BSP has already ended the synchronization. // if (ReleaseSemaphore (mSmmMpSyncData->Counter) == 0) { // // BSP has already ended the synchronization, so QUIT!!! + // Existing AP is too late now to enter SMI since BSP has already ended the synchronization!!! // // @@ -1783,6 +1883,47 @@ SmiRendezvous ( RestoreCr2 (Cr2); } +/** + Initialize PackageBsp Info. Processor specified by mPackageFirstThreadIndex[PackageIndex] + will do the package-scope register programming. Set default CpuIndex to (UINT32)-1, which + means not specified yet. + +**/ +VOID +InitPackageFirstThreadIndexInfo ( + VOID + ) +{ + UINT32 Index; + UINT32 PackageId; + UINT32 PackageCount; + + PackageId = 0; + PackageCount = 0; + + // + // Count the number of package, set to max PackageId + 1 + // + for (Index = 0; Index < mNumberOfCpus; Index++) { + if (PackageId < gSmmCpuPrivate->ProcessorInfo[Index].Location.Package) { + PackageId = gSmmCpuPrivate->ProcessorInfo[Index].Location.Package; + } + } + + PackageCount = PackageId + 1; + + mPackageFirstThreadIndex = (UINT32 *)AllocatePool (sizeof (UINT32) * PackageCount); + ASSERT (mPackageFirstThreadIndex != NULL); + if (mPackageFirstThreadIndex == NULL) { + return; + } + + // + // Set default CpuIndex to (UINT32)-1, which means not specified yet. + // + SetMem32 (mPackageFirstThreadIndex, sizeof (UINT32) * PackageCount, (UINT32)-1); +} + /** Allocate buffer for SpinLock and Wrapper function buffer. diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 40aabeda72..37e3cfc449 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -1045,6 +1045,11 @@ PiCpuSmmEntry ( // InitializeDataForMmMp (); + // + // Initialize Package First Thread Index Info. + // + InitPackageFirstThreadIndexInfo (); + // // Install the SMM Mp Protocol into SMM protocol database // diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index ef8bf5947d..0bfba7e359 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -194,11 +194,6 @@ typedef struct { #define INVALID_APIC_ID 0xFFFFFFFFFFFFFFFFULL -typedef UINT32 SMM_CPU_ARRIVAL_EXCEPTIONS; -#define ARRIVAL_EXCEPTION_BLOCKED 0x1 -#define ARRIVAL_EXCEPTION_DELAYED 0x2 -#define ARRIVAL_EXCEPTION_SMI_DISABLED 0x4 - // // Wrapper used to convert EFI_AP_PROCEDURE2 and EFI_AP_PROCEDURE. // @@ -1462,6 +1457,17 @@ RegisterStartupProcedure ( IN OUT VOID *ProcedureArguments OPTIONAL ); +/** + Initialize PackageBsp Info. Processor specified by mPackageFirstThreadIndex[PackageIndex] + will do the package-scope register programming. Set default CpuIndex to (UINT32)-1, which + means not specified yet. + +**/ +VOID +InitPackageFirstThreadIndexInfo ( + VOID + ); + /** Allocate buffer for SpinLock and Wrapper function buffer. From 0873d6d0c6741a42e11ae68920e2fca12a77c579 Mon Sep 17 00:00:00 2001 From: Robert Guenzel Date: Thu, 8 Dec 2022 16:44:15 +0800 Subject: [PATCH 0353/1529] UefiCpuPkg: Bug fix in 5LPage handling When build in DEBUG, the code asserts that 5LPage support is there when the physical address width is larger than 48. In a RELEASE build it will just force LA57 to 1 in CR4 even if CPUID(7).ECX[16] says it is not supported. UefiCpuPkg: Bug fix in 5LPage handling The hang (in the ASSERT) in DEBUG is not warranted as there are legal configurations with CPUID(7).ECX[16](==LA57)=0 and with a physical address width of larger than 48 (like 52). This is also supported by this code: https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L221 There (as long as physical address width is smaller or equal to 52) any address width above 48 will be reduced to 48 and the system can and will work without 5LPaging. The forced setting of LA57 in CR4 (in the absence of LA57 in CPUID(7).ECX) is a spec violation and should not happen. Hence the proposed fix a) removes the assert. b) only returns TRUE from Is5LevelPagingNeeded if 5LPaging is actually supported by HW. Signed-off-by: Robert Guenzel --- UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c index 6587212f4e..bf90050503 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c @@ -1,7 +1,7 @@ /** @file Page Fault (#PF) handler for X64 processors -Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -104,8 +104,9 @@ Is5LevelPagingNeeded ( ExtFeatureEcx.Bits.FiveLevelPage )); - if (VirPhyAddressSize.Bits.PhysicalAddressBits > 4 * 9 + 12) { - ASSERT (ExtFeatureEcx.Bits.FiveLevelPage == 1); + if ((VirPhyAddressSize.Bits.PhysicalAddressBits > 4 * 9 + 12) && + (ExtFeatureEcx.Bits.FiveLevelPage == 1)) + { return TRUE; } else { return FALSE; From 177c66e2d650fdcb63d699effb1d6add3bfe0857 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Tue, 6 Dec 2022 13:40:52 +0800 Subject: [PATCH 0354/1529] EmulatorPkg: Add persistent memory in EmuThunkPpi The persistent memory is for PEIM to use, and won't lose during cold or warm reset. PcdPersistentMemorySize is only used by WinHost.c, other modules can check the persistent memory size using the field PersistentMemorySize. Cc: Andrew Fish Reviewed-by: Ray Ni Signed-off-by: Zhiguang Liu --- EmulatorPkg/EmulatorPkg.dec | 3 ++- EmulatorPkg/Include/Ppi/EmuThunk.h | 4 +++- EmulatorPkg/Unix/Host/Host.c | 13 +++++++++++-- EmulatorPkg/Unix/Host/Host.inf | 3 ++- EmulatorPkg/Win/Host/WinHost.c | 11 ++++++++++- EmulatorPkg/Win/Host/WinHost.inf | 2 +- 6 files changed, 29 insertions(+), 7 deletions(-) diff --git a/EmulatorPkg/EmulatorPkg.dec b/EmulatorPkg/EmulatorPkg.dec index b9c70b63b3..fe81652b04 100644 --- a/EmulatorPkg/EmulatorPkg.dec +++ b/EmulatorPkg/EmulatorPkg.dec @@ -2,7 +2,7 @@ # # This is the Emu Emulation Environment Platform # -# Copyright (c) 2008 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2011, Apple Inc. All rights reserved. # (C) Copyright 2020 Hewlett Packard Enterprise Development LP
# @@ -86,6 +86,7 @@ # The user ID and password are fixed as below. gEmulatorPkgTokenSpaceGuid.PcdRedfishServieUserId|"admin"|VOID*|0x00001022 gEmulatorPkgTokenSpaceGuid.PcdRedfishServiePassword|"pwd123456"|VOID*|0x00001023 + gEmulatorPkgTokenSpaceGuid.PcdPersistentMemorySize|0x4000000|UINT32|0x00001024 [PcdsFixedAtBuild, PcdsPatchableInModule] gEmulatorPkgTokenSpaceGuid.PcdEmuBootMode|1|UINT32|0x00001006 diff --git a/EmulatorPkg/Include/Ppi/EmuThunk.h b/EmulatorPkg/Include/Ppi/EmuThunk.h index c0e2bc6b98..cf29cf824c 100644 --- a/EmulatorPkg/Include/Ppi/EmuThunk.h +++ b/EmulatorPkg/Include/Ppi/EmuThunk.h @@ -2,7 +2,7 @@ Emulator Thunk to abstract OS services from pure EFI code Copyright (c) 2008 - 2011, Apple Inc. All rights reserved.
- + Copyright (c) 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -107,6 +107,8 @@ typedef struct { EMU_PEI_AUTOSCAN MemoryAutoScan; EMU_PEI_FD_INFORMATION FirmwareDevices; EMU_PEI_THUNK_INTERFACE Thunk; + UINTN PersistentMemorySize; + UINT8 PersistentMemory[0]; } EMU_THUNK_PPI; extern EFI_GUID gEmuThunkPpiGuid; diff --git a/EmulatorPkg/Unix/Host/Host.c b/EmulatorPkg/Unix/Host/Host.c index 38c01c84af..8d0be5b54b 100644 --- a/EmulatorPkg/Unix/Host/Host.c +++ b/EmulatorPkg/Unix/Host/Host.c @@ -1,6 +1,6 @@ /*++ @file -Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2011, Apple Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -102,6 +102,7 @@ main ( CHAR16 *FirmwareVolumesStr; UINTN *StackPointer; FILE *GdbTempFile; + EMU_THUNK_PPI *SecEmuThunkPpi; // // Xcode does not support sourcing gdb scripts directly, so the Xcode XML @@ -137,7 +138,15 @@ main ( // // PPIs pased into PEI_CORE // - AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, &mSecEmuThunkPpi); + SecEmuThunkPpi = AllocateZeroPool (sizeof (EMU_THUNK_PPI) + FixedPcdGet32 (PcdPersistentMemorySize)); + if (SecEmuThunkPpi == NULL) { + printf ("ERROR : Can not allocate memory for SecEmuThunkPpi. Exiting.\n"); + exit (1); + } + + CopyMem (SecEmuThunkPpi, &mSecEmuThunkPpi, sizeof (EMU_THUNK_PPI)); + SecEmuThunkPpi->PersistentMemorySize = FixedPcdGet32 (PcdPersistentMemorySize); + AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, SecEmuThunkPpi); SecInitThunkProtocol (); diff --git a/EmulatorPkg/Unix/Host/Host.inf b/EmulatorPkg/Unix/Host/Host.inf index c479d2b7d0..f5ebbed683 100644 --- a/EmulatorPkg/Unix/Host/Host.inf +++ b/EmulatorPkg/Unix/Host/Host.inf @@ -2,7 +2,7 @@ # Entry Point of Emu Emulator # # Main executable file of Unix Emulator that loads PEI core after initialization finished. -# Copyright (c) 2008 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2011, Apple Inc. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -106,6 +106,7 @@ gEmulatorPkgTokenSpaceGuid.PcdEmuFlashNvStorageFtwSpareBase gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize gEmulatorPkgTokenSpaceGuid.PcdPeiServicesTablePage + gEmulatorPkgTokenSpaceGuid.PcdPersistentMemorySize [FeaturePcd] gEmulatorPkgTokenSpaceGuid.PcdEmulatorLazyLoadSymbols diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 084cd4cbd7..19199c648c 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -450,6 +450,7 @@ Routine Description: UINTN SystemAffinityMask; INT32 LowBit; UINTN ResetJumpCode; + EMU_THUNK_PPI *SecEmuThunkPpi; // // Enable the privilege so that RTC driver can successfully run SetTime() @@ -491,7 +492,15 @@ Routine Description: // // PPIs pased into PEI_CORE // - AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, &mSecEmuThunkPpi); + SecEmuThunkPpi = AllocateZeroPool (sizeof (EMU_THUNK_PPI) + FixedPcdGet32 (PcdPersistentMemorySize)); + if (SecEmuThunkPpi == NULL) { + SecPrint ("ERROR : Can not allocate memory for SecEmuThunkPpi. Exiting.\n"); + exit (1); + } + + CopyMem (SecEmuThunkPpi, &mSecEmuThunkPpi, sizeof (EMU_THUNK_PPI)); + SecEmuThunkPpi->PersistentMemorySize = FixedPcdGet32 (PcdPersistentMemorySize); + AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, SecEmuThunkPpi); AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEfiPeiReset2PpiGuid, &mEmuReset2Ppi); // diff --git a/EmulatorPkg/Win/Host/WinHost.inf b/EmulatorPkg/Win/Host/WinHost.inf index b61901fae2..4dac6e033e 100644 --- a/EmulatorPkg/Win/Host/WinHost.inf +++ b/EmulatorPkg/Win/Host/WinHost.inf @@ -74,7 +74,7 @@ [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdInitValueInTempStack - + gEmulatorPkgTokenSpaceGuid.PcdPersistentMemorySize gEmulatorPkgTokenSpaceGuid.PcdEmuBootMode gEmulatorPkgTokenSpaceGuid.PcdEmuFirmwareVolume gEmulatorPkgTokenSpaceGuid.PcdEmuMemorySize From 799bd373741cb2d0c2850392a0d69eb5a9223247 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Tue, 6 Dec 2022 13:30:18 +0800 Subject: [PATCH 0355/1529] EmulatorPkg: Remove unnecessary dependency on EmbeddedPkg EmulatorPkg doesn't need depend on EmbeddedPkg, so remove the dependency. Cc: Andrew Fish Reviewed-by: Ray Ni Signed-off-by: Zhiguang Liu --- EmulatorPkg/EmulatorPkg.ci.yaml | 3 +-- .../Library/DxeEmuSerialPortLib/DxeEmuSerialPortLib.inf | 3 +-- .../Library/PeiEmuSerialPortLib/PeiEmuSerialPortLib.inf | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/EmulatorPkg/EmulatorPkg.ci.yaml b/EmulatorPkg/EmulatorPkg.ci.yaml index 338d5fc2d3..6e9b2857cb 100644 --- a/EmulatorPkg/EmulatorPkg.ci.yaml +++ b/EmulatorPkg/EmulatorPkg.ci.yaml @@ -5,7 +5,7 @@ # used for code analysis. # # Copyright (c) Microsoft Corporation -# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## { @@ -55,7 +55,6 @@ "EmulatorPkg/EmulatorPkg.dec", "NetworkPkg/NetworkPkg.dec", "RedfishPkg/RedfishPkg.dec", - "EmbeddedPkg/EmbeddedPkg.dec", ## is this one OK?? ], # For host based unit tests "AcceptableDependencies-HOST_APPLICATION":[ diff --git a/EmulatorPkg/Library/DxeEmuSerialPortLib/DxeEmuSerialPortLib.inf b/EmulatorPkg/Library/DxeEmuSerialPortLib/DxeEmuSerialPortLib.inf index d91f7de181..dfdabde22a 100644 --- a/EmulatorPkg/Library/DxeEmuSerialPortLib/DxeEmuSerialPortLib.inf +++ b/EmulatorPkg/Library/DxeEmuSerialPortLib/DxeEmuSerialPortLib.inf @@ -1,7 +1,7 @@ ## @file # Write only instance of Serial Port Library with empty functions. # -# Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2011, Apple Inc. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -25,7 +25,6 @@ [Packages] MdePkg/MdePkg.dec EmulatorPkg/EmulatorPkg.dec - EmbeddedPkg/EmbeddedPkg.dec [LibraryClasses] EmuThunkLib diff --git a/EmulatorPkg/Library/PeiEmuSerialPortLib/PeiEmuSerialPortLib.inf b/EmulatorPkg/Library/PeiEmuSerialPortLib/PeiEmuSerialPortLib.inf index 2f5e656fd7..7ef3e3baaf 100644 --- a/EmulatorPkg/Library/PeiEmuSerialPortLib/PeiEmuSerialPortLib.inf +++ b/EmulatorPkg/Library/PeiEmuSerialPortLib/PeiEmuSerialPortLib.inf @@ -1,7 +1,7 @@ ## @file # Write only instance of Serial Port Library with empty functions. # -# Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2011, Apple Inc. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -28,7 +28,6 @@ [Packages] MdePkg/MdePkg.dec EmulatorPkg/EmulatorPkg.dec - EmbeddedPkg/EmbeddedPkg.dec [LibraryClasses] PeiServicesLib From e2ef28c3c369004178a2c73276b5fa21836c901b Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Tue, 6 Dec 2022 13:41:36 +0800 Subject: [PATCH 0356/1529] EmulatorPkg: Record Argc, Argv and Envp in EmuThunk Ppi Record Argc, Argv and Envp in EmuThunk Ppi so that other modules can use these fields to change behavior depends on boot parameters or environment. Cc: Andrew Fish Reviewed-by: Ray Ni Signed-off-by: Zhiguang Liu --- EmulatorPkg/Include/Ppi/EmuThunk.h | 3 +++ EmulatorPkg/Unix/Host/Host.c | 3 +++ EmulatorPkg/Win/Host/WinHost.c | 3 +++ 3 files changed, 9 insertions(+) diff --git a/EmulatorPkg/Include/Ppi/EmuThunk.h b/EmulatorPkg/Include/Ppi/EmuThunk.h index cf29cf824c..c78ad692ed 100644 --- a/EmulatorPkg/Include/Ppi/EmuThunk.h +++ b/EmulatorPkg/Include/Ppi/EmuThunk.h @@ -107,6 +107,9 @@ typedef struct { EMU_PEI_AUTOSCAN MemoryAutoScan; EMU_PEI_FD_INFORMATION FirmwareDevices; EMU_PEI_THUNK_INTERFACE Thunk; + INTN Argc; + CHAR8 **Argv; + CHAR8 **Envp; UINTN PersistentMemorySize; UINT8 PersistentMemory[0]; } EMU_THUNK_PPI; diff --git a/EmulatorPkg/Unix/Host/Host.c b/EmulatorPkg/Unix/Host/Host.c index 8d0be5b54b..1f29dd00a3 100644 --- a/EmulatorPkg/Unix/Host/Host.c +++ b/EmulatorPkg/Unix/Host/Host.c @@ -145,6 +145,9 @@ main ( } CopyMem (SecEmuThunkPpi, &mSecEmuThunkPpi, sizeof (EMU_THUNK_PPI)); + SecEmuThunkPpi->Argc = Argc; + SecEmuThunkPpi->Argv = Argv; + SecEmuThunkPpi->Envp = Envp; SecEmuThunkPpi->PersistentMemorySize = FixedPcdGet32 (PcdPersistentMemorySize); AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, SecEmuThunkPpi); diff --git a/EmulatorPkg/Win/Host/WinHost.c b/EmulatorPkg/Win/Host/WinHost.c index 19199c648c..193a947fbd 100644 --- a/EmulatorPkg/Win/Host/WinHost.c +++ b/EmulatorPkg/Win/Host/WinHost.c @@ -499,6 +499,9 @@ Routine Description: } CopyMem (SecEmuThunkPpi, &mSecEmuThunkPpi, sizeof (EMU_THUNK_PPI)); + SecEmuThunkPpi->Argc = Argc; + SecEmuThunkPpi->Argv = Argv; + SecEmuThunkPpi->Envp = Envp; SecEmuThunkPpi->PersistentMemorySize = FixedPcdGet32 (PcdPersistentMemorySize); AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, SecEmuThunkPpi); AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEfiPeiReset2PpiGuid, &mEmuReset2Ppi); From 31e524ee646312516acb6ec4e5ab3289059f6960 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 7 Dec 2022 18:49:45 +0100 Subject: [PATCH 0357/1529] MdeModulePkg/DxeCore: Use correct type for alignment mask The page allocator code in CoreFindFreePagesI() uses a mask derived from its UINTN Alignment argument to align the descriptor end address of a MEMORY_MAP entry to the requested alignment, in order to check whether the descriptor covers enough sufficiently aligned area to satisfy the request. However, on 32-bit architectures, 'Alignment' is a 32-bit type, whereas DescEnd is a 64-bit type, and so the resulting operation performed on the end address comes down to masking with 0xfffff000 instead of the intended 0xffffffff_fffff000. Given the -1 at the end of the expression, the resulting address is 0xffffffff_fffffffff for any descriptor that ends on a 4G aligned boundary, and this is certainly not what was intended. So cast Alignment to UINT64 to ensure that the mask has the right size. Signed-off-by: Ard Biesheuvel Reported-by: Nathan Chancellor Reviewed-by: Michael D Kinney --- MdeModulePkg/Core/Dxe/Mem/Page.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c index 160289c1f9..5903ce7ab5 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Page.c +++ b/MdeModulePkg/Core/Dxe/Mem/Page.c @@ -1097,7 +1097,7 @@ CoreFindFreePagesI ( DescEnd = MaxAddress; } - DescEnd = ((DescEnd + 1) & (~(Alignment - 1))) - 1; + DescEnd = ((DescEnd + 1) & (~((UINT64)Alignment - 1))) - 1; // Skip if DescEnd is less than DescStart after alignment clipping if (DescEnd < DescStart) { From 50de512493780f5af4947daa131109c134414167 Mon Sep 17 00:00:00 2001 From: Ryan Afranji Date: Thu, 8 Dec 2022 08:51:15 +0800 Subject: [PATCH 0358/1529] OvmfPkg: Add INVD case in #VE handler According to the Intel GHCI specification document section 2.4.1, the goal for instructions that do not have a corresponding TDCALL is for the handler to treat the instruction as a NOP. INVD does not have a corresponding TDCALL. This patch makes the #VE handler treat INVD as a NOP. Signed-off-by: Ryan Afranji Reviewed-by: Jiewen Yao --- OvmfPkg/Library/CcExitLib/CcExitVeHandler.c | 1 + 1 file changed, 1 insertion(+) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index 081af7e12a..30d547d5fe 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -545,6 +545,7 @@ CcExitHandleVe ( case EXIT_REASON_MONITOR_INSTRUCTION: case EXIT_REASON_WBINVD: case EXIT_REASON_RDPMC: + case EXIT_REASON_INVD: /* Handle as nops. */ break; From 8ba3a6c82f359c9e42be0d40733b80b250fb47ab Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 9 Dec 2022 21:03:46 +0800 Subject: [PATCH 0359/1529] OvmfPkg: move dsc and fdf include snippets for TPM support to subdirs Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/AmdSev/AmdSevX64.dsc | 14 +++++++------- OvmfPkg/CloudHv/CloudHvX64.dsc | 14 +++++++------- .../{ => Include/Dsc}/OvmfTpmComponentsDxe.dsc.inc | 0 .../{ => Include/Dsc}/OvmfTpmComponentsPei.dsc.inc | 0 OvmfPkg/{ => Include/Dsc}/OvmfTpmDefines.dsc.inc | 0 OvmfPkg/{ => Include/Dsc}/OvmfTpmLibs.dsc.inc | 0 OvmfPkg/{ => Include/Dsc}/OvmfTpmPcds.dsc.inc | 0 OvmfPkg/{ => Include/Dsc}/OvmfTpmPcdsHii.dsc.inc | 0 .../{ => Include/Dsc}/OvmfTpmSecurityStub.dsc.inc | 0 OvmfPkg/Microvm/MicrovmX64.dsc | 2 +- OvmfPkg/OvmfPkgIa32.dsc | 14 +++++++------- OvmfPkg/OvmfPkgIa32X64.dsc | 14 +++++++------- OvmfPkg/OvmfPkgX64.dsc | 14 +++++++------- 13 files changed, 36 insertions(+), 36 deletions(-) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmComponentsDxe.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmComponentsPei.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmDefines.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmLibs.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmPcds.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmPcdsHii.dsc.inc (100%) rename OvmfPkg/{ => Include/Dsc}/OvmfTpmSecurityStub.dsc.inc (100%) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 8f7cae787e..e0b04d6734 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -33,7 +33,7 @@ # DEFINE SOURCE_DEBUG_ENABLE = FALSE -!include OvmfPkg/OvmfTpmDefines.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc # # Shell can be useful for debugging but should not be enabled for production @@ -200,7 +200,7 @@ SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf -!include OvmfPkg/OvmfTpmLibs.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -527,12 +527,12 @@ # Set ConfidentialComputing defaults gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr|0 -!include OvmfPkg/OvmfTpmPcds.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc gEfiMdePkgTokenSpaceGuid.PcdFSBClock|1000000000 [PcdsDynamicHii] -!include OvmfPkg/OvmfTpmPcdsHii.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc ################################################################################ # @@ -573,7 +573,7 @@ UefiCpuPkg/CpuMpPei/CpuMpPei.inf OvmfPkg/AmdSev/SecretPei/SecretPei.inf -!include OvmfPkg/OvmfTpmComponentsPei.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc # # DXE Phase modules @@ -595,7 +595,7 @@ MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf { -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf @@ -766,4 +766,4 @@ # # TPM support # -!include OvmfPkg/OvmfTpmComponentsDxe.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index ce277cb239..fcc5722a6b 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -33,7 +33,7 @@ DEFINE SMM_REQUIRE = FALSE DEFINE SOURCE_DEBUG_ENABLE = FALSE -!include OvmfPkg/OvmfTpmDefines.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc # # Network definition @@ -247,7 +247,7 @@ SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf -!include OvmfPkg/OvmfTpmLibs.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -630,7 +630,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00 -!include OvmfPkg/OvmfTpmPcds.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc # IPv4 and IPv6 PXE Boot support. gEfiNetworkPkgTokenSpaceGuid.PcdIPv4PXESupport|0x01 @@ -640,7 +640,7 @@ gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr|0 [PcdsDynamicHii] -!include OvmfPkg/OvmfTpmPcdsHii.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc ################################################################################ # @@ -690,7 +690,7 @@ !endif UefiCpuPkg/CpuMpPei/CpuMpPei.inf -!include OvmfPkg/OvmfTpmComponentsPei.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc # # DXE Phase modules @@ -714,7 +714,7 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif } @@ -945,4 +945,4 @@ # # TPM support # -!include OvmfPkg/OvmfTpmComponentsDxe.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc diff --git a/OvmfPkg/OvmfTpmComponentsDxe.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmComponentsDxe.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc diff --git a/OvmfPkg/OvmfTpmComponentsPei.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmComponentsPei.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc diff --git a/OvmfPkg/OvmfTpmDefines.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmDefines.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc diff --git a/OvmfPkg/OvmfTpmLibs.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmLibs.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc diff --git a/OvmfPkg/OvmfTpmPcds.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmPcds.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc diff --git a/OvmfPkg/OvmfTpmPcdsHii.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmPcdsHii.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc diff --git a/OvmfPkg/OvmfTpmSecurityStub.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc similarity index 100% rename from OvmfPkg/OvmfTpmSecurityStub.dsc.inc rename to OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 994a02d301..649005201f 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -703,7 +703,7 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif } diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 6f774baf90..5a2214a872 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -34,7 +34,7 @@ DEFINE SOURCE_DEBUG_ENABLE = FALSE DEFINE LOAD_X64_ON_IA32_ENABLE = FALSE -!include OvmfPkg/OvmfTpmDefines.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc # # Shell can be useful for debugging but should not be enabled for production @@ -252,7 +252,7 @@ SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf -!include OvmfPkg/OvmfTpmLibs.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -657,7 +657,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00 -!include OvmfPkg/OvmfTpmPcds.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc # IPv4 and IPv6 PXE Boot support. gEfiNetworkPkgTokenSpaceGuid.PcdIPv4PXESupport|0x01 @@ -671,7 +671,7 @@ !endif [PcdsDynamicHii] -!include OvmfPkg/OvmfTpmPcdsHii.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc ################################################################################ # @@ -721,7 +721,7 @@ !endif UefiCpuPkg/CpuMpPei/CpuMpPei.inf -!include OvmfPkg/OvmfTpmComponentsPei.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc # # DXE Phase modules @@ -746,7 +746,7 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf !endif -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf @@ -1014,7 +1014,7 @@ # # TPM support # -!include OvmfPkg/OvmfTpmComponentsDxe.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc !if $(LOAD_X64_ON_IA32_ENABLE) == TRUE OvmfPkg/CompatImageLoaderDxe/CompatImageLoaderDxe.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index c851764dec..bac41d7309 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -33,7 +33,7 @@ DEFINE SMM_REQUIRE = FALSE DEFINE SOURCE_DEBUG_ENABLE = FALSE -!include OvmfPkg/OvmfTpmDefines.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc # # Shell can be useful for debugging but should not be enabled for production @@ -256,7 +256,7 @@ SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf -!include OvmfPkg/OvmfTpmLibs.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -669,7 +669,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00 -!include OvmfPkg/OvmfTpmPcds.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc # Set ConfidentialComputing defaults gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr|0 @@ -684,7 +684,7 @@ gEfiNetworkPkgTokenSpaceGuid.PcdIPv6PXESupport|0x01 [PcdsDynamicHii] -!include OvmfPkg/OvmfTpmPcdsHii.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc ################################################################################ # @@ -734,7 +734,7 @@ !endif UefiCpuPkg/CpuMpPei/CpuMpPei.inf -!include OvmfPkg/OvmfTpmComponentsPei.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc [Components.X64] # @@ -760,7 +760,7 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf !endif -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf @@ -1032,4 +1032,4 @@ # # TPM support # -!include OvmfPkg/OvmfTpmComponentsDxe.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 63c3a47aea..9b6257a691 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -33,7 +33,7 @@ DEFINE SMM_REQUIRE = FALSE DEFINE SOURCE_DEBUG_ENABLE = FALSE -!include OvmfPkg/OvmfTpmDefines.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc # # Shell can be useful for debugging but should not be enabled for production @@ -272,7 +272,7 @@ SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf -!include OvmfPkg/OvmfTpmLibs.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -693,7 +693,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00 -!include OvmfPkg/OvmfTpmPcds.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcds.dsc.inc # IPv4 and IPv6 PXE Boot support. gEfiNetworkPkgTokenSpaceGuid.PcdIPv4PXESupport|0x01 @@ -707,7 +707,7 @@ !endif [PcdsDynamicHii] -!include OvmfPkg/OvmfTpmPcdsHii.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmPcdsHii.dsc.inc ################################################################################ # @@ -780,7 +780,7 @@ NULL|OvmfPkg/Library/MpInitLibDepLib/PeiMpInitLibUpDepLib.inf } -!include OvmfPkg/OvmfTpmComponentsPei.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsPei.dsc.inc # # DXE Phase modules @@ -804,7 +804,7 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/OvmfTpmSecurityStub.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif } @@ -1102,4 +1102,4 @@ # # TPM support # -!include OvmfPkg/OvmfTpmComponentsDxe.dsc.inc +!include OvmfPkg/Include/Dsc/OvmfTpmComponentsDxe.dsc.inc From c5f3bbf4a25b22704d24b72cf0edd2fb9c641cb3 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 9 Dec 2022 21:03:47 +0800 Subject: [PATCH 0360/1529] OvmfPkg: move dsc include snippet for Network support to Include/Dsc Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/CloudHv/CloudHvX64.dsc | 2 +- OvmfPkg/{ => Include/Dsc}/NetworkComponents.dsc.inc | 0 OvmfPkg/Microvm/MicrovmX64.dsc | 2 +- OvmfPkg/OvmfPkgIa32.dsc | 2 +- OvmfPkg/OvmfPkgIa32X64.dsc | 2 +- OvmfPkg/OvmfPkgX64.dsc | 2 +- 6 files changed, 5 insertions(+), 5 deletions(-) rename OvmfPkg/{ => Include/Dsc}/NetworkComponents.dsc.inc (100%) diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index fcc5722a6b..4fe7cb5f1b 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -827,7 +827,7 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc -!include OvmfPkg/NetworkComponents.dsc.inc +!include OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc OvmfPkg/VirtioNetDxe/VirtioNet.inf diff --git a/OvmfPkg/NetworkComponents.dsc.inc b/OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc similarity index 100% rename from OvmfPkg/NetworkComponents.dsc.inc rename to OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 649005201f..93d4cf3da2 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -817,7 +817,7 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc -!include OvmfPkg/NetworkComponents.dsc.inc +!include OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc OvmfPkg/VirtioNetDxe/VirtioNet.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 5a2214a872..f8250fa635 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -879,7 +879,7 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc -!include OvmfPkg/NetworkComponents.dsc.inc +!include OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc OvmfPkg/VirtioNetDxe/VirtioNet.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index bac41d7309..aca292ce83 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -893,7 +893,7 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc -!include OvmfPkg/NetworkComponents.dsc.inc +!include OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc OvmfPkg/VirtioNetDxe/VirtioNet.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 9b6257a691..3f6465d8d6 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -961,7 +961,7 @@ # Network Support # !include NetworkPkg/NetworkComponents.dsc.inc -!include OvmfPkg/NetworkComponents.dsc.inc +!include OvmfPkg/Include/Dsc/NetworkComponents.dsc.inc OvmfPkg/VirtioNetDxe/VirtioNet.inf From 0bacc31308afcc36afdb4ca91281cfcf73ead644 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 9 Dec 2022 21:03:48 +0800 Subject: [PATCH 0361/1529] mv OvmfPkg: move fdf include snippets to Include/Fdf Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/AmdSev/AmdSevX64.fdf | 6 +++--- OvmfPkg/Bhyve/BhyveX64.fdf | 6 +++--- OvmfPkg/CloudHv/CloudHvX64.fdf | 2 +- OvmfPkg/{ => Include/Fdf}/FvmainCompactScratchEnd.fdf.inc | 0 OvmfPkg/{ => Include/Fdf}/OvmfPkgDefines.fdf.inc | 0 OvmfPkg/{ => Include/Fdf}/VarStore.fdf.inc | 0 OvmfPkg/{ => Include/Fdf}/XenElfHeader.fdf.inc | 0 OvmfPkg/Include/WorkArea.h | 2 +- OvmfPkg/IntelTdx/IntelTdxX64.fdf | 8 ++++---- OvmfPkg/Microvm/MicrovmX64.fdf | 6 +++--- OvmfPkg/OvmfPkgIa32.fdf | 8 ++++---- OvmfPkg/OvmfPkgIa32X64.fdf | 8 ++++---- OvmfPkg/OvmfPkgX64.fdf | 8 ++++---- OvmfPkg/OvmfXen.fdf | 8 ++++---- OvmfPkg/Sec/AmdSev.c | 2 +- OvmfPkg/Sec/AmdSev.h | 2 +- 16 files changed, 33 insertions(+), 33 deletions(-) rename OvmfPkg/{ => Include/Fdf}/FvmainCompactScratchEnd.fdf.inc (100%) rename OvmfPkg/{ => Include/Fdf}/OvmfPkgDefines.fdf.inc (100%) rename OvmfPkg/{ => Include/Fdf}/VarStore.fdf.inc (100%) rename OvmfPkg/{ => Include/Fdf}/XenElfHeader.fdf.inc (100%) diff --git a/OvmfPkg/AmdSev/AmdSevX64.fdf b/OvmfPkg/AmdSev/AmdSevX64.fdf index 4658e1d30e..5fb3b5d276 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.fdf +++ b/OvmfPkg/AmdSev/AmdSevX64.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkg/OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include OvmfPkg/VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -351,7 +351,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include OvmfPkg/FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/Bhyve/BhyveX64.fdf b/OvmfPkg/Bhyve/BhyveX64.fdf index e8227f865f..153b3cfeba 100644 --- a/OvmfPkg/Bhyve/BhyveX64.fdf +++ b/OvmfPkg/Bhyve/BhyveX64.fdf @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -43,7 +43,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.BHYVE_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -368,7 +368,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/CloudHv/CloudHvX64.fdf b/OvmfPkg/CloudHv/CloudHvX64.fdf index a41a553693..0d13d4066d 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.fdf +++ b/OvmfPkg/CloudHv/CloudHvX64.fdf @@ -378,7 +378,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include OvmfPkg/FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/FvmainCompactScratchEnd.fdf.inc b/OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc similarity index 100% rename from OvmfPkg/FvmainCompactScratchEnd.fdf.inc rename to OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc diff --git a/OvmfPkg/OvmfPkgDefines.fdf.inc b/OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc similarity index 100% rename from OvmfPkg/OvmfPkgDefines.fdf.inc rename to OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc diff --git a/OvmfPkg/VarStore.fdf.inc b/OvmfPkg/Include/Fdf/VarStore.fdf.inc similarity index 100% rename from OvmfPkg/VarStore.fdf.inc rename to OvmfPkg/Include/Fdf/VarStore.fdf.inc diff --git a/OvmfPkg/XenElfHeader.fdf.inc b/OvmfPkg/Include/Fdf/XenElfHeader.fdf.inc similarity index 100% rename from OvmfPkg/XenElfHeader.fdf.inc rename to OvmfPkg/Include/Fdf/XenElfHeader.fdf.inc diff --git a/OvmfPkg/Include/WorkArea.h b/OvmfPkg/Include/WorkArea.h index bf56fc4a6f..6c3702b716 100644 --- a/OvmfPkg/Include/WorkArea.h +++ b/OvmfPkg/Include/WorkArea.h @@ -21,7 +21,7 @@ // sizeof (CONFIDENTIAL_COMPUTING_WORK_AREA_HEADER) // PcdOvmfConfidentialComputingWorkAreaHeader defined in: // OvmfPkg/OvmfPkg.dec -// OvmfPkg/OvmfPkgDefines.fdf.inc +// OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc typedef struct _CONFIDENTIAL_COMPUTING_WORK_AREA_HEADER { UINT8 GuestType; UINT8 Reserved1[3]; diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.fdf b/OvmfPkg/IntelTdx/IntelTdxX64.fdf index 6923eb8831..e79ad3e102 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.fdf +++ b/OvmfPkg/IntelTdx/IntelTdxX64.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkg/OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include OvmfPkg/VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -43,7 +43,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include OvmfPkg/VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -332,7 +332,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -# !include OvmfPkg/FvmainCompactScratchEnd.fdf.inc +# !include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/Microvm/MicrovmX64.fdf b/OvmfPkg/Microvm/MicrovmX64.fdf index 380ba3a368..b83fd1e6e4 100644 --- a/OvmfPkg/Microvm/MicrovmX64.fdf +++ b/OvmfPkg/Microvm/MicrovmX64.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkg/OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include OvmfPkg/VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -335,7 +335,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include OvmfPkg/FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/OvmfPkgIa32.fdf b/OvmfPkg/OvmfPkgIa32.fdf index 7023ade8ce..72bce02cab 100644 --- a/OvmfPkg/OvmfPkgIa32.fdf +++ b/OvmfPkg/OvmfPkgIa32.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -43,7 +43,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -410,7 +410,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf index 80de4fa2c0..576c985ae0 100644 --- a/OvmfPkg/OvmfPkgIa32X64.fdf +++ b/OvmfPkg/OvmfPkgIa32X64.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -43,7 +43,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -413,7 +413,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf index c0f5a1ef3c..c4aa882431 100644 --- a/OvmfPkg/OvmfPkgX64.fdf +++ b/OvmfPkg/OvmfPkgX64.fdf @@ -11,7 +11,7 @@ ################################################################################ [Defines] -!include OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # Build the variable store and the firmware code as one unified flash device @@ -24,7 +24,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT @@ -43,7 +43,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -440,7 +440,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/OvmfXen.fdf b/OvmfPkg/OvmfXen.fdf index 029b7dadcb..8be69338c7 100644 --- a/OvmfPkg/OvmfXen.fdf +++ b/OvmfPkg/OvmfXen.fdf @@ -12,7 +12,7 @@ ################################################################################ [Defines] -!include OvmfPkgDefines.fdf.inc +!include OvmfPkg/Include/Fdf/OvmfPkgDefines.fdf.inc # # This will allow the flash device image to be recognize as an ELF, with first @@ -32,7 +32,7 @@ NumBlocks = $(FW_BLOCKS) 0x00000000|0x00040000 !endif -!include XenElfHeader.fdf.inc +!include OvmfPkg/Include/Fdf/XenElfHeader.fdf.inc !if ($(FD_SIZE_IN_KB) == 1024) || ($(FD_SIZE_IN_KB) == 2048) 0x0000e000|0x00001000 @@ -86,7 +86,7 @@ ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) -!include VarStore.fdf.inc +!include OvmfPkg/Include/Fdf/VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) @@ -388,7 +388,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { } } -!include FvmainCompactScratchEnd.fdf.inc +!include OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc ################################################################################ diff --git a/OvmfPkg/Sec/AmdSev.c b/OvmfPkg/Sec/AmdSev.c index 6af38aaf46..520b125132 100644 --- a/OvmfPkg/Sec/AmdSev.c +++ b/OvmfPkg/Sec/AmdSev.c @@ -284,7 +284,7 @@ SevEsIsEnabled ( /** Validate System RAM used for decompressing the PEI and DXE firmware volumes when SEV-SNP is active. The PCDs SecValidatedStart and SecValidatedEnd are - set in OvmfPkg/FvmainCompactScratchEnd.fdf.inc. + set in OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc. **/ VOID diff --git a/OvmfPkg/Sec/AmdSev.h b/OvmfPkg/Sec/AmdSev.h index dffd2ceb96..f75877096e 100644 --- a/OvmfPkg/Sec/AmdSev.h +++ b/OvmfPkg/Sec/AmdSev.h @@ -71,7 +71,7 @@ SevEsIsEnabled ( /** Validate System RAM used for decompressing the PEI and DXE firmware volumes when SEV-SNP is active. The PCDs SecValidatedStart and SecValidatedEnd are - set in OvmfPkg/FvmainCompactScratchEnd.fdf.inc. + set in OvmfPkg/Include/Fdf/FvmainCompactScratchEnd.fdf.inc. **/ VOID From ce17853b04338ff283a782fffacc983fcbf3b56f Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Mon, 28 Nov 2022 13:40:20 +0800 Subject: [PATCH 0362/1529] OvmfPkg/SmbiosPlatformDxe: use PcdFirmware* Instead of using hard-coded strings ("0.0.0" for BiosVersion etc) which is mostly useless read the PCDs (PcdFirmwareVendor, PcdFirmwareVersionString and PcdFirmwareReleaseDateString) and build the string table dynamuically at runtime. Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c | 115 +++++++++++------- .../SmbiosPlatformDxe/SmbiosPlatformDxe.inf | 6 + .../XenSmbiosPlatformDxe.inf | 9 +- 3 files changed, 85 insertions(+), 45 deletions(-) diff --git a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c index 94249d3ff1..dc1e6aed63 100644 --- a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c +++ b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c @@ -9,57 +9,43 @@ **/ #include // SMBIOS_TABLE_TYPE0 +#include +#include #include // ASSERT_EFI_ERROR() +#include +#include #include // gBS #include // EFI_SMBIOS_PROTOCOL #include "SmbiosPlatformDxe.h" -#define TYPE0_STRINGS \ - "EFI Development Kit II / OVMF\0" /* Vendor */ \ - "0.0.0\0" /* BiosVersion */ \ - "02/06/2015\0" /* BiosReleaseDate */ -// -// Type definition and contents of the default Type 0 SMBIOS table. -// -#pragma pack(1) -typedef struct { - SMBIOS_TABLE_TYPE0 Base; - UINT8 Strings[sizeof (TYPE0_STRINGS)]; -} OVMF_TYPE0; -#pragma pack() - -STATIC CONST OVMF_TYPE0 mOvmfDefaultType0 = { +STATIC CONST SMBIOS_TABLE_TYPE0 mOvmfDefaultType0 = { + // SMBIOS_STRUCTURE Hdr { - // SMBIOS_STRUCTURE Hdr - { - EFI_SMBIOS_TYPE_BIOS_INFORMATION, // UINT8 Type - sizeof (SMBIOS_TABLE_TYPE0), // UINT8 Length - }, - 1, // SMBIOS_TABLE_STRING Vendor - 2, // SMBIOS_TABLE_STRING BiosVersion - 0xE800, // UINT16 BiosSegment - 3, // SMBIOS_TABLE_STRING BiosReleaseDate - 0, // UINT8 BiosSize - { // MISC_BIOS_CHARACTERISTICS BiosCharacteristics - 0, // Reserved :2 - 0, // Unknown :1 - 1, // BiosCharacteristicsNotSupported :1 - // Remaining BiosCharacteristics bits left unset :60 - }, - { // BIOSCharacteristicsExtensionBytes[2] - 0, // BiosReserved - 0x1C // SystemReserved = VirtualMachineSupported | - // UefiSpecificationSupported | - // TargetContentDistributionEnabled - }, - 0, // UINT8 SystemBiosMajorRelease - 0, // UINT8 SystemBiosMinorRelease - 0xFF, // UINT8 EmbeddedControllerFirmwareMajorRelease - 0xFF // UINT8 EmbeddedControllerFirmwareMinorRelease + EFI_SMBIOS_TYPE_BIOS_INFORMATION, // UINT8 Type + sizeof (SMBIOS_TABLE_TYPE0), // UINT8 Length }, - // Text strings (unformatted area) - TYPE0_STRINGS + 1, // SMBIOS_TABLE_STRING Vendor + 2, // SMBIOS_TABLE_STRING BiosVersion + 0xE800, // UINT16 BiosSegment + 3, // SMBIOS_TABLE_STRING BiosReleaseDate + 0, // UINT8 BiosSize + { // MISC_BIOS_CHARACTERISTICS BiosCharacteristics + 0, // Reserved :2 + 0, // Unknown :1 + 1, // BiosCharacteristicsNotSupported :1 + // Remaining BiosCharacteristics bits left unset :60 + }, + { // BIOSCharacteristicsExtensionBytes[2] + 0, // BiosReserved + 0x1C // SystemReserved = VirtualMachineSupported | + // UefiSpecificationSupported | + // TargetContentDistributionEnabled + }, + 0, // UINT8 SystemBiosMajorRelease + 0, // UINT8 SystemBiosMinorRelease + 0xFF, // UINT8 EmbeddedControllerFirmwareMajorRelease + 0xFF // UINT8 EmbeddedControllerFirmwareMinorRelease }; /** @@ -153,14 +139,55 @@ InstallAllStructures ( // // Add OVMF default Type 0 (BIOS Information) table // + CHAR16 *VendStr, *VersStr, *DateStr; + UINTN VendLen, VersLen, DateLen; + CHAR8 *Type0; + + VendStr = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareVendor); + VendLen = StrLen (VendStr); + if (VendLen < 3) { + VendStr = L"unknown"; + VendLen = StrLen (VendStr); + } + + VersStr = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareVersionString); + VersLen = StrLen (VersStr); + if (VersLen < 3) { + VersStr = L"unknown"; + VersLen = StrLen (VersStr); + } + + DateStr = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareReleaseDateString); + DateLen = StrLen (DateStr); + if (DateLen < 3) { + DateStr = L"unknown"; + DateLen = StrLen (DateStr); + } + + DEBUG ((DEBUG_INFO, "FirmwareVendor: \"%s\" (%d chars)\n", VendStr, VendLen)); + DEBUG ((DEBUG_INFO, "FirmwareVersionString: \"%s\" (%d chars)\n", VersStr, VersLen)); + DEBUG ((DEBUG_INFO, "FirmwareReleaseDateString: \"%s\" (%d chars)\n", DateStr, DateLen)); + + Type0 = AllocateZeroPool (sizeof (mOvmfDefaultType0) + VendLen + VersLen + DateLen + 4); + if (Type0 == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + CopyMem (Type0, &mOvmfDefaultType0, sizeof (mOvmfDefaultType0)); + UnicodeStrToAsciiStrS (VendStr, Type0 + sizeof (mOvmfDefaultType0), VendLen + 1); + UnicodeStrToAsciiStrS (VersStr, Type0 + sizeof (mOvmfDefaultType0) + VendLen + 1, VersLen + 1); + UnicodeStrToAsciiStrS (DateStr, Type0 + sizeof (mOvmfDefaultType0) + VendLen + VersLen + 2, DateLen + 1); + SmbiosHandle = SMBIOS_HANDLE_PI_RESERVED; Status = Smbios->Add ( Smbios, NULL, &SmbiosHandle, - (EFI_SMBIOS_TABLE_HEADER *)&mOvmfDefaultType0 + (EFI_SMBIOS_TABLE_HEADER *)Type0 ); ASSERT_EFI_ERROR (Status); + + FreePool (Type0); } return EFI_SUCCESS; diff --git a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf index 0066bbc922..52689c96e5 100644 --- a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf +++ b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf @@ -32,9 +32,12 @@ [Packages] MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec OvmfPkg/OvmfPkg.dec [LibraryClasses] + BaseLib + BaseMemoryLib DebugLib MemoryAllocationLib PcdLib @@ -45,6 +48,9 @@ [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVendor + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareReleaseDateString [Protocols] gEfiSmbiosProtocolGuid # PROTOCOL ALWAYS_CONSUMED diff --git a/OvmfPkg/SmbiosPlatformDxe/XenSmbiosPlatformDxe.inf b/OvmfPkg/SmbiosPlatformDxe/XenSmbiosPlatformDxe.inf index 7f4588e33d..e646c88741 100644 --- a/OvmfPkg/SmbiosPlatformDxe/XenSmbiosPlatformDxe.inf +++ b/OvmfPkg/SmbiosPlatformDxe/XenSmbiosPlatformDxe.inf @@ -38,19 +38,26 @@ [Packages] MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec [Packages.IA32, Packages.X64] OvmfPkg/OvmfPkg.dec [LibraryClasses] + BaseLib + BaseMemoryLib DebugLib UefiBootServicesTableLib UefiDriverEntryPoint [LibraryClasses.IA32, LibraryClasses.X64] - BaseLib HobLib +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVendor + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareReleaseDateString + [Protocols] gEfiSmbiosProtocolGuid # PROTOCOL ALWAYS_CONSUMED From 3a6a693d84d7667441b34e72f8e071edb223c1d4 Mon Sep 17 00:00:00 2001 From: "Albecki, Mateusz" Date: Tue, 18 Oct 2022 23:54:19 +0800 Subject: [PATCH 0363/1529] MdeModulePkg/Ata: Fix command status reporting Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4016 AtaAtapiPassThru driver was reporting recovery status on failed command packets which led to incorrect flows in upper layers and to SCT tests fails. This commit will change the logic to report command status. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Mateusz Albecki Reviewed-by: Hao A Wu --- .../Bus/Ata/AtaAtapiPassThru/AhciMode.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c index a240be940d..06c4a3e052 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c @@ -949,6 +949,7 @@ AhciPioTransfer ( EFI_AHCI_COMMAND_LIST CmdList; UINT32 PrdCount; UINT32 Retry; + EFI_STATUS RecoveryStatus; if (Read) { Flag = EfiPciIoOperationBusMasterWrite; @@ -1026,8 +1027,8 @@ AhciPioTransfer ( if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "PIO command failed at retry %d\n", Retry)); - Status = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (Status)) { + RecoveryStatus = AhciRecoverPortError (PciIo, Port); + if (EFI_ERROR (RecoveryStatus)) { break; } } else { @@ -1122,6 +1123,7 @@ AhciDmaTransfer ( EFI_PCI_IO_PROTOCOL *PciIo; EFI_TPL OldTpl; UINT32 Retry; + EFI_STATUS RecoveryStatus; Map = NULL; PciIo = Instance->PciIo; @@ -1220,8 +1222,8 @@ AhciDmaTransfer ( Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "DMA command failed at retry: %d\n", Retry)); - Status = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (Status)) { + RecoveryStatus = AhciRecoverPortError (PciIo, Port); + if (EFI_ERROR (RecoveryStatus)) { break; } } else { @@ -1261,14 +1263,14 @@ AhciDmaTransfer ( Status = AhciCheckFisReceived (PciIo, Port, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "DMA command failed at retry: %d\n", Task->RetryTimes)); - Status = AhciRecoverPortError (PciIo, Port); + RecoveryStatus = AhciRecoverPortError (PciIo, Port); // // If recovery passed mark the Task as not started and change the status // to EFI_NOT_READY. This will make the higher level call this function again // and on next call the command will be re-issued due to IsStart being FALSE. // This also makes the next condition decrement the RetryTimes. // - if (Status == EFI_SUCCESS) { + if (RecoveryStatus == EFI_SUCCESS) { Task->IsStart = FALSE; Status = EFI_NOT_READY; } @@ -1375,6 +1377,7 @@ AhciNonDataTransfer ( EFI_AHCI_COMMAND_FIS CFis; EFI_AHCI_COMMAND_LIST CmdList; UINT32 Retry; + EFI_STATUS RecoveryStatus; // // Package read needed @@ -1415,8 +1418,8 @@ AhciNonDataTransfer ( Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "Non data transfer failed at retry %d\n", Retry)); - Status = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (Status)) { + RecoveryStatus = AhciRecoverPortError (PciIo, Port); + if (EFI_ERROR (RecoveryStatus)) { break; } } else { From c4c94042d2bcada78239753809a65d1679f2062c Mon Sep 17 00:00:00 2001 From: "Chevron Li (WH)" Date: Wed, 7 Dec 2022 19:08:39 +0800 Subject: [PATCH 0364/1529] MdeModulePkg: SdMmcPciHcDxe: Fix issue that SD1.0 cards can't be recognized SD1.0 cards don't support CMD8 and CMD6 CMD8 result can be used to distinguish the card is SD1.0 or not. CMD8 result can be used to decide following CMD6 is sent or skip. Cc: Hao A Wu Cc: Ray Ni Cc: Jian J Wang Cc: Liming Gao Signed-off-by: Chevron Li Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c index f5a3607e47..8bf452e9d0 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c @@ -1074,6 +1074,7 @@ SdGetTargetBusMode ( @param[in] Slot The slot number of the SD card to send the command to. @param[in] Rca The relative device address to be assigned. @param[in] S18A The boolean to show if it's a UHS-I SD card. + @param[in] SdVersion1 The boolean to show if it's a Version 1 SD card. @retval EFI_SUCCESS The operation is done correctly. @retval Others The operation fails. @@ -1085,7 +1086,8 @@ SdCardSetBusMode ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, IN UINT16 Rca, - IN BOOLEAN S18A + IN BOOLEAN S18A, + IN BOOLEAN SdVersion1 ) { EFI_STATUS Status; @@ -1095,6 +1097,8 @@ SdCardSetBusMode ( SD_MMC_HC_PRIVATE_DATA *Private; SD_MMC_BUS_SETTINGS BusMode; + ZeroMem (SwitchResp, 64 * sizeof (UINT8)); + Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru); Capability = &Private->Capability[Slot]; @@ -1117,10 +1121,13 @@ SdCardSetBusMode ( // // Get the supported bus speed from SWITCH cmd return data group #1. + // SdVersion1 don't support the SWITCH cmd // - Status = SdCardSwitch (PassThru, Slot, 0xFF, 0xF, SdDriverStrengthIgnore, 0xF, FALSE, SwitchResp); - if (EFI_ERROR (Status)) { - return Status; + if (!SdVersion1) { + Status = SdCardSwitch (PassThru, Slot, 0xFF, 0xF, SdDriverStrengthIgnore, 0xF, FALSE, SwitchResp); + if (EFI_ERROR (Status)) { + return Status; + } } SdGetTargetBusMode (Private, Slot, SwitchResp, S18A, &BusMode); @@ -1141,9 +1148,14 @@ SdCardSetBusMode ( } } - Status = SdCardSwitch (PassThru, Slot, BusMode.BusTiming, 0xF, BusMode.DriverStrength.Sd, 0xF, TRUE, SwitchResp); - if (EFI_ERROR (Status)) { - return Status; + // + // SdVersion1 don't support the SWITCH cmd + // + if (!SdVersion1) { + Status = SdCardSwitch (PassThru, Slot, BusMode.BusTiming, 0xF, BusMode.DriverStrength.Sd, 0xF, TRUE, SwitchResp); + if (EFI_ERROR (Status)) { + return Status; + } } Status = SdMmcSetDriverStrength (Private->PciIo, Slot, BusMode.DriverStrength.Sd); @@ -1214,8 +1226,10 @@ SdCardIdentification ( UINT8 HostCtrl2; UINTN Retry; BOOLEAN ForceVoltage33; + BOOLEAN SdVersion1; ForceVoltage33 = FALSE; + SdVersion1 = FALSE; PciIo = Private->PciIo; PassThru = &Private->PassThru; @@ -1231,12 +1245,12 @@ SdCardIdentification ( } // - // 2. Send Cmd8 to the device + // 2. Send Cmd8 to the device, the command will fail for SdVersion1 // Status = SdCardVoltageCheck (PassThru, Slot, 0x1, 0xFF); if (EFI_ERROR (Status)) { + SdVersion1 = TRUE; DEBUG ((DEBUG_INFO, "SdCardIdentification: Executing Cmd8 fails with %r\n", Status)); - return Status; } // @@ -1426,7 +1440,7 @@ SdCardIdentification ( DEBUG ((DEBUG_INFO, "SdCardIdentification: Found a SD device at slot [%d]\n", Slot)); Private->Slot[Slot].CardType = SdCardType; - Status = SdCardSetBusMode (PciIo, PassThru, Slot, Rca, ((Ocr & BIT24) != 0)); + Status = SdCardSetBusMode (PciIo, PassThru, Slot, Rca, ((Ocr & BIT24) != 0), SdVersion1); return Status; From 861b5cf57b9f0c1cbe3e1de7d1f53f7c646a0ffd Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Tue, 6 Sep 2022 10:28:59 +0200 Subject: [PATCH 0365/1529] DynamicTablesPkg: Remove duplicated words In an effort to clean the documentation of the above package, remove duplicated words. Cc: Sami Mujawar Cc: Alexei Fedorov Signed-off-by: Pierre Gondois Reviewed-by: Sami Mujawar --- DynamicTablesPkg/Include/Library/HwInfoParserLib.h | 2 +- .../Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c | 2 +- .../Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortGenerator.c | 2 +- DynamicTablesPkg/Library/Common/AmlLib/AmlNodeDefines.h | 2 +- DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.c | 2 +- DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.h | 2 +- DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c | 2 +- DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParser.c | 2 +- .../Library/FdtHwInfoParserLib/Gic/ArmGicDispatcher.c | 2 +- .../Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/DynamicTablesPkg/Include/Library/HwInfoParserLib.h b/DynamicTablesPkg/Include/Library/HwInfoParserLib.h index 05c21aeac0..9710f74661 100644 --- a/DynamicTablesPkg/Include/Library/HwInfoParserLib.h +++ b/DynamicTablesPkg/Include/Library/HwInfoParserLib.h @@ -83,7 +83,7 @@ HwInfoParse ( ); /** Cleanup any internal state and resources that were allocated - by the the HwInfoParser. + by the HwInfoParser. @param [in] ParserHandle A handle to the parser instance. diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c index 18c8b8d245..b990686d40 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c @@ -587,7 +587,7 @@ BuildSsdtCmn600TableEx ( return Status; } - // Setup the table list early so that that appropriate cleanup + // Setup the table list early so that appropriate cleanup // can be done in case of failure. *Table = TableList; diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortGenerator.c index 39cfbad959..b850320eed 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtSerialPortLibArm/SsdtSerialPortGenerator.c @@ -239,7 +239,7 @@ BuildSsdtSerialPortTableEx ( return Status; } - // Setup the table list early so that that appropriate cleanup + // Setup the table list early so that appropriate cleanup // can be done in case of failure. *Table = TableList; diff --git a/DynamicTablesPkg/Library/Common/AmlLib/AmlNodeDefines.h b/DynamicTablesPkg/Library/Common/AmlLib/AmlNodeDefines.h index 8ceb20ff41..d199f06cc5 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/AmlNodeDefines.h +++ b/DynamicTablesPkg/Library/Common/AmlLib/AmlNodeDefines.h @@ -34,7 +34,7 @@ typedef AML_NODE_HEADER *AML_NODE_HANDLE; /** AML root node. - The root node is unique and at the head of of tree. It is a fake node used + The root node is unique and at the head of tree. It is a fake node used to maintain the list of AML statements (stored as object nodes) which are at the first scope level. */ diff --git a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.c b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.c index 391c72bd32..8f460a9728 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.c @@ -27,7 +27,7 @@ of NameSegs that have less that 4 chars, like "DEV". "DEV" will be expanded as "DEV_". - An AML NameString is not NULL terminated and is is only composed of + An AML NameString is not NULL terminated and is only composed of 4 chars long NameSegs. @param [in] NameOpNode NameOp object node defining a variable. diff --git a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.h b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.h index 8bbf62bbcd..2b4c60d3ee 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.h +++ b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApiHelper.h @@ -19,7 +19,7 @@ of NameSegs that have less that 4 chars, like "DEV". "DEV" will be expanded as "DEV_". - An AML NameString is not NULL terminated and is is only composed of + An AML NameString is not NULL terminated and is only composed of 4 chars long NameSegs. @param [in] NameOpNode NameOp object node defining a variable. diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c index 7e67482f99..0b223379fa 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c @@ -1072,7 +1072,7 @@ AmlAddPrtEntry ( goto error_handler; } - // Append to the the list of _PRT entries. + // Append to the list of _PRT entries. Status = AmlVarListAddTail ( (AML_NODE_HANDLE)PrtEntryList, (AML_NODE_HANDLE)PackageNode diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParser.c index 35e34e765f..376de078bc 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParser.c @@ -168,7 +168,7 @@ HwInfoParse ( } /** Cleanup any internal state and resources that were allocated - by the the HwInfoParser. + by the HwInfoParser. @param [in] ParserHandle A handle to the parser instance. diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicDispatcher.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicDispatcher.c index 831f0d5b73..1f3af1f968 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicDispatcher.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicDispatcher.c @@ -130,7 +130,7 @@ ArmGicDispatcher ( Fdt = FdtParserHandle->Fdt; - // The "cpus" node resides at the the root of the DT. Fetch it. + // The "cpus" node resides at the root of the DT. Fetch it. CpusNode = fdt_path_offset (Fdt, "/cpus"); if (CpusNode < 0) { return EFI_NOT_FOUND; diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c index 0557e416b4..cfd032df4d 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c @@ -278,7 +278,7 @@ GetSerialConsoleNode ( return EFI_INVALID_PARAMETER; } - // The "chosen" node resides at the the root of the DT. Fetch it. + // The "chosen" node resides at the root of the DT. Fetch it. ChosenNode = fdt_path_offset (Fdt, "/chosen"); if (ChosenNode < 0) { return EFI_NOT_FOUND; From e3feaa5623c1a98c615f1c25a8e943b6dc22b99e Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Fri, 4 Nov 2022 10:04:47 -0600 Subject: [PATCH 0366/1529] MdePkg/IndustryStandard: add definitions for ACPI APMT This adds #defines and struct typedefs for the various node types in the ACPI Arm Performance Monitoring Unit (APMT) table. Signed-off-by: Jeff Brasen Reviewed-by: Zhichao Gao Reviewed-by: Liming Gao Reviewed-by: Sami Mujawar --- MdePkg/Include/IndustryStandard/Acpi64.h | 5 ++ .../ArmPerformanceMonitoringUnitTable.h | 69 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/ArmPerformanceMonitoringUnitTable.h diff --git a/MdePkg/Include/IndustryStandard/Acpi64.h b/MdePkg/Include/IndustryStandard/Acpi64.h index fe5ebfac2b..575ca0430c 100644 --- a/MdePkg/Include/IndustryStandard/Acpi64.h +++ b/MdePkg/Include/IndustryStandard/Acpi64.h @@ -2847,6 +2847,11 @@ typedef struct { /// #define EFI_ACPI_6_4_MULTIPLE_APIC_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('A', 'P', 'I', 'C') +/// +/// "APMT" Arm Performance Monitoring Unit Table +/// +#define EFI_ACPI_6_4_ARM_PERFORMANCE_MONITORING_UNIT_TABLE_SIGNATURE SIGNATURE_32('A', 'P', 'M', 'T') + /// /// "BERT" Boot Error Record Table /// diff --git a/MdePkg/Include/IndustryStandard/ArmPerformanceMonitoringUnitTable.h b/MdePkg/Include/IndustryStandard/ArmPerformanceMonitoringUnitTable.h new file mode 100644 index 0000000000..fe7084cffd --- /dev/null +++ b/MdePkg/Include/IndustryStandard/ArmPerformanceMonitoringUnitTable.h @@ -0,0 +1,69 @@ +/** @file + ACPI Arm Performance Monitoring Unit (APMT) table + as specified in ARM spec DEN0117 + + Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + Copyright (c) 2022, ARM Limited. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef ARM_PERFORMANCE_MONITORING_UNIT_TABLE_H_ +#define ARM_PERFORMANCE_MONITORING_UNIT_TABLE_H_ + +#include + +#pragma pack(1) + +/// +/// Arm Performance Monitoring Unit (APMT) tabl +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; +} EFI_ACPI_ARM_PERFORMANCE_MONITORING_UNIT_TABLE_HEADER; + +/// +/// APMT Revision (as defined in DEN0117.) +/// +#define EFI_ACPI_ARM_PERFORMANCE_MONITORING_UNIT_TABLE_REVISION 0x00 + +/// +/// Arm PMU Node Structure +/// + +// Node Flags +#define EFI_ACPI_APMT_DUAL_PAGE_EXTENSION_SUPPORTED BIT0 +#define EFI_ACPI_APMT_PROCESSOR_AFFINITY_TYPE_CONTAINER BIT1 +#define EFI_ACPI_APMT_PROCESSOR_AFFINITY_TYPE_PROCESSOR 0 // BIT 1 +#define EFI_ACPI_APMT_64BIT_SINGLE_COPY_ATOMICITY_SUPPORTED BIT2 + +// Interrupt Flags +#define EFI_ACPI_APMT_INTERRUPT_MODE_EDGE_TRIGGERED BIT0 +#define EFI_ACPI_APMT_INTERRUPT_MODE_LEVEL_TRIGGERED 0 // BIT 0 +#define EFI_ACPI_APMT_INTERRUPT_TYPE_WIRED 0 // BIT 1 + +// Node Type +#define EFI_ACPI_APMT_NODE_TYPE_MEMORY_CONTROLLER 0x00 +#define EFI_ACPI_APMT_NODE_TYPE_SMMU 0x01 +#define EFI_ACPI_APMT_NODE_TYPE_PCIE_ROOT_COMPLEX 0x02 +#define EFI_ACPI_APMT_NODE_TYPE_ACPI_DEVICE 0x03 +#define EFI_ACPI_APMT_NODE_TYPE_CPU_CACHE 0x04 + +typedef struct { + UINT16 Length; + UINT8 NodeFlags; + UINT8 NodeType; + UINT32 Identifier; + UINT64 NodeInstancePrimary; + UINT32 NodeInstanceSecondary; + UINT64 BaseAddress0; + UINT64 BaseAddress1; + UINT32 OverflowInterrupt; + UINT32 Reserved1; + UINT32 OverflowInterruptFlags; + UINT32 ProcessorAffinity; + UINT32 ImplementationId; +} EFI_ACPI_ARM_PERFORMANCE_MONITORING_UNIT_NODE; + +#pragma pack() + +#endif From 5e98631d6232825c745a798e1febc9facc3d090b Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Fri, 4 Nov 2022 10:04:48 -0600 Subject: [PATCH 0367/1529] ShellPkg/AcpiView: APMT Parser Add a new parser for the Arm Performance Monitoring Unit Table. The APMT table describes the properties of PMU support implemented by components in an Arm-based system. Signed-off-by: Jeff Brasen Reviewed-by: Zhichao Gao Reviewed-by: Sami Mujawar --- .../UefiShellAcpiViewCommandLib/AcpiParser.h | 21 ++++ .../Parsers/Apmt/ApmtParser.c | 106 ++++++++++++++++++ .../UefiShellAcpiViewCommandLib.c | 1 + .../UefiShellAcpiViewCommandLib.inf | 1 + .../UefiShellAcpiViewCommandLib.uni | 1 + 5 files changed, 130 insertions(+) create mode 100644 ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Apmt/ApmtParser.c diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h index db8c88f6df..6a1de4e12b 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h @@ -531,6 +531,27 @@ ParseAcpiAest ( IN UINT8 AcpiTableRevision ); +/** + This function parses the ACPI APMT table. + When trace is enabled this function parses the APMT table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiApmt ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ); + /** This function parses the ACPI BGRT table. When trace is enabled this function parses the BGRT table and diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Apmt/ApmtParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Apmt/ApmtParser.c new file mode 100644 index 0000000000..ad64adbb0a --- /dev/null +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Apmt/ApmtParser.c @@ -0,0 +1,106 @@ +/** @file + APMT table parser + + Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + Copyright (c) 2017 - 2018, ARM Limited. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.2 Specification - Errata A, September 2017 +**/ + +#include +#include +#include +#include "AcpiParser.h" +#include "AcpiTableParser.h" + +// Local variables +STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; +STATIC CONST UINT16 *NodeLength; + +/** + An ACPI_PARSER array describing the ACPI APMT Table. +**/ +STATIC CONST ACPI_PARSER ApmtParser[] = { + PARSE_ACPI_HEADER (&AcpiHdrInfo) +}; + +/** + An ACPI_PARSER array describing the ACPI Arm PMU Node. +**/ +STATIC CONST ACPI_PARSER ArmPmuNodeParser[] = { + { L"Length", 2, 0, L"0x%x", NULL, (VOID **)&NodeLength, NULL, NULL }, + { L"Node flags", 1, 2, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Node type", 1, 3, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Identifier", 4, 4, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Node Instance primary", 8, 8, L"0x%lx", NULL, NULL, NULL, NULL }, + { L"Node Instance secondary", 4, 16, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Base address 0", 8, 20, L"0x%lx", NULL, NULL, NULL, NULL }, + { L"Base address 1", 8, 28, L"0x%lx", NULL, NULL, NULL, NULL }, + { L"Overflow interrupt", 4, 36, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Reserved1", 4, 40, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Overflow interrupt flags", 4, 44, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Processor affinity", 4, 48, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Implementation ID", 4, 52, L"0x%x", NULL, NULL, NULL, NULL } +}; + +/** + This function parses the ACPI APMT table. + When trace is enabled this function parses the APMT table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiApmt ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ) +{ + UINT32 Offset; + + if (!Trace) { + return; + } + + ParseAcpi ( + Trace, + 0, + "APMT", + Ptr, + AcpiTableLength, + PARSER_PARAMS (ApmtParser) + ); + Offset = sizeof (EFI_ACPI_DESCRIPTION_HEADER); + + while (Offset < AcpiTableLength) { + ParseAcpi ( + Trace, + 2, + "Arm PMU node", + Ptr + Offset, + (AcpiTableLength - Offset), + PARSER_PARAMS (ArmPmuNodeParser) + ); + if (NodeLength == NULL) { + Print ( + L"ERROR: Insufficient remaining table buffer length to read the " \ + L"Node structure. Length = %d.\n", + (AcpiTableLength - Offset) + ); + IncrementErrorCount (); + break; + } + + Offset += *NodeLength; + } +} diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c index 09bdddb56e..53f06fc757 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c @@ -48,6 +48,7 @@ STATIC CONST ACPI_TABLE_PARSER ParserList[] = { { EFI_ACPI_6_3_ARM_ERROR_SOURCE_TABLE_SIGNATURE, ParseAcpiAest }, + { EFI_ACPI_6_4_ARM_PERFORMANCE_MONITORING_UNIT_TABLE_SIGNATURE, ParseAcpiApmt }, { EFI_ACPI_6_2_BOOT_GRAPHICS_RESOURCE_TABLE_SIGNATURE, ParseAcpiBgrt }, { EFI_ACPI_6_2_DEBUG_PORT_2_TABLE_SIGNATURE, ParseAcpiDbg2 }, { EFI_ACPI_6_2_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE, diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf index 63fc5a1281..b03ec1a31b 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf @@ -28,6 +28,7 @@ AcpiViewConfig.c AcpiViewConfig.h Parsers/Aest/AestParser.c + Parsers/Apmt/ApmtParser.c Parsers/Bgrt/BgrtParser.c Parsers/Dbg2/Dbg2Parser.c Parsers/Dsdt/DsdtParser.c diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.uni b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.uni index 393110e0ee..e4a9dd5b40 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.uni +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.uni @@ -80,6 +80,7 @@ " Extra A. Particular types:\r\n" " AEST - Arm Error Source Table\r\n" " APIC - Multiple APIC Description Table (MADT)\r\n" +" APMT - Arm Performance Monitoring Unit Table\r\n" " BGRT - Boot Graphics Resource Table\r\n" " DBG2 - Debug Port Table 2\r\n" " DSDT - Differentiated System Description Table\r\n" From 34b1d4393d7aeeaf7f81902a2e45080647a58180 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 9 Dec 2022 07:53:21 -0800 Subject: [PATCH 0368/1529] ShellPkg/Shell: Do not set end device path if already end Update Shell Protocol EfiShellGetMapFromDevicePath() to not set the end if the device path if it is already an end of entire device path. This removes a write operation that can cause failures if the Device Path Protocol is mapped to read-only memory. In general Device Path Protocols should not be modified unless the API explicitly states that the device path is modified. Cc: Ard Biesheuvel Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Zhichao Gao --- ShellPkg/Application/Shell/ShellProtocol.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ShellPkg/Application/Shell/ShellProtocol.c b/ShellPkg/Application/Shell/ShellProtocol.c index 509eb60e40..e6d20ab164 100644 --- a/ShellPkg/Application/Shell/ShellProtocol.c +++ b/ShellPkg/Application/Shell/ShellProtocol.c @@ -294,7 +294,13 @@ EfiShellGetMapFromDevicePath ( *DevicePath = NextDevicePathNode (*DevicePath); } - SetDevicePathEndNode (*DevicePath); + // + // Do not call SetDevicePathEndNode() if the device path node is already the + // end of an entire device path. + // + if (!IsDevicePathEnd (*DevicePath)) { + SetDevicePathEndNode (*DevicePath); + } } /* From 651f1b7bde5a435c000e11f5e5fbf2044ea24a65 Mon Sep 17 00:00:00 2001 From: Anthony PERARD Date: Fri, 16 Sep 2022 08:30:55 -0700 Subject: [PATCH 0369/1529] Maintainers.txt: Change Anthony's github id Signed-off-by: Anthony PERARD Reviewed-by: Michael D Kinney --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index 7e98083685..6a92922258 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -537,7 +537,7 @@ F: OvmfPkg/XenIoPvhDxe/ F: OvmfPkg/XenPlatformPei/ F: OvmfPkg/XenPvBlkDxe/ F: OvmfPkg/XenResetVector/ -R: Anthony Perard [sheep] +R: Anthony Perard [tperard] R: Julien Grall [jgrall] PcAtChipsetPkg From ab6c9e46807a91b9c4209ac1e36f33a5d51db70d Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Mon, 12 Dec 2022 15:30:22 +0800 Subject: [PATCH 0370/1529] MdePkg/BaseCpuLib: Remove assembly for CpuFlushTlb For different compilers, both IA32 and X64 can use Ia32/CpuFlushTlbGcc.c, which is C code (no inline assembly code). To simplify, remove other assemly file for CpuFlushTlb, and rename Ia32/CpuFlushTlbGcc.c to X86CpuFlushTlb.c. Reviewed-by: Michael D Kinney Cc: Liming Gao Signed-off-by: Ray Ni Signed-off-by: Zhiguang Liu --- MdePkg/Library/BaseCpuLib/BaseCpuLib.inf | 10 ++---- MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.c | 25 --------------- .../Library/BaseCpuLib/Ia32/CpuFlushTlb.nasm | 31 ------------------ .../Library/BaseCpuLib/X64/CpuFlushTlb.nasm | 32 ------------------- .../CpuFlushTlbGcc.c => X86CpuFlushTlb.c} | 4 +-- 5 files changed, 5 insertions(+), 97 deletions(-) delete mode 100644 MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.c delete mode 100644 MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.nasm delete mode 100644 MdePkg/Library/BaseCpuLib/X64/CpuFlushTlb.nasm rename MdePkg/Library/BaseCpuLib/{Ia32/CpuFlushTlbGcc.c => X86CpuFlushTlb.c} (75%) diff --git a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf index 6b230f6e6d..5b18343c59 100644 --- a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf +++ b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf @@ -4,7 +4,7 @@ # CPU Library implemented using ASM functions for IA32, X64, ARM, AARCH64, # PAL CALLs for IPF, and empty functions for EBC. # -# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
@@ -31,16 +31,12 @@ [Sources.IA32] Ia32/CpuSleep.c | MSFT - Ia32/CpuFlushTlb.c | MSFT - Ia32/CpuSleep.nasm| INTEL - Ia32/CpuFlushTlb.nasm| INTEL - Ia32/CpuSleepGcc.c | GCC - Ia32/CpuFlushTlbGcc.c | GCC + X86CpuFlushTlb.c [Sources.X64] - X64/CpuFlushTlb.nasm + X86CpuFlushTlb.c X64/CpuSleep.nasm diff --git a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.c b/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.c deleted file mode 100644 index 549f4eb8a0..0000000000 --- a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.c +++ /dev/null @@ -1,25 +0,0 @@ -/** @file - CpuFlushTlb function. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -/** - Flushes all the Translation Lookaside Buffers(TLB) entries in a CPU. - - Flushes all the Translation Lookaside Buffers(TLB) entries in a CPU. - -**/ -VOID -EFIAPI -CpuFlushTlb ( - VOID - ) -{ - _asm { - mov eax, cr3 - mov cr3, eax - } -} diff --git a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.nasm b/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.nasm deleted file mode 100644 index bc3b68e3f2..0000000000 --- a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlb.nasm +++ /dev/null @@ -1,31 +0,0 @@ -;------------------------------------------------------------------------------ ; -; Copyright (c) 2006, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; CpuFlushTlb.Asm -; -; Abstract: -; -; CpuFlushTlb function -; -; Notes: -; -;------------------------------------------------------------------------------ - - SECTION .text - -;------------------------------------------------------------------------------ -; VOID -; EFIAPI -; CpuFlushTlb ( -; VOID -; ); -;------------------------------------------------------------------------------ -global ASM_PFX(CpuFlushTlb) -ASM_PFX(CpuFlushTlb): - mov eax, cr3 - mov cr3, eax ; moving to CR3 flushes TLB - ret - diff --git a/MdePkg/Library/BaseCpuLib/X64/CpuFlushTlb.nasm b/MdePkg/Library/BaseCpuLib/X64/CpuFlushTlb.nasm deleted file mode 100644 index 8ddf7a2864..0000000000 --- a/MdePkg/Library/BaseCpuLib/X64/CpuFlushTlb.nasm +++ /dev/null @@ -1,32 +0,0 @@ -;------------------------------------------------------------------------------ ; -; Copyright (c) 2006, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; CpuFlushTlb.Asm -; -; Abstract: -; -; CpuFlushTlb function -; -; Notes: -; -;------------------------------------------------------------------------------ - - DEFAULT REL - SECTION .text - -;------------------------------------------------------------------------------ -; VOID -; EFIAPI -; CpuFlushTlb ( -; VOID -; ); -;------------------------------------------------------------------------------ -global ASM_PFX(CpuFlushTlb) -ASM_PFX(CpuFlushTlb): - mov rax, cr3 - mov cr3, rax - ret - diff --git a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlbGcc.c b/MdePkg/Library/BaseCpuLib/X86CpuFlushTlb.c similarity index 75% rename from MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlbGcc.c rename to MdePkg/Library/BaseCpuLib/X86CpuFlushTlb.c index ee44f2ea6e..17a351d054 100644 --- a/MdePkg/Library/BaseCpuLib/Ia32/CpuFlushTlbGcc.c +++ b/MdePkg/Library/BaseCpuLib/X86CpuFlushTlb.c @@ -1,7 +1,7 @@ /** @file - CpuFlushTlb function for Ia32/X64 GCC. + CpuFlushTlb function for Ia32/X64. - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent From 99b035b3e7f94bc6f431d54d77936a210d3eeb4d Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Tue, 6 Dec 2022 13:25:43 +0800 Subject: [PATCH 0371/1529] UnitTestFrameworkPkg: Modify APIs in UnitTestPersistenceLib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4183 UnitTestPersistenceLib now consumes private struct definition. Modify APIs in UnitTestPersistenceLib to make it easy to become a public library. Reviewed-by: Michael D Kinney Reviewed-by: Michael Kubacki Cc: Sean Brogan Reviewed-by: Ray Ni Signed-off-by: Zhiguang Liu --- .../Include/Library/UnitTestPersistenceLib.h | 14 +++++++---- .../Library/UnitTestLib/UnitTestLib.c | 6 +++-- .../UnitTestPersistenceLibNull.c | 11 ++++++--- .../UnitTestPersistenceLibSimpleFileSystem.c | 23 ++++++++++++------- 4 files changed, 36 insertions(+), 18 deletions(-) diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h index be29e079ec..5543b79a0d 100644 --- a/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h +++ b/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h @@ -4,7 +4,7 @@ (eg. a reboot-based test). Copyright (c) Microsoft Corporation.
- Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -12,7 +12,7 @@ #ifndef _UNIT_TEST_PERSISTENCE_LIB_H_ #define _UNIT_TEST_PERSISTENCE_LIB_H_ -#include +#include #define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 @@ -40,6 +40,7 @@ DoesCacheExist ( @param[in] FrameworkHandle A pointer to the framework that is being persisted. @param[in] SaveData A pointer to the buffer containing the serialized framework internal state. + @param[in] SaveStateSize The size of SaveData in bytes. @retval EFI_SUCCESS Data is persisted and the test can be safely quit. @retval Others Data is not persisted and test cannot be resumed upon exit. @@ -49,7 +50,8 @@ EFI_STATUS EFIAPI SaveUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData + IN VOID *SaveData, + IN UINTN SaveStateSize ); /** @@ -57,8 +59,9 @@ SaveUnitTestCache ( Will allocate a buffer to hold the loaded data. @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address + @param[out] SaveData A pointer pointer that will be updated with the address of the loaded data buffer. + @param[out] SaveStateSize Return the size of SaveData in bytes. @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated with a pointer to the buffer. @@ -70,7 +73,8 @@ EFI_STATUS EFIAPI LoadUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData + OUT VOID **SaveData, + OUT UINTN *SaveStateSize ); #endif diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 64d5880783..5b442ed122 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -2,6 +2,7 @@ Implement UnitTestLib Copyright (c) Microsoft Corporation. + Copyright (c) 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -210,6 +211,7 @@ InitUnitTestFramework ( EFI_STATUS Status; UNIT_TEST_FRAMEWORK_HANDLE NewFrameworkHandle; UNIT_TEST_FRAMEWORK *NewFramework; + UINTN SaveStateSize; Status = EFI_SUCCESS; NewFramework = NULL; @@ -267,7 +269,7 @@ InitUnitTestFramework ( // If there is a persisted context, load it now. // if (DoesCacheExist (NewFrameworkHandle)) { - Status = LoadUnitTestCache (NewFrameworkHandle, (UNIT_TEST_SAVE_HEADER **)(&NewFramework->SavedState)); + Status = LoadUnitTestCache (NewFrameworkHandle, (VOID **)(&NewFramework->SavedState), &SaveStateSize); if (EFI_ERROR (Status)) { // // Don't actually report it as an error, but emit a warning. @@ -852,7 +854,7 @@ SaveFrameworkState ( // // All that should be left to do is save it using the associated persistence lib. // - Status = SaveUnitTestCache (FrameworkHandle, Header); + Status = SaveUnitTestCache (FrameworkHandle, Header, Header->SaveStateSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status)); Status = EFI_DEVICE_ERROR; diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index e28327652e..abb24cff98 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -2,6 +2,7 @@ This is an instance of the Unit Test Persistence Lib that does nothing. Copyright (c) Microsoft Corporation.
+ Copyright (c) 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -35,6 +36,7 @@ DoesCacheExist ( @param[in] FrameworkHandle A pointer to the framework that is being persisted. @param[in] SaveData A pointer to the buffer containing the serialized framework internal state. + @param[in] SaveStateSize The size of SaveData in bytes. @retval EFI_SUCCESS Data is persisted and the test can be safely quit. @retval Others Data is not persisted and test cannot be resumed upon exit. @@ -44,7 +46,8 @@ EFI_STATUS EFIAPI SaveUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData + IN VOID *SaveData, + IN UINTN SaveStateSize ) { return EFI_UNSUPPORTED; @@ -55,8 +58,9 @@ SaveUnitTestCache ( Will allocate a buffer to hold the loaded data. @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address + @param[out] SaveData A pointer pointer that will be updated with the address of the loaded data buffer. + @param[out] SaveStateSize Return the size of SaveData in bytes. @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated with a pointer to the buffer. @@ -68,7 +72,8 @@ EFI_STATUS EFIAPI LoadUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData + OUT VOID **SaveData, + OUT UINTN *SaveStateSize ) { return EFI_UNSUPPORTED; diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c index ed4a7d1615..d7a62145da 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c @@ -4,6 +4,7 @@ version of the internal test state in case the test needs to quit and restore. Copyright (c) Microsoft Corporation.
+ Copyright (c) 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -16,6 +17,7 @@ #include #include #include +#include #define CACHE_FILE_SUFFIX L"_Cache.dat" @@ -213,6 +215,7 @@ DoesCacheExist ( @param[in] FrameworkHandle A pointer to the framework that is being persisted. @param[in] SaveData A pointer to the buffer containing the serialized framework internal state. + @param[in] SaveStateSize The size of SaveData in bytes. @retval EFI_SUCCESS Data is persisted and the test can be safely quit. @retval Others Data is not persisted and test cannot be resumed upon exit. @@ -222,7 +225,8 @@ EFI_STATUS EFIAPI SaveUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData + IN VOID *SaveData, + IN UINTN SaveStateSize ) { EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; @@ -280,7 +284,7 @@ SaveUnitTestCache ( // // Write the data to the file. // - WriteCount = SaveData->SaveStateSize; + WriteCount = SaveStateSize; DEBUG ((DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount)); Status = ShellWriteFile ( FileHandle, @@ -288,7 +292,7 @@ SaveUnitTestCache ( SaveData ); - if (EFI_ERROR (Status) || (WriteCount != SaveData->SaveStateSize)) { + if (EFI_ERROR (Status) || (WriteCount != SaveStateSize)) { DEBUG ((DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status)); } else { DEBUG ((DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__)); @@ -312,8 +316,9 @@ SaveUnitTestCache ( Will allocate a buffer to hold the loaded data. @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address + @param[out] SaveData A pointer pointer that will be updated with the address of the loaded data buffer. + @param[out] SaveStateSize Return the size of SaveData in bytes. @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated with a pointer to the buffer. @@ -325,7 +330,8 @@ EFI_STATUS EFIAPI LoadUnitTestCache ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData + OUT VOID **SaveData, + OUT UINTN *SaveStateSize ) { EFI_STATUS Status; @@ -334,7 +340,7 @@ LoadUnitTestCache ( BOOLEAN IsFileOpened; UINT64 LargeFileSize; UINTN FileSize; - UNIT_TEST_SAVE_HEADER *Buffer; + VOID *Buffer; IsFileOpened = FALSE; Buffer = NULL; @@ -380,8 +386,9 @@ LoadUnitTestCache ( // // Now that we know the size, let's allocated a buffer to hold the contents. // - FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. - Buffer = AllocatePool (FileSize); + FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. + *SaveStateSize = FileSize; + Buffer = AllocatePool (FileSize); if (Buffer == NULL) { DEBUG ((DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status)); Status = EFI_OUT_OF_RESOURCES; From facf0aab71f0a78d775325eef98981d01074d679 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Wed, 7 Dec 2022 09:36:47 +0800 Subject: [PATCH 0372/1529] MdePkg/UnitTestHostBaseLib: Remove HOST_APPLICATION limitation Remove HOST_APPLICATION limitation for UnitTestHostBaseLib, so that this library can be used as BaseLib by Emulator. Also, add some missing files Reviewed-by: Michael D Kinney Cc: Liming Gao Signed-off-by: Ray Ni Signed-off-by: Zhiguang Liu --- MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf b/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf index 09a610c31c..12a5cdcc0a 100644 --- a/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf +++ b/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf @@ -1,7 +1,8 @@ ## @file -# Base Library implementation for use with host based unit tests. +# Base Library implementation for use with host based unit tests, and +# can also be used by emulation platforms such as EmulatorPkg. # -# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2022, Intel Corporation. All rights reserved.
# Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
# Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
@@ -18,7 +19,7 @@ FILE_GUID = 9555A0D3-09BA-46C4-A51A-45198E3C765E MODULE_TYPE = BASE VERSION_STRING = 1.1 - LIBRARY_CLASS = BaseLib|HOST_APPLICATION + LIBRARY_CLASS = BaseLib LIBRARY_CLASS = UnitTestHostBaseLib|HOST_APPLICATION # @@ -128,6 +129,7 @@ X86RdRand.c X86SpeculationBarrier.c X86UnitTestHost.c + IntelTdxNull.c [Sources.X64] X64/LongJump.nasm @@ -168,6 +170,7 @@ X64/RdRand.nasm ChkStkGcc.c | GCC X86UnitTestHost.c + IntelTdxNull.c [Sources.EBC] Ebc/CpuBreakpoint.c From 658a9172b7af082490cf8b41edc17148f20148c1 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Tue, 15 Nov 2022 11:01:06 -0700 Subject: [PATCH 0373/1529] DynamicTablesPkg: SSDT _LPI revision is incorrect _LPI Revision should be 0 per the ACPI 6.5 specification. "The revision number of the _LPI object. Current revision is 0." Signed-off-by: Jeff Brasen Reviewed-by: Pierre Gondois Reviewed-by: Sami Mujawar --- .../Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c index d06c7615fb..91199c4af2 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c @@ -482,7 +482,7 @@ GenerateLpiStates ( } // We do not support the LevelId field for now, let it to 0. - Status = AmlCreateLpiNode (AslName, 1, 0, ScopeNode, &LpiNode); + Status = AmlCreateLpiNode (AslName, 0, 0, ScopeNode, &LpiNode); if (EFI_ERROR (Status)) { ASSERT (0); return Status; From 14a1c57ebe406f76678e1952ec5891325289c823 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:09:58 +0100 Subject: [PATCH 0374/1529] OvmfPkg/PlatformPei: AmdSev: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in AmdSevInitialize() and AmdSevEsInitialize() functions. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/AmdSev.c | 14 +++++++------- OvmfPkg/PlatformPei/Platform.c | 2 +- OvmfPkg/PlatformPei/Platform.h | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index e1b9fd9b7f..c23fae7fca 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -201,7 +201,7 @@ GhcbRegister ( STATIC VOID AmdSevEsInitialize ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { UINT8 *GhcbBase; @@ -228,7 +228,7 @@ AmdSevEsInitialize ( // Since the pages must survive across the UEFI to OS transition // make them reserved. // - GhcbPageCount = mPlatformInfoHob.PcdCpuMaxLogicalProcessorNumber * 2; + GhcbPageCount = PlatformInfoHob->PcdCpuMaxLogicalProcessorNumber * 2; GhcbBase = AllocateReservedPages (GhcbPageCount); ASSERT (GhcbBase != NULL); @@ -266,7 +266,7 @@ AmdSevEsInitialize ( // Allocate #VC recursion backup pages. The number of backup pages needed is // one less than the maximum VC count. // - GhcbBackupPageCount = mPlatformInfoHob.PcdCpuMaxLogicalProcessorNumber * (VMGEXIT_MAXIMUM_VC_COUNT - 1); + GhcbBackupPageCount = PlatformInfoHob->PcdCpuMaxLogicalProcessorNumber * (VMGEXIT_MAXIMUM_VC_COUNT - 1); GhcbBackupBase = AllocatePages (GhcbBackupPageCount); ASSERT (GhcbBackupBase != NULL); @@ -320,7 +320,7 @@ AmdSevEsInitialize ( **/ VOID AmdSevInitialize ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { UINT64 EncryptionMask; @@ -367,7 +367,7 @@ AmdSevInitialize ( // until after re-encryption, in order to prevent an information leak to the // hypervisor. // - if (mPlatformInfoHob.SmmSmramRequire && (mPlatformInfoHob.BootMode != BOOT_ON_S3_RESUME)) { + if (PlatformInfoHob->SmmSmramRequire && (PlatformInfoHob->BootMode != BOOT_ON_S3_RESUME)) { RETURN_STATUS LocateMapStatus; UINTN MapPagesBase; UINTN MapPagesCount; @@ -378,7 +378,7 @@ AmdSevInitialize ( ); ASSERT_RETURN_ERROR (LocateMapStatus); - if (mPlatformInfoHob.Q35SmramAtDefaultSmbase) { + if (PlatformInfoHob->Q35SmramAtDefaultSmbase) { // // The initial SMRAM Save State Map has been covered as part of a larger // reserved memory allocation in InitializeRamRegions(). @@ -400,7 +400,7 @@ AmdSevInitialize ( // // Check and perform SEV-ES initialization if required. // - AmdSevEsInitialize (); + AmdSevEsInitialize (PlatformInfoHob); // // Set the Confidential computing attr PCD to communicate which SEV diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index b1f8140d60..f2c1e2b213 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -379,7 +379,7 @@ InitializePlatform ( } InstallClearCacheCallback (); - AmdSevInitialize (); + AmdSevInitialize (&mPlatformInfoHob); if (mPlatformInfoHob.HostBridgeDevId == 0xffff) { MiscInitializationForMicrovm (&mPlatformInfoHob); } else { diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index 29b51b2deb..f245025fb4 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -82,7 +82,7 @@ InstallClearCacheCallback ( VOID AmdSevInitialize ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); /** From 6c40062826115510731c05ca1291b89a2509e6a7 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:09:59 +0100 Subject: [PATCH 0375/1529] OvmfPkg/PlatformPei: PeiFv: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in PeiFvInitialization() function. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/Fv.c | 6 +++--- OvmfPkg/PlatformPei/Platform.c | 2 +- OvmfPkg/PlatformPei/Platform.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/PlatformPei/Fv.c b/OvmfPkg/PlatformPei/Fv.c index e40c592220..fcf14c88fa 100644 --- a/OvmfPkg/PlatformPei/Fv.c +++ b/OvmfPkg/PlatformPei/Fv.c @@ -22,7 +22,7 @@ **/ EFI_STATUS PeiFvInitialization ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { BOOLEAN SecureS3Needed; @@ -37,7 +37,7 @@ PeiFvInitialization ( BuildMemoryAllocationHob ( PcdGet32 (PcdOvmfPeiMemFvBase), PcdGet32 (PcdOvmfPeiMemFvSize), - mPlatformInfoHob.S3Supported ? EfiACPIMemoryNVS : EfiBootServicesData + PlatformInfoHob->S3Supported ? EfiACPIMemoryNVS : EfiBootServicesData ); // @@ -45,7 +45,7 @@ PeiFvInitialization ( // BuildFvHob (PcdGet32 (PcdOvmfDxeMemFvBase), PcdGet32 (PcdOvmfDxeMemFvSize)); - SecureS3Needed = mPlatformInfoHob.S3Supported && mPlatformInfoHob.SmmSmramRequire; + SecureS3Needed = PlatformInfoHob->S3Supported && PlatformInfoHob->SmmSmramRequire; // // Create a memory allocation HOB for the DXE FV. diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index f2c1e2b213..9646a1fa63 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -372,7 +372,7 @@ InitializePlatform ( ReserveEmuVariableNvStore (); } - PeiFvInitialization (); + PeiFvInitialization (&mPlatformInfoHob); MemTypeInfoInitialization (); MemMapInitialization (&mPlatformInfoHob); NoexecDxeInitialization (); diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index f245025fb4..b13f45ecdb 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -62,7 +62,7 @@ MaxCpuCountInitialization ( EFI_STATUS PeiFvInitialization ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); VOID From b9d0403c032f7f65150f88a0338460712db8fdd7 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:00 +0100 Subject: [PATCH 0376/1529] OvmfPkg/PlatformPei Q35 SMM helpers: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in Q35TsegMbytesInitialization() and Q35SmramAtDefaultSmbaseInitialization() ) functions. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/MemDetect.c | 20 ++++++++++---------- OvmfPkg/PlatformPei/Platform.c | 4 ++-- OvmfPkg/PlatformPei/Platform.h | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/OvmfPkg/PlatformPei/MemDetect.c b/OvmfPkg/PlatformPei/MemDetect.c index 2e47b13229..b9207107b4 100644 --- a/OvmfPkg/PlatformPei/MemDetect.c +++ b/OvmfPkg/PlatformPei/MemDetect.c @@ -41,13 +41,13 @@ Module Name: VOID Q35TsegMbytesInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { UINT16 ExtendedTsegMbytes; RETURN_STATUS PcdStatus; - ASSERT (mPlatformInfoHob.HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID); + ASSERT (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID); // // Check if QEMU offers an extended TSEG. @@ -68,7 +68,7 @@ Q35TsegMbytesInitialization ( PciWrite16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB), MCH_EXT_TSEG_MB_QUERY); ExtendedTsegMbytes = PciRead16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB)); if (ExtendedTsegMbytes == MCH_EXT_TSEG_MB_QUERY) { - mPlatformInfoHob.Q35TsegMbytes = PcdGet16 (PcdQ35TsegMbytes); + PlatformInfoHob->Q35TsegMbytes = PcdGet16 (PcdQ35TsegMbytes); return; } @@ -80,19 +80,19 @@ Q35TsegMbytesInitialization ( )); PcdStatus = PcdSet16S (PcdQ35TsegMbytes, ExtendedTsegMbytes); ASSERT_RETURN_ERROR (PcdStatus); - mPlatformInfoHob.Q35TsegMbytes = ExtendedTsegMbytes; + PlatformInfoHob->Q35TsegMbytes = ExtendedTsegMbytes; } VOID Q35SmramAtDefaultSmbaseInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { RETURN_STATUS PcdStatus; - ASSERT (mPlatformInfoHob.HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID); + ASSERT (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID); - mPlatformInfoHob.Q35SmramAtDefaultSmbase = FALSE; + PlatformInfoHob->Q35SmramAtDefaultSmbase = FALSE; if (FeaturePcdGet (PcdCsmEnable)) { DEBUG (( DEBUG_INFO, @@ -106,19 +106,19 @@ Q35SmramAtDefaultSmbaseInitialization ( CtlReg = DRAMC_REGISTER_Q35 (MCH_DEFAULT_SMBASE_CTL); PciWrite8 (CtlReg, MCH_DEFAULT_SMBASE_QUERY); CtlRegVal = PciRead8 (CtlReg); - mPlatformInfoHob.Q35SmramAtDefaultSmbase = (BOOLEAN)(CtlRegVal == + PlatformInfoHob->Q35SmramAtDefaultSmbase = (BOOLEAN)(CtlRegVal == MCH_DEFAULT_SMBASE_IN_RAM); DEBUG (( DEBUG_INFO, "%a: SMRAM at default SMBASE %a\n", __FUNCTION__, - mPlatformInfoHob.Q35SmramAtDefaultSmbase ? "found" : "not found" + PlatformInfoHob->Q35SmramAtDefaultSmbase ? "found" : "not found" )); } PcdStatus = PcdSetBoolS ( PcdQ35SmramAtDefaultSmbase, - mPlatformInfoHob.Q35SmramAtDefaultSmbase + PlatformInfoHob->Q35SmramAtDefaultSmbase ); ASSERT_RETURN_ERROR (PcdStatus); } diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 9646a1fa63..8b055fb451 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -357,8 +357,8 @@ InitializePlatform ( if (mPlatformInfoHob.SmmSmramRequire) { Q35BoardVerification (); - Q35TsegMbytesInitialization (); - Q35SmramAtDefaultSmbaseInitialization (); + Q35TsegMbytesInitialization (&mPlatformInfoHob); + Q35SmramAtDefaultSmbaseInitialization (&mPlatformInfoHob); } PublishPeiMemory (); diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index b13f45ecdb..7baa5e1d28 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -22,12 +22,12 @@ AddressWidthInitialization ( VOID Q35TsegMbytesInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); VOID Q35SmramAtDefaultSmbaseInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); EFI_STATUS From 53d00c6a1278bec78ee42647754e9b483d2ec904 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:01 +0100 Subject: [PATCH 0377/1529] OvmfPkg/PlatformPei: PeiMemory: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in PublishPeiMemory() and GetPeiMemoryCap() functions. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/MemDetect.c | 36 ++++++++++++++++----------------- OvmfPkg/PlatformPei/Platform.c | 2 +- OvmfPkg/PlatformPei/Platform.h | 2 +- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/OvmfPkg/PlatformPei/MemDetect.c b/OvmfPkg/PlatformPei/MemDetect.c index b9207107b4..3d8375320d 100644 --- a/OvmfPkg/PlatformPei/MemDetect.c +++ b/OvmfPkg/PlatformPei/MemDetect.c @@ -188,7 +188,7 @@ AddressWidthInitialization ( STATIC UINT32 GetPeiMemoryCap ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { BOOLEAN Page1GSupport; @@ -225,15 +225,15 @@ GetPeiMemoryCap ( } } - if (mPlatformInfoHob.PhysMemAddressWidth <= 39) { + if (PlatformInfoHob->PhysMemAddressWidth <= 39) { Pml4Entries = 1; - PdpEntries = 1 << (mPlatformInfoHob.PhysMemAddressWidth - 30); + PdpEntries = 1 << (PlatformInfoHob->PhysMemAddressWidth - 30); ASSERT (PdpEntries <= 0x200); } else { - if (mPlatformInfoHob.PhysMemAddressWidth > 48) { + if (PlatformInfoHob->PhysMemAddressWidth > 48) { Pml4Entries = 0x200; } else { - Pml4Entries = 1 << (mPlatformInfoHob.PhysMemAddressWidth - 39); + Pml4Entries = 1 << (PlatformInfoHob->PhysMemAddressWidth - 39); } ASSERT (Pml4Entries <= 0x200); @@ -260,7 +260,7 @@ GetPeiMemoryCap ( **/ EFI_STATUS PublishPeiMemory ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { EFI_STATUS Status; @@ -271,12 +271,12 @@ PublishPeiMemory ( UINT32 S3AcpiReservedMemoryBase; UINT32 S3AcpiReservedMemorySize; - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (&mPlatformInfoHob); - if (mPlatformInfoHob.SmmSmramRequire) { + LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + if (PlatformInfoHob->SmmSmramRequire) { // // TSEG is chipped from the end of low RAM // - LowerMemorySize -= mPlatformInfoHob.Q35TsegMbytes * SIZE_1MB; + LowerMemorySize -= PlatformInfoHob->Q35TsegMbytes * SIZE_1MB; } S3AcpiReservedMemoryBase = 0; @@ -287,27 +287,27 @@ PublishPeiMemory ( // downwards. Its size is primarily dictated by CpuMpPei. The formula below // is an approximation. // - if (mPlatformInfoHob.S3Supported) { + if (PlatformInfoHob->S3Supported) { S3AcpiReservedMemorySize = SIZE_512KB + - mPlatformInfoHob.PcdCpuMaxLogicalProcessorNumber * + PlatformInfoHob->PcdCpuMaxLogicalProcessorNumber * PcdGet32 (PcdCpuApStackSize); S3AcpiReservedMemoryBase = LowerMemorySize - S3AcpiReservedMemorySize; LowerMemorySize = S3AcpiReservedMemoryBase; } - mPlatformInfoHob.S3AcpiReservedMemoryBase = S3AcpiReservedMemoryBase; - mPlatformInfoHob.S3AcpiReservedMemorySize = S3AcpiReservedMemorySize; + PlatformInfoHob->S3AcpiReservedMemoryBase = S3AcpiReservedMemoryBase; + PlatformInfoHob->S3AcpiReservedMemorySize = S3AcpiReservedMemorySize; - if (mPlatformInfoHob.BootMode == BOOT_ON_S3_RESUME) { + if (PlatformInfoHob->BootMode == BOOT_ON_S3_RESUME) { MemoryBase = S3AcpiReservedMemoryBase; MemorySize = S3AcpiReservedMemorySize; } else { - PeiMemoryCap = GetPeiMemoryCap (); + PeiMemoryCap = GetPeiMemoryCap (PlatformInfoHob); DEBUG (( DEBUG_INFO, "%a: PhysMemAddressWidth=%d PeiMemoryCap=%u KB\n", __FUNCTION__, - mPlatformInfoHob.PhysMemAddressWidth, + PlatformInfoHob->PhysMemAddressWidth, PeiMemoryCap >> 10 )); @@ -321,7 +321,7 @@ PublishPeiMemory ( // allocation HOB, and other allocations served from the permanent PEI RAM // shouldn't overlap with that HOB. // - MemoryBase = mPlatformInfoHob.S3Supported && mPlatformInfoHob.SmmSmramRequire ? + MemoryBase = PlatformInfoHob->S3Supported && PlatformInfoHob->SmmSmramRequire ? PcdGet32 (PcdOvmfDecompressionScratchEnd) : PcdGet32 (PcdOvmfDxeMemFvBase) + PcdGet32 (PcdOvmfDxeMemFvSize); MemorySize = LowerMemorySize - MemoryBase; @@ -336,7 +336,7 @@ PublishPeiMemory ( // normal boot permanent PEI RAM. Regarding the S3 boot path, the S3 // permanent PEI RAM is located even higher. // - if (mPlatformInfoHob.SmmSmramRequire && mPlatformInfoHob.Q35SmramAtDefaultSmbase) { + if (PlatformInfoHob->SmmSmramRequire && PlatformInfoHob->Q35SmramAtDefaultSmbase) { ASSERT (SMM_DEFAULT_SMBASE + MCH_DEFAULT_SMBASE_SIZE <= MemoryBase); } diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 8b055fb451..4cd77fd5f8 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -361,7 +361,7 @@ InitializePlatform ( Q35SmramAtDefaultSmbaseInitialization (&mPlatformInfoHob); } - PublishPeiMemory (); + PublishPeiMemory (&mPlatformInfoHob); PlatformQemuUc32BaseInitialization (&mPlatformInfoHob); diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index 7baa5e1d28..d0c673c5a3 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -32,7 +32,7 @@ Q35SmramAtDefaultSmbaseInitialization ( EFI_STATUS PublishPeiMemory ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); VOID From 245850ef7987dd0a68b4151f9f5677e8053a8b93 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:02 +0100 Subject: [PATCH 0378/1529] OvmfPkg/PlatformPei: MemTypeInfo: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in MemTypeInfoInitialization() function. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/MemTypeInfo.c | 4 ++-- OvmfPkg/PlatformPei/Platform.c | 2 +- OvmfPkg/PlatformPei/Platform.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/PlatformPei/MemTypeInfo.c b/OvmfPkg/PlatformPei/MemTypeInfo.c index c8fcf17326..eb37febb31 100644 --- a/OvmfPkg/PlatformPei/MemTypeInfo.c +++ b/OvmfPkg/PlatformPei/MemTypeInfo.c @@ -203,12 +203,12 @@ STATIC CONST EFI_PEI_NOTIFY_DESCRIPTOR mReadOnlyVariable2Notify = { VOID MemTypeInfoInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { EFI_STATUS Status; - if (!mPlatformInfoHob.SmmSmramRequire) { + if (!PlatformInfoHob->SmmSmramRequire) { // // EFI_PEI_READ_ONLY_VARIABLE2_PPI will never be available; install // the default memory type information HOB right away. diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 4cd77fd5f8..85b47e7ed8 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -373,7 +373,7 @@ InitializePlatform ( } PeiFvInitialization (&mPlatformInfoHob); - MemTypeInfoInitialization (); + MemTypeInfoInitialization (&mPlatformInfoHob); MemMapInitialization (&mPlatformInfoHob); NoexecDxeInitialization (); } diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index d0c673c5a3..0c0558f062 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -67,7 +67,7 @@ PeiFvInitialization ( VOID MemTypeInfoInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); VOID From 5b616469307922c17ca7a0dadb8ff79e198abc35 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:03 +0100 Subject: [PATCH 0379/1529] OvmfPkg/PlatformPei: NoExec: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in NoexecDxeInitialization() function. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/Platform.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 85b47e7ed8..7f3a260926 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -75,16 +75,17 @@ MemMapInitialization ( ASSERT_RETURN_ERROR (PcdStatus); } +STATIC VOID NoexecDxeInitialization ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { RETURN_STATUS Status; - Status = PlatformNoexecDxeInitialization (&mPlatformInfoHob); + Status = PlatformNoexecDxeInitialization (PlatformInfoHob); if (!RETURN_ERROR (Status)) { - Status = PcdSetBoolS (PcdSetNxForStack, mPlatformInfoHob.PcdSetNxForStack); + Status = PcdSetBoolS (PcdSetNxForStack, PlatformInfoHob->PcdSetNxForStack); ASSERT_RETURN_ERROR (Status); } } @@ -375,7 +376,7 @@ InitializePlatform ( PeiFvInitialization (&mPlatformInfoHob); MemTypeInfoInitialization (&mPlatformInfoHob); MemMapInitialization (&mPlatformInfoHob); - NoexecDxeInitialization (); + NoexecDxeInitialization (&mPlatformInfoHob); } InstallClearCacheCallback (); From 5e9716209bcfdd985a66051f4fef6fe2cbf1bd0c Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:04 +0100 Subject: [PATCH 0380/1529] OvmfPkg/PlatformPei: Verification: stop using mPlatformInfoHob Stop using the mPlatformInfoHob global variable in S3Verification() and Q35BoardVerification() functions. Pass a pointer to the PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/Platform.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 7f3a260926..d8c4499804 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -231,13 +231,14 @@ ReserveEmuVariableNvStore ( ASSERT_RETURN_ERROR (PcdStatus); } +STATIC VOID S3Verification ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { #if defined (MDE_CPU_X64) - if (mPlatformInfoHob.SmmSmramRequire && mPlatformInfoHob.S3Supported) { + if (PlatformInfoHob->SmmSmramRequire && PlatformInfoHob->S3Supported) { DEBUG (( DEBUG_ERROR, "%a: S3Resume2Pei doesn't support X64 PEI + SMM yet.\n", @@ -260,12 +261,13 @@ S3Verification ( #endif } +STATIC VOID Q35BoardVerification ( - VOID + IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - if (mPlatformInfoHob.HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { + if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { return; } @@ -274,7 +276,7 @@ Q35BoardVerification ( "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; " "only DID=0x%04x (Q35) is supported\n", __FUNCTION__, - mPlatformInfoHob.HostBridgeDevId, + PlatformInfoHob->HostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); ASSERT (FALSE); @@ -345,7 +347,7 @@ InitializePlatform ( ASSERT_EFI_ERROR (Status); } - S3Verification (); + S3Verification (&mPlatformInfoHob); BootModeInitialization (&mPlatformInfoHob); // @@ -357,7 +359,7 @@ InitializePlatform ( MaxCpuCountInitialization (&mPlatformInfoHob); if (mPlatformInfoHob.SmmSmramRequire) { - Q35BoardVerification (); + Q35BoardVerification (&mPlatformInfoHob); Q35TsegMbytesInitialization (&mPlatformInfoHob); Q35SmramAtDefaultSmbaseInitialization (&mPlatformInfoHob); } From 2c3975121f3579524263189ca6fb4e519fdb213c Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:05 +0100 Subject: [PATCH 0381/1529] OvmfPkg/PlatformPei: remove mPlatformInfoHob Stop using the mPlatformInfoHob global variable. Let BuildPlatformInfoHob() allocate and return PlatformInfoHob instead. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/Platform.c | 71 ++++++++++++++++++---------------- OvmfPkg/PlatformPei/Platform.h | 4 +- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index d8c4499804..ebce2ba129 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -41,8 +41,6 @@ #include "Platform.h" -EFI_HOB_PLATFORM_INFO mPlatformInfoHob = { 0 }; - EFI_PEI_PPI_DESCRIPTOR mPpiBootMode[] = { { EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, @@ -305,12 +303,18 @@ MaxCpuCountInitialization ( /** * @brief Builds PlatformInfo Hob */ -VOID +EFI_HOB_PLATFORM_INFO * BuildPlatformInfoHob ( VOID ) { - BuildGuidDataHob (&gUefiOvmfPkgPlatformInfoGuid, &mPlatformInfoHob, sizeof (EFI_HOB_PLATFORM_INFO)); + EFI_HOB_PLATFORM_INFO PlatformInfoHob; + EFI_HOB_GUID_TYPE *GuidHob; + + ZeroMem (&PlatformInfoHob, sizeof PlatformInfoHob); + BuildGuidDataHob (&gUefiOvmfPkgPlatformInfoGuid, &PlatformInfoHob, sizeof (EFI_HOB_PLATFORM_INFO)); + GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid); + return (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob); } /** @@ -329,69 +333,70 @@ InitializePlatform ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; + EFI_HOB_PLATFORM_INFO *PlatformInfoHob; + EFI_STATUS Status; DEBUG ((DEBUG_INFO, "Platform PEIM Loaded\n")); + PlatformInfoHob = BuildPlatformInfoHob (); - mPlatformInfoHob.SmmSmramRequire = FeaturePcdGet (PcdSmmSmramRequire); - mPlatformInfoHob.SevEsIsEnabled = MemEncryptSevEsIsEnabled (); - mPlatformInfoHob.PcdPciMmio64Size = PcdGet64 (PcdPciMmio64Size); - mPlatformInfoHob.DefaultMaxCpuNumber = PcdGet32 (PcdCpuMaxLogicalProcessorNumber); + PlatformInfoHob->SmmSmramRequire = FeaturePcdGet (PcdSmmSmramRequire); + PlatformInfoHob->SevEsIsEnabled = MemEncryptSevEsIsEnabled (); + PlatformInfoHob->PcdPciMmio64Size = PcdGet64 (PcdPciMmio64Size); + PlatformInfoHob->DefaultMaxCpuNumber = PcdGet32 (PcdCpuMaxLogicalProcessorNumber); PlatformDebugDumpCmos (); if (QemuFwCfgS3Enabled ()) { DEBUG ((DEBUG_INFO, "S3 support was detected on QEMU\n")); - mPlatformInfoHob.S3Supported = TRUE; + PlatformInfoHob->S3Supported = TRUE; Status = PcdSetBoolS (PcdAcpiS3Enable, TRUE); ASSERT_EFI_ERROR (Status); } - S3Verification (&mPlatformInfoHob); - BootModeInitialization (&mPlatformInfoHob); + S3Verification (PlatformInfoHob); + BootModeInitialization (PlatformInfoHob); // // Query Host Bridge DID // - mPlatformInfoHob.HostBridgeDevId = PciRead16 (OVMF_HOSTBRIDGE_DID); - AddressWidthInitialization (&mPlatformInfoHob); + PlatformInfoHob->HostBridgeDevId = PciRead16 (OVMF_HOSTBRIDGE_DID); + AddressWidthInitialization (PlatformInfoHob); - MaxCpuCountInitialization (&mPlatformInfoHob); + MaxCpuCountInitialization (PlatformInfoHob); - if (mPlatformInfoHob.SmmSmramRequire) { - Q35BoardVerification (&mPlatformInfoHob); - Q35TsegMbytesInitialization (&mPlatformInfoHob); - Q35SmramAtDefaultSmbaseInitialization (&mPlatformInfoHob); + if (PlatformInfoHob->SmmSmramRequire) { + Q35BoardVerification (PlatformInfoHob); + Q35TsegMbytesInitialization (PlatformInfoHob); + Q35SmramAtDefaultSmbaseInitialization (PlatformInfoHob); } - PublishPeiMemory (&mPlatformInfoHob); + PublishPeiMemory (PlatformInfoHob); - PlatformQemuUc32BaseInitialization (&mPlatformInfoHob); + PlatformQemuUc32BaseInitialization (PlatformInfoHob); - InitializeRamRegions (&mPlatformInfoHob); + InitializeRamRegions (PlatformInfoHob); - if (mPlatformInfoHob.BootMode != BOOT_ON_S3_RESUME) { - if (!mPlatformInfoHob.SmmSmramRequire) { + if (PlatformInfoHob->BootMode != BOOT_ON_S3_RESUME) { + if (!PlatformInfoHob->SmmSmramRequire) { ReserveEmuVariableNvStore (); } - PeiFvInitialization (&mPlatformInfoHob); - MemTypeInfoInitialization (&mPlatformInfoHob); - MemMapInitialization (&mPlatformInfoHob); - NoexecDxeInitialization (&mPlatformInfoHob); + PeiFvInitialization (PlatformInfoHob); + MemTypeInfoInitialization (PlatformInfoHob); + MemMapInitialization (PlatformInfoHob); + NoexecDxeInitialization (PlatformInfoHob); } InstallClearCacheCallback (); - AmdSevInitialize (&mPlatformInfoHob); - if (mPlatformInfoHob.HostBridgeDevId == 0xffff) { - MiscInitializationForMicrovm (&mPlatformInfoHob); + AmdSevInitialize (PlatformInfoHob); + if (PlatformInfoHob->HostBridgeDevId == 0xffff) { + MiscInitializationForMicrovm (PlatformInfoHob); } else { - MiscInitialization (&mPlatformInfoHob); + MiscInitialization (PlatformInfoHob); } IntelTdxInitialize (); InstallFeatureControlCallback (); - BuildPlatformInfoHob (); return EFI_SUCCESS; } diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index 0c0558f062..86f603ff64 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -13,8 +13,6 @@ #include #include -extern EFI_HOB_PLATFORM_INFO mPlatformInfoHob; - VOID AddressWidthInitialization ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob @@ -98,7 +96,7 @@ IntelTdxInitialize ( /** * @brief Builds PlatformInfo Hob */ -VOID +EFI_HOB_PLATFORM_INFO * BuildPlatformInfoHob ( VOID ); From 07ed8bfe344f341f22456a987cdcb3a64dc31894 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:06 +0100 Subject: [PATCH 0382/1529] OvmfPkg/PlatformPei: remove mFeatureControlValue Use PlatformInfoHob->FeatureControlValue instead. OnMpServicesAvailable() will find PlatformInfoHob using GetFirstGuidHob() and pass a pointer to the WriteFeatureControl callback. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/Include/Library/PlatformInitLib.h | 2 ++ OvmfPkg/PlatformPei/FeatureControl.c | 44 ++++++++++++++++------- OvmfPkg/PlatformPei/Platform.c | 2 +- OvmfPkg/PlatformPei/Platform.h | 2 +- 4 files changed, 36 insertions(+), 14 deletions(-) diff --git a/OvmfPkg/Include/Library/PlatformInitLib.h b/OvmfPkg/Include/Library/PlatformInitLib.h index c5234bf26d..da7ed76041 100644 --- a/OvmfPkg/Include/Library/PlatformInitLib.h +++ b/OvmfPkg/Include/Library/PlatformInitLib.h @@ -48,6 +48,8 @@ typedef struct { UINT32 S3AcpiReservedMemoryBase; UINT32 S3AcpiReservedMemorySize; + + UINT64 FeatureControlValue; } EFI_HOB_PLATFORM_INFO; #pragma pack() diff --git a/OvmfPkg/PlatformPei/FeatureControl.c b/OvmfPkg/PlatformPei/FeatureControl.c index 5864ee0c21..d8a398cd55 100644 --- a/OvmfPkg/PlatformPei/FeatureControl.c +++ b/OvmfPkg/PlatformPei/FeatureControl.c @@ -8,6 +8,7 @@ **/ #include +#include #include #include #include @@ -16,11 +17,6 @@ #include "Platform.h" -// -// The value to be written to the Feature Control MSR, retrieved from fw_cfg. -// -STATIC UINT64 mFeatureControlValue; - /** Write the Feature Control MSR on an Application Processor or the Boot Processor. @@ -38,10 +34,22 @@ WriteFeatureControl ( IN OUT VOID *WorkSpace ) { + EFI_HOB_PLATFORM_INFO *PlatformInfoHob = WorkSpace; + if (TdIsEnabled ()) { - TdVmCall (TDVMCALL_WRMSR, (UINT64)MSR_IA32_FEATURE_CONTROL, mFeatureControlValue, 0, 0, 0); + TdVmCall ( + TDVMCALL_WRMSR, + (UINT64)MSR_IA32_FEATURE_CONTROL, + PlatformInfoHob->FeatureControlValue, + 0, + 0, + 0 + ); } else { - AsmWriteMsr64 (MSR_IA32_FEATURE_CONTROL, mFeatureControlValue); + AsmWriteMsr64 ( + MSR_IA32_FEATURE_CONTROL, + PlatformInfoHob->FeatureControlValue + ); } } @@ -67,6 +75,15 @@ OnMpServicesAvailable ( { EFI_PEI_MP_SERVICES_PPI *MpServices; EFI_STATUS Status; + EFI_HOB_PLATFORM_INFO *PlatformInfoHob; + EFI_HOB_GUID_TYPE *GuidHob; + + GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid); + if (GuidHob == NULL) { + return EFI_UNSUPPORTED; + } + + PlatformInfoHob = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob); DEBUG ((DEBUG_VERBOSE, "%a: %a\n", gEfiCallerBaseName, __FUNCTION__)); @@ -80,7 +97,7 @@ OnMpServicesAvailable ( WriteFeatureControl, // Procedure FALSE, // SingleThread 0, // TimeoutInMicroSeconds: inf. - NULL // ProcedureArgument + PlatformInfoHob // ProcedureArgument ); if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) { DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __FUNCTION__, Status)); @@ -90,7 +107,7 @@ OnMpServicesAvailable ( // // Now write the MSR on the BSP too. // - WriteFeatureControl (NULL); + WriteFeatureControl (PlatformInfoHob); return EFI_SUCCESS; } @@ -107,7 +124,7 @@ STATIC CONST EFI_PEI_NOTIFY_DESCRIPTOR mMpServicesNotify = { VOID InstallFeatureControlCallback ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { EFI_STATUS Status; @@ -119,7 +136,7 @@ InstallFeatureControlCallback ( &FwCfgItem, &FwCfgSize ); - if (EFI_ERROR (Status) || (FwCfgSize != sizeof mFeatureControlValue)) { + if (EFI_ERROR (Status) || (FwCfgSize != sizeof (PlatformInfoHob->FeatureControlValue))) { // // Nothing to do. // @@ -127,7 +144,10 @@ InstallFeatureControlCallback ( } QemuFwCfgSelectItem (FwCfgItem); - QemuFwCfgReadBytes (sizeof mFeatureControlValue, &mFeatureControlValue); + QemuFwCfgReadBytes ( + sizeof (PlatformInfoHob->FeatureControlValue), + &(PlatformInfoHob->FeatureControlValue) + ); Status = PeiServicesNotifyPpi (&mMpServicesNotify); if (EFI_ERROR (Status)) { diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index ebce2ba129..148240342b 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -396,7 +396,7 @@ InitializePlatform ( } IntelTdxInitialize (); - InstallFeatureControlCallback (); + InstallFeatureControlCallback (PlatformInfoHob); return EFI_SUCCESS; } diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h index 86f603ff64..1cf44844a7 100644 --- a/OvmfPkg/PlatformPei/Platform.h +++ b/OvmfPkg/PlatformPei/Platform.h @@ -70,7 +70,7 @@ MemTypeInfoInitialization ( VOID InstallFeatureControlCallback ( - VOID + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); VOID From a300cc69d59de243505c116a12a5ac91b4c9d727 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:07 +0100 Subject: [PATCH 0383/1529] OvmfPkg/DebugLibIoPort: use Rom version for PEI This variant does not use global variables. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/AmdSev/AmdSevX64.dsc | 4 ++-- OvmfPkg/Bhyve/BhyveX64.dsc | 4 ++-- .../PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf | 2 +- OvmfPkg/Microvm/MicrovmX64.dsc | 4 ++-- OvmfPkg/OvmfPkgIa32.dsc | 4 ++-- OvmfPkg/OvmfPkgIa32X64.dsc | 4 ++-- OvmfPkg/OvmfPkgX64.dsc | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index e0b04d6734..d51c913a08 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -244,7 +244,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -260,7 +260,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc index e3bb367b6b..befec670d4 100644 --- a/OvmfPkg/Bhyve/BhyveX64.dsc +++ b/OvmfPkg/Bhyve/BhyveX64.dsc @@ -265,7 +265,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -281,7 +281,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf diff --git a/OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf b/OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf index 8f721d249d..c89b1571ba 100644 --- a/OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf +++ b/OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf @@ -16,7 +16,7 @@ FILE_GUID = CEB0D9D3-328F-4C24-8C02-28FA1986AE1B MODULE_TYPE = BASE VERSION_STRING = 1.0 - LIBRARY_CLASS = DebugLib|SEC + LIBRARY_CLASS = DebugLib|SEC PEI_CORE PEIM CONSTRUCTOR = PlatformRomDebugLibIoPortConstructor # diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 93d4cf3da2..bcca3afbf6 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -292,7 +292,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -308,7 +308,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index f8250fa635..dcf46d207d 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -294,7 +294,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -310,7 +310,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index aca292ce83..bc0036eda0 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -300,7 +300,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf @@ -316,7 +316,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 3f6465d8d6..b2b88f48d1 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -318,7 +318,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf CcProbeLib|OvmfPkg/Library/CcProbeLib/SecPeiCcProbeLib.inf @@ -335,7 +335,7 @@ !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else - DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf + DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf From bde71f9986daaa47d2e39e785031c7bb3f0d5011 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:08 +0100 Subject: [PATCH 0384/1529] OvmfPkg/QemuFwCfgLib: rewrite fw_cfg probe Move the code to a new QemuFwCfgProbe() function. Use direct Io*() calls instead of indirect QemuFwCfg*() calls to make sure we don't get recursive calls. Also simplify CC guest detection. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c | 101 +++++++----------- .../Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf | 1 - 2 files changed, 41 insertions(+), 61 deletions(-) diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c index 7ab7027af1..a936fd1039 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c @@ -13,7 +13,6 @@ #include #include #include -#include #include #include "QemuFwCfgLibInternal.h" @@ -27,15 +26,16 @@ STATIC BOOLEAN mQemuFwCfgDmaSupported; @retval TRUE It is Tdx guest @retval FALSE It is not Tdx guest **/ +STATIC BOOLEAN -QemuFwCfgIsTdxGuest ( +QemuFwCfgIsCcGuest ( VOID ) { CONFIDENTIAL_COMPUTING_WORK_AREA_HEADER *CcWorkAreaHeader; CcWorkAreaHeader = (CONFIDENTIAL_COMPUTING_WORK_AREA_HEADER *)FixedPcdGet32 (PcdOvmfWorkAreaBase); - return (CcWorkAreaHeader != NULL && CcWorkAreaHeader->GuestType == CcGuestTypeIntelTdx); + return (CcWorkAreaHeader != NULL && CcWorkAreaHeader->GuestType != CcGuestTypeNonEncrypted); } /** @@ -57,62 +57,49 @@ QemuFwCfgIsAvailable ( return InternalQemuFwCfgIsAvailable (); } +STATIC +VOID +QemuFwCfgProbe ( + BOOLEAN *Supported, + BOOLEAN *DmaSupported + ) +{ + UINT32 Signature; + UINT32 Revision; + BOOLEAN CcGuest; + + // Use direct Io* calls for probing to avoid recursion. + IoWrite16 (FW_CFG_IO_SELECTOR, (UINT16)QemuFwCfgItemSignature); + IoReadFifo8 (FW_CFG_IO_DATA, sizeof Signature, &Signature); + IoWrite16 (FW_CFG_IO_SELECTOR, (UINT16)QemuFwCfgItemInterfaceVersion); + IoReadFifo8 (FW_CFG_IO_DATA, sizeof Revision, &Revision); + CcGuest = QemuFwCfgIsCcGuest (); + + *Supported = FALSE; + *DmaSupported = FALSE; + if ((Signature == SIGNATURE_32 ('Q', 'E', 'M', 'U')) && (Revision >= 1)) { + *Supported = TRUE; + if ((Revision & FW_CFG_F_DMA) && !CcGuest) { + *DmaSupported = TRUE; + } + } + + DEBUG (( + DEBUG_INFO, + "%a: Supported %d, DMA %d\n", + __func__, + *Supported, + *DmaSupported + )); +} + RETURN_STATUS EFIAPI QemuFwCfgInitialize ( VOID ) { - UINT32 Signature; - UINT32 Revision; - - // - // Enable the access routines while probing to see if it is supported. - // For probing we always use the IO Port (IoReadFifo8()) access method. - // - mQemuFwCfgSupported = TRUE; - mQemuFwCfgDmaSupported = FALSE; - - 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")); - mQemuFwCfgSupported = FALSE; - return RETURN_SUCCESS; - } - - if ((Revision & FW_CFG_F_DMA) == 0) { - DEBUG ((DEBUG_INFO, "QemuFwCfg interface (IO Port) is supported.\n")); - } else { - // - // If SEV is enabled then we do not support DMA operations in PEI phase. - // This is mainly because DMA in SEV guest requires using bounce buffer - // (which need to allocate dynamic memory and allocating a PAGE size'd - // buffer can be challenge in PEI phase) - // - if (MemEncryptSevIsEnabled ()) { - DEBUG ((DEBUG_INFO, "SEV: QemuFwCfg fallback to IO Port interface.\n")); - } else if (QemuFwCfgIsTdxGuest ()) { - // - // If TDX is enabled then we do not support DMA operations in PEI phase. - // This is mainly because DMA in TDX guest requires using bounce buffer - // (which need to allocate dynamic memory and allocating a PAGE size'd - // buffer can be challenge in PEI phase) - // - DEBUG ((DEBUG_INFO, "TDX: QemuFwCfg fallback to IO Port interface.\n")); - } else { - mQemuFwCfgDmaSupported = TRUE; - DEBUG ((DEBUG_INFO, "QemuFwCfg interface (DMA) is supported.\n")); - } - } - + QemuFwCfgProbe (&mQemuFwCfgSupported, &mQemuFwCfgDmaSupported); return RETURN_SUCCESS; } @@ -183,17 +170,11 @@ InternalQemuFwCfgDmaBytes ( return; } - // - // SEV does not support DMA operations in PEI stage, we should - // not have reached here. - // - ASSERT (!MemEncryptSevIsEnabled ()); - // // TDX does not support DMA operations in PEI stage, we should // not have reached here. // - ASSERT (!QemuFwCfgIsTdxGuest ()); + ASSERT (!QemuFwCfgIsCcGuest ()); Access.Control = SwapBytes32 (Control); Access.Length = SwapBytes32 (Size); diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf index 3910511880..1d7543a7d4 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf @@ -41,7 +41,6 @@ DebugLib IoLib MemoryAllocationLib - MemEncryptSevLib [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase From 5508ac77fb074ac3d96165e88426864f94112a16 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 2 Dec 2022 14:10:09 +0100 Subject: [PATCH 0385/1529] OvmfPkg/QemuFwCfgLib: remove mQemuFwCfgSupported + mQemuFwCfgDmaSupported Remove global variables, store the state in PlatformInfoHob instead. Probing for fw_cfg happens on first use, at library initialization time the Hob might not be present yet. Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Acked-by: Ard Biesheuvel --- OvmfPkg/Include/Library/PlatformInitLib.h | 4 ++ OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c | 44 ++++++++++++++++--- .../Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf | 4 ++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/OvmfPkg/Include/Library/PlatformInitLib.h b/OvmfPkg/Include/Library/PlatformInitLib.h index da7ed76041..bf6f90a576 100644 --- a/OvmfPkg/Include/Library/PlatformInitLib.h +++ b/OvmfPkg/Include/Library/PlatformInitLib.h @@ -50,6 +50,10 @@ typedef struct { UINT32 S3AcpiReservedMemorySize; UINT64 FeatureControlValue; + + BOOLEAN QemuFwCfgChecked; + BOOLEAN QemuFwCfgSupported; + BOOLEAN QemuFwCfgDmaSupported; } EFI_HOB_PLATFORM_INFO; #pragma pack() diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c index a936fd1039..da86a3c84c 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c @@ -9,17 +9,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include #include -#include #include +#include +#include +#include #include #include #include "QemuFwCfgLibInternal.h" -STATIC BOOLEAN mQemuFwCfgSupported = FALSE; -STATIC BOOLEAN mQemuFwCfgDmaSupported; - /** Check if it is Tdx guest @@ -93,13 +93,39 @@ QemuFwCfgProbe ( )); } +STATIC +EFI_HOB_PLATFORM_INFO * +QemuFwCfgGetPlatformInfo ( + VOID + ) +{ + EFI_HOB_PLATFORM_INFO *PlatformInfoHob; + EFI_HOB_GUID_TYPE *GuidHob; + + GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid); + if (GuidHob == NULL) { + return NULL; + } + + PlatformInfoHob = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob); + + if (!PlatformInfoHob->QemuFwCfgChecked) { + QemuFwCfgProbe ( + &PlatformInfoHob->QemuFwCfgSupported, + &PlatformInfoHob->QemuFwCfgDmaSupported + ); + PlatformInfoHob->QemuFwCfgChecked = TRUE; + } + + return PlatformInfoHob; +} + RETURN_STATUS EFIAPI QemuFwCfgInitialize ( VOID ) { - QemuFwCfgProbe (&mQemuFwCfgSupported, &mQemuFwCfgDmaSupported); return RETURN_SUCCESS; } @@ -117,7 +143,9 @@ InternalQemuFwCfgIsAvailable ( VOID ) { - return mQemuFwCfgSupported; + EFI_HOB_PLATFORM_INFO *PlatformInfoHob = QemuFwCfgGetPlatformInfo (); + + return PlatformInfoHob->QemuFwCfgSupported; } /** @@ -132,7 +160,9 @@ InternalQemuFwCfgDmaIsAvailable ( VOID ) { - return mQemuFwCfgDmaSupported; + EFI_HOB_PLATFORM_INFO *PlatformInfoHob = QemuFwCfgGetPlatformInfo (); + + return PlatformInfoHob->QemuFwCfgDmaSupported; } /** diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf index 1d7543a7d4..b1f548febc 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf @@ -39,8 +39,12 @@ BaseLib BaseMemoryLib DebugLib + HobLib IoLib MemoryAllocationLib +[Guids] + gUefiOvmfPkgPlatformInfoGuid + [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase From 18973d95f2c77bf5153a950c5acd8a5952e9a664 Mon Sep 17 00:00:00 2001 From: "devel@edk2.groups.io" Date: Wed, 30 Nov 2022 15:02:15 -0800 Subject: [PATCH 0386/1529] UnitTestFrameworkPkg/UnitTestLib: Print expected Status on ASSERT fail Update the UnitTestAssertStatusEqual error message to print out the expected value in addition to the seen value. Signed-off-by: Jeshua Smith Reviewed-by: Michael Kubacki Reviewed-by: Michael D Kinney --- UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c index dc05bbd438..0d8e36c938 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -290,7 +290,7 @@ UnitTestAssertStatusEqual ( { CHAR8 TempStr[MAX_STRING_SIZE]; - snprintf (TempStr, sizeof (TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); + snprintf (TempStr, sizeof (TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p expected:%p)", Description, (VOID *)Status, (VOID *)Expected); _assert_true ((Status == Expected), TempStr, FileName, (INT32)LineNumber); return (Status == Expected); From 755bbf20ac0295039f26ad8edfce8ed20145ab41 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 14 Dec 2022 15:14:17 +0800 Subject: [PATCH 0387/1529] OvmfPkg/TdTcg2Dxe: Fix incorrect protocol and structure version BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4184 According to the Uefi spec 2.10 Section 38.2.2. EFI_CC_MEASUREMENT_PROTOCOL.GetCapability, the minor version of StructureVersion and ProtocolVersion should be 0. Cc: Erdem Aktas [ruleof2] Cc: James Bottomley [jejb] Cc: Jiewen Yao [jyao1] Cc: Tom Lendacky [tlendacky] Cc: Arti Gupta Reported-by: Arti Gupta Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c index e9315ecda1..a6b4f8e0aa 100644 --- a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c +++ b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c @@ -2411,9 +2411,9 @@ DriverEntry ( mTdxDxeData.BsCap.Size = sizeof (EFI_CC_BOOT_SERVICE_CAPABILITY); mTdxDxeData.BsCap.ProtocolVersion.Major = 1; - mTdxDxeData.BsCap.ProtocolVersion.Minor = 1; + mTdxDxeData.BsCap.ProtocolVersion.Minor = 0; mTdxDxeData.BsCap.StructureVersion.Major = 1; - mTdxDxeData.BsCap.StructureVersion.Minor = 1; + mTdxDxeData.BsCap.StructureVersion.Minor = 0; // // Get supported PCR and current Active PCRs From 0404e126189fb9c542e3a57d96836d79a569ab50 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 14 Dec 2022 15:14:18 +0800 Subject: [PATCH 0388/1529] OvmfPkg/TdTcg2Dxe: Fix the mapping error between PCR index and MR index BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4179 According to UEFI Spec 2.10 it is supposed to return the mapping from PCR index to CC MR index: // // In the current version, we use the below mapping for TDX: // // TPM PCR Index | CC Measurement Register Index | TDX-measurement register // ----------------------------------------------------------------------- // 0 | 0 | MRTD // 1, 7 | 1 | RTMR[0] // 2~6 | 2 | RTMR[1] // 8~15 | 3 | RTMR[2] In the current implementation TdMapPcrToMrIndex returns the index of RTMR, not the MR index. After fix the spec unconsistent, other related codes are updated accordingly. 1) The index of event log uses the input MrIndex. 2) MrIndex is decreated by 1 before it is sent for RTMR extending. Cc: Erdem Aktas [ruleof2] Cc: James Bottomley [jejb] Cc: Jiewen Yao [jyao1] Cc: Tom Lendacky [tlendacky] Cc: Arti Gupta Reported-by: Arti Gupta Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c | 89 +++++++++++++++++--------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c index a6b4f8e0aa..d19923b0c6 100644 --- a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c +++ b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c @@ -49,7 +49,11 @@ #define PERF_ID_CC_TCG2_DXE 0x3130 #define CC_EVENT_LOG_AREA_COUNT_MAX 1 -#define INVALID_RTMR_INDEX 4 +#define CC_MR_INDEX_0_MRTD 0 +#define CC_MR_INDEX_1_RTMR0 1 +#define CC_MR_INDEX_2_RTMR1 2 +#define CC_MR_INDEX_3_RTMR2 3 +#define CC_MR_INDEX_INVALID 4 typedef struct { CHAR16 *VariableName; @@ -240,7 +244,7 @@ EFI_HANDLE mImageHandle; Notes: PE/COFF image is checked by BasePeCoffLib PeCoffLoaderGetImageInfo(). - @param[in] MrIndex RTMR index + @param[in] RtmrIndex RTMR index @param[in] ImageAddress Start address of image buffer. @param[in] ImageSize Image size @param[out] DigestList Digest list of this image. @@ -251,7 +255,7 @@ EFI_HANDLE mImageHandle; **/ EFI_STATUS MeasurePeImageAndExtend ( - IN UINT32 MrIndex, + IN UINT32 RtmrIndex, IN EFI_PHYSICAL_ADDRESS ImageAddress, IN UINTN ImageSize, OUT TPML_DIGEST_VALUES *DigestList @@ -925,10 +929,22 @@ TcgCommLogEvent ( } /** - RTMR[0] => PCR[1,7] - RTMR[1] => PCR[2,3,4,5] - RTMR[2] => PCR[8~15] - RTMR[3] => NA + According to UEFI Spec 2.10 Section 38.4.1: + The following table shows the TPM PCR index mapping and CC event log measurement + register index interpretation for Intel TDX, where MRTD means Trust Domain Measurement + Register and RTMR means Runtime Measurement Register + + // TPM PCR Index | CC Measurement Register Index | TDX-measurement register + // ------------------------------------------------------------------------ + // 0 | 0 | MRTD + // 1, 7 | 1 | RTMR[0] + // 2~6 | 2 | RTMR[1] + // 8~15 | 3 | RTMR[2] + + @param[in] PCRIndex Index of the TPM PCR + + @retval UINT32 Index of the CC Event Log Measurement Register Index + @retval CC_MR_INDEX_INVALID Invalid MR Index **/ UINT32 EFIAPI @@ -938,18 +954,20 @@ MapPcrToMrIndex ( { UINT32 MrIndex; - if ((PCRIndex > 16) || (PCRIndex == 6) || (PCRIndex == 0)) { + if (PCRIndex > 15) { ASSERT (FALSE); - return INVALID_RTMR_INDEX; + return CC_MR_INDEX_INVALID; } MrIndex = 0; - if ((PCRIndex == 1) || (PCRIndex == 7)) { - MrIndex = 0; - } else if ((PCRIndex > 1) && (PCRIndex < 6)) { - MrIndex = 1; - } else if ((PCRIndex > 7) && (PCRIndex < 16)) { - MrIndex = 2; + if (PCRIndex == 0) { + MrIndex = CC_MR_INDEX_0_MRTD; + } else if ((PCRIndex == 1) || (PCRIndex == 7)) { + MrIndex = CC_MR_INDEX_1_RTMR0; + } else if ((PCRIndex >= 2) && (PCRIndex <= 6)) { + MrIndex = CC_MR_INDEX_2_RTMR1; + } else if ((PCRIndex >= 8) && (PCRIndex <= 15)) { + MrIndex = CC_MR_INDEX_3_RTMR2; } return MrIndex; @@ -967,13 +985,9 @@ TdMapPcrToMrIndex ( return EFI_INVALID_PARAMETER; } - if ((PCRIndex > 16) || (PCRIndex == 0) || (PCRIndex == 6)) { - return EFI_INVALID_PARAMETER; - } - *MrIndex = MapPcrToMrIndex (PCRIndex); - return *MrIndex == INVALID_RTMR_INDEX ? EFI_INVALID_PARAMETER : EFI_SUCCESS; + return *MrIndex == CC_MR_INDEX_INVALID ? EFI_INVALID_PARAMETER : EFI_SUCCESS; } /** @@ -1197,12 +1211,7 @@ TdxDxeLogHashEvent ( LogFormat = EFI_CC_EVENT_LOG_FORMAT_TCG_2; ZeroMem (&CcEvent, sizeof (CcEvent)); - // - // The index of event log is designed as below: - // 0 : MRTD - // 1-4: RTMR[0-3] - // - CcEvent.MrIndex = NewEventHdr->MrIndex + 1; + CcEvent.MrIndex = NewEventHdr->MrIndex; CcEvent.EventType = NewEventHdr->EventType; DigestBuffer = (UINT8 *)&CcEvent.Digests; EventSizePtr = CopyDigestListToBuffer (DigestBuffer, DigestList, HASH_ALG_SHA384); @@ -1270,8 +1279,16 @@ TdxDxeHashLogExtendEvent ( return Status; } + // + // According to UEFI Spec 2.10 Section 38.4.1 the mapping between MrIndex and Intel + // TDX Measurement Register is: + // MrIndex 0 <--> MRTD + // MrIndex 1-3 <--> RTMR[0-2] + // Only the RMTR registers can be extended in TDVF by HashAndExtend. So MrIndex will + // decreased by 1 before it is sent to HashAndExtend. + // Status = HashAndExtend ( - NewEventHdr->MrIndex, + NewEventHdr->MrIndex - 1, HashData, (UINTN)HashDataLen, &DigestList @@ -1335,7 +1352,13 @@ TdHashLogExtendEvent ( return EFI_INVALID_PARAMETER; } - if (CcEvent->Header.MrIndex > 4) { + if (CcEvent->Header.MrIndex == CC_MR_INDEX_0_MRTD) { + DEBUG ((DEBUG_ERROR, "%a: MRTD cannot be extended in TDVF.\n", __FUNCTION__)); + return EFI_INVALID_PARAMETER; + } + + if (CcEvent->Header.MrIndex >= CC_MR_INDEX_INVALID) { + DEBUG ((DEBUG_ERROR, "%a: MrIndex is invalid. (%d)\n", __FUNCTION__, CcEvent->Header.MrIndex)); return EFI_INVALID_PARAMETER; } @@ -1343,8 +1366,16 @@ TdHashLogExtendEvent ( NewEventHdr.EventType = CcEvent->Header.EventType; NewEventHdr.EventSize = CcEvent->Size - sizeof (UINT32) - CcEvent->Header.HeaderSize; if ((Flags & EFI_CC_FLAG_PE_COFF_IMAGE) != 0) { + // + // According to UEFI Spec 2.10 Section 38.4.1 the mapping between MrIndex and Intel + // TDX Measurement Register is: + // MrIndex 0 <--> MRTD + // MrIndex 1-3 <--> RTMR[0-2] + // Only the RMTR registers can be extended in TDVF by HashAndExtend. So MrIndex will + // decreased by 1 before it is sent to MeasurePeImageAndExtend. + // Status = MeasurePeImageAndExtend ( - NewEventHdr.MrIndex, + NewEventHdr.MrIndex - 1, DataToHash, (UINTN)DataToHashLen, &DigestList From b7c27a9189c211bc33366b0ce30df738058c40a7 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 14 Dec 2022 15:14:19 +0800 Subject: [PATCH 0389/1529] OvmfPkg/SecTpmMeasurementLib: Fix the mapping error of PCR and RTMR index BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4179 TDVF has the feature to do RTMR measurement in SEC phase. In the same time it builds a GUID hob which carries the hash value of the measurement so that in DXE phase a td event can be created based on this GUID Hob. There is a mapping error between TPM PCR index and RTMR index according to UEFI 2.10. That PCR6 is missing in the mapping. This patch fixes this issue. Cc: Erdem Aktas [ruleof2] Cc: James Bottomley [jejb] Cc: Jiewen Yao [jyao1] Cc: Tom Lendacky [tlendacky] Cc: Arti Gupta Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- .../Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.c b/SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.c index 38887b172d..36bfa373fe 100644 --- a/SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.c +++ b/SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.c @@ -33,12 +33,11 @@ typedef struct { /** Get the mapped RTMR index based on the input PCRIndex. RTMR[0] => PCR[1,7] - RTMR[1] => PCR[2,3,4,5] + RTMR[1] => PCR[2,3,4,5,6] RTMR[2] => PCR[8~15] RTMR[3] => NA Note: PCR[0] is mapped to MRTD and should not appear here. - PCR[6] is reserved for OEM. It is not used. @param[in] PCRIndex The input PCR index @@ -51,7 +50,7 @@ GetMappedRtmrIndex ( { UINT8 RtmrIndex; - if ((PCRIndex == 6) || (PCRIndex == 0) || (PCRIndex > 15)) { + if ((PCRIndex == 0) || (PCRIndex > 15)) { DEBUG ((DEBUG_ERROR, "Invalid PCRIndex(%d) map to MR Index.\n", PCRIndex)); ASSERT (FALSE); return INVALID_PCR2MR_INDEX; @@ -60,7 +59,7 @@ GetMappedRtmrIndex ( RtmrIndex = 0; if ((PCRIndex == 1) || (PCRIndex == 7)) { RtmrIndex = 0; - } else if ((PCRIndex >= 2) && (PCRIndex < 6)) { + } else if ((PCRIndex >= 2) && (PCRIndex <= 6)) { RtmrIndex = 1; } else if ((PCRIndex >= 8) && (PCRIndex <= 15)) { RtmrIndex = 2; From b391f54e318cac55dbb6a77b29a327741a562f40 Mon Sep 17 00:00:00 2001 From: Adam Dunlap Date: Sat, 10 Dec 2022 05:04:16 +0800 Subject: [PATCH 0390/1529] OvmfPkg/PlatformPei: Validate SEC's GHCB page When running under SEV-ES, a page of shared memory is allocated for the GHCB during the SEC phase at address 0x809000. This page of memory is eventually passed to the OS as EfiConventionalMemory. When running SEV-SNP, this page is not PVALIDATE'd in the RMP table, meaning that if the guest OS tries to access the page, it will think that the host has voilated the security guarantees and will likely crash. This patch validates this page immediately after EDK2 switches to using the GHCB page allocated for the PEI phase. This was tested by writing a UEFI application that reads to and writes from one byte of each page of memory and checks to see if a #VC exception is generated indicating that the page was not validated. Fixes: 6995a1b79bab ("OvmfPkg: Create a GHCB page for use during Sec phase") Signed-off-by: Adam Dunlap Reviewed-by: Tom Lendacky --- OvmfPkg/PlatformPei/AmdSev.c | 40 ++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index c23fae7fca..e4e7b72e67 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -212,7 +212,7 @@ AmdSevEsInitialize ( UINTN GhcbBackupPageCount; SEV_ES_PER_CPU_DATA *SevEsData; UINTN PageCount; - RETURN_STATUS PcdStatus, DecryptStatus; + RETURN_STATUS Status; IA32_DESCRIPTOR Gdtr; VOID *Gdt; @@ -220,8 +220,8 @@ AmdSevEsInitialize ( return; } - PcdStatus = PcdSetBoolS (PcdSevEsIsEnabled, TRUE); - ASSERT_RETURN_ERROR (PcdStatus); + Status = PcdSetBoolS (PcdSevEsIsEnabled, TRUE); + ASSERT_RETURN_ERROR (Status); // // Allocate GHCB and per-CPU variable pages. @@ -240,20 +240,20 @@ AmdSevEsInitialize ( // only clear the encryption mask for the GHCB pages. // for (PageCount = 0; PageCount < GhcbPageCount; PageCount += 2) { - DecryptStatus = MemEncryptSevClearPageEncMask ( - 0, - GhcbBasePa + EFI_PAGES_TO_SIZE (PageCount), - 1 - ); - ASSERT_RETURN_ERROR (DecryptStatus); + Status = MemEncryptSevClearPageEncMask ( + 0, + GhcbBasePa + EFI_PAGES_TO_SIZE (PageCount), + 1 + ); + ASSERT_RETURN_ERROR (Status); } ZeroMem (GhcbBase, EFI_PAGES_TO_SIZE (GhcbPageCount)); - PcdStatus = PcdSet64S (PcdGhcbBase, GhcbBasePa); - ASSERT_RETURN_ERROR (PcdStatus); - PcdStatus = PcdSet64S (PcdGhcbSize, EFI_PAGES_TO_SIZE (GhcbPageCount)); - ASSERT_RETURN_ERROR (PcdStatus); + Status = PcdSet64S (PcdGhcbBase, GhcbBasePa); + ASSERT_RETURN_ERROR (Status); + Status = PcdSet64S (PcdGhcbSize, EFI_PAGES_TO_SIZE (GhcbPageCount)); + ASSERT_RETURN_ERROR (Status); DEBUG (( DEBUG_INFO, @@ -295,6 +295,20 @@ AmdSevEsInitialize ( AsmWriteMsr64 (MSR_SEV_ES_GHCB, GhcbBasePa); + // + // Now that the PEI GHCB is set up, the SEC GHCB page is no longer necessary + // to keep shared. Later, it is exposed to the OS as EfiConventionalMemory, so + // it needs to be marked private. The size of the region is hardcoded in + // OvmfPkg/ResetVector/ResetVector.nasmb in the definition of + // SNP_SEC_MEM_BASE_DESC_2. + // + Status = MemEncryptSevSetPageEncMask ( + 0, // Cr3 -- use system Cr3 + FixedPcdGet32 (PcdOvmfSecGhcbBase), // BaseAddress + 1 // NumPages + ); + ASSERT_RETURN_ERROR (Status); + // // The SEV support will clear the C-bit from non-RAM areas. The early GDT // lives in a non-RAM area, so when an exception occurs (like a #VC) the GDT From af84db4d346b14e777a2df7af3def966c270730e Mon Sep 17 00:00:00 2001 From: Dov Murik Date: Thu, 15 Dec 2022 13:11:51 +0000 Subject: [PATCH 0391/1529] OvmfPkg/AmdSev/SecretDxe: Allocate secret location as EfiACPIReclaimMemory BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4186 Commit 079a58276b98 ("OvmfPkg/AmdSev/SecretPei: Mark SEV launch secret area as reserved") marked the launch secret area itself (1 page) as reserved so the guest OS can use it during the lifetime of the OS. However, the address and size of the secret area held in the CONFIDENTIAL_COMPUTING_SECRET_LOCATION struct are declared as STATIC in OVMF (in AmdSev/SecretDxe); therefore there's no guarantee that it will not be written over by OS data. Fix this by allocating the memory for the CONFIDENTIAL_COMPUTING_SECRET_LOCATION struct with the EfiACPIReclaimMemory memory type to ensure the guest OS will not reuse this memory. Fixes: 079a58276b98 ("OvmfPkg/AmdSev/SecretPei: Mark SEV launch secret ...") Signed-off-by: Dov Murik Reviewed-by: Tom Lendacky Reviewed-by: Ard Biesheuvel --- OvmfPkg/AmdSev/SecretDxe/SecretDxe.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/OvmfPkg/AmdSev/SecretDxe/SecretDxe.c b/OvmfPkg/AmdSev/SecretDxe/SecretDxe.c index 3d84b25450..c3258570e9 100644 --- a/OvmfPkg/AmdSev/SecretDxe/SecretDxe.c +++ b/OvmfPkg/AmdSev/SecretDxe/SecretDxe.c @@ -8,11 +8,6 @@ #include #include -STATIC CONFIDENTIAL_COMPUTING_SECRET_LOCATION mSecretDxeTable = { - FixedPcdGet32 (PcdSevLaunchSecretBase), - FixedPcdGet32 (PcdSevLaunchSecretSize), -}; - EFI_STATUS EFIAPI InitializeSecretDxe ( @@ -20,8 +15,23 @@ InitializeSecretDxe ( IN EFI_SYSTEM_TABLE *SystemTable ) { + EFI_STATUS Status; + CONFIDENTIAL_COMPUTING_SECRET_LOCATION *SecretDxeTable; + + Status = gBS->AllocatePool ( + EfiACPIReclaimMemory, + sizeof (CONFIDENTIAL_COMPUTING_SECRET_LOCATION), + (VOID **)&SecretDxeTable + ); + if (EFI_ERROR (Status)) { + return Status; + } + + SecretDxeTable->Base = FixedPcdGet32 (PcdSevLaunchSecretBase); + SecretDxeTable->Size = FixedPcdGet32 (PcdSevLaunchSecretSize); + return gBS->InstallConfigurationTable ( &gConfidentialComputingSecretGuid, - &mSecretDxeTable + SecretDxeTable ); } From 11ab49d573b44e7861fbfcbeb8115323f0403a10 Mon Sep 17 00:00:00 2001 From: Sebastien Boeuf Date: Thu, 15 Dec 2022 23:10:02 +0800 Subject: [PATCH 0392/1529] OvmfPkg/PlatformInitLib: Differentiate TDX case for Cloud Hypervisor Rely on the CcProbe() function to identify when running on TDX. This allows the firmware to follow a different codepath for Cloud Hypervisor, which means it doesn't rely on PVH to find out about memory below 4GiB. instead it falls back onto the CMOS to retrieve that information. Signed-off-by: Sebastien Boeuf Reviewed-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index b8feae4309..6dbdbf9306 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -26,6 +26,7 @@ Module Name: // #include #include +#include #include #include #include @@ -312,7 +313,9 @@ PlatformGetSystemMemorySizeBelow4gb ( UINT8 Cmos0x34; UINT8 Cmos0x35; - if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) { + if ((PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) && + (CcProbe () != CcGuestTypeIntelTdx)) + { // Get the information from PVH memmap return (UINT32)GetHighestSystemMemoryAddressFromPvhMemmap (TRUE); } From 527fcf80918024ed029ded1ea0957d25a3ed2251 Mon Sep 17 00:00:00 2001 From: Sebastien Boeuf Date: Thu, 15 Dec 2022 23:10:03 +0800 Subject: [PATCH 0393/1529] OvmfPkg/PlatformInitLib: Transfer GUID Extension HOB This is required for passing the ACPI tables from the VMM up to the guest OS. They are transferred through this GUID extension. Signed-off-by: Jiaqi Gao Signed-off-by: Sebastien Boeuf Reviewed-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c index acd114e38e..55ca3ecaa1 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c @@ -547,6 +547,7 @@ TransferTdxHobList ( EFI_PEI_HOB_POINTERS Hob; EFI_RESOURCE_TYPE ResourceType; EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute; + VOID *GuidedData; // // PcdOvmfSecGhcbBase is used as the TD_HOB in Tdx guest. @@ -577,6 +578,10 @@ TransferTdxHobList ( Hob.MemoryAllocation->AllocDescriptor.MemoryType ); break; + case EFI_HOB_TYPE_GUID_EXTENSION: + GuidedData = (VOID *)(&Hob.Guid->Name + 1); + BuildGuidDataHob (&Hob.Guid->Name, GuidedData, Hob.Guid->Header.HobLength - sizeof (EFI_HOB_GUID_TYPE)); + break; } Hob.Raw = GET_NEXT_HOB (Hob); From 359ad54442191c631325383e1a17ff42094efbf8 Mon Sep 17 00:00:00 2001 From: Sebastien Boeuf Date: Thu, 15 Dec 2022 23:10:04 +0800 Subject: [PATCH 0394/1529] OvmfPkg/AcpiPlatformDxe: Differentiate TDX case for Cloud Hypervisor Rely on CcProbe() to identify when running on TDX so that ACPI tables can be retrieved differently for Cloud Hypervisor. Instead of relying on the PVH structure to find the RSDP pointer, the tables are individually passed through the HOB. Signed-off-by: Jiaqi Gao Signed-off-by: Sebastien Boeuf Reviewed-by: Min Xu Reviewed-by: Jiewen Yao --- ArmVirtPkg/ArmVirtQemu.dsc | 1 + OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c | 8 +- OvmfPkg/AcpiPlatformDxe/AcpiPlatform.h | 6 ++ OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf | 3 + OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c | 87 +++++++++++++++++++++ OvmfPkg/OvmfPkg.dec | 1 + 6 files changed, 105 insertions(+), 1 deletion(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index f77443229e..1dea715e9e 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -68,6 +68,7 @@ VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + CcProbeLib|MdePkg/Library/CcProbeLibNull/CcProbeLibNull.inf BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf PlatformBootManagerLib|ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf PlatformBmPrintScLib|OvmfPkg/Library/PlatformBmPrintScLib/PlatformBmPrintScLib.inf diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c index fcfb9703bd..0cc3d958be 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c @@ -9,6 +9,8 @@ #include // CLOUDHV_DEVICE_ID +#include // CcProbe(), CcGuestTypeIntelTdx + #include "AcpiPlatform.h" /** @@ -33,7 +35,11 @@ InstallAcpiTables ( HostBridgeDevId = PcdGet16 (PcdOvmfHostBridgePciDevId); if (HostBridgeDevId == CLOUDHV_DEVICE_ID) { - Status = InstallCloudHvTables (AcpiTable); + if (CcProbe () == CcGuestTypeIntelTdx) { + Status = InstallCloudHvTablesTdx (AcpiTable); + } else { + Status = InstallCloudHvTables (AcpiTable); + } } else { Status = InstallQemuFwCfgTables (AcpiTable); } diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.h b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.h index 342339750d..3ec5098658 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.h +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.h @@ -19,6 +19,12 @@ typedef struct { typedef struct S3_CONTEXT S3_CONTEXT; +EFI_STATUS +EFIAPI +InstallCloudHvTablesTdx ( + IN EFI_ACPI_TABLE_PROTOCOL *AcpiProtocol + ); + EFI_STATUS EFIAPI InstallCloudHvTables ( diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf index 09daf30bcd..1647a90add 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf @@ -45,6 +45,8 @@ QemuFwCfgS3Lib UefiBootServicesTableLib UefiDriverEntryPoint + HobLib + CcProbeLib [Protocols] gEfiAcpiTableProtocolGuid # PROTOCOL ALWAYS_CONSUMED @@ -53,6 +55,7 @@ [Guids] gRootBridgesConnectedEventGroupGuid + gUefiOvmfPkgTdxAcpiHobGuid [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration diff --git a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c index ff59600d3e..cbe8bb9b0c 100644 --- a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c @@ -7,14 +7,101 @@ **/ +#include // EFI_ACPI_DESCRIPTION_HEADER #include // CLOUDHV_RSDP_ADDRESS #include // hvm_start_info #include // CpuDeadLoop() #include // DEBUG() #include // PcdGet32() +#include // GetFirstGuidHob(), GetNextGuidHob() +#include // gBS + +#include +#include +#include // QEMU_ACPI_TABLE_NOTIFY_PROTOCOL #include "AcpiPlatform.h" +EFI_HANDLE mChAcpiHandle = NULL; +QEMU_ACPI_TABLE_NOTIFY_PROTOCOL mChAcpiNotifyProtocol; + +EFI_STATUS +EFIAPI +InstallCloudHvTablesTdx ( + IN EFI_ACPI_TABLE_PROTOCOL *AcpiProtocol + ) +{ + EFI_STATUS Status; + UINTN TableHandle; + + EFI_PEI_HOB_POINTERS Hob; + EFI_ACPI_DESCRIPTION_HEADER *CurrentTable; + EFI_ACPI_DESCRIPTION_HEADER *DsdtTable; + + DsdtTable = NULL; + TableHandle = 0; + + Hob.Guid = (EFI_HOB_GUID_TYPE *)GetFirstGuidHob (&gUefiOvmfPkgTdxAcpiHobGuid); + + while (Hob.Guid != NULL) { + CurrentTable = (EFI_ACPI_DESCRIPTION_HEADER *)(&Hob.Guid->Name + 1); + if (!AsciiStrnCmp ((CHAR8 *)&CurrentTable->Signature, "DSDT", 4)) { + DsdtTable = CurrentTable; + } else { + // + // Install the tables + // + Status = AcpiProtocol->InstallAcpiTable ( + AcpiProtocol, + CurrentTable, + CurrentTable->Length, + &TableHandle + ); + for (UINTN i = 0; i < CurrentTable->Length; i++) { + DEBUG ((DEBUG_INFO, " %x", *((UINT8 *)CurrentTable + i))); + } + + DEBUG ((DEBUG_INFO, "\n")); + } + + Hob.Raw = GET_NEXT_HOB (Hob.Raw); + Hob.Guid = (EFI_HOB_GUID_TYPE *)GetNextGuidHob (&gUefiOvmfPkgTdxAcpiHobGuid, Hob.Raw); + } + + // + // Install DSDT table. If we reached this point without finding the DSDT, + // then we're out of sync with the hypervisor, and cannot continue. + // + if (DsdtTable == NULL) { + DEBUG ((DEBUG_INFO, "%a: no DSDT found\n", __FUNCTION__)); + ASSERT (FALSE); + } + + Status = AcpiProtocol->InstallAcpiTable ( + AcpiProtocol, + DsdtTable, + DsdtTable->Length, + &TableHandle + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + // + // Install a protocol to notify that the ACPI table provided by CH is + // ready. + // + gBS->InstallProtocolInterface ( + &mChAcpiHandle, + &gQemuAcpiTableNotifyProtocolGuid, + EFI_NATIVE_INTERFACE, + &mChAcpiNotifyProtocol + ); + + return EFI_SUCCESS; +} + // Get the ACPI tables from EBDA start EFI_STATUS EFIAPI diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index 5f5556c67c..a350bb8f84 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -151,6 +151,7 @@ gConfidentialComputingSevSnpBlobGuid = {0x067b1f5f, 0xcf26, 0x44c5, {0x85, 0x54, 0x93, 0xd7, 0x77, 0x91, 0x2d, 0x42}} gUefiOvmfPkgPlatformInfoGuid = {0xdec9b486, 0x1f16, 0x47c7, {0x8f, 0x68, 0xdf, 0x1a, 0x41, 0x88, 0x8b, 0xa5}} gVMMBootOrderGuid = {0x668f4529, 0x63d0, 0x4bb5, {0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a}} + gUefiOvmfPkgTdxAcpiHobGuid = {0x6a0c5870, 0xd4ed, 0x44f4, {0xa1, 0x35, 0xdd, 0x23, 0x8b, 0x6f, 0x0c, 0x8d}} [Ppis] # PPI whose presence in the PPI database signals that the TPM base address From 8e1c58161857c33cfa892c4077dc8489428491b0 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Dec 2022 11:45:13 -0500 Subject: [PATCH 0395/1529] .pytool/Readme.md: Add reference to new build instructions Adds a reference to the new build instructions on the TianoCore wiki that currently describe building with containers and Stuart. Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Acked-by: Ard Biesheuvel Reviewed-by: Gerd Hoffmann --- .pytool/Readme.md | 52 ++++++++++++++++------------------------------- 1 file changed, 17 insertions(+), 35 deletions(-) diff --git a/.pytool/Readme.md b/.pytool/Readme.md index 9c7b7f9abb..b2688d1687 100644 --- a/.pytool/Readme.md +++ b/.pytool/Readme.md @@ -1,5 +1,12 @@ # Edk2 Continuous Integration +This file focuses on information for those working with the `.pytools` directory +directly or interested in lower-level details about how CI works. + +If you just want to get started building code, visit +[Build Instructions](https://github.com/tianocore/tianocore.github.io/wiki/Build-Instruction) +on the TianoCore wiki. + ## Basic Status | Package | Windows VS2019 (IA32/X64)| Ubuntu GCC (IA32/X64/ARM/AARCH64) | Known Issues | @@ -82,43 +89,18 @@ easily and consistently running locally and in a cloud ci environment. To do that a few steps should be followed. Details of EDKII Tools can be found in the [docs folder here](https://github.com/tianocore/edk2-pytool-extensions/tree/master/docs) -### Prerequisites - -1. A supported toolchain (others might work but this is what is tested and validated) - * Windows 10: - * VS 2017 or VS 2019 - * Windows SDK (for rc) - * Windows WDK (for capsules) - * Ubuntu 18.04 or Fedora - * GCC5 - * Easy to add more but this is the current state -2. Python 3.7.x or newer on path -3. git on path -4. Recommended to setup and activate a python virtual environment -5. Install the requirements `pip install --upgrade -r pip-requirements.txt` - ### Running CI -1. clone your edk2 repo -2. Activate your python virtual environment in cmd window -3. Get code dependencies (done only when submodules change) - * `stuart_setup -c .pytool/CISettings.py TOOL_CHAIN_TAG=` -4. Update other dependencies (done more often) - * `stuart_update -c .pytool/CISettings.py TOOL_CHAIN_TAG=` -5. Run CI build (--help will give you options) - * `stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=` - * -p : To build only certain packages use a CSV list - * -a : To run only certain architectures use a CSV list - * -t : To run only tests related to certain targets use a - CSV list - * By default all tests are opted in. Then given a package.ci.yaml file those - tests can be configured for a package. Finally setting the check to the - value `skip` will skip that plugin. Examples: - * `CompilerPlugin=skip` skip the build test - * `GuidCheck=skip` skip the Guid check - * `SpellCheck=skip` skip the spell checker - * etc -6. Detailed reports and logs per package are captured in the `Build` directory +Quick notes: + +* By default all CI plugins are opted in. + * Setting the plugin to `skip` as an argument will skip running the plugin. + Examples: + * `CompilerPlugin=skip` skip the build test + * `GuidCheck=skip` skip the Guid check + * `SpellCheck=skip` skip the spell checker + * etc. +* Detailed reports and logs per package are captured in the `Build` directory. ## Current PyTool Test Capabilities From debcc35eb76176413032783e08806e806da4fa91 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Dec 2022 11:45:33 -0500 Subject: [PATCH 0396/1529] ArmVirtPkg: Add reference to new build instructions Adds a reference to the new build instructions on the TianoCore wiki that currently describe building with containers and Stuart. Cc: Ard Biesheuvel Cc: Leif Lindholm Cc: Sami Mujawar Cc: Gerd Hoffmann Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Acked-by: Ard Biesheuvel Reviewed-by: Gerd Hoffmann --- ArmVirtPkg/PlatformCI/ReadMe.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ArmVirtPkg/PlatformCI/ReadMe.md b/ArmVirtPkg/PlatformCI/ReadMe.md index 7c11d925f5..ee8d8cd61e 100644 --- a/ArmVirtPkg/PlatformCI/ReadMe.md +++ b/ArmVirtPkg/PlatformCI/ReadMe.md @@ -29,6 +29,9 @@ Pytools build system. ## Building with Pytools for ArmVirtPkg +If you are unfamiliar with Pytools, it is recommended to first read through +the generic set of edk2 [Build Instructions](https://github.com/tianocore/tianocore.github.io/wiki/Build-Instructions). + 1. [Optional] Create a Python Virtual Environment - generally once per workspace ``` bash From a45389c2610d9100dbf87d66475f974446d2764b Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Dec 2022 11:46:09 -0500 Subject: [PATCH 0397/1529] BaseTools: Add reference to new build instructions Adds a reference to the new build instructions on the TianoCore wiki that currently describe building with containers and Stuart. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Acked-by: Ard Biesheuvel Reviewed-by: Gerd Hoffmann --- BaseTools/ReadMe.rst | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/BaseTools/ReadMe.rst b/BaseTools/ReadMe.rst index de85ca4be6..592be51b1f 100644 --- a/BaseTools/ReadMe.rst +++ b/BaseTools/ReadMe.rst @@ -1,3 +1,13 @@ +:: + + Note: New build instructions are available. It is recommended to start with + the new instructions if learning how to build edk2 and/or BaseTools for the + first time. This page is retained for reference. + +New instructions: `Build Instructions`_ + +.. _`Build Instructions`: https://github.com/tianocore/tianocore.github.io/wiki/Build-Instructions + This directory contains the EDK II build tools and template files. Templates are located in the Conf directory, while the tools executables for Microsoft Windows Operating Systems are located in the Bin\\Win32 directory, other @@ -23,9 +33,6 @@ After this, you can run the toolsetup.bat file, which is in the same directory as this file. It should setup the remainder of the environment, and build the tools if necessary. -Please also refer to the ``BuildNotes.txt`` file for more information on -building under Windows. - Unix-like operating systems =========================== From aa53e367c4546e06f58a4722b2dea427faae9450 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Dec 2022 11:46:26 -0500 Subject: [PATCH 0398/1529] EmulatorPkg: Add reference to new build instructions Adds a reference to the new build instructions on the TianoCore wiki that currently describe building with containers and Stuart. Cc: Andrew Fish Cc: Ray Ni Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Acked-by: Ard Biesheuvel Reviewed-by: Gerd Hoffmann --- EmulatorPkg/PlatformCI/ReadMe.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/EmulatorPkg/PlatformCI/ReadMe.md b/EmulatorPkg/PlatformCI/ReadMe.md index 91c40b2093..f123bb2a48 100644 --- a/EmulatorPkg/PlatformCI/ReadMe.md +++ b/EmulatorPkg/PlatformCI/ReadMe.md @@ -42,6 +42,9 @@ Pytools build system. ## Building with Pytools for EmulatorPkg +If you are unfamiliar with Pytools, it is recommended to first read through +the generic set of edk2 [Build Instructions](https://github.com/tianocore/tianocore.github.io/wiki/Build-Instructions). + 1. [Optional] Create a Python Virtual Environment - generally once per workspace ``` bash From 67a83c58a1d2ce6dd226efffa284ce6f61594845 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 2 Dec 2022 11:46:43 -0500 Subject: [PATCH 0399/1529] OvmfPkg: Add reference to new build instructions Adds a reference to the new build instructions on the TianoCore wiki that currently describe building with containers and Stuart. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: Sean Brogan Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Michael Kubacki Acked-by: Ard Biesheuvel Reviewed-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/PlatformCI/ReadMe.md | 3 +++ OvmfPkg/README | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/PlatformCI/ReadMe.md b/OvmfPkg/PlatformCI/ReadMe.md index 1216dee126..10fa32ac48 100644 --- a/OvmfPkg/PlatformCI/ReadMe.md +++ b/OvmfPkg/PlatformCI/ReadMe.md @@ -31,6 +31,9 @@ Pytools build system. ## Building with Pytools for OvmfPkg +If you are unfamiliar with Pytools, it is recommended to first read through +the generic set of edk2 [Build Instructions](https://github.com/tianocore/tianocore.github.io/wiki/Build-Instructions). + 1. [Optional] Create a Python Virtual Environment - generally once per workspace ``` bash diff --git a/OvmfPkg/README b/OvmfPkg/README index d6e7e32848..0a408abf01 100644 --- a/OvmfPkg/README +++ b/OvmfPkg/README @@ -53,7 +53,10 @@ these binary outputs: * OvmfVideo.rom - This file is not built separately any longer, starting with svn r13520. -More information on building OVMF can be found at: +If you are new to building in edk2 or looking for the latest build +instructions, visit https://github.com/tianocore/tianocore.github.io/wiki/Build-Instructions + +More OVMF-specific build information can be found at: https://github.com/tianocore/tianocore.github.io/wiki/How%20to%20build%20OVMF From 1dd96fa3cef6868e6a74d209452e87ef449d9a7b Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 15 Dec 2022 13:18:07 +0800 Subject: [PATCH 0400/1529] OvmfPkg/IoMmuDxe: Reserve shared memory region for DMA operation BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4171 A typical QEMU fw_cfg read bytes with IOMMU for td guest is that: (QemuFwCfgReadBytes@QemuFwCfgLib.c is the example) 1) Allocate DMA Access buffer 2) Map actual data buffer 3) start the transfer and wait for the transfer to complete 4) Free DMA Access buffer 5) Un-map actual data buffer In step 1/2, Private memories are allocated, converted to shared memories. In Step 4/5 the shared memories are converted to private memories and accepted again. The final step is to free the pages. This is time-consuming and impacts td guest's boot perf (both direct boot and grub boot) badly. In a typical grub boot, there are about 5000 calls of page allocation and private/share conversion. Most of page size is less than 32KB. This patch allocates a memory region and initializes it into pieces of memory with different sizes. A piece of such memory consists of 2 parts: the first page is of private memory, and the other pages are shared memory. This is to meet the layout of common buffer. When allocating bounce buffer in IoMmuMap(), IoMmuAllocateBounceBuffer() is called to allocate the buffer. Accordingly when freeing bounce buffer in IoMmuUnmapWorker(), IoMmuFreeBounceBuffer() is called to free the bounce buffer. CommonBuffer is allocated by IoMmuAllocateCommonBuffer and accordingly freed by IoMmuFreeCommonBuffer. This feature is tested in Intel TDX pre-production platform. It saves up to hundreds of ms in a grub boot. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu Reviewed-by: Tom Lendacky --- OvmfPkg/IoMmuDxe/AmdSevIoMmu.c | 142 +++++----- OvmfPkg/IoMmuDxe/IoMmuBuffer.c | 465 +++++++++++++++++++++++++++++++ OvmfPkg/IoMmuDxe/IoMmuDxe.inf | 1 + OvmfPkg/IoMmuDxe/IoMmuInternal.h | 179 ++++++++++++ 4 files changed, 716 insertions(+), 71 deletions(-) create mode 100644 OvmfPkg/IoMmuDxe/IoMmuBuffer.c create mode 100644 OvmfPkg/IoMmuDxe/IoMmuInternal.h diff --git a/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c b/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c index 6b65897f03..77e46bbf4a 100644 --- a/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c +++ b/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c @@ -15,18 +15,7 @@ #include #include #include "AmdSevIoMmu.h" - -#define MAP_INFO_SIG SIGNATURE_64 ('M', 'A', 'P', '_', 'I', 'N', 'F', 'O') - -typedef struct { - UINT64 Signature; - LIST_ENTRY Link; - EDKII_IOMMU_OPERATION Operation; - UINTN NumberOfBytes; - UINTN NumberOfPages; - EFI_PHYSICAL_ADDRESS CryptedAddress; - EFI_PHYSICAL_ADDRESS PlainTextAddress; -} MAP_INFO; +#include "IoMmuInternal.h" // // List of the MAP_INFO structures that have been set up by IoMmuMap() and not @@ -35,7 +24,10 @@ typedef struct { // STATIC LIST_ENTRY mMapInfos = INITIALIZE_LIST_HEAD_VARIABLE (mMapInfos); -#define COMMON_BUFFER_SIG SIGNATURE_64 ('C', 'M', 'N', 'B', 'U', 'F', 'F', 'R') +// +// Indicate if the feature of reserved memory is supported in DMA operation. +// +BOOLEAN mReservedSharedMemSupported = FALSE; // // ASCII names for EDKII_IOMMU_OPERATION constants, for debug logging. @@ -50,30 +42,6 @@ mBusMasterOperationName[EdkiiIoMmuOperationMaximum] = { "CommonBuffer64" }; -// -// The following structure enables Map() and Unmap() to perform in-place -// decryption and encryption, respectively, for BusMasterCommonBuffer[64] -// operations, without dynamic memory allocation or release. -// -// Both COMMON_BUFFER_HEADER and COMMON_BUFFER_HEADER.StashBuffer are allocated -// by AllocateBuffer() and released by FreeBuffer(). -// -#pragma pack (1) -typedef struct { - UINT64 Signature; - - // - // Always allocated from EfiBootServicesData type memory, and always - // encrypted. - // - VOID *StashBuffer; - - // - // Followed by the actual common buffer, starting at the next page. - // -} COMMON_BUFFER_HEADER; -#pragma pack () - /** Provides the controller-specific addresses required to access system memory from a DMA bus master. On SEV/TDX guest, the DMA operations must be performed on @@ -139,6 +107,8 @@ IoMmuMap ( return EFI_INVALID_PARAMETER; } + Status = EFI_SUCCESS; + // // Allocate a MAP_INFO structure to remember the mapping when Unmap() is // called later. @@ -153,11 +123,12 @@ IoMmuMap ( // Initialize the MAP_INFO structure, except the PlainTextAddress field // ZeroMem (&MapInfo->Link, sizeof MapInfo->Link); - MapInfo->Signature = MAP_INFO_SIG; - MapInfo->Operation = Operation; - MapInfo->NumberOfBytes = *NumberOfBytes; - MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes); - MapInfo->CryptedAddress = (UINTN)HostAddress; + MapInfo->Signature = MAP_INFO_SIG; + MapInfo->Operation = Operation; + MapInfo->NumberOfBytes = *NumberOfBytes; + MapInfo->NumberOfPages = EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes); + MapInfo->CryptedAddress = (UINTN)HostAddress; + MapInfo->ReservedMemBitmap = 0; // // In the switch statement below, we point "MapInfo->PlainTextAddress" to the @@ -185,12 +156,11 @@ IoMmuMap ( // // Allocate the implicit plaintext bounce buffer. // - Status = gBS->AllocatePages ( - AllocateType, - EfiBootServicesData, - MapInfo->NumberOfPages, - &MapInfo->PlainTextAddress - ); + Status = IoMmuAllocateBounceBuffer ( + AllocateType, + EfiBootServicesData, + MapInfo + ); if (EFI_ERROR (Status)) { goto FreeMapInfo; } @@ -241,7 +211,8 @@ IoMmuMap ( // Point "DecryptionSource" to the stash buffer so that we decrypt // it to the original location, after the switch statement. // - DecryptionSource = CommonBufferHeader->StashBuffer; + DecryptionSource = CommonBufferHeader->StashBuffer; + MapInfo->ReservedMemBitmap = CommonBufferHeader->ReservedMemBitmap; break; default: @@ -264,12 +235,16 @@ IoMmuMap ( } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { // // Set the memory shared bit. + // If MapInfo->ReservedMemBitmap is 0, it means the bounce buffer is not allocated + // from the pre-allocated shared memory, so it must be converted to shared memory here. // - Status = MemEncryptTdxSetPageSharedBit ( - 0, - MapInfo->PlainTextAddress, - MapInfo->NumberOfPages - ); + if (MapInfo->ReservedMemBitmap == 0) { + Status = MemEncryptTdxSetPageSharedBit ( + 0, + MapInfo->PlainTextAddress, + MapInfo->NumberOfPages + ); + } } else { ASSERT (FALSE); } @@ -311,12 +286,13 @@ IoMmuMap ( DEBUG (( DEBUG_VERBOSE, - "%a: Mapping=0x%p Device(PlainText)=0x%Lx Crypted=0x%Lx Pages=0x%Lx\n", + "%a: Mapping=0x%p Device(PlainText)=0x%Lx Crypted=0x%Lx Pages=0x%Lx, ReservedMemBitmap=0x%Lx\n", __FUNCTION__, MapInfo, MapInfo->PlainTextAddress, MapInfo->CryptedAddress, - (UINT64)MapInfo->NumberOfPages + (UINT64)MapInfo->NumberOfPages, + MapInfo->ReservedMemBitmap )); return EFI_SUCCESS; @@ -435,11 +411,13 @@ IoMmuUnmapWorker ( // Restore the memory shared bit mask on the area we used to hold the // plaintext. // - Status = MemEncryptTdxClearPageSharedBit ( - 0, - MapInfo->PlainTextAddress, - MapInfo->NumberOfPages - ); + if (MapInfo->ReservedMemBitmap == 0) { + Status = MemEncryptTdxClearPageSharedBit ( + 0, + MapInfo->PlainTextAddress, + MapInfo->NumberOfPages + ); + } } else { ASSERT (FALSE); } @@ -470,8 +448,9 @@ IoMmuUnmapWorker ( (VOID *)(UINTN)MapInfo->PlainTextAddress, EFI_PAGES_TO_SIZE (MapInfo->NumberOfPages) ); + if (!MemoryMapLocked) { - gBS->FreePages (MapInfo->PlainTextAddress, MapInfo->NumberOfPages); + IoMmuFreeBounceBuffer (MapInfo); } } @@ -551,6 +530,7 @@ IoMmuAllocateBuffer ( VOID *StashBuffer; UINTN CommonBufferPages; COMMON_BUFFER_HEADER *CommonBufferHeader; + UINT32 ReservedMemBitmap; DEBUG (( DEBUG_VERBOSE, @@ -620,12 +600,13 @@ IoMmuAllocateBuffer ( PhysicalAddress = SIZE_4GB - 1; } - Status = gBS->AllocatePages ( - AllocateMaxAddress, - MemoryType, - CommonBufferPages, - &PhysicalAddress - ); + Status = IoMmuAllocateCommonBuffer ( + MemoryType, + CommonBufferPages, + &PhysicalAddress, + &ReservedMemBitmap + ); + if (EFI_ERROR (Status)) { goto FreeStashBuffer; } @@ -633,8 +614,9 @@ IoMmuAllocateBuffer ( CommonBufferHeader = (VOID *)(UINTN)PhysicalAddress; PhysicalAddress += EFI_PAGE_SIZE; - CommonBufferHeader->Signature = COMMON_BUFFER_SIG; - CommonBufferHeader->StashBuffer = StashBuffer; + CommonBufferHeader->Signature = COMMON_BUFFER_SIG; + CommonBufferHeader->StashBuffer = StashBuffer; + CommonBufferHeader->ReservedMemBitmap = ReservedMemBitmap; *HostAddress = (VOID *)(UINTN)PhysicalAddress; @@ -707,7 +689,7 @@ IoMmuFreeBuffer ( // Release the common buffer itself. Unmap() has re-encrypted it in-place, so // no need to zero it. // - return gBS->FreePages ((UINTN)CommonBufferHeader, CommonBufferPages); + return IoMmuFreeCommonBuffer (CommonBufferHeader, CommonBufferPages); } /** @@ -878,6 +860,11 @@ IoMmuUnmapAllMappings ( TRUE // MemoryMapLocked ); } + + // + // Release the reserved shared memory as well. + // + IoMmuReleaseReservedSharedMem (TRUE); } /** @@ -936,6 +923,19 @@ InstallIoMmuProtocol ( goto CloseExitBootEvent; } + // + // Currently only Tdx guest support Reserved shared memory for DMA operation. + // + if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + mReservedSharedMemSupported = TRUE; + Status = IoMmuInitReservedSharedMem (); + if (EFI_ERROR (Status)) { + mReservedSharedMemSupported = FALSE; + } else { + DEBUG ((DEBUG_INFO, "%a: Feature of reserved memory for DMA is supported.\n", __FUNCTION__)); + } + } + return EFI_SUCCESS; CloseExitBootEvent: diff --git a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c new file mode 100644 index 0000000000..2675223aa0 --- /dev/null +++ b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c @@ -0,0 +1,465 @@ +/** @file + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ +#include +#include +#include +#include +#include +#include +#include "IoMmuInternal.h" + +extern BOOLEAN mReservedSharedMemSupported; + +#define SIZE_OF_MEM_RANGE(MemRange) (MemRange->HeaderSize + MemRange->DataSize) + +#define RESERVED_MEM_BITMAP_4K_MASK 0xf +#define RESERVED_MEM_BITMAP_32K_MASK 0xff0 +#define RESERVED_MEM_BITMAP_128K_MASK 0x3000 +#define RESERVED_MEM_BITMAP_1M_MASK 0x40000 +#define RESERVED_MEM_BITMAP_2M_MASK 0x180000 +#define RESERVED_MEM_BITMAP_MASK 0x1fffff + +/** + * mReservedMemRanges describes the layout of the reserved memory. + * The reserved memory consists of disfferent size of memory region. + * The pieces of memory with the same size are managed by one entry + * in the mReservedMemRanges. All the pieces of memories are managed by + * mReservedMemBitmap which is a UINT32. It means it can manage at most + * 32 pieces of memory. Because of the layout of CommonBuffer + * (1-page header + n-page data), a piece of reserved memory consists of + * 2 parts: Header + Data. + * + * So put all these together, mReservedMemRanges and mReservedMemBitmap + * are designed to manage the reserved memory. + * + * Use the second entry of mReservedMemRanges as an example. + * { RESERVED_MEM_BITMAP_32K_MASK, 4, 8, SIZE_32KB, SIZE_4KB, 0 }, + * - RESERVED_MEM_BITMAP_32K_MASK is 0xff0. It means bit4-11 in mReservedMemBitmap + * is reserved for 32K size memory. + * - 4 is the shift of mReservedMemBitmap. + * - 8 means there are 8 pieces of 32K size memory. + * - SIZE_32KB indicates the size of Data part. + * - SIZE_4KB is the size of Header part. + * - 0 is the start address of this memory range which will be populated when + * the reserved memory is initialized. + * + * The size and count of the memory region are derived from the experience. For + * a typical grub boot, there are about 5100 IoMmu/DMA operation. Most of these + * DMA operation require the memory with size less than 32K (~5080). But we find + * in grub boot there may be 2 DMA operation which require for the memory larger + * than 1M. And these 2 DMA operation occur concurrently. So we reserve 2 pieces + * of memory with size of SIZE_2MB. This is for the best boot performance. + * + * If all the reserved memory are exausted, then it will fall back to the legacy + * memory allocation as before. + */ +STATIC IOMMU_RESERVED_MEM_RANGE mReservedMemRanges[] = { + { RESERVED_MEM_BITMAP_4K_MASK, 0, 4, SIZE_4KB, SIZE_4KB, 0 }, + { RESERVED_MEM_BITMAP_32K_MASK, 4, 8, SIZE_32KB, SIZE_4KB, 0 }, + { RESERVED_MEM_BITMAP_128K_MASK, 12, 2, SIZE_128KB, SIZE_4KB, 0 }, + { RESERVED_MEM_BITMAP_1M_MASK, 14, 1, SIZE_1MB, SIZE_4KB, 0 }, + { RESERVED_MEM_BITMAP_2M_MASK, 15, 2, SIZE_2MB, SIZE_4KB, 0 }, +}; + +// +// Bitmap of the allocation of reserved memory. +// +STATIC UINT32 mReservedMemBitmap = 0; + +// +// Start address of the reserved memory region. +// +STATIC EFI_PHYSICAL_ADDRESS mReservedSharedMemAddress = 0; + +// +// Total size of the reserved memory region. +// +STATIC UINT32 mReservedSharedMemSize = 0; + +/** + * Calculate the size of reserved memory. + * + * @retval UINT32 Size of the reserved memory + */ +STATIC +UINT32 +CalcuateReservedMemSize ( + VOID + ) +{ + UINT32 Index; + IOMMU_RESERVED_MEM_RANGE *MemRange; + + if (mReservedSharedMemSize != 0) { + return mReservedSharedMemSize; + } + + for (Index = 0; Index < ARRAY_SIZE (mReservedMemRanges); Index++) { + MemRange = &mReservedMemRanges[Index]; + mReservedSharedMemSize += (SIZE_OF_MEM_RANGE (MemRange) * MemRange->Slots); + } + + return mReservedSharedMemSize; +} + +/** + * Allocate a memory region and convert it to be shared. This memory region will be + * used in the DMA operation. + * + * The pre-alloc memory contains pieces of memory regions with different size. The + * allocation of the shared memory regions are indicated by a 32-bit bitmap (mReservedMemBitmap). + * + * The memory regions are consumed by IoMmuAllocateBuffer (in which CommonBuffer is allocated) and + * IoMmuMap (in which bounce buffer is allocated). + * + * The CommonBuffer contains 2 parts, one page for CommonBufferHeader which is private memory, + * the other part is shared memory. So the layout of a piece of memory region after initialization + * looks like: + * + * |------------|----------------------------| + * | Header | Data | <-- a piece of pre-alloc memory region + * | 4k, private| 4k/32k/128k/etc, shared | + * |-----------------------------------------| + * + * @retval EFI_SUCCESS Successfully initialize the reserved memory. + * @retval EFI_UNSUPPORTED This feature is not supported. + */ +EFI_STATUS +IoMmuInitReservedSharedMem ( + VOID + ) +{ + EFI_STATUS Status; + UINT32 Index1, Index2; + UINTN TotalPages; + IOMMU_RESERVED_MEM_RANGE *MemRange; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + + if (!mReservedSharedMemSupported) { + return EFI_UNSUPPORTED; + } + + TotalPages = EFI_SIZE_TO_PAGES (CalcuateReservedMemSize ()); + + PhysicalAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)AllocatePages (TotalPages); + DEBUG (( + DEBUG_VERBOSE, + "%a: ReservedMem (%d pages) address = 0x%llx\n", + __FUNCTION__, + TotalPages, + PhysicalAddress + )); + + mReservedMemBitmap = 0; + mReservedSharedMemAddress = PhysicalAddress; + + for (Index1 = 0; Index1 < ARRAY_SIZE (mReservedMemRanges); Index1++) { + MemRange = &mReservedMemRanges[Index1]; + MemRange->StartAddressOfMemRange = PhysicalAddress; + + for (Index2 = 0; Index2 < MemRange->Slots; Index2++) { + Status = MemEncryptTdxSetPageSharedBit ( + 0, + (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize), + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } + + PhysicalAddress += (MemRange->Slots * SIZE_OF_MEM_RANGE (MemRange)); + } + + return EFI_SUCCESS; +} + +/** + * Release the pre-alloc shared memory. + * + * @retval EFI_SUCCESS Successfully release the shared memory + */ +EFI_STATUS +IoMmuReleaseReservedSharedMem ( + BOOLEAN MemoryMapLocked + ) +{ + EFI_STATUS Status; + UINT32 Index1, Index2; + IOMMU_RESERVED_MEM_RANGE *MemRange; + + if (!mReservedSharedMemSupported) { + return EFI_SUCCESS; + } + + for (Index1 = 0; Index1 < ARRAY_SIZE (mReservedMemRanges); Index1++) { + MemRange = &mReservedMemRanges[Index1]; + for (Index2 = 0; Index2 < MemRange->Slots; Index2++) { + Status = MemEncryptTdxClearPageSharedBit ( + 0, + (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize), + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } + } + + if (!MemoryMapLocked) { + FreePages ((VOID *)(UINTN)mReservedSharedMemAddress, EFI_SIZE_TO_PAGES (CalcuateReservedMemSize ())); + mReservedSharedMemAddress = 0; + mReservedMemBitmap = 0; + } + + mReservedSharedMemSupported = FALSE; + + return EFI_SUCCESS; +} + +/** + * Allocate from the reserved memory pool. + * If the reserved shared memory is exausted or there is no suitalbe size, it turns + * to the LegacyAllocateBuffer. + * + * @param Type Allocate type + * @param MemoryType The memory type to be allocated + * @param Pages Pages to be allocated. + * @param ReservedMemBitmap Bitmap of the allocated memory region + * @param PhysicalAddress Pointer to the data part of allocated memory region + * + * @retval EFI_SUCCESS Successfully allocate the buffer + * @retval Other As the error code indicates + */ +STATIC +EFI_STATUS +InternalAllocateBuffer ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + IN OUT UINT32 *ReservedMemBitmap, + IN OUT EFI_PHYSICAL_ADDRESS *PhysicalAddress + ) +{ + UINT32 MemBitmap; + UINT8 Index; + IOMMU_RESERVED_MEM_RANGE *MemRange; + UINTN PagesOfLastMemRange; + + *ReservedMemBitmap = 0; + + if (Pages == 0) { + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; + } + + if (!mReservedSharedMemSupported) { + goto LegacyAllocateBuffer; + } + + if (mReservedSharedMemAddress == 0) { + goto LegacyAllocateBuffer; + } + + PagesOfLastMemRange = 0; + + for (Index = 0; Index < ARRAY_SIZE (mReservedMemRanges); Index++) { + if ((Pages > PagesOfLastMemRange) && (Pages <= EFI_SIZE_TO_PAGES (mReservedMemRanges[Index].DataSize))) { + break; + } + + PagesOfLastMemRange = EFI_SIZE_TO_PAGES (mReservedMemRanges[Index].DataSize); + } + + if (Index == ARRAY_SIZE (mReservedMemRanges)) { + // There is no suitable size of reserved memory. Turn to legacy allocate. + goto LegacyAllocateBuffer; + } + + MemRange = &mReservedMemRanges[Index]; + + if ((mReservedMemBitmap & MemRange->BitmapMask) == MemRange->BitmapMask) { + // The reserved memory is exausted. Turn to legacy allocate. + goto LegacyAllocateBuffer; + } + + MemBitmap = (mReservedMemBitmap & MemRange->BitmapMask) >> MemRange->Shift; + + for (Index = 0; Index < MemRange->Slots; Index++) { + if ((MemBitmap & (UINT8)(1<Slots); + + *PhysicalAddress = MemRange->StartAddressOfMemRange + Index * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize; + *ReservedMemBitmap = (UINT32)(1 << (Index + MemRange->Shift)); + + DEBUG (( + DEBUG_VERBOSE, + "%a: range-size: %lx, start-address=0x%llx, pages=0x%llx, bits=0x%lx, bitmap: %lx => %lx\n", + __FUNCTION__, + MemRange->DataSize, + *PhysicalAddress, + Pages, + *ReservedMemBitmap, + mReservedMemBitmap, + mReservedMemBitmap | *ReservedMemBitmap + )); + + return EFI_SUCCESS; + +LegacyAllocateBuffer: + + *ReservedMemBitmap = 0; + return gBS->AllocatePages (Type, MemoryType, Pages, PhysicalAddress); +} + +/** + * Allocate reserved shared memory for bounce buffer. + * + * @param Type Allocate type + * @param MemoryType The memory type to be allocated + * @param MapInfo Pointer to the MAP_INFO + * + * @retval EFI_SUCCESS Successfully allocate the bounce buffer + * @retval Other As the error code indicates + + */ +EFI_STATUS +IoMmuAllocateBounceBuffer ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN OUT MAP_INFO *MapInfo + ) +{ + EFI_STATUS Status; + UINT32 ReservedMemBitmap; + + ReservedMemBitmap = 0; + Status = InternalAllocateBuffer ( + Type, + MemoryType, + MapInfo->NumberOfPages, + &ReservedMemBitmap, + &MapInfo->PlainTextAddress + ); + MapInfo->ReservedMemBitmap = ReservedMemBitmap; + mReservedMemBitmap |= ReservedMemBitmap; + + ASSERT (Status == EFI_SUCCESS); + + return Status; +} + +/** + * Free the bounce buffer allocated in IoMmuAllocateBounceBuffer. + * + * @param MapInfo Pointer to the MAP_INFO + * @return EFI_SUCCESS Successfully free the bounce buffer. + */ +EFI_STATUS +IoMmuFreeBounceBuffer ( + IN OUT MAP_INFO *MapInfo + ) +{ + if (MapInfo->ReservedMemBitmap == 0) { + gBS->FreePages (MapInfo->PlainTextAddress, MapInfo->NumberOfPages); + } else { + DEBUG (( + DEBUG_VERBOSE, + "%a: PlainTextAddress=0x%Lx, bits=0x%Lx, bitmap: %Lx => %Lx\n", + __FUNCTION__, + MapInfo->PlainTextAddress, + MapInfo->ReservedMemBitmap, + mReservedMemBitmap, + mReservedMemBitmap & ((UINT32)(~MapInfo->ReservedMemBitmap)) + )); + MapInfo->PlainTextAddress = 0; + mReservedMemBitmap &= (UINT32)(~MapInfo->ReservedMemBitmap); + MapInfo->ReservedMemBitmap = 0; + } + + return EFI_SUCCESS; +} + +/** + * Allocate CommonBuffer from pre-allocated shared memory. + * + * @param MemoryType Memory type + * @param CommonBufferPages Pages of CommonBuffer + * @param PhysicalAddress Allocated physical address + * @param ReservedMemBitmap Bitmap which indicates the allocation of reserved memory + * + * @retval EFI_SUCCESS Successfully allocate the common buffer + * @retval Other As the error code indicates + */ +EFI_STATUS +IoMmuAllocateCommonBuffer ( + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN CommonBufferPages, + OUT EFI_PHYSICAL_ADDRESS *PhysicalAddress, + OUT UINT32 *ReservedMemBitmap + ) +{ + EFI_STATUS Status; + + Status = InternalAllocateBuffer ( + AllocateMaxAddress, + MemoryType, + CommonBufferPages, + ReservedMemBitmap, + PhysicalAddress + ); + ASSERT (Status == EFI_SUCCESS); + + mReservedMemBitmap |= *ReservedMemBitmap; + + if (*ReservedMemBitmap != 0) { + *PhysicalAddress -= SIZE_4KB; + } + + return Status; +} + +/** + * Free CommonBuffer which is allocated by IoMmuAllocateCommonBuffer(). + * + * @param CommonBufferHeader Pointer to the CommonBufferHeader + * @param CommonBufferPages Pages of CommonBuffer + * + * @retval EFI_SUCCESS Successfully free the common buffer + * @retval Other As the error code indicates + */ +EFI_STATUS +IoMmuFreeCommonBuffer ( + IN COMMON_BUFFER_HEADER *CommonBufferHeader, + IN UINTN CommonBufferPages + ) +{ + if (!mReservedSharedMemSupported) { + goto LegacyFreeCommonBuffer; + } + + if (CommonBufferHeader->ReservedMemBitmap == 0) { + goto LegacyFreeCommonBuffer; + } + + DEBUG (( + DEBUG_VERBOSE, + "%a: CommonBuffer=0x%Lx, bits=0x%Lx, bitmap: %Lx => %Lx\n", + __FUNCTION__, + (UINT64)(UINTN)CommonBufferHeader + SIZE_4KB, + CommonBufferHeader->ReservedMemBitmap, + mReservedMemBitmap, + mReservedMemBitmap & ((UINT32)(~CommonBufferHeader->ReservedMemBitmap)) + )); + + mReservedMemBitmap &= (UINT32)(~CommonBufferHeader->ReservedMemBitmap); + return EFI_SUCCESS; + +LegacyFreeCommonBuffer: + return gBS->FreePages ((UINTN)CommonBufferHeader, CommonBufferPages); +} diff --git a/OvmfPkg/IoMmuDxe/IoMmuDxe.inf b/OvmfPkg/IoMmuDxe/IoMmuDxe.inf index e10be1dcff..2192145ea6 100644 --- a/OvmfPkg/IoMmuDxe/IoMmuDxe.inf +++ b/OvmfPkg/IoMmuDxe/IoMmuDxe.inf @@ -21,6 +21,7 @@ AmdSevIoMmu.c AmdSevIoMmu.h IoMmuDxe.c + IoMmuBuffer.c [Packages] MdePkg/MdePkg.dec diff --git a/OvmfPkg/IoMmuDxe/IoMmuInternal.h b/OvmfPkg/IoMmuDxe/IoMmuInternal.h new file mode 100644 index 0000000000..936c35aa53 --- /dev/null +++ b/OvmfPkg/IoMmuDxe/IoMmuInternal.h @@ -0,0 +1,179 @@ +/** @file + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef IOMMU_INTERNAL_H_ +#define IOMMU_INTERNAL_H_ + +#include +#include +#include +#include + +#define MAP_INFO_SIG SIGNATURE_64 ('M', 'A', 'P', '_', 'I', 'N', 'F', 'O') + +typedef struct { + UINT64 Signature; + LIST_ENTRY Link; + EDKII_IOMMU_OPERATION Operation; + UINTN NumberOfBytes; + UINTN NumberOfPages; + EFI_PHYSICAL_ADDRESS CryptedAddress; + EFI_PHYSICAL_ADDRESS PlainTextAddress; + UINT32 ReservedMemBitmap; +} MAP_INFO; + +#define COMMON_BUFFER_SIG SIGNATURE_64 ('C', 'M', 'N', 'B', 'U', 'F', 'F', 'R') + +#pragma pack (1) +// +// The following structure enables Map() and Unmap() to perform in-place +// decryption and encryption, respectively, for BusMasterCommonBuffer[64] +// operations, without dynamic memory allocation or release. +// +// Both COMMON_BUFFER_HEADER and COMMON_BUFFER_HEADER.StashBuffer are allocated +// by AllocateBuffer() and released by FreeBuffer(). +// +typedef struct { + UINT64 Signature; + + // + // Always allocated from EfiBootServicesData type memory, and always + // encrypted. + // + VOID *StashBuffer; + + // + // Bitmap of reserved memory + // + UINT32 ReservedMemBitmap; + + // + // Followed by the actual common buffer, starting at the next page. + // +} COMMON_BUFFER_HEADER; + +// +// This data structure defines a memory range in the reserved memory region. +// Please refer to IoMmuInitReservedSharedMem() for detailed information. +// +// The memory region looks like: +// |------------|----------------------------| +// | Header | Data | +// | 4k, private| 4k/32k/128k/etc, shared | +// |-----------------------------------------| +// +typedef struct { + UINT32 BitmapMask; + UINT32 Shift; + UINT32 Slots; + UINT32 DataSize; + UINT32 HeaderSize; + EFI_PHYSICAL_ADDRESS StartAddressOfMemRange; +} IOMMU_RESERVED_MEM_RANGE; +#pragma pack() + +/** + * Allocate a memory region and convert it to be shared. This memory region will be + * used in the DMA operation. + * + * The pre-alloc memory contains pieces of memory regions with different size. The + * allocation of the shared memory regions are indicated by a 32-bit bitmap (mReservedMemBitmap). + * + * The memory regions are consumed by IoMmuAllocateBuffer (in which CommonBuffer is allocated) and + * IoMmuMap (in which bounce buffer is allocated). + * + * The CommonBuffer contains 2 parts, one page for CommonBufferHeader which is private memory, + * the other part is shared memory. So the layout of a piece of memory region after initialization + * looks like: + * + * |------------|----------------------------| + * | Header | Data | <-- a piece of pre-alloc memory region + * | 4k, private| 4k/32k/128k/etc, shared | + * |-----------------------------------------| + * + * @retval EFI_SUCCESS Successfully initialize the reserved memory. + * @retval EFI_UNSUPPORTED This feature is not supported. + */ +EFI_STATUS +IoMmuInitReservedSharedMem ( + VOID + ); + +/** + * Release the pre-alloc shared memory. + * + * @retval EFI_SUCCESS Successfully release the shared memory + */ +EFI_STATUS +IoMmuReleaseReservedSharedMem ( + BOOLEAN MemoryMapLocked + ); + +/** + * Allocate reserved shared memory for bounce buffer. + * + * @param Type Allocate type + * @param MemoryType The memory type to be allocated + * @param MapInfo Pointer to the MAP_INFO + * + * @retval EFI_SUCCESS Successfully allocate the bounce buffer + * @retval Other As the error code indicates + */ +EFI_STATUS +IoMmuAllocateBounceBuffer ( + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN OUT MAP_INFO *MapInfo + ); + +/** + * Free the bounce buffer allocated in IoMmuAllocateBounceBuffer. + * + * @param MapInfo Pointer to the MAP_INFO + * @return EFI_SUCCESS Successfully free the bounce buffer. + */ +EFI_STATUS +IoMmuFreeBounceBuffer ( + IN OUT MAP_INFO *MapInfo + ); + +/** + * Allocate CommonBuffer from pre-allocated shared memory. + * + * @param MemoryType Memory type + * @param CommonBufferPages Pages of CommonBuffer + * @param PhysicalAddress Allocated physical address + * @param ReservedMemBitmap Bitmap which indicates the allocation of reserved memory + * + * @retval EFI_SUCCESS Successfully allocate the common buffer + * @retval Other As the error code indicates + */ +EFI_STATUS +IoMmuAllocateCommonBuffer ( + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN CommonBufferPages, + OUT EFI_PHYSICAL_ADDRESS *PhysicalAddress, + OUT UINT32 *ReservedMemBitmap + ); + +/** + * Free CommonBuffer which is allocated by IoMmuAllocateCommonBuffer(). + * + * @param CommonBufferHeader Pointer to the CommonBufferHeader + * @param CommonBufferPages Pages of CommonBuffer + * + * @retval EFI_SUCCESS Successfully free the common buffer + * @retval Other As the error code indicates + */ +EFI_STATUS +IoMmuFreeCommonBuffer ( + IN COMMON_BUFFER_HEADER *CommonBufferHeader, + IN UINTN CommonBufferPages + ); + +#endif From 1f5c6e4cb67b603a03470dd687a867de45b73a3c Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 15 Dec 2022 13:18:08 +0800 Subject: [PATCH 0401/1529] OvmfPkg/IoMmuDxe: Rename AmdSevIoMmu to CcIoMmu BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4171 IoMmuDxe once was designed to support DMA operation when SEV is enabled. After TDX is enabled in IoMmuDxe, some files' name in IoMmuDxe need to be more general. So this patch rename: AmdSevIoMmu.h -> CcIoMmu.h AmdSevIoMmu.c -> CcIoMmu.c Accordingly there are some udates in IoMmuDxe.c and IoMmuDxe.inf. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu Reviewed-by: Tom Lendacky --- OvmfPkg/IoMmuDxe/{AmdSevIoMmu.c => CcIoMmu.c} | 2 +- OvmfPkg/IoMmuDxe/{AmdSevIoMmu.h => CcIoMmu.h} | 0 OvmfPkg/IoMmuDxe/IoMmuDxe.c | 2 +- OvmfPkg/IoMmuDxe/IoMmuDxe.inf | 5 ++--- 4 files changed, 4 insertions(+), 5 deletions(-) rename OvmfPkg/IoMmuDxe/{AmdSevIoMmu.c => CcIoMmu.c} (96%) rename OvmfPkg/IoMmuDxe/{AmdSevIoMmu.h => CcIoMmu.h} (100%) diff --git a/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c b/OvmfPkg/IoMmuDxe/CcIoMmu.c similarity index 96% rename from OvmfPkg/IoMmuDxe/AmdSevIoMmu.c rename to OvmfPkg/IoMmuDxe/CcIoMmu.c index 77e46bbf4a..1479af4698 100644 --- a/OvmfPkg/IoMmuDxe/AmdSevIoMmu.c +++ b/OvmfPkg/IoMmuDxe/CcIoMmu.c @@ -14,7 +14,7 @@ #include #include -#include "AmdSevIoMmu.h" +#include "CcIoMmu.h" #include "IoMmuInternal.h" // diff --git a/OvmfPkg/IoMmuDxe/AmdSevIoMmu.h b/OvmfPkg/IoMmuDxe/CcIoMmu.h similarity index 100% rename from OvmfPkg/IoMmuDxe/AmdSevIoMmu.h rename to OvmfPkg/IoMmuDxe/CcIoMmu.h diff --git a/OvmfPkg/IoMmuDxe/IoMmuDxe.c b/OvmfPkg/IoMmuDxe/IoMmuDxe.c index 86777dd05c..aab6d8b906 100644 --- a/OvmfPkg/IoMmuDxe/IoMmuDxe.c +++ b/OvmfPkg/IoMmuDxe/IoMmuDxe.c @@ -9,7 +9,7 @@ **/ -#include "AmdSevIoMmu.h" +#include "CcIoMmu.h" EFI_STATUS EFIAPI diff --git a/OvmfPkg/IoMmuDxe/IoMmuDxe.inf b/OvmfPkg/IoMmuDxe/IoMmuDxe.inf index 2192145ea6..17fca52856 100644 --- a/OvmfPkg/IoMmuDxe/IoMmuDxe.inf +++ b/OvmfPkg/IoMmuDxe/IoMmuDxe.inf @@ -18,8 +18,8 @@ ENTRY_POINT = IoMmuDxeEntryPoint [Sources] - AmdSevIoMmu.c - AmdSevIoMmu.h + CcIoMmu.c + CcIoMmu.h IoMmuDxe.c IoMmuBuffer.c @@ -27,7 +27,6 @@ MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec OvmfPkg/OvmfPkg.dec -# UefiCpuPkg/UefiCpuPkg.dec [LibraryClasses] BaseLib From f681a90089f8a2fe59455e88d0ce82940c1bde01 Mon Sep 17 00:00:00 2001 From: Tom Lendacky Date: Thu, 15 Dec 2022 13:18:09 +0800 Subject: [PATCH 0402/1529] OvmfPkg/IoMmuDxe: Add SEV support for reserved shared memory Add support to use the reserved shared memory within the IoMmu library. This improves boot times for all SEV guests, with SEV-SNP benefiting the most as it avoids the page state change call to the hypervisor. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Min Xu Cc: Gerd Hoffmann Acked-by: Jiewen Yao Signed-off-by: Tom Lendacky --- OvmfPkg/IoMmuDxe/CcIoMmu.c | 82 +++++++++++++++++----------------- OvmfPkg/IoMmuDxe/IoMmuBuffer.c | 54 +++++++++++++++++----- 2 files changed, 83 insertions(+), 53 deletions(-) diff --git a/OvmfPkg/IoMmuDxe/CcIoMmu.c b/OvmfPkg/IoMmuDxe/CcIoMmu.c index 1479af4698..7c2843cd23 100644 --- a/OvmfPkg/IoMmuDxe/CcIoMmu.c +++ b/OvmfPkg/IoMmuDxe/CcIoMmu.c @@ -223,30 +223,32 @@ IoMmuMap ( goto FreeMapInfo; } - if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + if (MapInfo->ReservedMemBitmap == 0) { // - // Clear the memory encryption mask on the plaintext buffer. - // - Status = MemEncryptSevClearPageEncMask ( - 0, - MapInfo->PlainTextAddress, - MapInfo->NumberOfPages - ); - } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { - // - // Set the memory shared bit. // If MapInfo->ReservedMemBitmap is 0, it means the bounce buffer is not allocated // from the pre-allocated shared memory, so it must be converted to shared memory here. // - if (MapInfo->ReservedMemBitmap == 0) { + if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + // + // Clear the memory encryption mask on the plaintext buffer. + // + Status = MemEncryptSevClearPageEncMask ( + 0, + MapInfo->PlainTextAddress, + MapInfo->NumberOfPages + ); + } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + // + // Set the memory shared bit. + // Status = MemEncryptTdxSetPageSharedBit ( 0, MapInfo->PlainTextAddress, MapInfo->NumberOfPages ); + } else { + ASSERT (FALSE); } - } else { - ASSERT (FALSE); } ASSERT_EFI_ERROR (Status); @@ -396,30 +398,30 @@ IoMmuUnmapWorker ( break; } - if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { - // - // Restore the memory encryption mask on the area we used to hold the - // plaintext. - // - Status = MemEncryptSevSetPageEncMask ( - 0, - MapInfo->PlainTextAddress, - MapInfo->NumberOfPages - ); - } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { - // - // Restore the memory shared bit mask on the area we used to hold the - // plaintext. - // - if (MapInfo->ReservedMemBitmap == 0) { + if (MapInfo->ReservedMemBitmap == 0) { + if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + // + // Restore the memory encryption mask on the area we used to hold the + // plaintext. + // + Status = MemEncryptSevSetPageEncMask ( + 0, + MapInfo->PlainTextAddress, + MapInfo->NumberOfPages + ); + } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + // + // Restore the memory shared bit mask on the area we used to hold the + // plaintext. + // Status = MemEncryptTdxClearPageSharedBit ( 0, MapInfo->PlainTextAddress, MapInfo->NumberOfPages ); + } else { + ASSERT (FALSE); } - } else { - ASSERT (FALSE); } ASSERT_EFI_ERROR (Status); @@ -924,16 +926,14 @@ InstallIoMmuProtocol ( } // - // Currently only Tdx guest support Reserved shared memory for DMA operation. + // For CC guests, use reserved shared memory for DMA operation. // - if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { - mReservedSharedMemSupported = TRUE; - Status = IoMmuInitReservedSharedMem (); - if (EFI_ERROR (Status)) { - mReservedSharedMemSupported = FALSE; - } else { - DEBUG ((DEBUG_INFO, "%a: Feature of reserved memory for DMA is supported.\n", __FUNCTION__)); - } + mReservedSharedMemSupported = TRUE; + Status = IoMmuInitReservedSharedMem (); + if (EFI_ERROR (Status)) { + mReservedSharedMemSupported = FALSE; + } else { + DEBUG ((DEBUG_INFO, "%a: Feature of reserved memory for DMA is supported.\n", __FUNCTION__)); } return EFI_SUCCESS; diff --git a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c index 2675223aa0..83c7c59583 100644 --- a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c +++ b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c @@ -9,7 +9,9 @@ #include #include #include +#include #include +#include #include #include "IoMmuInternal.h" @@ -139,6 +141,7 @@ IoMmuInitReservedSharedMem ( UINTN TotalPages; IOMMU_RESERVED_MEM_RANGE *MemRange; EFI_PHYSICAL_ADDRESS PhysicalAddress; + UINT64 SharedAddress; if (!mReservedSharedMemSupported) { return EFI_UNSUPPORTED; @@ -163,12 +166,25 @@ IoMmuInitReservedSharedMem ( MemRange->StartAddressOfMemRange = PhysicalAddress; for (Index2 = 0; Index2 < MemRange->Slots; Index2++) { - Status = MemEncryptTdxSetPageSharedBit ( - 0, - (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize), - EFI_SIZE_TO_PAGES (MemRange->DataSize) - ); - ASSERT (!EFI_ERROR (Status)); + SharedAddress = (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize); + + if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + Status = MemEncryptSevClearPageEncMask ( + 0, + SharedAddress, + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + Status = MemEncryptTdxSetPageSharedBit ( + 0, + SharedAddress, + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } else { + ASSERT (FALSE); + } } PhysicalAddress += (MemRange->Slots * SIZE_OF_MEM_RANGE (MemRange)); @@ -190,6 +206,7 @@ IoMmuReleaseReservedSharedMem ( EFI_STATUS Status; UINT32 Index1, Index2; IOMMU_RESERVED_MEM_RANGE *MemRange; + UINT64 SharedAddress; if (!mReservedSharedMemSupported) { return EFI_SUCCESS; @@ -198,12 +215,25 @@ IoMmuReleaseReservedSharedMem ( for (Index1 = 0; Index1 < ARRAY_SIZE (mReservedMemRanges); Index1++) { MemRange = &mReservedMemRanges[Index1]; for (Index2 = 0; Index2 < MemRange->Slots; Index2++) { - Status = MemEncryptTdxClearPageSharedBit ( - 0, - (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize), - EFI_SIZE_TO_PAGES (MemRange->DataSize) - ); - ASSERT (!EFI_ERROR (Status)); + SharedAddress = (UINT64)(UINTN)(MemRange->StartAddressOfMemRange + Index2 * SIZE_OF_MEM_RANGE (MemRange) + MemRange->HeaderSize); + + if (CC_GUEST_IS_SEV (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + Status = MemEncryptSevSetPageEncMask ( + 0, + SharedAddress, + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } else if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { + Status = MemEncryptTdxClearPageSharedBit ( + 0, + SharedAddress, + EFI_SIZE_TO_PAGES (MemRange->DataSize) + ); + ASSERT (!EFI_ERROR (Status)); + } else { + ASSERT (FALSE); + } } } From 68d5f19171e6d0ce1e32ff217cd191ece131794e Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 15 Dec 2022 13:18:10 +0800 Subject: [PATCH 0403/1529] Maintainers: Update OvmfPkg/IoMmuDxe https://bugzilla.tianocore.org/show_bug.cgi?id=4171 AmdSevIoMmu.* is renamed as CcIoMmu*. The related section in Maintainers.txt should be updated as well. Cc: Michael D Kinney Cc: Liming Gao Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Jiewen Yao Signed-off-by: Min Xu Reviewed-by: Tom Lendacky --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index 6a92922258..13e1335a57 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -478,7 +478,7 @@ F: OvmfPkg/AmdSev/ F: OvmfPkg/AmdSevDxe/ F: OvmfPkg/Include/Guid/ConfidentialComputingSecret.h F: OvmfPkg/Include/Library/MemEncryptSevLib.h -F: OvmfPkg/IoMmuDxe/AmdSevIoMmu.* +F: OvmfPkg/IoMmuDxe/CcIoMmu.* F: OvmfPkg/Library/BaseMemEncryptSevLib/ F: OvmfPkg/Library/PlatformBootManagerLibGrub/ F: OvmfPkg/Library/CcExitLib/ From f594b87d0013c8fe773de003e23e7fff2e6501e3 Mon Sep 17 00:00:00 2001 From: "Kuo, Ted" Date: Fri, 16 Dec 2022 20:46:26 +0800 Subject: [PATCH 0404/1529] UefiCpuPkg: Supporting S3 in 64bit PEI https://bugzilla.tianocore.org/show_bug.cgi?id=4195 1.Updated the GDT table in VTF0 to align with the one in S3Resume2Pei. By doing so can simplify the changes to enable S3 in 64bit PEI. 2.Use SwitchStack() between PEI and SMM in S3 resume path when both are in the same execution mode. 3.Transfer from PEI to OS waking vector by calling SwitchStack() when both are in the same execution mode. 4.Removed the debug assertion in S3Resume.c to support 64bit PEI. Reviewed-by: Ray Ni Reviewed-by: Zhiguang Liu Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Cc: Ashraf Ali S Cc: Chinni B Duggapu Signed-off-by: Ted Kuo --- UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c | 13 ++- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 1 + .../ResetVector/Vtf0/Ia16/Real16ToFlat32.asm | 63 ++++++++---- .../Universal/Acpi/S3Resume2Pei/S3Resume.c | 97 ++++++++++++------- 4 files changed, 117 insertions(+), 57 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c index 9b45c442c9..fb4a44eab6 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c @@ -1,7 +1,7 @@ /** @file Code for Processor S3 restoration -Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -783,7 +783,11 @@ SmmRestoreCpu ( SmmS3ResumeState = mSmmS3ResumeState; ASSERT (SmmS3ResumeState != NULL); - if (SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_64) { + // + // Setup 64bit IDT in 64bit SMM env when called from 32bit PEI. + // Note: 64bit PEI and 32bit DXE is not a supported combination. + // + if ((SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_64) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode) == TRUE)) { // // Save the IA32 IDT Descriptor // @@ -846,9 +850,10 @@ SmmRestoreCpu ( DEBUG ((DEBUG_INFO, "SMM S3 Return Stack Pointer = %x\n", SmmS3ResumeState->ReturnStackPointer)); // - // If SMM is in 32-bit mode, then use SwitchStack() to resume PEI Phase + // If SMM is in 32-bit mode or PcdDxeIplSwitchToLongMode is FALSE, then use SwitchStack() to resume PEI Phase. + // Note: 64bit PEI and 32bit DXE is not a supported combination. // - if (SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_32) { + if ((SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_32) || (FeaturePcdGet (PcdDxeIplSwitchToLongMode) == FALSE)) { DEBUG ((DEBUG_INFO, "Call SwitchStack() to return to S3 Resume in PEI Phase\n")); SwitchStack ( diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index deef00f9c6..b4b327f60c 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -124,6 +124,7 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileEnable ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileRingBuffer ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmFeatureControlMsrLock ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode ## CONSUMES [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/ResetVector/Vtf0/Ia16/Real16ToFlat32.asm b/UefiCpuPkg/ResetVector/Vtf0/Ia16/Real16ToFlat32.asm index 0e79a3984b..f59fc6ead4 100644 --- a/UefiCpuPkg/ResetVector/Vtf0/Ia16/Real16ToFlat32.asm +++ b/UefiCpuPkg/ResetVector/Vtf0/Ia16/Real16ToFlat32.asm @@ -2,7 +2,7 @@ ; @file ; Transition from 16 bit real mode into 32 bit flat protected mode ; -; Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved.
+; Copyright (c) 2008 - 2022, Intel Corporation. All rights reserved.
; SPDX-License-Identifier: BSD-2-Clause-Patent ; ;------------------------------------------------------------------------------ @@ -92,7 +92,7 @@ ALIGN 16 GDT_BASE: ; null descriptor -NULL_SEL equ $-GDT_BASE +NULL_SEL equ $-GDT_BASE ; Selector [0x0] DW 0 ; limit 15:0 DW 0 ; base 15:0 DB 0 ; base 23:16 @@ -100,42 +100,67 @@ NULL_SEL equ $-GDT_BASE DB 0 ; limit 19:16, flags DB 0 ; base 31:24 +; Spare segment descriptor +SPARE1_SEL equ $-GDT_BASE ; Selector [0x8] + DW 0 ; limit 15:0 + DW 0 ; base 15:0 + DB 0 ; base 23:16 + DB 0 ; sys flag, dpl, type + DB 0 ; limit 19:16, flags + DB 0 ; base 31:24 + +; linear code segment descriptor +LINEAR_CODE_SEL equ $-GDT_BASE ; Selector [0x10] + DW 0xffff ; limit 15:0 + DW 0 ; base 15:0 + DB 0 ; base 23:16 + DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE32_TYPE) ; 09Bh + DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) ; 0CFh + DB 0 ; base 31:24 + ; linear data segment descriptor -LINEAR_SEL equ $-GDT_BASE +LINEAR_SEL equ $-GDT_BASE ; Selector [0x18] DW 0xffff ; limit 15:0 DW 0 ; base 15:0 DB 0 ; base 23:16 - DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(DATA32_TYPE) - DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) + DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(DATA32_TYPE) ; 093h + DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) ; 0CFh DB 0 ; base 31:24 -; linear code segment descriptor -LINEAR_CODE_SEL equ $-GDT_BASE +; Spare segment descriptor +SPARE2_SEL equ $-GDT_BASE ; Selector [0x20] + DW 0 ; limit 15:0 + DW 0 ; base 15:0 + DB 0 ; base 23:16 + DB 0 ; sys flag, dpl, type + DB 0 ; limit 19:16, flags + DB 0 ; base 31:24 + +; linear code (16-bit) segment descriptor +LINEAR_CODE16_SEL equ $-GDT_BASE ; Selector [0x28] DW 0xffff ; limit 15:0 DW 0 ; base 15:0 DB 0 ; base 23:16 - DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE32_TYPE) - DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(1)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) + DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE32_TYPE) ; 09Bh + DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(0)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) ; 08Fh DB 0 ; base 31:24 -%ifdef ARCH_X64 -; linear code (64-bit) segment descriptor -LINEAR_CODE64_SEL equ $-GDT_BASE +; linear data (16-bit) segment descriptor +LINEAR_DATA16_SEL equ $-GDT_BASE ; Selector [0x30] DW 0xffff ; limit 15:0 DW 0 ; base 15:0 DB 0 ; base 23:16 - DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE64_TYPE) - DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(0)|CODE64_FLAG(1)|UPPER_LIMIT(0xf) + DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(DATA32_TYPE) ; 093h + DB 0 DB 0 ; base 31:24 -%endif -; linear code segment descriptor -LINEAR_CODE16_SEL equ $-GDT_BASE +; linear code (64-bit) segment descriptor +LINEAR_CODE64_SEL equ $-GDT_BASE ; Selector [0x38] DW 0xffff ; limit 15:0 DW 0 ; base 15:0 DB 0 ; base 23:16 - DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE32_TYPE) - DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(0)|CODE64_FLAG(0)|UPPER_LIMIT(0xf) + DB PRESENT_FLAG(1)|DPL(0)|SYSTEM_FLAG(1)|DESC_TYPE(CODE64_TYPE) ; 09Bh + DB GRANULARITY_FLAG(1)|DEFAULT_SIZE32(0)|CODE64_FLAG(1)|UPPER_LIMIT(0xf) ; 0AFh DB 0 ; base 31:24 GDT_END: diff --git a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c index 8419a4e32a..e82f179569 100644 --- a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c +++ b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c @@ -4,7 +4,7 @@ This module will execute the boot script saved during last boot and after that, control is passed to OS waking up handler. - Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -332,9 +332,8 @@ IsLongModeWakingVector ( ((Facs->OspmFlags & EFI_ACPI_4_0_OSPM_64BIT_WAKE__F) != 0)) { // Both BIOS and OS wants 64bit vector - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { - return TRUE; - } + ASSERT ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))); + return TRUE; } } @@ -521,8 +520,11 @@ S3ResumeBootOs ( // // X64 long mode waking vector // - DEBUG ((DEBUG_INFO, "Transfer to 64bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); + DEBUG ((DEBUG_INFO, "Transfer from PEI to 64bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + // + // 32bit PEI calls to 64bit OS S3 waking vector + // AsmEnablePaging64 ( 0x38, Facs->XFirmwareWakingVector, @@ -531,29 +533,58 @@ S3ResumeBootOs ( (UINT64)(UINTN)TempStackTop ); } else { - // - // Report Status code that no valid waking vector is found - // - REPORT_STATUS_CODE ( - EFI_ERROR_CODE | EFI_ERROR_MAJOR, - (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_EC_S3_OS_WAKE_ERROR) - ); - DEBUG ((DEBUG_ERROR, "Unsupported for 32bit DXE transfer to 64bit OS waking vector!\r\n")); - ASSERT (FALSE); - CpuDeadLoop (); - return; + if (sizeof (UINTN) == sizeof (UINT64)) { + // + // 64bit PEI calls to 64bit OS S3 waking vector + // + SwitchStack ( + (SWITCH_STACK_ENTRY_POINT)(UINTN)Facs->XFirmwareWakingVector, + NULL, + NULL, + (VOID *)(UINTN)TempStackTop + ); + } else { + // + // Report Status code that no valid waking vector is found. + // Note: 32bit PEI + 32bit DXE firmware calling to 64bit OS S3 waking vector is an invalid configuration. + // + REPORT_STATUS_CODE ( + EFI_ERROR_CODE | EFI_ERROR_MAJOR, + (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_EC_S3_OS_WAKE_ERROR) + ); + DEBUG ((DEBUG_ERROR, "Unsupported for 32bit DXE transfer to 64bit OS waking vector!\r\n")); + ASSERT (FALSE); + CpuDeadLoop (); + return; + } } } else { // // IA32 protected mode waking vector (Page disabled) // DEBUG ((DEBUG_INFO, "Transfer to 32bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); - SwitchStack ( - (SWITCH_STACK_ENTRY_POINT)(UINTN)Facs->XFirmwareWakingVector, - NULL, - NULL, - (VOID *)(UINTN)TempStackTop - ); + if (sizeof (UINTN) == sizeof (UINT64)) { + // + // 64bit PEI calls to 32bit OS S3 waking vector + // + AsmDisablePaging64 ( + 0x10, + (UINT32)Facs->XFirmwareWakingVector, + 0, + 0, + (UINT32)TempStackTop + ); + } else { + // + // 32bit PEI calls to 32bit OS S3 waking vector + // + SwitchStack ( + (SWITCH_STACK_ENTRY_POINT)(UINTN)Facs->XFirmwareWakingVector, + NULL, + NULL, + (VOID *)(UINTN)TempStackTop + ); + } } } else { // @@ -579,7 +610,7 @@ S3ResumeBootOs ( /** Restore S3 page table because we do not trust ACPINvs content. - If BootScriptExector driver will not run in 64-bit mode, this function will do nothing. + If BootScriptExecutor driver will not run in 64-bit mode, this function will do nothing. @param S3NvsPageTableAddress PageTableAddress in ACPINvs @param Build4GPageTableOnly If BIOS just build 4G page table only @@ -590,7 +621,7 @@ RestoreS3PageTables ( IN BOOLEAN Build4GPageTableOnly ) { - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { UINT32 RegEax; UINT32 RegEdx; UINT8 PhysicalAddressBits; @@ -825,7 +856,7 @@ S3ResumeExecuteBootScript ( SignalToSmmByCommunication (&gEdkiiS3SmmInitDoneGuid); } - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { AsmWriteCr3 ((UINTN)AcpiS3Context->S3NvsPageTableAddress); } @@ -1021,7 +1052,7 @@ S3RestoreConfig2 ( CpuDeadLoop (); } - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { // // Need reconstruct page table here, since we do not trust ACPINvs. // @@ -1039,13 +1070,6 @@ S3RestoreConfig2 ( // GuidHob = GetFirstGuidHob (&gEfiAcpiVariableGuid); if (GuidHob != NULL) { - // - // Below SwitchStack/AsmEnablePaging64 function has - // assumption that it's in 32 bits mode now. - // Add ASSERT code to indicate this assumption. - // - ASSERT (sizeof (UINTN) == sizeof (UINT32)); - Status = PeiServicesLocatePpi ( &gPeiSmmAccessPpiGuid, 0, @@ -1079,7 +1103,12 @@ S3RestoreConfig2 ( DEBUG ((DEBUG_INFO, "SMM S3 Return Stack Pointer = %x\n", SmmS3ResumeState->ReturnStackPointer)); DEBUG ((DEBUG_INFO, "SMM S3 Smst = %x\n", SmmS3ResumeState->Smst)); - if (SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_32) { + // + // Directly do the switch stack when PEI and SMM env run in the same execution mode. + // + if (((SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_32) && (sizeof (UINTN) == sizeof (UINT32))) || + ((SmmS3ResumeState->Signature == SMM_S3_RESUME_SMM_64) && (sizeof (UINTN) == sizeof (UINT64)))) + { SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)SmmS3ResumeState->SmmS3ResumeEntryPoint, (VOID *)AcpiS3Context, From 66103b54b5d4fc8fb6d8d2fc347a46107c08ddbc Mon Sep 17 00:00:00 2001 From: "Kuo, Ted" Date: Fri, 16 Dec 2022 20:46:27 +0800 Subject: [PATCH 0405/1529] MdeModulePkg: Supporting S3 in 64bit PEI https://bugzilla.tianocore.org/show_bug.cgi?id=4195 Transfer from DXE to OS waking vector by calling SwitchStack() when both are in the same execution mode. Reviewed-by: Ray Ni Reviewed-by: Zhiguang Liu Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Cc: Ashraf Ali S Cc: Chinni B Duggapu Signed-off-by: Ted Kuo --- .../BootScriptExecutorDxe/ScriptExecute.c | 21 +++++++++++++------ .../BootScriptExecutorDxe/X64/SetIdtEntry.c | 4 ++-- .../Acpi/S3SaveStateDxe/AcpiS3ContextSave.c | 10 ++++----- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/ScriptExecute.c b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/ScriptExecute.c index 82481aacd6..98c5abecf8 100644 --- a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/ScriptExecute.c +++ b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/ScriptExecute.c @@ -4,7 +4,7 @@ This driver is dispatched by Dxe core and the driver will reload itself to ACPI reserved memory in the entry point. The functionality is to interpret and restore the S3 boot script -Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -95,7 +95,7 @@ S3BootScriptExecutorEntryFunction ( PeiS3ResumeState->ReturnStatus = (UINT64)(UINTN)Status; if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { // - // X64 S3 Resume + // X64 DXE to IA32 PEI S3 Resume // DEBUG ((DEBUG_INFO, "Call AsmDisablePaging64() to return to S3 Resume in PEI Phase\n")); PeiS3ResumeState->AsmTransferControl = (EFI_PHYSICAL_ADDRESS)(UINTN)AsmTransferControl32; @@ -121,7 +121,7 @@ S3BootScriptExecutorEntryFunction ( ); } else { // - // IA32 S3 Resume + // IA32 DXE to IA32 PEI S3 Resume / X64 DXE to X64 PEI S3 Resume // DEBUG ((DEBUG_INFO, "Call SwitchStack() to return to S3 Resume in PEI Phase\n")); PeiS3ResumeState->AsmTransferControl = (EFI_PHYSICAL_ADDRESS)(UINTN)AsmTransferControl; @@ -156,8 +156,11 @@ S3BootScriptExecutorEntryFunction ( // // X64 long mode waking vector // - DEBUG ((DEBUG_INFO, "Transfer to 64bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + DEBUG ((DEBUG_INFO, "Transfer from 64bit DXE to 64bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); + if (sizeof (UINTN) == sizeof (UINT64)) { + // + // 64bit DXE calls to 64bit OS S3 waking vector + // SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)Facs->XFirmwareWakingVector, NULL, @@ -174,7 +177,10 @@ S3BootScriptExecutorEntryFunction ( // IA32 protected mode waking vector (Page disabled) // DEBUG ((DEBUG_INFO, "Transfer to 32bit OS waking vector - %x\r\n", (UINTN)Facs->XFirmwareWakingVector)); - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if (sizeof (UINTN) == sizeof (UINT64)) { + // + // 64bit DXE calls to 32bit OS S3 waking vector + // AsmDisablePaging64 ( 0x10, (UINT32)Facs->XFirmwareWakingVector, @@ -183,6 +189,9 @@ S3BootScriptExecutorEntryFunction ( (UINT32)TempStackTop ); } else { + // + // 32bit DXE calls to 32bit OS S3 waking vector + // SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)Facs->XFirmwareWakingVector, NULL, diff --git a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c index 6b44f50bac..7fc6cdcb4e 100644 --- a/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c +++ b/MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/X64/SetIdtEntry.c @@ -3,7 +3,7 @@ Set a IDT entry for interrupt vector 3 for debug purpose for x64 platform -Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
@@ -118,7 +118,7 @@ IsLongModeWakingVector ( ((Facs->OspmFlags & EFI_ACPI_4_0_OSPM_64BIT_WAKE__F) != 0)) { // Both BIOS and OS wants 64bit vector - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if (sizeof (UINTN) == sizeof (UINT64)) { return TRUE; } } diff --git a/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/AcpiS3ContextSave.c b/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/AcpiS3ContextSave.c index 03f7a332d3..70bee7a67b 100644 --- a/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/AcpiS3ContextSave.c +++ b/MdeModulePkg/Universal/Acpi/S3SaveStateDxe/AcpiS3ContextSave.c @@ -1,7 +1,7 @@ /** @file This is the implementation to save ACPI S3 Context. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -97,7 +97,7 @@ IsLongModeWakingVectorSupport ( // // BIOS supports 64bit waking vector. // - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if (sizeof (UINTN) == sizeof (UINT64)) { return TRUE; } } @@ -110,11 +110,11 @@ IsLongModeWakingVectorSupport ( @param[in] LongModeWakingVectorSupport Support long mode waking vector or not. - If BootScriptExector driver will run in 64-bit mode, this function will establish the 1:1 + If BootScriptExecutor driver will run in 64-bit mode, this function will establish the 1:1 virtual to physical mapping page table when long mode waking vector is supported, otherwise create 4G page table when long mode waking vector is not supported and let PF handler to handle > 4G request. - If BootScriptExector driver will not run in 64-bit mode, this function will do nothing. + If BootScriptExecutor driver will not run in 64-bit mode, this function will do nothing. @return Page table base address. @@ -124,7 +124,7 @@ S3AllocatePageTablesBuffer ( IN BOOLEAN LongModeWakingVectorSupport ) { - if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { + if ((FeaturePcdGet (PcdDxeIplSwitchToLongMode)) || (sizeof (UINTN) == sizeof (UINT64))) { UINTN ExtraPageTablePages; UINT32 RegEax; UINT32 RegEdx; From c5d29817b1995c9105fdaf1f19becf28f93c210e Mon Sep 17 00:00:00 2001 From: MarsX Lin Date: Mon, 19 Dec 2022 10:50:05 +0800 Subject: [PATCH 0406/1529] UefiPayloadPkg: Move bdsdxe.inf from DXEFV to BDSFV REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4196 Since UefiPayload had supported multiple fv, move bdsdxe.inf to new firmware volume and modify the script of UniversalPayloadPkgBuild.py to support bdsdxe fv in elf file Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: MarsX Lin --- UefiPayloadPkg/UefiPayloadPkg.fdf | 27 ++++++++++++++++++++++++- UefiPayloadPkg/UniversalPayloadBuild.py | 12 ++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.fdf b/UefiPayloadPkg/UefiPayloadPkg.fdf index 9c9e2f2741..94ba922244 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.fdf +++ b/UefiPayloadPkg/UefiPayloadPkg.fdf @@ -59,8 +59,33 @@ INF UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf FILE FV_IMAGE = 4E35FD93-9C72-4c15-8C4B-E77F1DB2D793 { SECTION FV_IMAGE = DXEFV } +FILE FV_IMAGE = FBE6C1E3-2F80-4770-88B0-494186E3346F { + SECTION FV_IMAGE = BDSFV +} ################################################################################ +[FV.BDSFV] +FvNameGuid = CA5590AF-9558-4822-B5EA-BE2E876CD3EC +BlockSize = $(FD_BLOCK_SIZE) +FvForceRebase = FALSE +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE + +INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf [FV.DXEFV] FvNameGuid = 8063C21A-8E58-4576-95CE-089E87975D23 @@ -106,7 +131,7 @@ INF CryptoPkg/Driver/CryptoDxe.inf INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf !endif INF UefiCpuPkg/CpuDxe/CpuDxe.inf -INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf + INF RuleOverride = UI MdeModulePkg/Application/UiApp/UiApp.inf INF MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenuApp.inf INF PcAtChipsetPkg/HpetTimerDxe/HpetTimerDxe.inf diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 50a5950e7c..6d62b8b20f 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -67,7 +67,8 @@ def BuildUniversalPayload(Args, MacroList): EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc") - FvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) + DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) + BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt") UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin") @@ -119,21 +120,22 @@ def BuildUniversalPayload(Args, MacroList): # # Copy the DXEFV as a section in elf format Universal Payload entry. # - remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv {}'.format ( + remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv --remove-section .upld.bds_fv {}'.format ( LlvmObjcopyPath, ObjCopyFlag, ObjCopyFlag, EntryOutputDir ) - add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} {}'.format ( + add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} --add-section .upld.bds_fv={} {}'.format ( LlvmObjcopyPath, ObjCopyFlag, ObjCopyFlag, UpldInfoFile, - FvOutputDir, + DxeFvOutputDir, + BdsFvOutputDir, EntryOutputDir ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 {}'.format ( + set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=16 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( LlvmObjcopyPath, ObjCopyFlag, ObjCopyFlag, From 93cd111ec9762035a44b12dc9b3f34e1a1bd3b41 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Mon, 7 Nov 2022 08:57:11 -0700 Subject: [PATCH 0407/1529] DynamicTablesPkg: Allow for specified CPU names Allow object to specify the name of processor and processor container nodes and the UID of processor containers. This allows these to be more accurately referenced from other tables. For example for the _PSL method or the UID in the APMT table. The UID and Name for processor container may be different as if the intention is to set names as the corresponding affinity level the UID may need to be different if there are multiple levels of containers. Signed-off-by: Jeff Brasen Reviewed-by: Sami Mujawar --- .../Include/ArmNameSpaceObjects.h | 11 +++++ .../SsdtCpuTopologyGenerator.c | 40 ++++++++++++++----- .../ConfigurationManagerObjectParser.c | 3 ++ 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h index 6aafd41a2e..19098609de 100644 --- a/DynamicTablesPkg/Include/ArmNameSpaceObjects.h +++ b/DynamicTablesPkg/Include/ArmNameSpaceObjects.h @@ -768,6 +768,17 @@ typedef struct CmArmProcHierarchyInfo { /// Token identifying a CM_ARM_OBJ_REF structure, itself referencing /// CM_ARM_LPI_INFO objects. CM_OBJECT_TOKEN LpiToken; + /// Set to TRUE if UID should override index for name and _UID + /// for processor container nodes and name of processors. + /// This should be consistently set for containers or processors to avoid + /// duplicate values + BOOLEAN OverrideNameUidEnabled; + /// If OverrideNameUidEnabled is TRUE then this value will be used for name of + /// processors and processor containers. + UINT16 OverrideName; + /// If OverrideNameUidEnabled is TRUE then this value will be used for + /// the UID of processor containers. + UINT32 OverrideUid; } CM_ARM_PROC_HIERARCHY_INFO; /** A structure that describes the Cache Type Structure (Type 1) in PPTT diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c index 91199c4af2..c24da8ec71 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c @@ -553,7 +553,7 @@ GenerateLpiStates ( @param [in] Generator The SSDT Cpu Topology generator. @param [in] ParentNode Parent node to attach the Cpu node to. @param [in] GicCInfo CM_ARM_GICC_INFO object used to create the node. - @param [in] CpuIndex Index used to generate the node name. + @param [in] CpuName Value used to generate the node name. @param [out] CpuNodePtr If not NULL, return the created Cpu node. @retval EFI_SUCCESS Success. @@ -567,7 +567,7 @@ CreateAmlCpu ( IN ACPI_CPU_TOPOLOGY_GENERATOR *Generator, IN AML_NODE_HANDLE ParentNode, IN CM_ARM_GICC_INFO *GicCInfo, - IN UINT32 CpuIndex, + IN UINT32 CpuName, OUT AML_OBJECT_NODE_HANDLE *CpuNodePtr OPTIONAL ) { @@ -579,7 +579,7 @@ CreateAmlCpu ( ASSERT (ParentNode != NULL); ASSERT (GicCInfo != NULL); - Status = WriteAslName ('C', CpuIndex, AslName); + Status = WriteAslName ('C', CpuName, AslName); if (EFI_ERROR (Status)) { ASSERT (0); return Status; @@ -628,7 +628,7 @@ CreateAmlCpu ( @param [in] CfgMgrProtocol Pointer to the Configuration Manager Protocol Interface. @param [in] ParentNode Parent node to attach the Cpu node to. - @param [in] CpuIndex Index used to generate the node name. + @param [in] CpuName Value used to generate the node name. @param [in] ProcHierarchyNodeInfo CM_ARM_PROC_HIERARCHY_INFO describing the Cpu. @@ -643,7 +643,7 @@ CreateAmlCpuFromProcHierarchy ( IN ACPI_CPU_TOPOLOGY_GENERATOR *Generator, IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, IN AML_NODE_HANDLE ParentNode, - IN UINT32 CpuIndex, + IN UINT32 CpuName, IN CM_ARM_PROC_HIERARCHY_INFO *ProcHierarchyNodeInfo ) { @@ -668,7 +668,7 @@ CreateAmlCpuFromProcHierarchy ( return Status; } - Status = CreateAmlCpu (Generator, ParentNode, GicCInfo, CpuIndex, &CpuNode); + Status = CreateAmlCpu (Generator, ParentNode, GicCInfo, CpuName, &CpuNode); if (EFI_ERROR (Status)) { ASSERT (0); return Status; @@ -735,7 +735,8 @@ CreateAmlProcessorContainer ( IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL *CONST CfgMgrProtocol, IN AML_NODE_HANDLE ParentNode, IN CM_ARM_PROC_HIERARCHY_INFO *ProcHierarchyNodeInfo, - IN UINT32 ProcContainerIndex, + IN UINT16 ProcContainerName, + IN UINT32 ProcContainerUid, OUT AML_OBJECT_NODE_HANDLE *ProcContainerNodePtr ) { @@ -749,7 +750,7 @@ CreateAmlProcessorContainer ( ASSERT (ProcHierarchyNodeInfo != NULL); ASSERT (ProcContainerNodePtr != NULL); - Status = WriteAslName ('C', ProcContainerIndex, AslNameProcContainer); + Status = WriteAslName ('C', ProcContainerName, AslNameProcContainer); if (EFI_ERROR (Status)) { ASSERT (0); return Status; @@ -765,7 +766,7 @@ CreateAmlProcessorContainer ( // and EFI_ACPI_6_3_PPTT_PROCESSOR_ID_INVALID is set for non-Cpus. Status = AmlCodeGenNameInteger ( "_UID", - ProcContainerIndex, + ProcContainerUid, ProcContainerNode, NULL ); @@ -838,6 +839,8 @@ CreateAmlCpuTopologyTree ( UINT32 Index; UINT32 CpuIndex; AML_OBJECT_NODE_HANDLE ProcContainerNode; + UINT32 Uid; + UINT16 Name; ASSERT (Generator != NULL); ASSERT (Generator->ProcNodeList != NULL); @@ -868,11 +871,17 @@ CreateAmlCpuTopologyTree ( return EFI_INVALID_PARAMETER; } + if (Generator->ProcNodeList[Index].OverrideNameUidEnabled) { + Name = Generator->ProcNodeList[Index].OverrideName; + } else { + Name = CpuIndex; + } + Status = CreateAmlCpuFromProcHierarchy ( Generator, CfgMgrProtocol, ParentNode, - CpuIndex, + Name, &Generator->ProcNodeList[Index] ); if (EFI_ERROR (Status)) { @@ -897,12 +906,21 @@ CreateAmlCpuTopologyTree ( return EFI_INVALID_PARAMETER; } + if (Generator->ProcNodeList[Index].OverrideNameUidEnabled) { + Name = Generator->ProcNodeList[Index].OverrideName; + Uid = Generator->ProcNodeList[Index].OverrideUid; + } else { + Name = *ProcContainerIndex; + Uid = *ProcContainerIndex; + } + Status = CreateAmlProcessorContainer ( Generator, CfgMgrProtocol, ParentNode, &Generator->ProcNodeList[Index], - *ProcContainerIndex, + Name, + Uid, &ProcContainerNode ); if (EFI_ERROR (Status)) { diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 5a01ed0fb8..5e4b88e8cc 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -305,6 +305,9 @@ STATIC CONST CM_OBJ_PARSER CmArmProcHierarchyInfoParser[] = { { "NoOfPrivateResources", 4, "0x%x", NULL }, { "PrivateResourcesArrayToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, { "LpiToken", sizeof (CM_OBJECT_TOKEN), "0x%p", NULL }, + { "OverrideNameUidEnabled", 1, "%d", NULL }, + { "OverrideName", 2, "0x%x", NULL }, + { "OverrideUid", 4, "0x%x", NULL } }; /** A parser for EArmObjCacheInfo. From db189a55ac29cac7106368f753bd45a41615fd3f Mon Sep 17 00:00:00 2001 From: Judah Vang Date: Tue, 8 Nov 2022 06:15:53 +0800 Subject: [PATCH 0408/1529] CryptoPkg: Need to enable crypto functions REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3992 V1: Enable CryptAes for PEI phase. Enable CryptHkdf for SMM phase. Update Readme.md Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Nishant C Mistry Signed-off-by: Jian J Wang Signed-off-by: Nishant C Mistry Signed-off-by: Judah Vang Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/PeiCryptLib.inf | 2 +- .../Library/BaseCryptLib/SmmCryptLib.inf | 2 +- CryptoPkg/Readme.md | 27 ++++++++++--------- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 2aafa5f0ac..66261138a0 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -47,7 +47,7 @@ Hash/CryptDispatchApPei.c Hmac/CryptHmac.c Kdf/CryptHkdf.c - Cipher/CryptAesNull.c + Cipher/CryptAes.c Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasic.c Pk/CryptRsaExtNull.c diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 00ea7bf4c5..55df99f843 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -44,7 +44,7 @@ Hash/CryptParallelHash.c Hash/CryptDispatchApMm.c Hmac/CryptHmac.c - Kdf/CryptHkdfNull.c + Kdf/CryptHkdf.c Cipher/CryptAes.c Cipher/CryptAeadAesGcmNull.c Pk/CryptRsaBasic.c diff --git a/CryptoPkg/Readme.md b/CryptoPkg/Readme.md index 067465b8eb..cb072db723 100644 --- a/CryptoPkg/Readme.md +++ b/CryptoPkg/Readme.md @@ -447,18 +447,20 @@ and CryptoSmm modules. #### Common PEI PcdCryptoServiceFamilyEnable Settings ``` - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Pkcs1Verify | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.New | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha1.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sha512.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Sm3.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Pkcs1Verify | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.New | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Services.Sha256ExtractAndExpand | TRUE ``` #### Common DXE and SMM PcdCryptoServiceFamilyEnable Settings @@ -466,6 +468,7 @@ and CryptoSmm modules. ``` gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha256.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.HmacSha384.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs1v2Encrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs7Verify | TRUE From efcb6f436f883d238aa0f634292370ef66b09f59 Mon Sep 17 00:00:00 2001 From: jdzhang Date: Mon, 19 Dec 2022 19:59:42 +0800 Subject: [PATCH 0409/1529] UefiPayloadPkg: Define default values for the DynamicEX PCDs The following PCDs have no value in UefiPayloadPkg.dsc and they can not pass the Ecc tool check, so assign the default values the same as they are in *.dec file. 1. gEfiMdeModulePkgTokenSpaceGuid.PcdAriSupport 2. gEfiMdeModulePkgTokenSpaceGuid.PcdMrIovSupport 3. gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSuppor 4. gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSystemPageSize 5. gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds 6. gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode 7. gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress 8. gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize Reviewed-by: Gua Guo Signed-off-by: jdzhang --- UefiPayloadPkg/UefiPayloadPkg.dsc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 723a50a422..c2ca9106d1 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -530,14 +530,14 @@ gEfiMdePkgTokenSpaceGuid.PcdUartDefaultParity|$(UART_DEFAULT_PARITY) gEfiMdePkgTokenSpaceGuid.PcdUartDefaultStopBits|$(UART_DEFAULT_STOP_BITS) gEfiMdePkgTokenSpaceGuid.PcdDefaultTerminalType|$(DEFAULT_TERMINAL_TYPE) - gEfiMdeModulePkgTokenSpaceGuid.PcdAriSupport - gEfiMdeModulePkgTokenSpaceGuid.PcdMrIovSupport - gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSupport - gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSystemPageSize - gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds - gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode - gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress - gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize + gEfiMdeModulePkgTokenSpaceGuid.PcdAriSupport|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdMrIovSupport|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSupport|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdSrIovSystemPageSize|0x1 + gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000 + gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode|1 + gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress|0x0 + gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize|0x0 !if ($(TARGET) == DEBUG || $(USE_CBMEM_FOR_CONSOLE) == TRUE) gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|TRUE !else From 32d486269d512290f11b91fd7d41215e9638b61d Mon Sep 17 00:00:00 2001 From: Chun-Yi Lee Date: Thu, 15 Dec 2022 22:27:23 +0800 Subject: [PATCH 0410/1529] OvmfPkg/PlatformInitLib: Fix integrity checking failed of NvVarStore In the commit 4f173db8b4 "OvmfPkg/PlatformInitLib: Add functions for EmuVariableNvStore", it introduced a PlatformValidateNvVarStore() function for checking the integrity of NvVarStore. In some cases when the VariableHeader->StartId is VARIABLE_DATA, the VariableHeader->State is not just one of the four primary states: VAR_IN_DELETED_TRANSITION, VAR_DELETED, VAR_HEADER_VALID_ONLY, VAR_ADDED. The state may combined two or three states, e.g. 0x3C = (VAR_IN_DELETED_TRANSITION & VAR_ADDED) & VAR_DELETED or 0x3D = VAR_ADDED & VAR_DELETED When the variable store has those variables, system booting/rebooting will hangs in a ASSERT: NvVarStore Variable header State was invalid. ASSERT /mnt/working/source_code-git/edk2/OvmfPkg/Library/PlatformInitLib/Platform.c(819): ((BOOLEAN)(0==1)) Adding more log to UpdateVariable() and PlatformValidateNvVarStore(), we saw some variables which have 0x3C or 0x3D state in store. e.g. UpdateVariable(), VariableName=BootOrder L1871, State=0000003F <-- VAR_ADDED State &= VAR_DELETED=0000003D FlushHobVariableToFlash(), VariableName=BootOrder ... UpdateVariable(), VariableName=InitialAttemptOrder L1977, State=0000003F State &= VAR_IN_DELETED_TRANSITION=0000003E L2376, State=0000003E State &= VAR_DELETED=0000003C FlushHobVariableToFlash(), VariableName=InitialAttemptOrder ... UpdateVariable(), VariableName=ConIn L1977, State=0000003F State &= VAR_IN_DELETED_TRANSITION=0000003E L2376, State=0000003E State &= VAR_DELETED=0000003C FlushHobVariableToFlash(), VariableName=ConIn ... So, only allowing the four primary states is not enough. This patch changes the falid states list (Follow Jiewen Yao's suggestion): 1. VAR_HEADER_VALID_ONLY (0x7F) - Header added (*) 2. VAR_ADDED (0x3F) - Header + data added 3. VAR_ADDED & VAR_IN_DELETED_TRANSITION (0x3E) - marked as deleted, but still valid, before new data is added. (*) 4. VAR_ADDED & VAR_IN_DELETED_TRANSITION & VAR_DELETED (0x3C) - deleted, after new data is added. 5. VAR_ADDED & VAR_DELETED (0x3D) - deleted directly, without new data. (*) means to support surprise shutdown. And removed (VAR_IN_DELETED_TRANSITION) and (VAR_DELETED) because they are invalid states. v2: Follow Jiewen Yao's suggestion to add the following valid states: VAR_ADDED & VAR_DELETED (0x3D) VAR_ADDED & VAR_IN_DELETED_TRANSITION (0x3E) VAR_ADDED & VAR_IN_DELETED_TRANSITION & VAR_DELETED (0x3C) and removed the following invalid states: VAR_IN_DELETED_TRANSITION VAR_DELETED Signed-off-by: Chun-Yi Lee Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/Platform.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 77f22de046..3e13c5d4b3 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -702,10 +702,11 @@ PlatformValidateNvVarStore ( VariableOffset = NvVarStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER); } else { - if (!((VariableHeader->State == VAR_IN_DELETED_TRANSITION) || - (VariableHeader->State == VAR_DELETED) || - (VariableHeader->State == VAR_HEADER_VALID_ONLY) || - (VariableHeader->State == VAR_ADDED))) + if (!((VariableHeader->State == VAR_HEADER_VALID_ONLY) || + (VariableHeader->State == VAR_ADDED) || + (VariableHeader->State == (VAR_ADDED & VAR_DELETED)) || + (VariableHeader->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION)) || + (VariableHeader->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION & VAR_DELETED)))) { DEBUG ((DEBUG_ERROR, "NvVarStore Variable header State was invalid.\n")); return FALSE; From 5f448b6d2f3613934c9370570ae8f008e00a0e9e Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 19 Dec 2022 21:18:00 +0800 Subject: [PATCH 0411/1529] RedfishPkg/RedfishHostInterface: Platform Redfish HI notification For some use cases, Redfish host interface table relies on the certain EFI protocols installation at the driver connection. Redfish host interface DXE driver is not able to build the SMBIOS type 42h record at driver entry point. This patch adds the mechanism in Redfish host interface DXE driver to listen to EFI protocol installed by platform library that indicates the necessary information is ready for building SMBIOS 42h record. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Nickle Wang --- .../Include/Library/RedfishHostInterfaceLib.h | 28 ++++++- .../PlatformHostInterfaceLibNull.c | 26 ++++++- .../RedfishHostInterfaceDxe.c | 73 ++++++++++++++++++- 3 files changed, 121 insertions(+), 6 deletions(-) diff --git a/RedfishPkg/Include/Library/RedfishHostInterfaceLib.h b/RedfishPkg/Include/Library/RedfishHostInterfaceLib.h index 8d8389b964..22a8f9283c 100644 --- a/RedfishPkg/Include/Library/RedfishHostInterfaceLib.h +++ b/RedfishPkg/Include/Library/RedfishHostInterfaceLib.h @@ -2,6 +2,7 @@ Definitinos of RedfishHostInterfaceDxe driver. (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -19,7 +20,7 @@ /** Get platform Redfish host interface device descriptor. - @param[in] DeviceType Pointer to retrieve device type. + @param[out] DeviceType Pointer to retrieve device type. @param[out] DeviceDescriptor Pointer to retrieve REDFISH_INTERFACE_DATA, caller has to free this memory using FreePool(). @retval EFI_SUCCESS Device descriptor is returned successfully in DeviceDescriptor. @@ -28,7 +29,7 @@ **/ EFI_STATUS RedfishPlatformHostInterfaceDeviceDescriptor ( - IN UINT8 *DeviceType, + OUT UINT8 *DeviceType, OUT REDFISH_INTERFACE_DATA **DeviceDescriptor ); @@ -40,7 +41,7 @@ RedfishPlatformHostInterfaceDeviceDescriptor ( @param[in, out] ProtocolRecord Pointer to retrieve the first or the next protocol record. caller has to free the new protocol record returned from this function using FreePool(). - param[in] IndexOfProtocolData The index of protocol data. + @param[in] IndexOfProtocolData The index of protocol data. @retval EFI_SUCCESS Protocol records are all returned. @retval EFI_NOT_FOUND No more protocol records. @@ -52,4 +53,25 @@ RedfishPlatformHostInterfaceProtocolData ( IN UINT8 IndexOfProtocolData ); +/** + Get the EFI protocol GUID installed by platform library which + indicates the necessary information is ready for building + SMBIOS 42h record. + + @param[out] InformationReadinessGuid Pointer to retrive the protocol + GUID. + + @retval EFI_SUCCESS Notification is required for building up + SMBIOS type 42h record. + @retval EFI_UNSUPPORTED Notification is not required for building up + SMBIOS type 42h record. + @retval EFI_ALREADY_STARTED Platform host information is already ready. + @retval Others Other errors. +**/ + +EFI_STATUS +RedfishPlatformHostInterfaceNotification ( + OUT EFI_GUID **InformationReadinessGuid + ); + #endif diff --git a/RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.c b/RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.c index b30f9e37a4..40642469c9 100644 --- a/RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.c +++ b/RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.c @@ -2,6 +2,7 @@ NULL instace of RedfishPlatformHostInterfaceLib (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -23,7 +24,7 @@ **/ EFI_STATUS RedfishPlatformHostInterfaceDeviceDescriptor ( - IN UINT8 *DeviceType, + OUT UINT8 *DeviceType, OUT REDFISH_INTERFACE_DATA **DeviceDescriptor ) { @@ -51,3 +52,26 @@ RedfishPlatformHostInterfaceProtocolData ( { return EFI_NOT_FOUND; } + +/** + Get the EFI protocol GUID installed by platform library which + indicates the necessary information is ready for building + SMBIOS 42h record. + + @param[out] InformationReadinessGuid Pointer to retrive the protocol + GUID. + + @retval EFI_SUCCESS Notification is required for building up + SMBIOS type 42h record. + @retval EFI_UNSUPPORTED Notification is not required for building up + SMBIOS type 42h record. + @retval EFI_ALREADY_STARTED Platform host information is already ready. + @retval Others Other errors. +**/ +EFI_STATUS +RedfishPlatformHostInterfaceNotification ( + OUT EFI_GUID **InformationReadinessGuid + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c index 623350bc26..3e12e0c8b9 100644 --- a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c +++ b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c @@ -6,6 +6,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -21,6 +22,9 @@ #include #include +static EFI_EVENT mPlatformHostInterfaceReadylEvent = NULL; +static VOID *mPlatformHostInterfaceReadyRegistration = NULL; + /** Create SMBIOS type 42 record for Redfish host interface. @@ -238,6 +242,27 @@ RedfishCreateSmbiosTable42 ( return Status; } +/** + Notification event of platform Redfish Host Interface readiness. + + @param[in] Event Event whose notification function is being invoked. + @param[in] Context The pointer to the notification function's context, + which is implementation-dependent. + +**/ +VOID +EFIAPI +PlatformHostInterfaceInformationReady ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + DEBUG ((DEBUG_INFO, "%a: Platform Redfish Host Interface informtion is ready\n", __FUNCTION__)); + + RedfishCreateSmbiosTable42 (); + return; +} + /** Main entry for this driver. @@ -254,8 +279,52 @@ RedfishHostInterfaceDxeEntryPoint ( IN EFI_SYSTEM_TABLE *SystemTable ) { + EFI_STATUS Status; + EFI_GUID *ReadyGuid; + + DEBUG ((DEBUG_INFO, "%a: Entry\n.", __FUNCTION__)); + // - // Create SMBIOS type 42 record. + // Check if the Redfish Host Interface depends on + // the specific protocol installation. // - return RedfishCreateSmbiosTable42 (); + Status = RedfishPlatformHostInterfaceNotification (&ReadyGuid); + if (Status == EFI_SUCCESS) { + DEBUG ((DEBUG_INFO, " Create protocol install notification to know the installation of platform Redfish host interface readiness\n")); + DEBUG ((DEBUG_INFO, " Protocol GUID: %g\n", ReadyGuid)); + // + // Register event for ReadyGuid protocol installed by + // platform Redfish host interface library. + // + Status = gBS->CreateEvent ( + EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + PlatformHostInterfaceInformationReady, + NULL, + &mPlatformHostInterfaceReadylEvent + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Fail to create event for the installation of platform Redfish host interface readiness.\n")); + return Status; + } + + Status = gBS->RegisterProtocolNotify ( + ReadyGuid, + mPlatformHostInterfaceReadylEvent, + &mPlatformHostInterfaceReadyRegistration + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Fail to register event for the installation of platform Redfish host interface readiness.\n")); + return Status; + } + + return EFI_SUCCESS; + } + + if ((Status == EFI_UNSUPPORTED) || (Status == EFI_ALREADY_STARTED)) { + Status = RedfishCreateSmbiosTable42 (); + } + + // Return other erros. + return Status; } From 8cf971255c9c62f2b68b69291a4b3c27b8840ad7 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 19 Dec 2022 21:18:20 +0800 Subject: [PATCH 0412/1529] EmulatorPkg/RedfishHostInterface: Add NULL function Add NULL function RedfishPlatformHostInterfaceNotification that returns EFI_UNSUPPORTED. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Nickle Wang --- .../RedfishPlatformHostInterfaceLib.c | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c b/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c index 3f053307a6..4361bd4170 100644 --- a/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c +++ b/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c @@ -3,6 +3,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -544,3 +545,26 @@ RedfishPlatformHostInterfaceConstructor ( return EFI_SUCCESS; } + +/** + Get the EFI protocol GUID installed by platform library which + indicates the necessary information is ready for building + SMBIOS 42h record. + + @param[out] InformationReadinessGuid Pointer to retrive the protocol + GUID. + + @retval EFI_SUCCESS Notification is required for building up + SMBIOS type 42h record. + @retval EFI_UNSUPPORTED Notification is not required for building up + SMBIOS type 42h record. + @retval EFI_ALREADY_STARTED Platform host information is already ready. + @retval Others Other errors. +**/ +EFI_STATUS +RedfishPlatformHostInterfaceNotification ( + OUT EFI_GUID **InformationReadinessGuid + ) +{ + return EFI_UNSUPPORTED; +} From 6c927a9dc90f204aaa8a6a9b28ab855e29b9eeb7 Mon Sep 17 00:00:00 2001 From: Kavya Date: Tue, 20 Dec 2022 09:26:59 +0530 Subject: [PATCH 0413/1529] UefiPayloadPkg/SerialPortLib: Enhance multi port behaviour Add condition to return success if mUartCount is greater than zero in SerialPortInitialize() to avoid filling mUartInfo with the same hob data when SerialPortInitialize() is called multiple times. Also add proper conditions in SerialPortRead function to read the data properly from multiple UART's. Cc: Guo Dong Cc: Ray Ni Cc: James Lu Reviewed-by: Gua Guo Signed-off-by: Kavya --- .../BaseSerialPortLibHob.c | 41 ++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/UefiPayloadPkg/Library/BaseSerialPortLibHob/BaseSerialPortLibHob.c b/UefiPayloadPkg/Library/BaseSerialPortLibHob/BaseSerialPortLibHob.c index 809fa2e9c9..8216195c62 100644 --- a/UefiPayloadPkg/Library/BaseSerialPortLibHob/BaseSerialPortLibHob.c +++ b/UefiPayloadPkg/Library/BaseSerialPortLibHob/BaseSerialPortLibHob.c @@ -138,6 +138,10 @@ SerialPortInitialize ( BOOLEAN MmioEnable; UINT8 Value; + if (mUartCount > 0) { + return RETURN_SUCCESS; + } + GuidHob = GetFirstGuidHob (&gUniversalPayloadSerialPortInfoGuid); while (GuidHob != NULL) { SerialPortInfo = (UNIVERSAL_PAYLOAD_SERIAL_PORT_INFO *)GET_GUID_HOB_DATA (GuidHob); @@ -329,6 +333,7 @@ SerialPortRead ( { UINTN BaseAddress; BOOLEAN UseMmio; + BOOLEAN IsNextPort; UINT8 *DataBuffer; UINTN BytesLeft; UINTN Result; @@ -353,6 +358,7 @@ SerialPortRead ( DataBuffer = Buffer; BytesLeft = NumberOfBytes; + IsNextPort = FALSE; Mcr = (UINT8)(SerialPortReadRegister (BaseAddress, R_UART_MCR, UseMmio, Stride) & ~B_UART_MCR_RTS); @@ -367,6 +373,13 @@ SerialPortRead ( // SerialPortWriteRegister (BaseAddress, R_UART_MCR, (UINT8)(Mcr | B_UART_MCR_RTS), UseMmio, Stride); } + + IsNextPort = TRUE; + break; + } + + if (IsNextPort) { + break; } if (PcdGetBool (PcdSerialUseHardwareFlowControl)) { @@ -382,6 +395,10 @@ SerialPortRead ( *DataBuffer = SerialPortReadRegister (BaseAddress, R_UART_RXBUF, UseMmio, Stride); } + if ((!IsNextPort) && (*(--DataBuffer) != '\0')) { + return Result; + } + Count++; } @@ -409,10 +426,9 @@ SerialPortPoll ( BOOLEAN UseMmio; UINT8 Stride; UINT8 Count; - BOOLEAN Status; + BOOLEAN IsDataReady; - Count = 0; - Status = FALSE; + Count = 0; while (Count < mUartCount) { BaseAddress = mUartInfo[Count].BaseAddress; UseMmio = mUartInfo[Count].UseMmio; @@ -423,7 +439,7 @@ SerialPortPoll ( continue; } - Status = FALSE; + IsDataReady = FALSE; // // Read the serial port status @@ -436,7 +452,7 @@ SerialPortPoll ( SerialPortWriteRegister (BaseAddress, R_UART_MCR, (UINT8)(SerialPortReadRegister (BaseAddress, R_UART_MCR, UseMmio, Stride) & ~B_UART_MCR_RTS), UseMmio, Stride); } - Status = TRUE; + IsDataReady = TRUE; } if (PcdGetBool (PcdSerialUseHardwareFlowControl)) { @@ -446,10 +462,14 @@ SerialPortPoll ( SerialPortWriteRegister (BaseAddress, R_UART_MCR, (UINT8)(SerialPortReadRegister (BaseAddress, R_UART_MCR, UseMmio, Stride) | B_UART_MCR_RTS), UseMmio, Stride); } + if (IsDataReady) { + return IsDataReady; + } + Count++; } - return Status; + return IsDataReady; } /** @@ -603,6 +623,15 @@ SerialPortGetControl ( *Control |= EFI_SERIAL_INPUT_BUFFER_EMPTY; } + if ((((*Control & EFI_SERIAL_OUTPUT_BUFFER_EMPTY) == EFI_SERIAL_OUTPUT_BUFFER_EMPTY) && + ((*Control & EFI_SERIAL_INPUT_BUFFER_EMPTY) != EFI_SERIAL_INPUT_BUFFER_EMPTY)) || + ((*Control & (EFI_SERIAL_DATA_SET_READY | EFI_SERIAL_CLEAR_TO_SEND | + EFI_SERIAL_CARRIER_DETECT)) == (EFI_SERIAL_DATA_SET_READY | EFI_SERIAL_CLEAR_TO_SEND | + EFI_SERIAL_CARRIER_DETECT))) + { + return RETURN_SUCCESS; + } + Count++; } From e01d6116017d79e441d6b4db8cd5f5ce9773e633 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Tue, 20 Dec 2022 05:40:14 +0800 Subject: [PATCH 0414/1529] UefiCpuPkg: Duplicated AsmRelocateApLoop as AsmRelocateApLoopAmd AsmRelocateApLoop is replicated for future Intel Logic Extraction, further brings AP into 64-bit, and enables paging. Signed-off-by: Yuanhao Xie Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 52 +++--- UefiCpuPkg/Library/MpInitLib/MpEqu.inc | 2 + UefiCpuPkg/Library/MpInitLib/MpLib.h | 27 +++ UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm | 169 ++++++++++++++++++ UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 5 + 5 files changed, 235 insertions(+), 20 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index a84e9e33ba..445e0853d2 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -1,7 +1,7 @@ /** @file MP initialize support functions for DXE phase. - Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -378,32 +378,44 @@ RelocateApLoop ( IN OUT VOID *Buffer ) { - CPU_MP_DATA *CpuMpData; - BOOLEAN MwaitSupport; - ASM_RELOCATE_AP_LOOP AsmRelocateApLoopFunc; - UINTN ProcessorNumber; - UINTN StackStart; + CPU_MP_DATA *CpuMpData; + BOOLEAN MwaitSupport; + ASM_RELOCATE_AP_LOOP AsmRelocateApLoopFunc; + ASM_RELOCATE_AP_LOOP_AMD AsmRelocateApLoopFuncAmd; + UINTN ProcessorNumber; + UINTN StackStart; MpInitLibWhoAmI (&ProcessorNumber); CpuMpData = GetCpuMpData (); MwaitSupport = IsMwaitSupport (); - if (CpuMpData->UseSevEsAPMethod) { - StackStart = CpuMpData->SevEsAPResetStackStart; + if (StandardSignatureIsAuthenticAMD ()) { + StackStart = CpuMpData->UseSevEsAPMethod ? CpuMpData->SevEsAPResetStackStart : mReservedTopOfApStack; + AsmRelocateApLoopFuncAmd = (ASM_RELOCATE_AP_LOOP_AMD)(UINTN)mReservedApLoopFunc; + AsmRelocateApLoopFuncAmd ( + MwaitSupport, + CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, + StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, + (UINTN)&mNumberToFinish, + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer + ); } else { - StackStart = mReservedTopOfApStack; + StackStart = mReservedTopOfApStack; + AsmRelocateApLoopFunc = (ASM_RELOCATE_AP_LOOP)(UINTN)mReservedApLoopFunc; + AsmRelocateApLoopFunc ( + MwaitSupport, + CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, + StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, + (UINTN)&mNumberToFinish, + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer + ); } - AsmRelocateApLoopFunc = (ASM_RELOCATE_AP_LOOP)(UINTN)mReservedApLoopFunc; - AsmRelocateApLoopFunc ( - MwaitSupport, - CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, - StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, - (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer - ); // // It should never reach here // diff --git a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc index ebadcc6fb3..ea202d4aef 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc +++ b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc @@ -26,6 +26,8 @@ struc MP_ASSEMBLY_ADDRESS_MAP .RendezvousFunnelSize CTYPE_UINTN 1 .RelocateApLoopFuncAddress CTYPE_UINTN 1 .RelocateApLoopFuncSize CTYPE_UINTN 1 + .RelocateApLoopFuncAddressAmd CTYPE_UINTN 1 + .RelocateApLoopFuncSizeAmd CTYPE_UINTN 1 .ModeTransitionOffset CTYPE_UINTN 1 .SwitchToRealNoNxOffset CTYPE_UINTN 1 .SwitchToRealPM16ModeOffset CTYPE_UINTN 1 diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index f5086e497e..1102003a93 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -179,6 +179,8 @@ typedef struct { UINTN RendezvousFunnelSize; UINT8 *RelocateApLoopFuncAddress; UINTN RelocateApLoopFuncSize; + UINT8 *RelocateApLoopFuncAddressAmd; + UINTN RelocateApLoopFuncSizeAmd; UINTN ModeTransitionOffset; UINTN SwitchToRealNoNxOffset; UINTN SwitchToRealPM16ModeOffset; @@ -346,6 +348,31 @@ typedef extern EFI_GUID mCpuInitMpLibHobGuid; +/** + Assembly code to place AP into safe loop mode for Amd. + Place AP into targeted C-State if MONITOR is supported, otherwise + place AP into hlt state. + Place AP in protected mode if the current is long mode. Due to AP maybe + wakeup by some hardware event. It could avoid accessing page table that + may not available during booting to OS. + @param[in] MwaitSupport TRUE indicates MONITOR is supported. + FALSE indicates MONITOR is not supported. + @param[in] ApTargetCState Target C-State value. + @param[in] PmCodeSegment Protected mode code segment value. +**/ +typedef + VOID +(EFIAPI *ASM_RELOCATE_AP_LOOP_AMD)( + IN BOOLEAN MwaitSupport, + IN UINTN ApTargetCState, + IN UINTN PmCodeSegment, + IN UINTN TopOfApStack, + IN UINTN NumberToFinish, + IN UINTN Pm16CodeSegment, + IN UINTN SevEsAPJumpTable, + IN UINTN WakeupBuffer + ); + /** Assembly code to place AP into safe loop mode. diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm index 7c2469f9c5..b2d95adf6d 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm @@ -346,3 +346,172 @@ PM16Mode: iret SwitchToRealProcEnd: +;------------------------------------------------------------------------------------- +; AsmRelocateApLoopAmd (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); +;------------------------------------------------------------------------------------- + +AsmRelocateApLoopStartAmd: +BITS 64 + cmp qword [rsp + 56], 0 ; SevEsAPJumpTable + je NoSevEsAmd + + ; + ; Perform some SEV-ES related setup before leaving 64-bit mode + ; + push rcx + push rdx + + ; + ; Get the RDX reset value using CPUID + ; + mov rax, 1 + cpuid + mov rsi, rax ; Save off the reset value for RDX + + ; + ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call + ; - Must be done while in 64-bit long mode so that writes to + ; the GHCB memory will be unencrypted. + ; - No NAE events can be generated once this is set otherwise + ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. + ; + mov rcx, 0xc0010130 + rdmsr ; Retrieve current GHCB address + shl rdx, 32 + or rdx, rax + + mov rdi, rdx + xor rax, rax + mov rcx, 0x800 + shr rcx, 3 + rep stosq ; Clear the GHCB + + mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD + mov [rdx + 0x390], rax + mov rax, 114 ; Set SwExitCode valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo1 valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo2 valid bit + bts [rdx + 0x3f0], rax + + pop rdx + pop rcx + +NoSevEsAmd: + cli ; Disable interrupt before switching to 32-bit mode + mov rax, [rsp + 40] ; CountTofinish + lock dec dword [rax] ; (*CountTofinish)-- + + mov r10, [rsp + 48] ; Pm16CodeSegment + mov rax, [rsp + 56] ; SevEsAPJumpTable + mov rbx, [rsp + 64] ; WakeupBuffer + mov rsp, r9 ; TopOfApStack + + push rax ; Save SevEsAPJumpTable + push rbx ; Save WakeupBuffer + push r10 ; Save Pm16CodeSegment + push rcx ; Save MwaitSupport + push rdx ; Save ApTargetCState + + lea rax, [PmEntryAmd] ; rax <- The start address of transition code + + push r8 + push rax + + ; + ; Clear R8 - R15, for reset, before going into 32-bit mode + ; + xor r8, r8 + xor r9, r9 + xor r10, r10 + xor r11, r11 + xor r12, r12 + xor r13, r13 + xor r14, r14 + xor r15, r15 + + ; + ; Far return into 32-bit mode + ; +o64 retf + +BITS 32 +PmEntryAmd: + mov eax, cr0 + btr eax, 31 ; Clear CR0.PG + mov cr0, eax ; Disable paging and caches + + mov ecx, 0xc0000080 + rdmsr + and ah, ~ 1 ; Clear LME + wrmsr + mov eax, cr4 + and al, ~ (1 << 5) ; Clear PAE + mov cr4, eax + + pop edx + add esp, 4 + pop ecx, + add esp, 4 + +MwaitCheckAmd: + cmp cl, 1 ; Check mwait-monitor support + jnz HltLoopAmd + mov ebx, edx ; Save C-State to ebx +MwaitLoopAmd: + cli + mov eax, esp ; Set Monitor Address + xor ecx, ecx ; ecx = 0 + xor edx, edx ; edx = 0 + monitor + mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] + shl eax, 4 + mwait + jmp MwaitLoopAmd + +HltLoopAmd: + pop edx ; PM16CodeSegment + add esp, 4 + pop ebx ; WakeupBuffer + add esp, 4 + pop eax ; SevEsAPJumpTable + add esp, 4 + cmp eax, 0 ; Check for SEV-ES + je DoHltAmd + + cli + ; + ; SEV-ES is enabled, use VMGEXIT (GHCB information already + ; set by caller) + ; +BITS 64 + rep vmmcall +BITS 32 + + ; + ; Back from VMGEXIT AP_HLT_LOOP + ; Push the FLAGS/CS/IP values to use + ; + push word 0x0002 ; EFLAGS + xor ecx, ecx + mov cx, [eax + 2] ; CS + push cx + mov cx, [eax] ; IP + push cx + push word 0x0000 ; For alignment, will be discarded + + push edx + push ebx + + mov edx, esi ; Restore RDX reset value + + retf + +DoHltAmd: + cli + hlt + jmp DoHltAmd + +BITS 64 +AsmRelocateApLoopEndAmd: diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 5d71995bf8..39c3e8606a 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -460,6 +460,11 @@ ASM_PFX(AsmGetAddressMap): mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddress], rax mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSize], AsmRelocateApLoopEnd - AsmRelocateApLoopStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.ModeTransitionOffset], Flat32Start - RendezvousFunnelProcStart + + lea rax, [AsmRelocateApLoopStartAmd] + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressAmd], rax + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeAmd], AsmRelocateApLoopEndAmd - AsmRelocateApLoopStartAmd + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealNoNxOffset], SwitchToRealProcStart - Flat32Start mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeOffset], PM16Mode - RendezvousFunnelProcStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeSize], SwitchToRealProcEnd - PM16Mode From 77b84662a5ae4d06fd953ac31c9d4e076d3c74b0 Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Tue, 20 Dec 2022 05:40:15 +0800 Subject: [PATCH 0415/1529] UefiCpuPkg: Has APs in 64 bit long-mode before booting to OS. During the finalization of Mp initialization before booting into the OS, depending on whether Mwait is supported or not, AsmRelocateApLoop places Aps in MWAIT-loop or HLT-loop. Since paging is necessary for long mode, the original implementation of moving APs to 32-bit was to disable paging to ensure that the booting does not crash. The current modification creates a page table in reserved memory, avoiding switching modes and reclaiming memory by OS. This modification is only for 64 bit mode. More specifically, we keep the AMD logic as the original code flow, extract and update the Intel-related code, where the APs would stay in 64-bit, and run in a Mwait or Hlt loop until the OS wake them up. Signed-off-by: Ray Ni Signed-off-by: Yuanhao Xie Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 7 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 84 ++++----- .../Library/MpInitLib/Ia32/CreatePageTable.c | 27 +++ UefiCpuPkg/Library/MpInitLib/MpLib.h | 19 +- .../Library/MpInitLib/X64/CreatePageTable.c | 75 ++++++++ UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 171 +++--------------- UefiCpuPkg/UefiCpuPkg.dsc | 1 + 7 files changed, 184 insertions(+), 200 deletions(-) create mode 100644 UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c create mode 100644 UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index cd07de3a3c..8c8b81d933 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -1,7 +1,7 @@ ## @file # MP Initialize Library instance for DXE driver. # -# Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -24,9 +24,11 @@ [Sources.IA32] Ia32/AmdSev.c Ia32/MpFuncs.nasm + Ia32/CreatePageTable.c [Sources.X64] X64/AmdSev.c + X64/CreatePageTable.c X64/MpFuncs.nasm [Sources.common] @@ -57,6 +59,9 @@ CcExitLib MicrocodeLib +[LibraryClasses.X64] + CpuPageTableLib + [Protocols] gEfiTimerArchProtocolGuid ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index 445e0853d2..beab06a5b1 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -28,6 +28,7 @@ volatile BOOLEAN mStopCheckAllApsStatus = TRUE; VOID *mReservedApLoopFunc = NULL; UINTN mReservedTopOfApStack; volatile UINT32 mNumberToFinish = 0; +UINTN mApPageTable; // // Begin wakeup buffer allocation below 0x88000 @@ -407,12 +408,9 @@ RelocateApLoop ( AsmRelocateApLoopFunc ( MwaitSupport, CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer + mApPageTable ); } @@ -477,7 +475,6 @@ InitMpGlobalData ( ) { EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS Address; UINTN ApSafeBufferSize; UINTN Index; EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; @@ -545,60 +542,45 @@ InitMpGlobalData ( // Allocating it in advance since memory services are not available in // Exit Boot Services callback function. // - ApSafeBufferSize = EFI_PAGES_TO_SIZE ( - EFI_SIZE_TO_PAGES ( - CpuMpData->AddressMap.RelocateApLoopFuncSize - ) - ); - Address = BASE_4GB - 1; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - EFI_SIZE_TO_PAGES (ApSafeBufferSize), - &Address - ); - ASSERT_EFI_ERROR (Status); - - mReservedApLoopFunc = (VOID *)(UINTN)Address; - ASSERT (mReservedApLoopFunc != NULL); - - // - // Make sure that the buffer memory is executable if NX protection is enabled - // for EfiReservedMemoryType. - // - // TODO: Check EFI_MEMORY_XP bit set or not once it's available in DXE GCD - // service. + // +------------+ + // | Ap Loop | + // +------------+ + // | Stack * N | + // +------------+ (low address) // - Status = gDS->GetMemorySpaceDescriptor (Address, &MemDesc); - if (!EFI_ERROR (Status)) { - gDS->SetMemorySpaceAttributes ( - Address, - ApSafeBufferSize, - MemDesc.Attributes & (~EFI_MEMORY_XP) - ); - } - ApSafeBufferSize = EFI_PAGES_TO_SIZE ( EFI_SIZE_TO_PAGES ( CpuMpData->CpuCount * AP_SAFE_STACK_SIZE + + CpuMpData->AddressMap.RelocateApLoopFuncSize ) ); - Address = BASE_4GB - 1; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - EFI_SIZE_TO_PAGES (ApSafeBufferSize), - &Address - ); - ASSERT_EFI_ERROR (Status); - mReservedTopOfApStack = (UINTN)Address + ApSafeBufferSize; + mReservedTopOfApStack = (UINTN)AllocateReservedPages (EFI_SIZE_TO_PAGES (ApSafeBufferSize)); + ASSERT (mReservedTopOfApStack != 0); ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); - CopyMem ( - mReservedApLoopFunc, - CpuMpData->AddressMap.RelocateApLoopFuncAddress, - CpuMpData->AddressMap.RelocateApLoopFuncSize - ); + ASSERT ((AP_SAFE_STACK_SIZE & (CPU_STACK_ALIGNMENT - 1)) == 0); + + mReservedApLoopFunc = (VOID *)(mReservedTopOfApStack + CpuMpData->CpuCount * AP_SAFE_STACK_SIZE); + if (StandardSignatureIsAuthenticAMD ()) { + CopyMem ( + mReservedApLoopFunc, + CpuMpData->AddressMap.RelocateApLoopFuncAddressAmd, + CpuMpData->AddressMap.RelocateApLoopFuncSizeAmd + ); + } else { + CopyMem ( + mReservedApLoopFunc, + CpuMpData->AddressMap.RelocateApLoopFuncAddress, + CpuMpData->AddressMap.RelocateApLoopFuncSize + ); + + mApPageTable = CreatePageTable ( + mReservedTopOfApStack, + ApSafeBufferSize + ); + } + + mReservedTopOfApStack += CpuMpData->CpuCount * AP_SAFE_STACK_SIZE; Status = gBS->CreateEvent ( EVT_TIMER | EVT_NOTIFY_SIGNAL, diff --git a/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c new file mode 100644 index 0000000000..525885b77d --- /dev/null +++ b/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c @@ -0,0 +1,27 @@ +/** @file + Function to create page talbe. + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +/** + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ) +{ + return 0; +} diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 1102003a93..13d515c2df 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -392,12 +392,9 @@ typedef (EFIAPI *ASM_RELOCATE_AP_LOOP)( IN BOOLEAN MwaitSupport, IN UINTN ApTargetCState, - IN UINTN PmCodeSegment, IN UINTN TopOfApStack, IN UINTN NumberToFinish, - IN UINTN Pm16CodeSegment, - IN UINTN SevEsAPJumpTable, - IN UINTN WakeupBuffer + IN UINTN Cr3 ); /** @@ -512,6 +509,20 @@ WakeUpAP ( IN BOOLEAN WakeUpDisabledAps ); +/** + Create 1:1 mapping page table in reserved memory to map the specified address range. + + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ); + /** Initialize global data for MP support. diff --git a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c new file mode 100644 index 0000000000..548ef3f2c8 --- /dev/null +++ b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c @@ -0,0 +1,75 @@ +/** @file + Function to create page talbe. + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ +#include +#include +#include +#include +#include + +/** + Create 1:1 mapping page table in reserved memory to map the specified address range. + + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ) +{ + EFI_STATUS Status; + VOID *PageTableBuffer; + UINTN PageTableBufferSize; + UINTN PageTable; + + IA32_MAP_ATTRIBUTE MapAttribute; + IA32_MAP_ATTRIBUTE MapMask; + + MapAttribute.Uint64 = Address; + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; + + MapMask.Bits.PageTableBaseAddress = 1; + MapMask.Bits.Present = 1; + MapMask.Bits.ReadWrite = 1; + + PageTable = 0; + PageTableBufferSize = 0; + + Status = PageTableMap ( + &PageTable, + Paging4Level, + NULL, + &PageTableBufferSize, + Address, + Length, + &MapAttribute, + &MapMask + ); + ASSERT (Status == EFI_BUFFER_TOO_SMALL); + DEBUG ((DEBUG_INFO, "AP Page Table Buffer Size = %x\n", PageTableBufferSize)); + + PageTableBuffer = AllocateReservedPages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); + ASSERT (PageTableBuffer != NULL); + Status = PageTableMap ( + &PageTable, + Paging4Level, + PageTableBuffer, + &PageTableBufferSize, + Address, + Length, + &MapAttribute, + &MapMask + ); + ASSERT_EFI_ERROR (Status); + return PageTable; +} diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 39c3e8606a..8ae287dd8d 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -279,120 +279,42 @@ CProcedureInvoke: RendezvousFunnelProcEnd: ;------------------------------------------------------------------------------------- -; AsmRelocateApLoop (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); +; AsmRelocateApLoop (MwaitSupport, ApTargetCState, TopOfApStack, CountTofinish, Cr3); +; This function is called during the finalizaiton of Mp initialization before booting +; to OS, and aim to put Aps either in Mwait or HLT. ;------------------------------------------------------------------------------------- -AsmRelocateApLoopStart: -BITS 64 - cmp qword [rsp + 56], 0 ; SevEsAPJumpTable - je NoSevEs - - ; - ; Perform some SEV-ES related setup before leaving 64-bit mode - ; - push rcx - push rdx - - ; - ; Get the RDX reset value using CPUID - ; - mov rax, 1 - cpuid - mov rsi, rax ; Save off the reset value for RDX - - ; - ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call - ; - Must be done while in 64-bit long mode so that writes to - ; the GHCB memory will be unencrypted. - ; - No NAE events can be generated once this is set otherwise - ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. - ; - mov rcx, 0xc0010130 - rdmsr ; Retrieve current GHCB address - shl rdx, 32 - or rdx, rax - - mov rdi, rdx - xor rax, rax - mov rcx, 0x800 - shr rcx, 3 - rep stosq ; Clear the GHCB - - mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD - mov [rdx + 0x390], rax - mov rax, 114 ; Set SwExitCode valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo1 valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo2 valid bit - bts [rdx + 0x3f0], rax +; +----------------+ +; | Cr3 | rsp+40 +; +----------------+ +; | CountTofinish | r9 +; +----------------+ +; | TopOfApStack | r8 +; +----------------+ +; | ApTargetCState | rdx +; +----------------+ +; | MwaitSupport | rcx +; +----------------+ +; | the return | +; +----------------+ low address - pop rdx - pop rcx - -NoSevEs: - cli ; Disable interrupt before switching to 32-bit mode - mov rax, [rsp + 40] ; CountTofinish +AsmRelocateApLoopStart: + mov rax, r9 ; CountTofinish lock dec dword [rax] ; (*CountTofinish)-- - mov r10, [rsp + 48] ; Pm16CodeSegment - mov rax, [rsp + 56] ; SevEsAPJumpTable - mov rbx, [rsp + 64] ; WakeupBuffer - mov rsp, r9 ; TopOfApStack - - push rax ; Save SevEsAPJumpTable - push rbx ; Save WakeupBuffer - push r10 ; Save Pm16CodeSegment - push rcx ; Save MwaitSupport - push rdx ; Save ApTargetCState - - lea rax, [PmEntry] ; rax <- The start address of transition code - - push r8 - push rax - - ; - ; Clear R8 - R15, for reset, before going into 32-bit mode - ; - xor r8, r8 - xor r9, r9 - xor r10, r10 - xor r11, r11 - xor r12, r12 - xor r13, r13 - xor r14, r14 - xor r15, r15 - - ; - ; Far return into 32-bit mode - ; - retfq - -BITS 32 -PmEntry: - mov eax, cr0 - btr eax, 31 ; Clear CR0.PG - mov cr0, eax ; Disable paging and caches - - mov ecx, 0xc0000080 - rdmsr - and ah, ~ 1 ; Clear LME - wrmsr - mov eax, cr4 - and al, ~ (1 << 5) ; Clear PAE - mov cr4, eax - - pop edx - add esp, 4 - pop ecx, - add esp, 4 + mov rax, [rsp + 40] ; Cr3 + ; Do not push on old stack, since old stack is not mapped + ; in the page table pointed by cr3 + mov cr3, rax + mov rsp, r8 ; TopOfApStack MwaitCheck: cmp cl, 1 ; Check mwait-monitor support jnz HltLoop - mov ebx, edx ; Save C-State to ebx + mov rbx, rdx ; Save C-State to ebx + MwaitLoop: cli - mov eax, esp ; Set Monitor Address + mov rax, rsp ; Set Monitor Address xor ecx, ecx ; ecx = 0 xor edx, edx ; edx = 0 monitor @@ -402,49 +324,10 @@ MwaitLoop: jmp MwaitLoop HltLoop: - pop edx ; PM16CodeSegment - add esp, 4 - pop ebx ; WakeupBuffer - add esp, 4 - pop eax ; SevEsAPJumpTable - add esp, 4 - cmp eax, 0 ; Check for SEV-ES - je DoHlt - - cli - ; - ; SEV-ES is enabled, use VMGEXIT (GHCB information already - ; set by caller) - ; -BITS 64 - rep vmmcall -BITS 32 - - ; - ; Back from VMGEXIT AP_HLT_LOOP - ; Push the FLAGS/CS/IP values to use - ; - push word 0x0002 ; EFLAGS - xor ecx, ecx - mov cx, [eax + 2] ; CS - push cx - mov cx, [eax] ; IP - push cx - push word 0x0000 ; For alignment, will be discarded - - push edx - push ebx - - mov edx, esi ; Restore RDX reset value - - retf - -DoHlt: cli hlt - jmp DoHlt + jmp HltLoop -BITS 64 AsmRelocateApLoopEnd: ;------------------------------------------------------------------------------------- diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index f9a46089d2..781acedfc5 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -94,6 +94,7 @@ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf RegisterCpuFeaturesLib|UefiCpuPkg/Library/RegisterCpuFeaturesLib/DxeRegisterCpuFeaturesLib.inf CpuCacheInfoLib|UefiCpuPkg/Library/CpuCacheInfoLib/DxeCpuCacheInfoLib.inf From 79c712a42d6f3d9f22e7a3c27d49eb8232c54144 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Tue, 20 Dec 2022 05:40:16 +0800 Subject: [PATCH 0416/1529] OvmfPkg: Add CpuPageTableLib required by MpInitLib. Add CpuPageTableLib required by MpInitLib in OvmfPkg. Signed-off-by: Yuanhao Xie Reviewed-by: Ray Ni Acked-by: Jiewen Yao --- OvmfPkg/AmdSev/AmdSevX64.dsc | 3 ++- OvmfPkg/CloudHv/CloudHvX64.dsc | 1 + OvmfPkg/IntelTdx/IntelTdxX64.dsc | 4 +++- OvmfPkg/Microvm/MicrovmX64.dsc | 3 ++- OvmfPkg/OvmfPkgIa32X64.dsc | 1 + OvmfPkg/OvmfPkgX64.dsc | 2 ++ OvmfPkg/OvmfXen.dsc | 3 ++- 7 files changed, 13 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index d51c913a08..bb91e8c734 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -3,7 +3,7 @@ # virtual machine remote attestation and secret injection # # Copyright (c) 2020 James Bottomley, IBM Corporation. -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -352,6 +352,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 4fe7cb5f1b..4d7107fd19 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -403,6 +403,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 3458926515..ea538fd783 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -313,6 +313,7 @@ CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf @@ -577,6 +578,7 @@ UefiCpuPkg/CpuDxe/CpuDxe.inf { + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf # # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index bcca3afbf6..285ba50671 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -402,6 +402,7 @@ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf PciPcdProducerLib|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index bc0036eda0..d0746cb72b 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -414,6 +414,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index b2b88f48d1..2caa4d2ecc 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -434,6 +434,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf @@ -813,6 +814,7 @@ UefiCpuPkg/CpuDxe/CpuDxe.inf { + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf # # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index 8bb497088b..2af4682b78 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) 2019, Citrix Systems, Inc. # Copyright (c) Microsoft Corporation. @@ -339,6 +339,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf From 2456867c6a5f91d8eab19d901b13908bc340c18a Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Tue, 20 Dec 2022 05:40:17 +0800 Subject: [PATCH 0417/1529] UefiPayloadPkg: Add CpuPageTableLib required by MpInitLib. Add CpuPageTableLib required by MpInitLib in UefiPayloadPkg. Signed-off-by: Yuanhao Xie Reviewed-by: Gua Guo Reviewed-by: Ray Ni --- UefiPayloadPkg/UefiPayloadPkg.dsc | 1 + 1 file changed, 1 insertion(+) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index c2ca9106d1..12e80a9e74 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -340,6 +340,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf !if $(PERFORMANCE_MEASUREMENT_ENABLE) PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf From d5eeb6575dae39c275189d6aa4d94f53f7e59a9b Mon Sep 17 00:00:00 2001 From: Matt DeVillier Date: Fri, 16 Dec 2022 16:58:05 +0800 Subject: [PATCH 0418/1529] MdeModulePkg/XhciDxe/Xhci: Don't check for invalid PSIV PSID matching relies on comparing the PSIV against the PortSpeed value. This patch stops edk2 from checking for a PSIV of 0, as it is not valid; this reduces the number of register access by approximately 6 per second. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Matt DeVillier Reviewed-by: Sean Rhodes Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 44 ++++++++++++++++------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index 15fb49f28f..8dd7a8fbb7 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -371,6 +371,7 @@ XhcGetRootHubPortStatus ( UINT32 TotalPort; UINTN Index; UINTN MapSize; + UINT8 PortSpeed; EFI_STATUS Status; USB_DEV_ROUTE ParentRouteChart; EFI_TPL OldTpl; @@ -397,32 +398,37 @@ XhcGetRootHubPortStatus ( State = XhcReadOpReg (Xhc, Offset); + PortSpeed = (State & XHC_PORTSC_PS) >> 10; + // // According to XHCI 1.1 spec November 2017, // Section 7.2 xHCI Support Protocol Capability // - PortStatus->PortStatus = XhcCheckUsbPortSpeedUsedPsic (Xhc, ((State & XHC_PORTSC_PS) >> 10)); - if (PortStatus->PortStatus == 0) { - // - // According to XHCI 1.1 spec November 2017, - // bit 10~13 of the root port status register identifies the speed of the attached device. - // - switch ((State & XHC_PORTSC_PS) >> 10) { - case 2: - PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; - break; + if (PortSpeed > 0) { + PortStatus->PortStatus = XhcCheckUsbPortSpeedUsedPsic (Xhc, PortSpeed); + // If no match found in ext cap reg, fall back to PORTSC + if (PortStatus->PortStatus == 0) { + // + // According to XHCI 1.1 spec November 2017, + // bit 10~13 of the root port status register identifies the speed of the attached device. + // + switch (PortSpeed) { + case 2: + PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; + break; - case 3: - PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; - break; + case 3: + PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; + break; - case 4: - case 5: - PortStatus->PortStatus |= USB_PORT_STAT_SUPER_SPEED; - break; + case 4: + case 5: + PortStatus->PortStatus |= USB_PORT_STAT_SUPER_SPEED; + break; - default: - break; + default: + break; + } } } From af1b9b54ab6b800450e1295d9d3c873b18033c15 Mon Sep 17 00:00:00 2001 From: Sean Rhodes Date: Fri, 16 Dec 2022 16:58:06 +0800 Subject: [PATCH 0419/1529] MdeModulePkg/Bus/Pci/XhciDxe: Check port is compatible before getting PSIV On some platforms, including Sky Lake and Kaby Lake, the PSIV (Protocol Speed ID Value) indices are shared between Protocol Speed ID DWORD' in the extended capabilities registers for both USB2 (Full Speed) and USB3 (Super Speed). An example can be found below: XhcCheckUsbPortSpeedUsedPsic: checking for USB2 ext caps XhciPsivGetPsid: found 3 PSID entries XhciPsivGetPsid: looking for port speed 1 XhciPsivGetPsid: PSIV 1 PSIE 2 PLT 0 PSIM 12 XhciPsivGetPsid: PSIV 2 PSIE 1 PLT 0 PSIM 1500 XhciPsivGetPsid: PSIV 3 PSIE 2 PLT 0 PSIM 480 XhcCheckUsbPortSpeedUsedPsic: checking for USB3 ext caps XhciPsivGetPsid: found 3 PSID entries XhciPsivGetPsid: looking for port speed 1 XhciPsivGetPsid: PSIV 1 PSIE 3 PLT 0 PSIM 5 XhciPsivGetPsid: PSIV 2 PSIE 3 PLT 0 PSIM 10 XhciPsivGetPsid: PSIV 34 PSIE 2 PLT 0 PSIM 1248 The result is edk2 detecting USB2 devices as USB3 devices, which consequently causes enumeration to fail. To avoid incorrect detection, check the Compatible Port Offset to find the starting Port of Root Hubs that support the protocol. Signed-off-by: Sean Rhodes Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 2 +- MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c | 35 +++++++++++++++++++++----- MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h | 10 +++++--- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index 8dd7a8fbb7..461b2cd9b5 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -405,7 +405,7 @@ XhcGetRootHubPortStatus ( // Section 7.2 xHCI Support Protocol Capability // if (PortSpeed > 0) { - PortStatus->PortStatus = XhcCheckUsbPortSpeedUsedPsic (Xhc, PortSpeed); + PortStatus->PortStatus = XhcCheckUsbPortSpeedUsedPsic (Xhc, PortSpeed, PortNumber); // If no match found in ext cap reg, fall back to PORTSC if (PortStatus->PortStatus == 0) { // diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c index 2b4a4b2444..5700fc5fb8 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c @@ -636,6 +636,7 @@ XhcGetSupportedProtocolCapabilityAddr ( @param Xhc The XHCI Instance. @param ExtCapOffset The USB Major Version in xHCI Support Protocol Capability Field @param PortSpeed The Port Speed Field in USB PortSc register + @param PortNumber The Port Number (0-indexed) @return The Protocol Speed ID (PSI) from xHCI Supported Protocol capability register. @@ -644,12 +645,15 @@ UINT32 XhciPsivGetPsid ( IN USB_XHCI_INSTANCE *Xhc, IN UINT32 ExtCapOffset, - IN UINT8 PortSpeed + IN UINT8 PortSpeed, + IN UINT8 PortNumber ) { XHC_SUPPORTED_PROTOCOL_DW2 PortId; XHC_SUPPORTED_PROTOCOL_PROTOCOL_SPEED_ID Reg; UINT32 Count; + UINT32 MinPortIndex; + UINT32 MaxPortIndex; if ((Xhc == NULL) || (ExtCapOffset == 0xFFFFFFFF)) { return 0; @@ -663,6 +667,23 @@ XhciPsivGetPsid ( // PortId.Dword = XhcReadExtCapReg (Xhc, ExtCapOffset + XHC_SUPPORTED_PROTOCOL_DW2_OFFSET); + // + // According to XHCI 1.1 spec November 2017, valid values + // for CompPortOffset are 1 to CompPortCount - 1. + // + // PortNumber is zero-indexed, so subtract 1. + // + if ((PortId.Data.CompPortOffset == 0) || (PortId.Data.CompPortCount == 0)) { + return 0; + } + + MinPortIndex = PortId.Data.CompPortOffset - 1; + MaxPortIndex = MinPortIndex + PortId.Data.CompPortCount - 1; + + if ((PortNumber < MinPortIndex) || (PortNumber > MaxPortIndex)) { + return 0; + } + for (Count = 0; Count < PortId.Data.Psic; Count++) { Reg.Dword = XhcReadExtCapReg (Xhc, ExtCapOffset + XHC_SUPPORTED_PROTOCOL_PSI_OFFSET + (Count << 2)); if (Reg.Data.Psiv == PortSpeed) { @@ -676,8 +697,9 @@ XhciPsivGetPsid ( /** Find PortSpeed value match case in XHCI Supported Protocol Capability - @param Xhc The XHCI Instance. - @param PortSpeed The Port Speed Field in USB PortSc register + @param Xhc The XHCI Instance. + @param PortSpeed The Port Speed Field in USB PortSc register + @param PortNumber The Port Number (0-indexed) @return The USB Port Speed. @@ -685,7 +707,8 @@ XhciPsivGetPsid ( UINT16 XhcCheckUsbPortSpeedUsedPsic ( IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 PortSpeed + IN UINT8 PortSpeed, + IN UINT8 PortNumber ) { XHC_SUPPORTED_PROTOCOL_PROTOCOL_SPEED_ID SpField; @@ -703,7 +726,7 @@ XhcCheckUsbPortSpeedUsedPsic ( // PortSpeed definition when the Major Revision is 03h. // if (Xhc->Usb3SupOffset != 0xFFFFFFFF) { - SpField.Dword = XhciPsivGetPsid (Xhc, Xhc->Usb3SupOffset, PortSpeed); + SpField.Dword = XhciPsivGetPsid (Xhc, Xhc->Usb3SupOffset, PortSpeed, PortNumber); if (SpField.Dword != 0) { // // Found the corresponding PORTSC value in PSIV field of USB3 offset. @@ -717,7 +740,7 @@ XhcCheckUsbPortSpeedUsedPsic ( // PortSpeed definition when the Major Revision is 02h. // if ((UsbSpeedIdMap == 0) && (Xhc->Usb2SupOffset != 0xFFFFFFFF)) { - SpField.Dword = XhciPsivGetPsid (Xhc, Xhc->Usb2SupOffset, PortSpeed); + SpField.Dword = XhciPsivGetPsid (Xhc, Xhc->Usb2SupOffset, PortSpeed, PortNumber); if (SpField.Dword != 0) { // // Found the corresponding PORTSC value in PSIV field of USB2 offset. diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h index 5fe2ba4f0e..63bcae8974 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h @@ -621,10 +621,11 @@ XhcGetSupportedProtocolCapabilityAddr ( ); /** - Find SpeedField value match with Port Speed ID value. + Find PortSpeed value match case in XHCI Supported Protocol Capability - @param Xhc The XHCI Instance. - @param Speed The Port Speed filed in USB PortSc register + @param Xhc The XHCI Instance. + @param PortSpeed The Port Speed Field in USB PortSc register + @param PortNumber The Port Number (0-indexed) @return The USB Port Speed. @@ -632,7 +633,8 @@ XhcGetSupportedProtocolCapabilityAddr ( UINT16 XhcCheckUsbPortSpeedUsedPsic ( IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 Speed + IN UINT8 PortSpeed, + IN UINT8 PortNumber ); #endif From a293752308e026cb9b6ce878bb8f307bb49b0475 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 29 Nov 2022 20:27:26 +0800 Subject: [PATCH 0420/1529] MdePkg: Fix typo of EFI_INVALID_PARAMETER in Protocol/UsbIo.h Fix typo of EFI_INVALID_PARAMETER in Protocol/UsbIo.h by adding a missing 'R'. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- MdePkg/Include/Protocol/UsbIo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/Protocol/UsbIo.h b/MdePkg/Include/Protocol/UsbIo.h index 4816b9039e..a780b4e07b 100644 --- a/MdePkg/Include/Protocol/UsbIo.h +++ b/MdePkg/Include/Protocol/UsbIo.h @@ -105,7 +105,7 @@ EFI_STATUS @retval EFI_SUCCESS The control transfer has been successfully executed. @retval EFI_DEVICE_ERROR The transfer failed. The transfer status is returned in Status. - @retval EFI_INVALID_PARAMETE One or more parameters are invalid. + @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_TIMEOUT The control transfer fails due to timeout. @@ -148,7 +148,7 @@ EFI_STATUS @retval EFI_SUCCESS The bulk transfer has been successfully executed. @retval EFI_DEVICE_ERROR The transfer failed. The transfer status is returned in Status. - @retval EFI_INVALID_PARAMETE One or more parameters are invalid. + @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The request could not be submitted due to a lack of resources. @retval EFI_TIMEOUT The control transfer fails due to timeout. From a32c0a304e9ab20c3258b695d54688d252180168 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 29 Nov 2022 20:22:55 +0800 Subject: [PATCH 0421/1529] MdePkg: Fix typos and spacing in Library/PerformanceLib.h - Fix typos of "disable". - Fix typos of "performance". - Fix missing spaces. - Use comma instead of period when the sentence continues on the next line. - Fix typo of "PERF_CORE_LOAD_IMAGE". Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- MdePkg/Include/Library/PerformanceLib.h | 62 ++++++++++++------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/MdePkg/Include/Library/PerformanceLib.h b/MdePkg/Include/Library/PerformanceLib.h index 711e3fc06f..34ec956b9c 100644 --- a/MdePkg/Include/Library/PerformanceLib.h +++ b/MdePkg/Include/Library/PerformanceLib.h @@ -352,7 +352,7 @@ LogPerformanceMeasurement ( Begin Macro to measure the performance of StartImage in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT1(dsiable PERF_CORE_START_IMAGE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT1 (disable PERF_CORE_START_IMAGE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -367,7 +367,7 @@ LogPerformanceMeasurement ( End Macro to measure the performance of StartImage in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT1 (dsiable PERF_CORE_START_IMAGE)of PcdPerformanceLibraryPropertyMask is not set. + and the BIT1 (disable PERF_CORE_START_IMAGE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -382,7 +382,7 @@ LogPerformanceMeasurement ( Begin Macro to measure the performance of LoadImage in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT2 (dsiable PERF_CORE_LOAD_IAMGE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT2 (disable PERF_CORE_LOAD_IMAGE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -397,7 +397,7 @@ LogPerformanceMeasurement ( End Macro to measure the performance of LoadImage in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT2 (dsiable PERF_CORE_LOAD_IAMGE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT2 (disable PERF_CORE_LOAD_IMAGE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -412,7 +412,7 @@ LogPerformanceMeasurement ( Start Macro to measure the performance of DriverBinding Support in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT3 (dsiable PERF_CORE_DB_SUPPORT) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT3 (disable PERF_CORE_DB_SUPPORT) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -427,7 +427,7 @@ LogPerformanceMeasurement ( End Macro to measure the performance of DriverBinding Support in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT3 (dsiable PERF_CORE_DB_SUPPORT) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT3 (disable PERF_CORE_DB_SUPPORT) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -442,7 +442,7 @@ LogPerformanceMeasurement ( Begin Macro to measure the performance of DriverBinding Start in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT4 (dsiable PERF_CORE_DB_START) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT4 (disable PERF_CORE_DB_START) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -457,7 +457,7 @@ LogPerformanceMeasurement ( End Macro to measure the performance of DriverBinding Start in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT4 (dsiable PERF_CORE_DB_START) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT4 (disable PERF_CORE_DB_START) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -472,7 +472,7 @@ LogPerformanceMeasurement ( Start Macro to measure the performance of DriverBinding Stop in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT5 (dsiable PERF_CORE_DB_STOP) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT5 (disable PERF_CORE_DB_STOP) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -487,7 +487,7 @@ LogPerformanceMeasurement ( End Macro to measure the performance of DriverBinding Stop in core. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT5 (dsiable PERF_CORE_DB_STOP) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT5 (disable PERF_CORE_DB_STOP) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -503,7 +503,7 @@ LogPerformanceMeasurement ( It can be used to log a meaningful thing which happens at a time point. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -515,11 +515,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - Begin Macro to measure the perofrmance of evnent signal behavior in any module. + Begin Macro to measure the performance of evnent signal behavior in any module. The event guid will be passed with this macro. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -531,11 +531,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - End Macro to measure the perofrmance of evnent signal behavior in any module. + End Macro to measure the performance of evnent signal behavior in any module. The event guid will be passed with this macro. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -547,11 +547,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - Begin Macro to measure the perofrmance of a callback function in any module. + Begin Macro to measure the performance of a callback function in any module. The event guid which trigger the callback function will be passed with this macro. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -563,11 +563,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - End Macro to measure the perofrmance of a callback function in any module. + End Macro to measure the performance of a callback function in any module. The event guid which trigger the callback function will be passed with this macro. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -579,10 +579,10 @@ LogPerformanceMeasurement ( } while (FALSE) /** - Begin Macro to measure the perofrmance of a general function in any module. + Begin Macro to measure the performance of a general function in any module. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -594,10 +594,10 @@ LogPerformanceMeasurement ( } while (FALSE) /** - End Macro to measure the perofrmance of a general function in any module. + End Macro to measure the performance of a general function in any module. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -609,10 +609,10 @@ LogPerformanceMeasurement ( } while (FALSE) /** - Begin Macro to measure the perofrmance of a behavior within one module. + Begin Macro to measure the performance of a behavior within one module. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -624,10 +624,10 @@ LogPerformanceMeasurement ( } while (FALSE) /** - End Macro to measure the perofrmance of a behavior within one module. + End Macro to measure the performance of a behavior within one module. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -639,11 +639,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - Begin Macro to measure the perofrmance of a behavior in different modules. + Begin Macro to measure the performance of a behavior in different modules. Such as the performance of PEI phase, DXE phase, BDS phase. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ @@ -655,11 +655,11 @@ LogPerformanceMeasurement ( } while (FALSE) /** - End Macro to measure the perofrmance of a behavior in different modules. + End Macro to measure the performance of a behavior in different modules. Such as the performance of PEI phase, DXE phase, BDS phase. If the PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED bit of PcdPerformanceLibraryPropertyMask is set, - and the BIT6 (dsiable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set. + and the BIT6 (disable PERF_GENERAL_TYPE) of PcdPerformanceLibraryPropertyMask is not set, then LogPerformanceMeasurement() is called. **/ From b6a06526a05fd3f1aab06fccfc323f11d96d9b83 Mon Sep 17 00:00:00 2001 From: MarsX Lin Date: Tue, 20 Dec 2022 17:03:35 +0800 Subject: [PATCH 0422/1529] UefiPayloadPkg: Fixed that The UPL info section is not aligned at 4-byte REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4196 Align .upld_info with 4-byte boundary by spec Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: MarsX Lin --- UefiPayloadPkg/UniversalPayloadBuild.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 6d62b8b20f..522855eba4 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -135,7 +135,7 @@ def BuildUniversalPayload(Args, MacroList): BdsFvOutputDir, EntryOutputDir ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=16 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( + set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( LlvmObjcopyPath, ObjCopyFlag, ObjCopyFlag, From 753e990b95f9da9c9122425da12180811ed8d9ed Mon Sep 17 00:00:00 2001 From: Jian J Wang Date: Thu, 15 Dec 2022 11:02:23 +0800 Subject: [PATCH 0423/1529] SecurityPkg: deprecate RpmcLib and VariableKeyLib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2594 There's no real usage of these two libraries. They're deprecated. Cc: Jiewen Yao Cc: Michael D Kinney Cc: Nishant C Mistry Cc: Judah Vang Signed-off-by: Jian J Wang Reviewed-by: Jiewen Yao Acked-by: Michael D Kinney --- SecurityPkg/Include/Library/RpmcLib.h | 42 ------------ SecurityPkg/Include/Library/VariableKeyLib.h | 59 ----------------- SecurityPkg/Library/RpmcLibNull/RpmcLibNull.c | 46 ------------- .../Library/RpmcLibNull/RpmcLibNull.inf | 33 ---------- .../VariableKeyLibNull/VariableKeyLibNull.c | 66 ------------------- .../VariableKeyLibNull/VariableKeyLibNull.inf | 33 ---------- SecurityPkg/SecurityPkg.dec | 8 --- SecurityPkg/SecurityPkg.dsc | 4 -- 8 files changed, 291 deletions(-) delete mode 100644 SecurityPkg/Include/Library/RpmcLib.h delete mode 100644 SecurityPkg/Include/Library/VariableKeyLib.h delete mode 100644 SecurityPkg/Library/RpmcLibNull/RpmcLibNull.c delete mode 100644 SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf delete mode 100644 SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.c delete mode 100644 SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf diff --git a/SecurityPkg/Include/Library/RpmcLib.h b/SecurityPkg/Include/Library/RpmcLib.h deleted file mode 100644 index df4ba34ba8..0000000000 --- a/SecurityPkg/Include/Library/RpmcLib.h +++ /dev/null @@ -1,42 +0,0 @@ -/** @file - Public definitions for the Replay Protected Monotonic Counter (RPMC) Library. - -Copyright (c) 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef _RPMC_LIB_H_ -#define _RPMC_LIB_H_ - -#include - -/** - Requests the monotonic counter from the designated RPMC counter. - - @param[out] CounterValue A pointer to a buffer to store the RPMC value. - - @retval EFI_SUCCESS The operation completed successfully. - @retval EFI_DEVICE_ERROR A device error occurred while attempting to update the counter. - @retval EFI_UNSUPPORTED The operation is un-supported. -**/ -EFI_STATUS -EFIAPI -RequestMonotonicCounter ( - OUT UINT32 *CounterValue - ); - -/** - Increments the monotonic counter in the SPI flash device by 1. - - @retval EFI_SUCCESS The operation completed successfully. - @retval EFI_DEVICE_ERROR A device error occurred while attempting to update the counter. - @retval EFI_UNSUPPORTED The operation is un-supported. -**/ -EFI_STATUS -EFIAPI -IncrementMonotonicCounter ( - VOID - ); - -#endif diff --git a/SecurityPkg/Include/Library/VariableKeyLib.h b/SecurityPkg/Include/Library/VariableKeyLib.h deleted file mode 100644 index 561ebad09d..0000000000 --- a/SecurityPkg/Include/Library/VariableKeyLib.h +++ /dev/null @@ -1,59 +0,0 @@ -/** @file - Public definitions for Variable Key Library. - -Copyright (c) 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef _VARIABLE_KEY_LIB_H_ -#define _VARIABLE_KEY_LIB_H_ - -#include - -/** - Retrieves the key for integrity and/or confidentiality of variables. - - @param[out] VariableKey A pointer to pointer for the variable key buffer. - @param[in,out] VariableKeySize The size in bytes of the variable key. - - @retval EFI_SUCCESS The variable key was returned. - @retval EFI_DEVICE_ERROR An error occurred while attempting to get the variable key. - @retval EFI_ACCESS_DENIED The function was invoked after locking the key interface. - @retval EFI_UNSUPPORTED The variable key is not supported in the current boot configuration. -**/ -EFI_STATUS -EFIAPI -GetVariableKey ( - OUT VOID **VariableKey, - IN OUT UINTN *VariableKeySize - ); - -/** - Regenerates the variable key. - - @retval EFI_SUCCESS The variable key was regenerated successfully. - @retval EFI_DEVICE_ERROR An error occurred while attempting to regenerate the key. - @retval EFI_ACCESS_DENIED The function was invoked after locking the key interface. - @retval EFI_UNSUPPORTED Key regeneration is not supported in the current boot configuration. -**/ -EFI_STATUS -EFIAPI -RegenerateVariableKey ( - VOID - ); - -/** - Locks the regenerate key interface. - - @retval EFI_SUCCESS The key interface was locked successfully. - @retval EFI_UNSUPPORTED Locking the key interface is not supported in the current boot configuration. - @retval Others An error occurred while attempting to lock the key interface. -**/ -EFI_STATUS -EFIAPI -LockVariableKeyInterface ( - VOID - ); - -#endif diff --git a/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.c b/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.c deleted file mode 100644 index 792e48250e..0000000000 --- a/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.c +++ /dev/null @@ -1,46 +0,0 @@ -/** @file - NULL RpmcLib instance for build purpose. - -Copyright (c) 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Requests the monotonic counter from the designated RPMC counter. - - @param[out] CounterValue A pointer to a buffer to store the RPMC value. - - @retval EFI_SUCCESS The operation completed successfully. - @retval EFI_DEVICE_ERROR A device error occurred while attempting to update the counter. - @retval EFI_UNSUPPORTED The operation is un-supported. -**/ -EFI_STATUS -EFIAPI -RequestMonotonicCounter ( - OUT UINT32 *CounterValue - ) -{ - ASSERT (FALSE); - return EFI_UNSUPPORTED; -} - -/** - Increments the monotonic counter in the SPI flash device by 1. - - @retval EFI_SUCCESS The operation completed successfully. - @retval EFI_DEVICE_ERROR A device error occurred while attempting to update the counter. - @retval EFI_UNSUPPORTED The operation is un-supported. -**/ -EFI_STATUS -EFIAPI -IncrementMonotonicCounter ( - VOID - ) -{ - ASSERT (FALSE); - return EFI_UNSUPPORTED; -} diff --git a/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf b/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf deleted file mode 100644 index 500edfa87d..0000000000 --- a/SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf +++ /dev/null @@ -1,33 +0,0 @@ -## @file -# Provides Null version of RpmcLib for build purpose. -# -# Copyright (c) 2020, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010029 - BASE_NAME = RpmcLibNull - FILE_GUID = FAE0BA22-92E2-4334-8F0F-96AFF9BAE360 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = RpmcLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 Arm AArch64 -# - -[Sources] - RpmcLibNull.c - -[Packages] - MdePkg/MdePkg.dec - SecurityPkg/SecurityPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - diff --git a/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.c b/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.c deleted file mode 100644 index a08def767b..0000000000 --- a/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.c +++ /dev/null @@ -1,66 +0,0 @@ -/** @file - Null version of VariableKeyLib for build purpose. Don't use it in real product. - -Copyright (c) 2020, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ -#include -#include - -/** - Retrieves the key for integrity and/or confidentiality of variables. - - @param[out] VariableKey A pointer to pointer for the variable key buffer. - @param[in,out] VariableKeySize The size in bytes of the variable key. - - @retval EFI_SUCCESS The variable key was returned. - @retval EFI_DEVICE_ERROR An error occurred while attempting to get the variable key. - @retval EFI_ACCESS_DENIED The function was invoked after locking the key interface. - @retval EFI_UNSUPPORTED The variable key is not supported in the current boot configuration. -**/ -EFI_STATUS -EFIAPI -GetVariableKey ( - OUT VOID **VariableKey, - IN OUT UINTN *VariableKeySize - ) -{ - ASSERT (FALSE); - return EFI_UNSUPPORTED; -} - -/** - Regenerates the variable key. - - @retval EFI_SUCCESS The variable key was regenerated successfully. - @retval EFI_DEVICE_ERROR An error occurred while attempting to regenerate the key. - @retval EFI_ACCESS_DENIED The function was invoked after locking the key interface. - @retval EFI_UNSUPPORTED Key regeneration is not supported in the current boot configuration. -**/ -EFI_STATUS -EFIAPI -RegenerateVariableKey ( - VOID - ) -{ - ASSERT (FALSE); - return EFI_UNSUPPORTED; -} - -/** - Locks the regenerate key interface. - - @retval EFI_SUCCESS The key interface was locked successfully. - @retval EFI_UNSUPPORTED Locking the key interface is not supported in the current boot configuration. - @retval Others An error occurred while attempting to lock the key interface. -**/ -EFI_STATUS -EFIAPI -LockVariableKeyInterface ( - VOID - ) -{ - ASSERT (FALSE); - return EFI_UNSUPPORTED; -} diff --git a/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf b/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf deleted file mode 100644 index ea74e38cf9..0000000000 --- a/SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf +++ /dev/null @@ -1,33 +0,0 @@ -## @file -# Provides Null version of VariableKeyLib for build only. -# -# Copyright (c) 2020, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010029 - BASE_NAME = VariableKeyLibNull - FILE_GUID = 2B640ED8-1E6A-4516-9F1D-25910E59BC4A - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = VariableKeyLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 Arm AArch64 -# - -[Sources] - VariableKeyLibNull.c - -[Packages] - MdePkg/MdePkg.dec - SecurityPkg/SecurityPkg.dec - -[LibraryClasses] - BaseLib - DebugLib - diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 7ecf9565d9..358b3dc543 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -80,14 +80,6 @@ # TcgStorageOpalLib|Include/Library/TcgStorageOpalLib.h - ## @libraryclass Provides interfaces to access RPMC device. - # - RpmcLib|Include/Library/RpmcLib.h - - ## @libraryclass Provides interfaces to access variable root key. - # - VariableKeyLib|Include/Library/VariableKeyLib.h - ## @libraryclass Provides interfaces about firmware TPM measurement. # TcgEventLogRecordLib|Include/Library/TcgEventLogRecordLib.h diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index 30d911d8a1..2f679c87a9 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -68,8 +68,6 @@ TcgStorageCoreLib|SecurityPkg/Library/TcgStorageCoreLib/TcgStorageCoreLib.inf TcgStorageOpalLib|SecurityPkg/Library/TcgStorageOpalLib/TcgStorageOpalLib.inf ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf - VariableKeyLib|SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf - RpmcLib|SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf TcgEventLogRecordLib|SecurityPkg/Library/TcgEventLogRecordLib/TcgEventLogRecordLib.inf MmUnblockMemoryLib|MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf @@ -264,8 +262,6 @@ # # Variable Confidentiality & Integrity # - SecurityPkg/Library/VariableKeyLibNull/VariableKeyLibNull.inf - SecurityPkg/Library/RpmcLibNull/RpmcLibNull.inf SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.inf # From 56edb9c9409430ec9b29439dc41b2b414129602f Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:35 +0800 Subject: [PATCH 0424/1529] OvmfPkg/TdxMailboxLib: Delete global variables BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 TdxMailboxLib once was designed to be used in DXE phase. But now it is going to be used in SEC/PEI phase (in the following patches). Global variables are not allowed. The library is refactored after those global variables are deleted. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c index 74cb55611f..c580a28856 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c @@ -13,14 +13,10 @@ #include #include #include -#include #include #include #include -volatile VOID *mMailBox = NULL; -UINT32 mNumOfCpus = 0; - /** This function will be called by BSP to get the CPU number. @@ -32,11 +28,17 @@ GetCpusNum ( VOID ) { - if (mNumOfCpus == 0) { - mNumOfCpus = TdVCpuNum (); + UINT64 Status; + TD_RETURN_DATA TdReturnData; + + Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (Status == TDX_EXIT_REASON_SUCCESS) { + return TdReturnData.TdInfo.NumVcpus; + } else { + DEBUG ((DEBUG_ERROR, "Failed call TDCALL_TDINFO. %llx\n", Status)); } - return mNumOfCpus; + return 0; } /** @@ -48,11 +50,7 @@ GetTdxMailBox ( VOID ) { - if (mMailBox == NULL) { - mMailBox = (VOID *)(UINTN)PcdGet32 (PcdOvmfSecGhcbBackupBase); - } - - return mMailBox; + return (VOID *)(UINTN)PcdGet32 (PcdOvmfSecGhcbBackupBase); } /** From 2fa6fc1236d4eae3d8fd3b365977e70dcc94bbaa Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:36 +0800 Subject: [PATCH 0425/1529] OvmfPkg/TdxMailboxLib: Add NULL instance of TdxMailboxLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 TdxMailboxLib is designed only for TDX guest which arch is X64. This patch set the VALID_ARCHITECTURES of TdxMailboxLib as X64. Because in the following patches TdxMailboxLib will be included in PlatformInitLib. While PlatformInitLib is imported by some X64 platforms (for example AmdSevX64.dsc). So we need a NULL instance of TdxMailboxLib which VALID_ARCHITECTURES is X64 as well. Based on this consideration we design TdxMailboxLibNull. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- .../Library/TdxMailboxLib/TdxMailboxLib.inf | 7 ++-- .../TdxMailboxLib/TdxMailboxLibNull.inf | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf index 3cf3690a16..e504bda0dd 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf @@ -1,6 +1,6 @@ #/** @file # -# TBD +# TdxMailbox Library # # Copyright (c) 2018, Intel Corporation. All rights reserved.
# Copyright (c) 2008, Apple Inc. All rights reserved.
@@ -19,12 +19,9 @@ LIBRARY_CLASS = TdxMailboxLib # -# VALID_ARCHITECTURES = X64 IA32 +# VALID_ARCHITECTURES = X64 # -[Sources.IA32] - TdxMailboxNull.c - [Sources.X64] TdxMailbox.c diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf new file mode 100644 index 0000000000..8380d9f4f6 --- /dev/null +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf @@ -0,0 +1,34 @@ +#/** @file +# +# Null instance of TdxMailboxLib +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2008, Apple Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +#**/ + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TdxMailboxLibNull + FILE_GUID = 002a1265-a1a0-47cd-bc69-4342b147f57d + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = TdxMailboxLib + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TdxMailboxNull.c + +[Packages] + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib + DebugLib From c9d6feea269cbee4a43fa64d0a2da579fb244231 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:37 +0800 Subject: [PATCH 0426/1529] OvmfPkg: Add TdxMailboxLibNull in some platform dsc BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 In the following patches TdxMailboxLib will be included in PlatformInitLib. While PlatformInitLib is imported by some IA32/X64 platforms (for example AmdSevX64.dsc). So TdxMailboxLibNull is added in those platforms which don't support TDX feature. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/AmdSev/AmdSevX64.dsc | 1 + OvmfPkg/CloudHv/CloudHvX64.dsc | 1 + OvmfPkg/Microvm/MicrovmX64.dsc | 1 + OvmfPkg/OvmfPkgIa32.dsc | 1 + OvmfPkg/OvmfPkgIa32X64.dsc | 2 +- 5 files changed, 5 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index bb91e8c734..18c2922540 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -206,6 +206,7 @@ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf + TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 4d7107fd19..98daf98f43 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -253,6 +253,7 @@ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf + TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 285ba50671..de3b355254 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -255,6 +255,7 @@ FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf VirtioMmioDeviceLib|OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceLib.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf + TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf [LibraryClasses.common.SEC] QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index dcf46d207d..f617aa60ca 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -257,6 +257,7 @@ [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf + TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index d0746cb72b..cbd5df63a1 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -262,7 +262,7 @@ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf TdxLib|MdePkg/Library/TdxLib/TdxLib.inf - TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf + TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLibNull.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf From a500fd5cd0f543fd022de37a0924f71623fcc634 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:38 +0800 Subject: [PATCH 0427/1529] OvmfPkg/Sec: Move TDX APs related nasm code to IntelTdxAPs.nasm BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 This patch moves the TDX APs nasm code from SecEntry.nasm to IntelTdxAPs.nasm. IntelTdxX64 and OvmfPkgX64 use the same nasm so that it can be easier to be managed. In the following patch there will be AcceptMemory related changes in IntelTdxAPs.nasm. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm | 58 +++++++++++++++++++++++ OvmfPkg/IntelTdx/Sec/X64/SecEntry.nasm | 58 ++--------------------- OvmfPkg/Sec/X64/SecEntry.nasm | 58 ++--------------------- 3 files changed, 68 insertions(+), 106 deletions(-) create mode 100644 OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm diff --git a/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm b/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm new file mode 100644 index 0000000000..034ac0ee94 --- /dev/null +++ b/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm @@ -0,0 +1,58 @@ +;------------------------------------------------------------------------------ +; @file +; Intel TDX APs +; +; Copyright (c) 2021 - 2022, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;------------------------------------------------------------------------------ + +%include "TdxCommondefs.inc" + + ; + ; Note: BSP never gets here. APs will be unblocked by DXE + ; + ; R8 [31:0] NUM_VCPUS + ; [63:32] MAX_VCPUS + ; R9 [31:0] VCPU_INDEX + ; +ParkAp: + +do_wait_loop: + ; + ; register itself in [rsp + CpuArrivalOffset] + ; + mov rax, 1 + lock xadd dword [rsp + CpuArrivalOffset], eax + inc eax + +.check_arrival_cnt: + cmp eax, r8d + je .check_command + mov eax, dword[rsp + CpuArrivalOffset] + jmp .check_arrival_cnt + +.check_command: + mov eax, dword[rsp + CommandOffset] + cmp eax, MpProtectedModeWakeupCommandNoop + je .check_command + + cmp eax, MpProtectedModeWakeupCommandWakeup + je .do_wakeup + + ; Don't support this command, so ignore + jmp .check_command + +.do_wakeup: + ; + ; BSP sets these variables before unblocking APs + ; RAX: WakeupVectorOffset + ; RBX: Relocated mailbox address + ; RBP: vCpuId + ; + mov rax, 0 + mov eax, dword[rsp + WakeupVectorOffset] + mov rbx, [rsp + WakeupArgsRelocatedMailBox] + nop + jmp rax + jmp $ diff --git a/OvmfPkg/IntelTdx/Sec/X64/SecEntry.nasm b/OvmfPkg/IntelTdx/Sec/X64/SecEntry.nasm index 4528fec309..5a38c42139 100644 --- a/OvmfPkg/IntelTdx/Sec/X64/SecEntry.nasm +++ b/OvmfPkg/IntelTdx/Sec/X64/SecEntry.nasm @@ -10,7 +10,6 @@ ;------------------------------------------------------------------------------ #include -%include "TdxCommondefs.inc" DEFAULT REL SECTION .text @@ -49,6 +48,7 @@ ASM_PFX(_ModuleEntryPoint): cmp byte[eax], VM_GUEST_TYPE_TDX jne InitStack + %define TDCALL_TDINFO 1 mov rax, TDCALL_TDINFO tdcall @@ -62,7 +62,9 @@ ASM_PFX(_ModuleEntryPoint): mov rax, r9 and rax, 0xffff test rax, rax - jne ParkAp + jz InitStack + mov rsp, FixedPcdGet32 (PcdOvmfSecGhcbBackupBase) + jmp ParkAp InitStack: @@ -98,54 +100,4 @@ InitStack: sub rsp, 0x20 call ASM_PFX(SecCoreStartupWithStack) - ; - ; Note: BSP never gets here. APs will be unblocked by DXE - ; - ; R8 [31:0] NUM_VCPUS - ; [63:32] MAX_VCPUS - ; R9 [31:0] VCPU_INDEX - ; -ParkAp: - - mov rbp, r9 - -.do_wait_loop: - mov rsp, FixedPcdGet32 (PcdOvmfSecGhcbBackupBase) - - ; - ; register itself in [rsp + CpuArrivalOffset] - ; - mov rax, 1 - lock xadd dword [rsp + CpuArrivalOffset], eax - inc eax - -.check_arrival_cnt: - cmp eax, r8d - je .check_command - mov eax, dword[rsp + CpuArrivalOffset] - jmp .check_arrival_cnt - -.check_command: - mov eax, dword[rsp + CommandOffset] - cmp eax, MpProtectedModeWakeupCommandNoop - je .check_command - - cmp eax, MpProtectedModeWakeupCommandWakeup - je .do_wakeup - - ; Don't support this command, so ignore - jmp .check_command - -.do_wakeup: - ; - ; BSP sets these variables before unblocking APs - ; RAX: WakeupVectorOffset - ; RBX: Relocated mailbox address - ; RBP: vCpuId - ; - mov rax, 0 - mov eax, dword[rsp + WakeupVectorOffset] - mov rbx, [rsp + WakeupArgsRelocatedMailBox] - nop - jmp rax - jmp $ +%include "IntelTdxAPs.nasm" diff --git a/OvmfPkg/Sec/X64/SecEntry.nasm b/OvmfPkg/Sec/X64/SecEntry.nasm index 4528fec309..0f82051720 100644 --- a/OvmfPkg/Sec/X64/SecEntry.nasm +++ b/OvmfPkg/Sec/X64/SecEntry.nasm @@ -10,7 +10,6 @@ ;------------------------------------------------------------------------------ #include -%include "TdxCommondefs.inc" DEFAULT REL SECTION .text @@ -49,6 +48,7 @@ ASM_PFX(_ModuleEntryPoint): cmp byte[eax], VM_GUEST_TYPE_TDX jne InitStack + %define TDCALL_TDINFO 1 mov rax, TDCALL_TDINFO tdcall @@ -62,7 +62,9 @@ ASM_PFX(_ModuleEntryPoint): mov rax, r9 and rax, 0xffff test rax, rax - jne ParkAp + jz InitStack + mov rsp, FixedPcdGet32 (PcdOvmfSecGhcbBackupBase) + jmp ParkAp InitStack: @@ -98,54 +100,4 @@ InitStack: sub rsp, 0x20 call ASM_PFX(SecCoreStartupWithStack) - ; - ; Note: BSP never gets here. APs will be unblocked by DXE - ; - ; R8 [31:0] NUM_VCPUS - ; [63:32] MAX_VCPUS - ; R9 [31:0] VCPU_INDEX - ; -ParkAp: - - mov rbp, r9 - -.do_wait_loop: - mov rsp, FixedPcdGet32 (PcdOvmfSecGhcbBackupBase) - - ; - ; register itself in [rsp + CpuArrivalOffset] - ; - mov rax, 1 - lock xadd dword [rsp + CpuArrivalOffset], eax - inc eax - -.check_arrival_cnt: - cmp eax, r8d - je .check_command - mov eax, dword[rsp + CpuArrivalOffset] - jmp .check_arrival_cnt - -.check_command: - mov eax, dword[rsp + CommandOffset] - cmp eax, MpProtectedModeWakeupCommandNoop - je .check_command - - cmp eax, MpProtectedModeWakeupCommandWakeup - je .do_wakeup - - ; Don't support this command, so ignore - jmp .check_command - -.do_wakeup: - ; - ; BSP sets these variables before unblocking APs - ; RAX: WakeupVectorOffset - ; RBX: Relocated mailbox address - ; RBP: vCpuId - ; - mov rax, 0 - mov eax, dword[rsp + WakeupVectorOffset] - mov rbx, [rsp + WakeupArgsRelocatedMailBox] - nop - jmp rax - jmp $ +%include "../../IntelTdx/Sec/X64/IntelTdxAPs.nasm" From afc3900c065d2ad9936ae03377767c97baafe4de Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:39 +0800 Subject: [PATCH 0428/1529] OvmfPkg: Enable APs to accept memory for TDVF BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 TDVF APs once did nothing but spin around to wait for the Wakeup command. This patch enables APs to handle the AcceptPages command. Once APs find the AcceptPages command, it set its stack and jump to the function of ApAcceptMemoryResourceRange (which will be introduced in the following patch). Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Include/TdxCommondefs.inc | 4 +- OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm | 61 +++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/Include/TdxCommondefs.inc b/OvmfPkg/Include/TdxCommondefs.inc index 970eac9659..a29d2fad42 100644 --- a/OvmfPkg/Include/TdxCommondefs.inc +++ b/OvmfPkg/Include/TdxCommondefs.inc @@ -15,8 +15,8 @@ FirmwareArgsOffset equ 800h WakeupArgsRelocatedMailBox equ 800h AcceptPageArgsPhysicalStart equ 800h AcceptPageArgsPhysicalEnd equ 808h -AcceptPageArgsChunkSize equ 810h -AcceptPageArgsPageSize equ 818h +AcceptPageArgsTopStackAddress equ 810h +AcceptPageArgsApStackSize equ 818h CpuArrivalOffset equ 900h CpusExitingOffset equ 0a00h TalliesOffset equ 0a08h diff --git a/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm b/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm index 034ac0ee94..4a984ecc10 100644 --- a/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm +++ b/OvmfPkg/IntelTdx/Sec/X64/IntelTdxAPs.nasm @@ -40,9 +40,70 @@ do_wait_loop: cmp eax, MpProtectedModeWakeupCommandWakeup je .do_wakeup + cmp eax, MpProtectedModeWakeupCommandAcceptPages + je .do_accept_pages + ; Don't support this command, so ignore jmp .check_command +.do_accept_pages: + ; + ; Read the top stack address from arguments + mov rsi, [rsp + AcceptPageArgsTopStackAddress] + + ; + ; Calculate the top stack address of the AP. + ; ApStackAddr = BaseStackAddr + (vCpuIndex) * ApStackSize + xor rdx, rdx + xor rbx, rbx + xor rax, rax + mov eax, [rsp + AcceptPageArgsApStackSize] + mov ebx, r9d ; vCpuIndex + mul ebx + add rsi, rax ; now rsi is ApStackAddr + +.start_accept_pages: + ; + ; Read the function address which will be called + mov rax, [rsp + WakeupVectorOffset] + + ; + ; vCPU index as the first argument + mov ecx, r9d + mov rdx, [rsp + AcceptPageArgsPhysicalStart] + mov r8, [rsp + AcceptPageArgsPhysicalEnd] + + ; save the Mailbox address to rbx + mov rbx, rsp + + ; + ; set AP Stack + mov rsp, rsi + nop + + ; save rax (the Mailbox address) + push rbx + + call rax + + ; recove rsp + pop rbx + mov rsp, rbx + ; + ; recover r8, r9 + mov rax, 1 + tdcall + + mov eax, 0FFFFFFFFh + lock xadd dword [rsp + CpusExitingOffset], eax + dec eax + +.check_exiting_cnt: + cmp eax, 0 + je do_wait_loop + mov eax, dword[rsp + CpusExitingOffset] + jmp .check_exiting_cnt + .do_wakeup: ; ; BSP sets these variables before unblocking APs From 2c09915a0957e5aa945785dc9956805e904841ee Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 20 Dec 2022 16:42:40 +0800 Subject: [PATCH 0429/1529] OvmfPkg/PlatformInitLib: Implement multi-core accept memory for TDVF BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4172 TDVF once accepts memory only by BSP. To improve the boot performance this patch introduce the multi-core accpet memory. Multi-core means BSP and APs work together to accept memory. TDVF leverages mailbox to wake up APs. It is not enabled in MpInitLib (Which requires SIPI). So multi-core accept memory cannot leverages MpInitLib to coordinate BSP and APs to work together. So TDVF split the accept memory into 2 phases. - AcceptMemoryForAPsStack: BSP accepts a small piece of memory which is then used by APs to setup stack. We assign a 16KB stack for each AP. So a td-guest with 256 vCPU requires 255*16KB = 4080KB. - AcceptMemory: After above small piece of memory is accepted, BSP commands APs to accept memory by sending AcceptPages command in td-mailbox. Together with the command and accpet-function, the APsStack address is send as well. APs then set the stack and jump to accept-function to accept memory. AcceptMemoryForAPsStack accepts as small memory as possible and then jump to AcceptMemory. It fully takes advantage of BSP/APs to work together. After accept memory is done, the memory region for APsStack is not used anymore. It can be used as other private memory. Because accept-memory is in the very beginning of boot process and it will not impact other phases. Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 411 +++++++++++++++--- .../PlatformInitLib/PlatformInitLib.inf | 1 + 2 files changed, 363 insertions(+), 49 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c index 55ca3ecaa1..6cb63139cb 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,10 @@ #define ALIGNED_2MB_MASK 0x1fffff #define MEGABYTE_SHIFT 20 +#define ACCEPT_CHUNK_SIZE SIZE_32MB +#define AP_STACK_SIZE SIZE_16KB +#define APS_STACK_SIZE(CpusNum) (ALIGN_VALUE(CpusNum*AP_STACK_SIZE, SIZE_2MB)) + /** This function will be called to accept pages. Only BSP accepts pages. @@ -81,8 +86,6 @@ BspAcceptMemoryResourceRange ( return EFI_SUCCESS; } - DEBUG ((DEBUG_INFO, "TdAccept: 0x%llx - 0x%llx\n", PhysicalAddress, TotalLength)); - if (ALIGN_VALUE (PhysicalAddress, SIZE_2MB) != PhysicalAddress) { StartAddress1 = PhysicalAddress; Length1 = ALIGN_VALUE (PhysicalAddress, SIZE_2MB) - PhysicalAddress; @@ -106,11 +109,6 @@ BspAcceptMemoryResourceRange ( Length3 = TotalLength; } - DEBUG ((DEBUG_INFO, " Part1: 0x%llx - 0x%llx\n", StartAddress1, Length1)); - DEBUG ((DEBUG_INFO, " Part2: 0x%llx - 0x%llx\n", StartAddress2, Length2)); - DEBUG ((DEBUG_INFO, " Part3: 0x%llx - 0x%llx\n", StartAddress3, Length3)); - DEBUG ((DEBUG_INFO, " Page : 0x%x\n", AcceptPageSize)); - Status = EFI_SUCCESS; if (Length1 > 0) { Pages = Length1 / SIZE_4KB; @@ -140,6 +138,342 @@ BspAcceptMemoryResourceRange ( return Status; } +/** + * This function is called by BSP and APs to accept memory. + * Note: + * The input PhysicalStart/PhysicalEnd indicates the whole memory region + * to be accepted. BSP or AP only accepts one piece in the whole memory region. + * + * @param CpuIndex vCPU index + * @param CpusNum Total vCPU number of a Tdx guest + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Other Other errors as indicated + */ +STATIC +EFI_STATUS +EFIAPI +BspApAcceptMemoryResourceRange ( + UINT32 CpuIndex, + UINT32 CpusNum, + EFI_PHYSICAL_ADDRESS PhysicalStart, + EFI_PHYSICAL_ADDRESS PhysicalEnd + ) +{ + UINT64 Status; + UINT64 Pages; + UINT64 Stride; + UINT64 AcceptPageSize; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + + AcceptPageSize = (UINT64)(UINTN)FixedPcdGet32 (PcdTdxAcceptPageSize); + + Status = EFI_SUCCESS; + Stride = (UINTN)CpusNum * ACCEPT_CHUNK_SIZE; + PhysicalAddress = PhysicalStart + ACCEPT_CHUNK_SIZE * (UINTN)CpuIndex; + + while (!EFI_ERROR (Status) && PhysicalAddress < PhysicalEnd) { + Pages = MIN (ACCEPT_CHUNK_SIZE, PhysicalEnd - PhysicalAddress) / AcceptPageSize; + Status = TdAcceptPages (PhysicalAddress, Pages, (UINT32)(UINTN)AcceptPageSize); + ASSERT (!EFI_ERROR (Status)); + PhysicalAddress += Stride; + } + + return EFI_SUCCESS; +} + +/** + * This function is called by APs to accept memory. + * + * @param CpuIndex vCPU index of an AP + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Others Other errors as indicated + */ +STATIC +EFI_STATUS +EFIAPI +ApAcceptMemoryResourceRange ( + UINT32 CpuIndex, + EFI_PHYSICAL_ADDRESS PhysicalStart, + EFI_PHYSICAL_ADDRESS PhysicalEnd + ) +{ + UINT64 Status; + TD_RETURN_DATA TdReturnData; + + Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (Status != TDX_EXIT_REASON_SUCCESS) { + ASSERT (FALSE); + return EFI_ABORTED; + } + + if ((CpuIndex == 0) || (CpuIndex >= TdReturnData.TdInfo.NumVcpus)) { + ASSERT (FALSE); + return EFI_ABORTED; + } + + return BspApAcceptMemoryResourceRange (CpuIndex, TdReturnData.TdInfo.NumVcpus, PhysicalStart, PhysicalEnd); +} + +/** + * This function is called by BSP. It coordinates BSP/APs to accept memory together. + * + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * @param APsStackAddress APs stack address + * @param CpusNum Total vCPU number of the Tdx guest + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Others Other errors as indicated + */ +EFI_STATUS +EFIAPI +MpAcceptMemoryResourceRange ( + IN EFI_PHYSICAL_ADDRESS PhysicalStart, + IN EFI_PHYSICAL_ADDRESS PhysicalEnd, + IN OUT EFI_PHYSICAL_ADDRESS APsStackAddress, + IN UINT32 CpusNum + ) +{ + UINT64 Length; + EFI_STATUS Status; + + Length = PhysicalEnd - PhysicalStart; + + DEBUG ((DEBUG_INFO, "MpAccept : 0x%llx - 0x%llx (0x%llx)\n", PhysicalStart, PhysicalEnd, Length)); + + if (Length == 0) { + return EFI_SUCCESS; + } + + // + // The start address is not 2M aligned. BSP first accept the part which is not 2M aligned. + // + if (ALIGN_VALUE (PhysicalStart, SIZE_2MB) != PhysicalStart) { + Length = MIN (ALIGN_VALUE (PhysicalStart, SIZE_2MB) - PhysicalStart, Length); + Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalStart + Length); + ASSERT (Status == EFI_SUCCESS); + + PhysicalStart += Length; + Length = PhysicalEnd - PhysicalStart; + } + + if (Length == 0) { + return EFI_SUCCESS; + } + + // + // BSP will accept the memory by itself if the memory is not big enough compared with a chunk. + // + if (Length <= ACCEPT_CHUNK_SIZE) { + return BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); + } + + // + // Now APs are asked to accept the memory together. + // + MpSerializeStart (); + + MpSendWakeupCommand ( + MpProtectedModeWakeupCommandAcceptPages, + (UINT64)(UINTN)ApAcceptMemoryResourceRange, + PhysicalStart, + PhysicalEnd, + APsStackAddress, + AP_STACK_SIZE + ); + + // + // Now BSP does its job. + // + BspApAcceptMemoryResourceRange (0, CpusNum, PhysicalStart, PhysicalEnd); + + MpSerializeEnd (); + + return EFI_SUCCESS; +} + +/** + BSP accept a small piece of memory which will be used as APs stack. + + @param[in] VmmHobList The Hoblist pass the firmware + @param[in] APsStackSize APs stack size + @param[out] PhysicalAddressEnd The physical end address of accepted memory in phase-1 + + @retval EFI_SUCCESS Process the HobList successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +AcceptMemoryForAPsStack ( + IN CONST VOID *VmmHobList, + IN UINT32 APsStackSize, + OUT EFI_PHYSICAL_ADDRESS *PhysicalAddressEnd + ) +{ + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + EFI_PHYSICAL_ADDRESS PhysicalStart; + UINT64 ResourceLength; + BOOLEAN MemoryRegionFound; + + ASSERT (VmmHobList != NULL); + + Status = EFI_SUCCESS; + Hob.Raw = (UINT8 *)VmmHobList; + MemoryRegionFound = FALSE; + + DEBUG ((DEBUG_INFO, "AcceptMemoryForAPsStack with APsStackSize=0x%x\n", APsStackSize)); + + // + // Parse the HOB list until end of list or matching type is found. + // + while (!END_OF_HOB_LIST (Hob) && !MemoryRegionFound) { + if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { + DEBUG ((DEBUG_INFO, "\nResourceType: 0x%x\n", Hob.ResourceDescriptor->ResourceType)); + + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { + ResourceLength = Hob.ResourceDescriptor->ResourceLength; + PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; + PhysicalEnd = PhysicalStart + ResourceLength; + + DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); + DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", PhysicalStart)); + DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", ResourceLength)); + DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); + + if (ResourceLength >= APsStackSize) { + MemoryRegionFound = TRUE; + if (ResourceLength > ACCEPT_CHUNK_SIZE) { + PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + APsStackSize; + } + } + + Status = BspAcceptMemoryResourceRange ( + Hob.ResourceDescriptor->PhysicalStart, + PhysicalEnd + ); + if (EFI_ERROR (Status)) { + break; + } + } + } + + Hob.Raw = GET_NEXT_HOB (Hob); + } + + ASSERT (MemoryRegionFound); + *PhysicalAddressEnd = PhysicalEnd; + + return Status; +} + +/** + BSP and APs work togeter to accept memory which is under the address of 4G. + + @param[in] VmmHobList The Hoblist pass the firmware + @param[in] CpusNum Number of vCPUs + @param[in] APsStackStartAddres Start address of APs stack + @param[in] PhysicalAddressStart Start physical address which to be accepted + + @retval EFI_SUCCESS Process the HobList successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +AcceptMemory ( + IN CONST VOID *VmmHobList, + IN UINT32 CpusNum, + IN EFI_PHYSICAL_ADDRESS APsStackStartAddress, + IN EFI_PHYSICAL_ADDRESS PhysicalAddressStart + ) +{ + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS PhysicalStart; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + EFI_PHYSICAL_ADDRESS AcceptMemoryEndAddress; + + Status = EFI_SUCCESS; + AcceptMemoryEndAddress = BASE_4GB; + + ASSERT (VmmHobList != NULL); + Hob.Raw = (UINT8 *)VmmHobList; + + DEBUG ((DEBUG_INFO, "AcceptMemory under address of 4G\n")); + + // + // Parse the HOB list until end of list or matching type is found. + // + while (!END_OF_HOB_LIST (Hob)) { + if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { + PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; + PhysicalEnd = PhysicalStart + Hob.ResourceDescriptor->ResourceLength; + + if (PhysicalEnd <= PhysicalAddressStart) { + // this memory region has been accepted. Skipped it. + Hob.Raw = GET_NEXT_HOB (Hob); + continue; + } + + if (PhysicalStart >= AcceptMemoryEndAddress) { + // this memory region is not to be accepted. And we're done. + break; + } + + if (PhysicalStart >= PhysicalAddressStart) { + // this memory region has not been acceted. + } else if ((PhysicalStart < PhysicalAddressStart) && (PhysicalEnd > PhysicalAddressStart)) { + // part of the memory region has been accepted. + PhysicalStart = PhysicalAddressStart; + } + + // then compare the PhysicalEnd with AcceptMemoryEndAddress + if (PhysicalEnd >= AcceptMemoryEndAddress) { + PhysicalEnd = AcceptMemoryEndAddress; + } + + DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); + DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", Hob.ResourceDescriptor->PhysicalStart)); + DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); + DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); + + // Now we're ready to accept memory [PhysicalStart, PhysicalEnd) + if (CpusNum == 1) { + Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); + } else { + Status = MpAcceptMemoryResourceRange ( + PhysicalStart, + PhysicalEnd, + APsStackStartAddress, + CpusNum + ); + } + + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + break; + } + + if (PhysicalEnd == AcceptMemoryEndAddress) { + break; + } + } + } + + Hob.Raw = GET_NEXT_HOB (Hob); + } + + return Status; +} + /** Check the value whether in the valid list. @@ -375,55 +709,34 @@ ProcessHobList ( ) { EFI_STATUS Status; - EFI_PEI_HOB_POINTERS Hob; + UINT32 CpusNum; EFI_PHYSICAL_ADDRESS PhysicalEnd; - UINT64 ResourceLength; - UINT64 AccumulateAcceptedMemory; + EFI_PHYSICAL_ADDRESS APsStackStartAddress; - Status = EFI_SUCCESS; - ASSERT (VmmHobList != NULL); - Hob.Raw = (UINT8 *)VmmHobList; - - AccumulateAcceptedMemory = 0; + CpusNum = GetCpusNum (); // - // Parse the HOB list until end of list or matching type is found. + // If there are mutli-vCPU in a TDX guest, accept memory is split into 2 phases. + // Phase-1 accepts a small piece of memory by BSP. This piece of memory + // is used to setup AP's stack. + // After that phase-2 accepts a big piece of memory by BSP/APs. // - while (!END_OF_HOB_LIST (Hob)) { - if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - DEBUG ((DEBUG_INFO, "\nResourceType: 0x%x\n", Hob.ResourceDescriptor->ResourceType)); - - if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { - DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); - DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", Hob.ResourceDescriptor->PhysicalStart)); - DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); - DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); - - PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength; - ResourceLength = Hob.ResourceDescriptor->ResourceLength; - - if (Hob.ResourceDescriptor->PhysicalStart >= BASE_4GB) { - // - // In current stage, we only accept the memory under 4G - // - break; - } - - Status = BspAcceptMemoryResourceRange ( - Hob.ResourceDescriptor->PhysicalStart, - PhysicalEnd - ); - if (EFI_ERROR (Status)) { - break; - } - - AccumulateAcceptedMemory += ResourceLength; - } - } - - Hob.Raw = GET_NEXT_HOB (Hob); + // TDVF supports 4K and 2M accept-page-size. The memory which can be accpeted + // in 2M accept-page-size must be 2M aligned and multiple 2M. So we align + // APsStackSize to 2M size aligned. + // + if (CpusNum > 1) { + Status = AcceptMemoryForAPsStack (VmmHobList, APS_STACK_SIZE (CpusNum), &PhysicalEnd); + ASSERT (Status == EFI_SUCCESS); + APsStackStartAddress = PhysicalEnd - APS_STACK_SIZE (CpusNum); + } else { + PhysicalEnd = 0; + APsStackStartAddress = 0; } + Status = AcceptMemory (VmmHobList, CpusNum, APsStackStartAddress, PhysicalEnd); + ASSERT (Status == EFI_SUCCESS); + return Status; } diff --git a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf index 86a82ad3e0..140216979a 100644 --- a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf +++ b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf @@ -52,6 +52,7 @@ PcdLib PciLib PeiHardwareInfoLib + TdxMailboxLib [LibraryClasses.X64] TdxLib From fe9d26bf1ee6f5701b9c975398c31888c2d61300 Mon Sep 17 00:00:00 2001 From: Anthony PERARD Date: Tue, 20 Dec 2022 00:36:20 +0800 Subject: [PATCH 0430/1529] OvmfPkg/OvmfXen: Build platform info HOB in XenPlatformPei Copy the function BuildPlatformInfoHob() from OvmfPkg/PlatformPei. QemuFwCfgLib expect this HOB to be present, or fails to do anything. InternalQemuFwCfgIsAvailable() from QemuFwCfgPeiLib module will not check if the HOB is actually present for example and try to use a NULL pointer. Fixes: cda98df16228 ("OvmfPkg/QemuFwCfgLib: remove mQemuFwCfgSupported + mQemuFwCfgDmaSupported") Signed-off-by: Anthony PERARD Reviewed-by: Gerd Hoffmann Acked-by: Jiewen Yao --- OvmfPkg/XenPlatformPei/Platform.c | 20 ++++++++++++++++++++ OvmfPkg/XenPlatformPei/Platform.h | 1 + 2 files changed, 21 insertions(+) diff --git a/OvmfPkg/XenPlatformPei/Platform.c b/OvmfPkg/XenPlatformPei/Platform.c index 2d97a41ca7..6c1886c158 100644 --- a/OvmfPkg/XenPlatformPei/Platform.c +++ b/OvmfPkg/XenPlatformPei/Platform.c @@ -17,6 +17,7 @@ // // The Library classes this module consumes // +#include #include #include #include @@ -409,6 +410,20 @@ DebugDumpCmos ( } } +EFI_HOB_PLATFORM_INFO * +BuildPlatformInfoHob ( + VOID + ) +{ + EFI_HOB_PLATFORM_INFO PlatformInfoHob; + EFI_HOB_GUID_TYPE *GuidHob; + + ZeroMem (&PlatformInfoHob, sizeof PlatformInfoHob); + BuildGuidDataHob (&gUefiOvmfPkgPlatformInfoGuid, &PlatformInfoHob, sizeof (EFI_HOB_PLATFORM_INFO)); + GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid); + return (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob); +} + /** Perform Platform PEI initialization. @@ -429,6 +444,11 @@ InitializeXenPlatform ( DEBUG ((DEBUG_INFO, "Platform PEIM Loaded\n")); + // + // Platform Info HOB used by QemuFw libraries + // + BuildPlatformInfoHob (); + DebugDumpCmos (); if (!XenDetect ()) { diff --git a/OvmfPkg/XenPlatformPei/Platform.h b/OvmfPkg/XenPlatformPei/Platform.h index 039af50ffa..7b4de128e7 100644 --- a/OvmfPkg/XenPlatformPei/Platform.h +++ b/OvmfPkg/XenPlatformPei/Platform.h @@ -12,6 +12,7 @@ #define _PLATFORM_PEI_H_INCLUDED_ #include +#include VOID AddIoMemoryBaseSizeHob ( From 9d6e162cc948f2c281e7e90210f2d94bd90ddc5c Mon Sep 17 00:00:00 2001 From: duntan Date: Wed, 21 Dec 2022 12:21:54 +0800 Subject: [PATCH 0431/1529] UefiCpuPkg/PiSmmCpuDxeSmm: Introduce page table pool mechanism Introduce page table pool mechanism for smm page table to simplify page table memory management and protection. This mechanism has been used in DxeIpl. The basic idea is to allocate a bunch of continuous pages of memory in advance, and all future page tables consumption will happen in those pool instead of system memory. Since we have centralized page tables, we only need to mark all page table pools as RO, instead of searching page table memory layer by layer in smm page table. Once current page table pool has been used up, another memory pool will be allocated and the new pool will also be set as RO if current page table memory has been marked as RO. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c | 20 +-- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 30 ---- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 31 ++++ .../PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c | 137 ++++++++++++++++++ UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c | 20 +-- 5 files changed, 172 insertions(+), 66 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c index 97058a2810..bbc536a567 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c @@ -10,24 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PiSmmCpuDxeSmm.h" -/** - Disable CET. -**/ -VOID -EFIAPI -DisableCet ( - VOID - ); - -/** - Enable CET. -**/ -VOID -EFIAPI -EnableCet ( - VOID - ); - /** Create PageTable for SMM use. @@ -320,6 +302,8 @@ SetPageTableAttributes ( EnableCet (); } + mIsReadOnlyPageTable = TRUE; + return; } diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 37e3cfc449..655175a2c6 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -1322,36 +1322,6 @@ ConfigSmmCodeAccessCheck ( } } -/** - This API provides a way to allocate memory for page table. - - This API can be called more once to allocate memory for page tables. - - Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the - allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL - is returned. If there is not enough memory remaining to satisfy the request, then NULL is - returned. - - @param Pages The number of 4 KB pages to allocate. - - @return A pointer to the allocated buffer or NULL if allocation fails. - -**/ -VOID * -AllocatePageTableMemory ( - IN UINTN Pages - ) -{ - VOID *Buffer; - - Buffer = SmmCpuFeaturesAllocatePageTableMemory (Pages); - if (Buffer != NULL) { - return Buffer; - } - - return AllocatePages (Pages); -} - /** Allocate pages for code. diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 0bfba7e359..3e69e043ca 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -260,12 +260,43 @@ extern UINTN mNumberOfCpus; extern EFI_SMM_CPU_PROTOCOL mSmmCpu; extern EFI_MM_MP_PROTOCOL mSmmMp; extern BOOLEAN m5LevelPagingNeeded; +extern BOOLEAN mIsReadOnlyPageTable; /// /// The mode of the CPU at the time an SMI occurs /// extern UINT8 mSmmSaveStateRegisterLma; +#define PAGE_TABLE_POOL_ALIGNMENT BASE_128KB +#define PAGE_TABLE_POOL_UNIT_SIZE BASE_128KB +#define PAGE_TABLE_POOL_UNIT_PAGES EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE) +#define PAGE_TABLE_POOL_ALIGN_MASK \ + (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT - 1)) + +typedef struct { + VOID *NextPool; + UINTN Offset; + UINTN FreePages; +} PAGE_TABLE_POOL; + +/** + Disable CET. +**/ +VOID +EFIAPI +DisableCet ( + VOID + ); + +/** + Enable CET. +**/ +VOID +EFIAPI +EnableCet ( + VOID + ); + // // SMM CPU Protocol function prototypes. // diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c index 773ab927e6..11df7af016 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c @@ -35,6 +35,143 @@ PAGE_ATTRIBUTE_TABLE mPageAttributeTable[] = { BOOLEAN mIsShadowStack = FALSE; BOOLEAN m5LevelPagingNeeded = FALSE; +// +// Global variable to keep track current available memory used as page table. +// +PAGE_TABLE_POOL *mPageTablePool = NULL; + +// +// If memory used by SMM page table has been mareked as ReadOnly. +// +BOOLEAN mIsReadOnlyPageTable = FALSE; + +/** + Initialize a buffer pool for page table use only. + + To reduce the potential split operation on page table, the pages reserved for + page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and + at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always + initialized with number of pages greater than or equal to the given PoolPages. + + Once the pages in the pool are used up, this method should be called again to + reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. But usually this won't + happen in practice. + + @param PoolPages The least page number of the pool to be created. + + @retval TRUE The pool is initialized successfully. + @retval FALSE The memory is out of resource. +**/ +BOOLEAN +InitializePageTablePool ( + IN UINTN PoolPages + ) +{ + VOID *Buffer; + BOOLEAN CetEnabled; + + // + // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for + // header. + // + PoolPages += 1; // Add one page for header. + PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) * + PAGE_TABLE_POOL_UNIT_PAGES; + Buffer = AllocateAlignedPages (PoolPages, PAGE_TABLE_POOL_ALIGNMENT); + if (Buffer == NULL) { + DEBUG ((DEBUG_ERROR, "ERROR: Out of aligned pages\r\n")); + return FALSE; + } + + // + // Link all pools into a list for easier track later. + // + if (mPageTablePool == NULL) { + mPageTablePool = Buffer; + mPageTablePool->NextPool = mPageTablePool; + } else { + ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool; + mPageTablePool->NextPool = Buffer; + mPageTablePool = Buffer; + } + + // + // Reserve one page for pool header. + // + mPageTablePool->FreePages = PoolPages - 1; + mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1); + + // + // If page table memory has been marked as RO, mark the new pool pages as read-only. + // + if (mIsReadOnlyPageTable) { + CetEnabled = ((AsmReadCr4 () & CR4_CET_ENABLE) != 0) ? TRUE : FALSE; + if (CetEnabled) { + // + // CET must be disabled if WP is disabled. + // + DisableCet (); + } + + AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); + SmmSetMemoryAttributes ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_PAGES_TO_SIZE (PoolPages), EFI_MEMORY_RO); + AsmWriteCr0 (AsmReadCr0 () | CR0_WP); + if (CetEnabled) { + // + // re-enable CET. + // + EnableCet (); + } + } + + return TRUE; +} + +/** + This API provides a way to allocate memory for page table. + + This API can be called more once to allocate memory for page tables. + + Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the + allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL + is returned. If there is not enough memory remaining to satisfy the request, then NULL is + returned. + + @param Pages The number of 4 KB pages to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ +VOID * +AllocatePageTableMemory ( + IN UINTN Pages + ) +{ + VOID *Buffer; + + if (Pages == 0) { + return NULL; + } + + // + // Renew the pool if necessary. + // + if ((mPageTablePool == NULL) || + (Pages > mPageTablePool->FreePages)) + { + if (!InitializePageTablePool (Pages)) { + return NULL; + } + } + + Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset; + + mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages); + mPageTablePool->FreePages -= Pages; + + return Buffer; +} + /** Return length according to page attributes. diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c index bf90050503..8d42d89801 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c @@ -20,24 +20,6 @@ BOOLEAN m1GPageTableSupport = FALSE; BOOLEAN mCpuSmmRestrictedMemoryAccess; X86_ASSEMBLY_PATCH_LABEL gPatch5LevelPagingNeeded; -/** - Disable CET. -**/ -VOID -EFIAPI -DisableCet ( - VOID - ); - -/** - Enable CET. -**/ -VOID -EFIAPI -EnableCet ( - VOID - ); - /** Check if 1-GByte pages is supported by processor or not. @@ -1305,6 +1287,8 @@ SetPageTableAttributes ( EnableCet (); } + mIsReadOnlyPageTable = TRUE; + return; } From 02498a448c54c93eaabd1751fd7f16917d703995 Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Wed, 21 Dec 2022 12:21:55 +0800 Subject: [PATCH 0432/1529] UefiCpuPkg: Remove unused API in SmmCpuFeaturesLib.h Remove SmmCpuFeaturesAllocatePageTableMemory in this headfile. This API is not used by PiSmmCpuDxeSmm driver any more. Also no other files use this API. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- .../Include/Library/SmmCpuFeaturesLib.h | 25 ------------------- 1 file changed, 25 deletions(-) diff --git a/UefiCpuPkg/Include/Library/SmmCpuFeaturesLib.h b/UefiCpuPkg/Include/Library/SmmCpuFeaturesLib.h index 54cae865a2..52160c7145 100644 --- a/UefiCpuPkg/Include/Library/SmmCpuFeaturesLib.h +++ b/UefiCpuPkg/Include/Library/SmmCpuFeaturesLib.h @@ -386,29 +386,4 @@ SmmCpuFeaturesCompleteSmmReadyToLock ( VOID ); -/** - This API provides a method for a CPU to allocate a specific region for storing page tables. - - This API can be called more once to allocate memory for page tables. - - Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the - allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL - is returned. If there is not enough memory remaining to satisfy the request, then NULL is - returned. - - This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM. - - @param Pages The number of 4 KB pages to allocate. - - @return A pointer to the allocated buffer for page tables. - @retval NULL Fail to allocate a specific region for storing page tables, - Or there is no preference on where the page tables are allocated in SMRAM. - -**/ -VOID * -EFIAPI -SmmCpuFeaturesAllocatePageTableMemory ( - IN UINTN Pages - ); - #endif From 56ee358eef5edb0f3e340f1f1acdda5b21d45006 Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Wed, 21 Dec 2022 12:21:56 +0800 Subject: [PATCH 0433/1529] UefiCpuPkg: Simplify the code to set smm page table as RO Simplify the code to set memory used by smm page table as RO. Since memory used by smm page table are in PageTablePool list, we only need to set all PageTablePool as ReadOnly in smm page table itself. Also, we only need to flush tlb once after setting all page table pool as Read Only. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c | 105 ------------ UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 1 - .../PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c | 136 ++++++++++++++++ UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c | 153 ------------------ 4 files changed, 136 insertions(+), 259 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c index bbc536a567..34bf6e1a25 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c @@ -202,111 +202,6 @@ SmiPFHandler ( ReleaseSpinLock (mPFLock); } -/** - This function sets memory attribute for page table. -**/ -VOID -SetPageTableAttributes ( - VOID - ) -{ - UINTN Index2; - UINTN Index3; - UINT64 *L1PageTable; - UINT64 *L2PageTable; - UINT64 *L3PageTable; - UINTN PageTableBase; - BOOLEAN IsSplitted; - BOOLEAN PageTableSplitted; - BOOLEAN CetEnabled; - - // - // Don't mark page table to read-only if heap guard is enabled. - // - // BIT2: SMM page guard enabled - // BIT3: SMM pool guard enabled - // - if ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) { - DEBUG ((DEBUG_INFO, "Don't mark page table to read-only as heap guard is enabled\n")); - return; - } - - // - // Don't mark page table to read-only if SMM profile is enabled. - // - if (FeaturePcdGet (PcdCpuSmmProfileEnable)) { - DEBUG ((DEBUG_INFO, "Don't mark page table to read-only as SMM profile is enabled\n")); - return; - } - - DEBUG ((DEBUG_INFO, "SetPageTableAttributes\n")); - - // - // Disable write protection, because we need mark page table to be write protected. - // We need *write* page table memory, to mark itself to be *read only*. - // - CetEnabled = ((AsmReadCr4 () & CR4_CET_ENABLE) != 0) ? TRUE : FALSE; - if (CetEnabled) { - // - // CET must be disabled if WP is disabled. - // - DisableCet (); - } - - AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); - - do { - DEBUG ((DEBUG_INFO, "Start...\n")); - PageTableSplitted = FALSE; - - PageTableBase = AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64; - L3PageTable = (UINT64 *)PageTableBase; - - SmmSetMemoryAttributesEx (PageTableBase, FALSE, (EFI_PHYSICAL_ADDRESS)PageTableBase, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - - for (Index3 = 0; Index3 < 4; Index3++) { - L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L2PageTable == NULL) { - continue; - } - - SmmSetMemoryAttributesEx (PageTableBase, FALSE, (EFI_PHYSICAL_ADDRESS)(UINTN)L2PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - - for (Index2 = 0; Index2 < SIZE_4KB/sizeof (UINT64); Index2++) { - if ((L2PageTable[Index2] & IA32_PG_PS) != 0) { - // 2M - continue; - } - - L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L1PageTable == NULL) { - continue; - } - - SmmSetMemoryAttributesEx (PageTableBase, FALSE, (EFI_PHYSICAL_ADDRESS)(UINTN)L1PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - } - } - } while (PageTableSplitted); - - // - // Enable write protection, after page table updated. - // - AsmWriteCr0 (AsmReadCr0 () | CR0_WP); - if (CetEnabled) { - // - // re-enable CET. - // - EnableCet (); - } - - mIsReadOnlyPageTable = TRUE; - - return; -} - /** This function returns with no action for 32 bit. diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 3e69e043ca..5f0a38e400 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -260,7 +260,6 @@ extern UINTN mNumberOfCpus; extern EFI_SMM_CPU_PROTOCOL mSmmCpu; extern EFI_MM_MP_PROTOCOL mSmmMp; extern BOOLEAN m5LevelPagingNeeded; -extern BOOLEAN mIsReadOnlyPageTable; /// /// The mode of the CPU at the time an SMI occurs diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c index 11df7af016..4bb23f6920 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c @@ -1753,3 +1753,139 @@ EdkiiSmmGetMemoryAttributes ( return EFI_SUCCESS; } + +/** + Prevent the memory pages used for SMM page table from been overwritten. +**/ +VOID +EnablePageTableProtection ( + VOID + ) +{ + PAGE_TABLE_POOL *HeadPool; + PAGE_TABLE_POOL *Pool; + UINT64 PoolSize; + EFI_PHYSICAL_ADDRESS Address; + UINTN PageTableBase; + + if (mPageTablePool == NULL) { + return; + } + + PageTableBase = AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64; + + // + // ConvertMemoryPageAttributes might update mPageTablePool. It's safer to + // remember original one in advance. + // + HeadPool = mPageTablePool; + Pool = HeadPool; + do { + Address = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool; + PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool->FreePages); + // + // Set entire pool including header, used-memory and left free-memory as ReadOnly in SMM page table. + // + ConvertMemoryPageAttributes (PageTableBase, m5LevelPagingNeeded, Address, PoolSize, EFI_MEMORY_RO, TRUE, NULL, NULL); + Pool = Pool->NextPool; + } while (Pool != HeadPool); +} + +/** + Return whether memory used by SMM page table need to be set as Read Only. + + @retval TRUE Need to set SMM page table as Read Only. + @retval FALSE Do not set SMM page table as Read Only. +**/ +BOOLEAN +IfReadOnlyPageTableNeeded ( + VOID + ) +{ + // + // Don't mark page table memory as read-only if + // - no restriction on access to non-SMRAM memory; or + // - SMM heap guard feature enabled; or + // BIT2: SMM page guard enabled + // BIT3: SMM pool guard enabled + // - SMM profile feature enabled + // + if (!IsRestrictedMemoryAccess () || + ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) || + FeaturePcdGet (PcdCpuSmmProfileEnable)) + { + if (sizeof (UINTN) == sizeof (UINT64)) { + // + // Restriction on access to non-SMRAM memory and heap guard could not be enabled at the same time. + // + ASSERT ( + !(IsRestrictedMemoryAccess () && + (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) + ); + + // + // Restriction on access to non-SMRAM memory and SMM profile could not be enabled at the same time. + // + ASSERT (!(IsRestrictedMemoryAccess () && FeaturePcdGet (PcdCpuSmmProfileEnable))); + } + + return FALSE; + } + + return TRUE; +} + +/** + This function sets memory attribute for page table. +**/ +VOID +SetPageTableAttributes ( + VOID + ) +{ + BOOLEAN CetEnabled; + + if (!IfReadOnlyPageTableNeeded ()) { + return; + } + + DEBUG ((DEBUG_INFO, "SetPageTableAttributes\n")); + + // + // Disable write protection, because we need mark page table to be write protected. + // We need *write* page table memory, to mark itself to be *read only*. + // + CetEnabled = ((AsmReadCr4 () & CR4_CET_ENABLE) != 0) ? TRUE : FALSE; + if (CetEnabled) { + // + // CET must be disabled if WP is disabled. + // + DisableCet (); + } + + AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); + + // Set memory used by page table as Read Only. + DEBUG ((DEBUG_INFO, "Start...\n")); + EnablePageTableProtection (); + + // + // Enable write protection, after page table attribute updated. + // + AsmWriteCr0 (AsmReadCr0 () | CR0_WP); + mIsReadOnlyPageTable = TRUE; + + // + // Flush TLB after mark all page table pool as read only. + // + FlushTlbForAll (); + + if (CetEnabled) { + // + // re-enable CET. + // + EnableCet (); + } + + return; +} diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c index 8d42d89801..3deb1ffd67 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c @@ -1139,159 +1139,6 @@ SmiPFHandler ( ReleaseSpinLock (mPFLock); } -/** - This function sets memory attribute for page table. -**/ -VOID -SetPageTableAttributes ( - VOID - ) -{ - UINTN Index2; - UINTN Index3; - UINTN Index4; - UINTN Index5; - UINT64 *L1PageTable; - UINT64 *L2PageTable; - UINT64 *L3PageTable; - UINT64 *L4PageTable; - UINT64 *L5PageTable; - UINTN PageTableBase; - BOOLEAN IsSplitted; - BOOLEAN PageTableSplitted; - BOOLEAN CetEnabled; - BOOLEAN Enable5LevelPaging; - IA32_CR4 Cr4; - - // - // Don't mark page table memory as read-only if - // - no restriction on access to non-SMRAM memory; or - // - SMM heap guard feature enabled; or - // BIT2: SMM page guard enabled - // BIT3: SMM pool guard enabled - // - SMM profile feature enabled - // - if (!mCpuSmmRestrictedMemoryAccess || - ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) || - FeaturePcdGet (PcdCpuSmmProfileEnable)) - { - // - // Restriction on access to non-SMRAM memory and heap guard could not be enabled at the same time. - // - ASSERT ( - !(mCpuSmmRestrictedMemoryAccess && - (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) - ); - - // - // Restriction on access to non-SMRAM memory and SMM profile could not be enabled at the same time. - // - ASSERT (!(mCpuSmmRestrictedMemoryAccess && FeaturePcdGet (PcdCpuSmmProfileEnable))); - return; - } - - DEBUG ((DEBUG_INFO, "SetPageTableAttributes\n")); - - // - // Disable write protection, because we need mark page table to be write protected. - // We need *write* page table memory, to mark itself to be *read only*. - // - CetEnabled = ((AsmReadCr4 () & CR4_CET_ENABLE) != 0) ? TRUE : FALSE; - if (CetEnabled) { - // - // CET must be disabled if WP is disabled. - // - DisableCet (); - } - - AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); - - do { - DEBUG ((DEBUG_INFO, "Start...\n")); - PageTableSplitted = FALSE; - L5PageTable = NULL; - - PageTableBase = AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64; - Cr4.UintN = AsmReadCr4 (); - Enable5LevelPaging = (BOOLEAN)(Cr4.Bits.LA57 == 1); - - if (Enable5LevelPaging) { - L5PageTable = (UINT64 *)PageTableBase; - SmmSetMemoryAttributesEx (PageTableBase, Enable5LevelPaging, (EFI_PHYSICAL_ADDRESS)PageTableBase, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - } - - for (Index5 = 0; Index5 < (Enable5LevelPaging ? SIZE_4KB/sizeof (UINT64) : 1); Index5++) { - if (Enable5LevelPaging) { - L4PageTable = (UINT64 *)(UINTN)(L5PageTable[Index5] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L4PageTable == NULL) { - continue; - } - } else { - L4PageTable = (UINT64 *)PageTableBase; - } - - SmmSetMemoryAttributesEx (PageTableBase, Enable5LevelPaging, (EFI_PHYSICAL_ADDRESS)(UINTN)L4PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - - for (Index4 = 0; Index4 < SIZE_4KB/sizeof (UINT64); Index4++) { - L3PageTable = (UINT64 *)(UINTN)(L4PageTable[Index4] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L3PageTable == NULL) { - continue; - } - - SmmSetMemoryAttributesEx (PageTableBase, Enable5LevelPaging, (EFI_PHYSICAL_ADDRESS)(UINTN)L3PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - - for (Index3 = 0; Index3 < SIZE_4KB/sizeof (UINT64); Index3++) { - if ((L3PageTable[Index3] & IA32_PG_PS) != 0) { - // 1G - continue; - } - - L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L2PageTable == NULL) { - continue; - } - - SmmSetMemoryAttributesEx (PageTableBase, Enable5LevelPaging, (EFI_PHYSICAL_ADDRESS)(UINTN)L2PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - - for (Index2 = 0; Index2 < SIZE_4KB/sizeof (UINT64); Index2++) { - if ((L2PageTable[Index2] & IA32_PG_PS) != 0) { - // 2M - continue; - } - - L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); - if (L1PageTable == NULL) { - continue; - } - - SmmSetMemoryAttributesEx (PageTableBase, Enable5LevelPaging, (EFI_PHYSICAL_ADDRESS)(UINTN)L1PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); - PageTableSplitted = (PageTableSplitted || IsSplitted); - } - } - } - } - } while (PageTableSplitted); - - // - // Enable write protection, after page table updated. - // - AsmWriteCr0 (AsmReadCr0 () | CR0_WP); - if (CetEnabled) { - // - // re-enable CET. - // - EnableCet (); - } - - mIsReadOnlyPageTable = TRUE; - - return; -} - /** This function reads CR2 register when on-demand paging is enabled. From 537e8d5566f50ad9f7a73439efeb166730f35e8b Mon Sep 17 00:00:00 2001 From: Judah Vang Date: Wed, 21 Dec 2022 11:04:18 +0800 Subject: [PATCH 0434/1529] CryptoPkg: Need to enable crypto functions REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3992 V2: Update Readme and CryptoPkg.dsc to reflect changes and be in sync. V1: Enable CryptAes for PEI phase. Enable CryptHkdf for SMM phase. Update Readme.md Cc: Jiewen Yao Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Guomin Jiang Cc: Nishant C Mistry Signed-off-by: Jian J Wang Signed-off-by: Nishant C Mistry Signed-off-by: Judah Vang Reviewed-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/CryptoPkg.dsc | 8 +++++++- CryptoPkg/Readme.md | 12 ++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc index 3b245979c3..4676193e89 100644 --- a/CryptoPkg/CryptoPkg.dsc +++ b/CryptoPkg/CryptoPkg.dsc @@ -2,7 +2,7 @@ # Cryptographic Library Package for UEFI Security Implementation. # PEIM, DXE Driver, and SMM Driver with all crypto services enabled. # -# Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -239,6 +239,11 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.GetContextSize | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.Init | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcEncrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif # @@ -278,6 +283,7 @@ gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Aes.Services.CbcDecrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Encrypt | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.AeadAesGcm.Services.Decrypt | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY !endif ################################################################################################### diff --git a/CryptoPkg/Readme.md b/CryptoPkg/Readme.md index cb072db723..284a16f299 100644 --- a/CryptoPkg/Readme.md +++ b/CryptoPkg/Readme.md @@ -207,15 +207,15 @@ also configured. | Sha512 | N | N | C | C | C | C | C | | X509 | N | N | | | C | C | C | | Tdes | Y | Y | | | | | | -| Aes.GetContextSize | N | N | | | C | C | C | -| Aes.Init | N | N | | | C | C | C | +| Aes.GetContextSize | N | N | | C | C | C | C | +| Aes.Init | N | N | | C | C | C | C | | Aes.EcbEncrypt | Y | Y | | | | | | | Aes.EcbDecrypt | Y | Y | | | | | | -| Aes.CbcEncrypt | N | N | | | C | C | C | -| Aes.CbcDecrypt | N | N | | | C | C | C | +| Aes.CbcEncrypt | N | N | | C | C | C | C | +| Aes.CbcDecrypt | N | N | | C | C | C | C | | Arc4 | Y | Y | | | | | | | Sm3 | N | N | | C | C | C | C | -| Hkdf | N | N | | C | C | | C | +| Hkdf | N | N | | C | C | C | C | | Tls | N | N | | | C-Tls | | | | TlsSet | N | N | | | C-Tls | | | | TlsGet | N | N | | | C-Tls | | | @@ -460,7 +460,7 @@ and CryptoSmm modules. gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.Free | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Rsa.Services.SetKey | TRUE gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Pkcs.Services.Pkcs5HashPassword | TRUE - gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Services.Sha256ExtractAndExpand | TRUE + gEfiCryptoPkgTokenSpaceGuid.PcdCryptoServiceFamilyEnable.Hkdf.Family | PCD_CRYPTO_SERVICE_ENABLE_FAMILY ``` #### Common DXE and SMM PcdCryptoServiceFamilyEnable Settings From 354f2570656a74782cb32c51c0e001cabd58a5e5 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 30 Nov 2022 17:44:13 +0800 Subject: [PATCH 0435/1529] tools_def: remove GCC_IA32_CC_FLAGS/GCC_X64_CC_FLAGS They are not used anywhere. Remove them. Signed-off-by: Gerd Hoffmann Reviewed-by: Liming Gao --- BaseTools/Conf/tools_def.template | 2 -- 1 file changed, 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index c4e4c7ded0..73f95b2a3a 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1850,8 +1850,6 @@ NOOPT_*_*_OBJCOPY_ADDDEBUGFLAG = --add-gnu-debuglink=$(DEBUG_DIR)/$(MODULE_N *_*_*_DTC_PATH = DEF(DTC_BIN) DEFINE GCC_ALL_CC_FLAGS = -g -Os -fshort-wchar -fno-builtin -fno-strict-aliasing -Wall -Werror -Wno-array-bounds -include AutoGen.h -fno-common -DEFINE GCC_IA32_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -m32 -malign-double -freorder-blocks -freorder-blocks-and-partition -O2 -mno-stack-arg-probe -DEFINE GCC_X64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mno-red-zone -Wno-address -mno-stack-arg-probe DEFINE GCC_ARM_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -mabi=aapcs -fno-short-enums -funsigned-char -ffunction-sections -fdata-sections -fomit-frame-pointer -Wno-address -mthumb -mfloat-abi=soft -fno-pic -fno-pie DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mabi=lp64d -fno-asynchronous-unwind-tables -fno-plt -Wno-address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections DEFINE GCC_ARM_CC_XIPFLAGS = -mno-unaligned-access From d48ad8b4f43a1d17bad230f6f096869fca4d834d Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 30 Nov 2022 17:44:14 +0800 Subject: [PATCH 0436/1529] tools_def: add -fno-omit-frame-pointer to GCC48_{IA32,X64}_CC_FLAGS Fixes problems due to code assuming it runs with frame pointers and thus updates rbp / ebp registers when switching stacks. Signed-off-by: Gerd Hoffmann Tested-by: Liming Gao --- BaseTools/Conf/tools_def.template | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 73f95b2a3a..f1fd6a0030 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1888,8 +1888,8 @@ DEFINE GCC_DEPS_FLAGS = -MMD -MF $@.deps DEFINE GCC48_ALL_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -ffunction-sections -fdata-sections -DSTRING_ARRAY_NAME=$(BASE_NAME)Strings DEFINE GCC48_IA32_X64_DLINK_COMMON = -nostdlib -Wl,-n,-q,--gc-sections -z common-page-size=0x20 -DEFINE GCC48_IA32_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) -m32 -march=i586 -malign-double -fno-stack-protector -D EFI32 -fno-asynchronous-unwind-tables -Wno-address -DEFINE GCC48_X64_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) -m64 -fno-stack-protector "-DEFIAPI=__attribute__((ms_abi))" -maccumulate-outgoing-args -mno-red-zone -Wno-address -mcmodel=small -fpie -fno-asynchronous-unwind-tables -Wno-address +DEFINE GCC48_IA32_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) -m32 -march=i586 -malign-double -fno-stack-protector -D EFI32 -fno-asynchronous-unwind-tables -Wno-address -fno-omit-frame-pointer +DEFINE GCC48_X64_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) -m64 -fno-stack-protector "-DEFIAPI=__attribute__((ms_abi))" -maccumulate-outgoing-args -mno-red-zone -Wno-address -mcmodel=small -fpie -fno-asynchronous-unwind-tables -Wno-address -fno-omit-frame-pointer DEFINE GCC48_IA32_X64_ASLDLINK_FLAGS = DEF(GCC48_IA32_X64_DLINK_COMMON) -Wl,--entry,ReferenceAcpiTable -u ReferenceAcpiTable DEFINE GCC48_IA32_X64_DLINK_FLAGS = DEF(GCC48_IA32_X64_DLINK_COMMON) -Wl,--entry,$(IMAGE_ENTRY_POINT) -u $(IMAGE_ENTRY_POINT) -Wl,-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map,--whole-archive DEFINE GCC48_IA32_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 DEF(GCC_DLINK2_FLAGS_COMMON) From 3175a045f0d536a6613acd38d9bb07e6e294aee0 Mon Sep 17 00:00:00 2001 From: KasimX Liu Date: Wed, 14 Dec 2022 15:56:23 +0800 Subject: [PATCH 0437/1529] PcAtChipsetPkg: Move RTC PCD to dynamic PCD REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4193 In order to remove RTC_INDEX/RTC_TARGET from the UplBuild macro list,change the RTC_INDEX /RTC_TARGET type from PcdsFixedAtBuild to PcdsDynamicEx Cc: Guo Dong Reviewed-by: Ray Ni Cc: James Lu Reviewed-by: Gua Guo Signed-off-by: KasimX Liu --- PcAtChipsetPkg/PcAtChipsetPkg.dec | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/PcAtChipsetPkg/PcAtChipsetPkg.dec b/PcAtChipsetPkg/PcAtChipsetPkg.dec index ed2d95550b..a53ca777e8 100644 --- a/PcAtChipsetPkg/PcAtChipsetPkg.dec +++ b/PcAtChipsetPkg/PcAtChipsetPkg.dec @@ -84,6 +84,14 @@ # @Prompt RTC Target Register address gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister64|0x0|UINT64|0x00000023 + ## Specifies RTC Index Register address in I/O space. + # @Prompt RTC Index Register address + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister|0x70|UINT8|0x0000001E + + ## Specifies RTC Target Register address in I/O space. + # @Prompt RTC Target Register address + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister|0x71|UINT8|0x0000001F + [PcdsFixedAtBuild, PcdsPatchableInModule] ## Defines the ACPI register set base address. # The invalid 0xFFFF is as its default value. It must be configured to the real value. @@ -146,14 +154,6 @@ # @Prompt Initial value for Register_D in RTC. gPcAtChipsetPkgTokenSpaceGuid.PcdInitialValueRtcRegisterD|0x00|UINT8|0x0000001D - ## Specifies RTC Index Register address in I/O space. - # @Prompt RTC Index Register address - gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister|0x70|UINT8|0x0000001E - - ## Specifies RTC Target Register address in I/O space. - # @Prompt RTC Target Register address - gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister|0x71|UINT8|0x0000001F - ## RTC Update Timeout Value(microsecond). # @Prompt RTC Update Timeout Value. gPcAtChipsetPkgTokenSpaceGuid.PcdRealTimeClockUpdateTimeout|100000|UINT32|0x00000020 From e78900eca034aae317bad9a0d74bd717b89020c5 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 22 Dec 2022 21:11:55 +0800 Subject: [PATCH 0438/1529] OvmfPkg/AcpiPlatformDxe: Check PcdConfidentialComputingGuestAttr PcdConfidentialComputingGuestAttr can be used to check the cc guest type, including td-guest or sev-guest. CcProbe() can do the same thing but CcProbeLib should be included in the dsc which uses AcpiPlatformDxe. The difference between PcdConfidentialComputingGuestAttr and CcProbe() is that PcdConfidentialComputingGuestAttr cannot be used in multi-processor scenario but CcProbe() can. But there is no such issue in AcpiPlatformDxe. So we use PcdConfidentialComputingGuestAttr instead of CcProbeLib so that it is simpler. Cc: Ard Biesheuvel Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Signed-off-by: Min Xu --- OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c | 6 ++---- OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c index 0cc3d958be..b446bb4872 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatform.c @@ -8,9 +8,7 @@ **/ #include // CLOUDHV_DEVICE_ID - -#include // CcProbe(), CcGuestTypeIntelTdx - +#include #include "AcpiPlatform.h" /** @@ -35,7 +33,7 @@ InstallAcpiTables ( HostBridgeDevId = PcdGet16 (PcdOvmfHostBridgePciDevId); if (HostBridgeDevId == CLOUDHV_DEVICE_ID) { - if (CcProbe () == CcGuestTypeIntelTdx) { + if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) { Status = InstallCloudHvTablesTdx (AcpiTable); } else { Status = InstallCloudHvTables (AcpiTable); diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf index 1647a90add..8939dde425 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf @@ -46,7 +46,6 @@ UefiBootServicesTableLib UefiDriverEntryPoint HobLib - CcProbeLib [Protocols] gEfiAcpiTableProtocolGuid # PROTOCOL ALWAYS_CONSUMED @@ -62,6 +61,7 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId gUefiOvmfPkgTokenSpaceGuid.PcdXenPvhStartOfDayStructPtr gUefiOvmfPkgTokenSpaceGuid.PcdXenPvhStartOfDayStructPtrSize + gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr [Depex] gEfiAcpiTableProtocolGuid From 778c3e33603cb290aa956ecf2d5f540fc09fe1cc Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 22 Dec 2022 21:11:56 +0800 Subject: [PATCH 0439/1529] ArmVirtPkg: Remove CcProbeLib from ArmVirtQemu.dsc Since CcProbeLib is not used in AcpiPlatformDxe, CcProbeLib can be removed from ArmVirtQemu.dsc. Cc: Ard Biesheuvel Cc: Leif Lindholm Cc: Sami Mujawar Cc: Gerd Hoffmann Signed-off-by: Min Xu --- ArmVirtPkg/ArmVirtQemu.dsc | 1 - 1 file changed, 1 deletion(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 1dea715e9e..f77443229e 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -68,7 +68,6 @@ VirtNorFlashPlatformLib|ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf - CcProbeLib|MdePkg/Library/CcProbeLibNull/CcProbeLibNull.inf BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf PlatformBootManagerLib|ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf PlatformBmPrintScLib|OvmfPkg/Library/PlatformBmPrintScLib/PlatformBmPrintScLib.inf From bb8e66d991aeec854b7c84578265f7893e8a9d71 Mon Sep 17 00:00:00 2001 From: Guo Dong Date: Wed, 21 Dec 2022 11:36:37 -0700 Subject: [PATCH 0440/1529] UefiPayloadPkg: Fix boot issue for non-universal payload BDS module was moved from DXEFV to newly created BDSFV recently. Non-universal UEFI payload doesn't support multiple FV, so it failed to boot since BDS module could not be found. This patch add BDS back to DXEFV when UNIVERSAL_PAYLOAD is not set. Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Guo Dong Reviewed-by: James Lu Reviewed-by: Gua Guo --- UefiPayloadPkg/UefiPayloadPkg.fdf | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.fdf b/UefiPayloadPkg/UefiPayloadPkg.fdf index 94ba922244..ee7d718b3f 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.fdf +++ b/UefiPayloadPkg/UefiPayloadPkg.fdf @@ -59,9 +59,6 @@ INF UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf FILE FV_IMAGE = 4E35FD93-9C72-4c15-8C4B-E77F1DB2D793 { SECTION FV_IMAGE = DXEFV } -FILE FV_IMAGE = FBE6C1E3-2F80-4770-88B0-494186E3346F { - SECTION FV_IMAGE = BDSFV -} ################################################################################ [FV.BDSFV] @@ -277,6 +274,10 @@ INF MdeModulePkg/Universal/Acpi/AcpiPlatformDxe/AcpiPlatformDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf !endif +!if $(UNIVERSAL_PAYLOAD) == FALSE +INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf +!endif + # # UEFI network modules # From fad294372bc3564ede7a39b023374f44b3ec3088 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 9 Dec 2022 12:22:44 +0100 Subject: [PATCH 0441/1529] OvmfPkg: fix PlatformConfig The Hii form is named "MainFormState" and the EFI variable is named "PlatformConfig". Take into account the different names. Fixes: aefcc91805fd ("OvmfPkg/PlatformDxe: Handle all requests in ExtractConfig and RouteConfig") Signed-off-by: Gerd Hoffmann --- OvmfPkg/PlatformDxe/Platform.c | 4 ++-- OvmfPkg/PlatformDxe/PlatformConfig.c | 1 + OvmfPkg/PlatformDxe/PlatformConfig.h | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/PlatformDxe/Platform.c b/OvmfPkg/PlatformDxe/Platform.c index ac31fafbdc..e58e75eb22 100644 --- a/OvmfPkg/PlatformDxe/Platform.c +++ b/OvmfPkg/PlatformDxe/Platform.c @@ -258,7 +258,7 @@ ExtractConfig ( !HiiIsConfigHdrMatch ( Request, &gOvmfPlatformConfigGuid, - mVariableName + mHiiFormName ) ) { @@ -447,7 +447,7 @@ RouteConfig ( !HiiIsConfigHdrMatch ( Configuration, &gOvmfPlatformConfigGuid, - mVariableName + mHiiFormName ) ) { diff --git a/OvmfPkg/PlatformDxe/PlatformConfig.c b/OvmfPkg/PlatformDxe/PlatformConfig.c index f5ac2d0609..4058a324eb 100644 --- a/OvmfPkg/PlatformDxe/PlatformConfig.c +++ b/OvmfPkg/PlatformDxe/PlatformConfig.c @@ -22,6 +22,7 @@ // Name of the UEFI variable that we use for persistent storage. // CHAR16 mVariableName[] = L"PlatformConfig"; +CHAR16 mHiiFormName[] = L"MainFormState"; /** Serialize and persistently save platform configuration. diff --git a/OvmfPkg/PlatformDxe/PlatformConfig.h b/OvmfPkg/PlatformDxe/PlatformConfig.h index 5d9b457b1b..93d06a9a6b 100644 --- a/OvmfPkg/PlatformDxe/PlatformConfig.h +++ b/OvmfPkg/PlatformDxe/PlatformConfig.h @@ -51,5 +51,6 @@ PlatformConfigLoad ( #define PLATFORM_CONFIG_F_DOWNGRADE BIT63 extern CHAR16 mVariableName[]; +extern CHAR16 mHiiFormName[]; #endif // _PLATFORM_CONFIG_H_ From c9f0d3b23815dff8dd3f9e32e41c2d45337c6847 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 7 Dec 2022 06:32:15 +0100 Subject: [PATCH 0442/1529] OvmfPkg/PlatformInitLib: pass through reservations from qemu qemu uses the etc/e820 fw_cfg file not only for memory, but also for reservations. Handle reservations by adding resource descriptor hobs for them. A typical qemu configuration has a small reservation between lapic and flash: # sudo cat /proc/iomem [ ... ] fee00000-fee00fff : Local APIC feffc000-feffffff : Reserved <= HERE ffc00000-ffffffff : Reserved [ ... ] Signed-off-by: Gerd Hoffmann --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 6dbdbf9306..0c49568526 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -229,6 +229,22 @@ PlatformScanOrAdd64BitE820Ram ( )); } } + } else if (E820Entry.Type == EfiAcpiAddressRangeReserved) { + if (AddHighHob) { + DEBUG (( + DEBUG_INFO, + "%a: Reserved: Base=0x%Lx Length=0x%Lx\n", + __FUNCTION__, + E820Entry.BaseAddr, + E820Entry.Length + )); + BuildResourceDescriptorHob ( + EFI_RESOURCE_MEMORY_RESERVED, + 0, + E820Entry.BaseAddr, + E820Entry.Length + ); + } } } From 2c6f7dd6e1a703df14461db48b7e7c66b7314837 Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Fri, 9 Dec 2022 10:20:21 +0000 Subject: [PATCH 0443/1529] OvmfPkg: Send EOI before RestoreTPL() in timer interrupt handlers Deferring the EOI until after the call to RestoreTPL() means that any callbacks invoked by RestoreTPL() will run with timer interrupt delivery disabled. If any such callbacks themselves rely on timers to implement timeout loops, then the callbacks will get stuck in an infinite loop from which the system will never recover. This reverts commit 239b50a86 ("OvmfPkg: End timer interrupt later to avoid stack overflow under load"). Cc: Paolo Bonzini Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4162 Signed-off-by: Michael Brown Acked-by: Laszlo Ersek --- OvmfPkg/8254TimerDxe/Timer.c | 5 ++--- OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/OvmfPkg/8254TimerDxe/Timer.c b/OvmfPkg/8254TimerDxe/Timer.c index e49a438b44..7feaaaba2b 100644 --- a/OvmfPkg/8254TimerDxe/Timer.c +++ b/OvmfPkg/8254TimerDxe/Timer.c @@ -80,6 +80,8 @@ TimerInterruptHandler ( OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + mLegacy8259->EndOfInterrupt (mLegacy8259, Efi8259Irq0); + if (mTimerNotifyFunction != NULL) { // // @bug : This does not handle missed timer interrupts @@ -88,9 +90,6 @@ TimerInterruptHandler ( } gBS->RestoreTPL (OriginalTPL); - - DisableInterrupts (); - mLegacy8259->EndOfInterrupt (mLegacy8259, Efi8259Irq0); } /** diff --git a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c index cbc17c979c..3e04b49d6b 100644 --- a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c +++ b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c @@ -62,6 +62,8 @@ TimerInterruptHandler ( OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + SendApicEoi (); + if (mTimerNotifyFunction != NULL) { // // @bug : This does not handle missed timer interrupts @@ -70,9 +72,6 @@ TimerInterruptHandler ( } gBS->RestoreTPL (OriginalTPL); - - DisableInterrupts (); - SendApicEoi (); } /** From 60a5991e32f7dafc66d46cc2bf4ea62c6bc77717 Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Fri, 9 Dec 2022 10:20:24 +0000 Subject: [PATCH 0444/1529] OvmfPkg: Add library to handle TPL from within nested interrupt handlers UEFI requires us to support nested interrupts, but provides no way for an interrupt handler to call RestoreTPL() without implicitly re-enabling interrupts. In a virtual machine, it is possible for a large burst of interrupts to arrive. We must prevent such a burst from leading to stack underrun, while continuing to allow nested interrupts to occur. This can be achieved by allowing, when provably safe to do so, an inner interrupt handler to return from the interrupt without restoring the TPL and with interrupts remaining disabled after IRET, with the deferred call to RestoreTPL() then being issued from the outer interrupt handler. This is necessarily messy and involves direct manipulation of the interrupt stack frame, and so should not be implemented as open-coded logic within each interrupt handler. Add the Nested Interrupt TPL Library (NestedInterruptTplLib) to provide helper functions that can be used by nested interrupt handlers in place of RaiseTPL()/RestoreTPL(). Example call tree for a timer interrupt occurring at TPL_APPLICATION with a nested timer interrupt that makes its own call to RestoreTPL(): outer TimerInterruptHandler() InterruptedTPL == TPL_APPLICATION ... IsrState->InProgressRestoreTPL = TPL_APPLICATION; gBS->RestoreTPL (TPL_APPLICATION); EnableInterrupts(); dispatch a TPL_CALLBACK event gEfiCurrentTpl = TPL_CALLBACK; nested timer interrupt occurs inner TimerInterruptHandler() InterruptedTPL == TPL_CALLBACK ... IsrState->InProgressRestoreTPL = TPL_CALLBACK; gBS->RestoreTPL (TPL_CALLBACK); EnableInterrupts(); DisableInterrupts(); IsrState->InProgressRestoreTPL = TPL_APPLICATION; IRET re-enables interrupts ... finish dispatching TPL_CALLBACK events ... gEfiCurrentTpl = TPL_APPLICATION; DisableInterrupts(); IsrState->InProgressRestoreTPL = 0; sees IsrState->DeferredRestoreTPL == FALSE and returns IRET re-enables interrupts Example call tree for a timer interrupt occurring at TPL_APPLICATION with a nested timer interrupt that defers its call to RestoreTPL() to the outer instance of the interrupt handler: outer TimerInterruptHandler() InterruptedTPL == TPL_APPLICATION ... IsrState->InProgressRestoreTPL = TPL_APPLICATION; gBS->RestoreTPL (TPL_APPLICATION); EnableInterrupts(); dispatch a TPL_CALLBACK event ... finish dispatching TPL_CALLBACK events ... gEfiCurrentTpl = TPL_APPLICATION; nested timer interrupt occurs inner TimerInterruptHandler() InterruptedTPL == TPL_APPLICATION; ... sees InterruptedTPL == IsrState->InProgressRestoreTPL IsrState->DeferredRestoreTPL = TRUE; DisableInterruptsOnIret(); IRET returns without re-enabling interrupts DisableInterrupts(); IsrState->InProgressRestoreTPL = 0; sees IsrState->DeferredRestoreTPL == TRUE and loops IsrState->InProgressRestoreTPL = TPL_APPLICATION; gBS->RestoreTPL (TPL_APPLICATION); <-- deferred call EnableInterrupts(); DisableInterrupts(); IsrState->InProgressRestoreTPL = 0; sees IsrState->DeferredRestoreTPL == FALSE and returns IRET re-enables interrupts Cc: Paolo Bonzini Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4162 Signed-off-by: Michael Brown Acked-by: Laszlo Ersek --- .../Include/Library/NestedInterruptTplLib.h | 87 +++++++ OvmfPkg/Library/NestedInterruptTplLib/Iret.c | 62 +++++ OvmfPkg/Library/NestedInterruptTplLib/Iret.h | 19 ++ .../NestedInterruptTplLib.inf | 35 +++ OvmfPkg/Library/NestedInterruptTplLib/Tpl.c | 216 ++++++++++++++++++ OvmfPkg/OvmfPkg.dec | 4 + 6 files changed, 423 insertions(+) create mode 100644 OvmfPkg/Include/Library/NestedInterruptTplLib.h create mode 100644 OvmfPkg/Library/NestedInterruptTplLib/Iret.c create mode 100644 OvmfPkg/Library/NestedInterruptTplLib/Iret.h create mode 100644 OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf create mode 100644 OvmfPkg/Library/NestedInterruptTplLib/Tpl.c diff --git a/OvmfPkg/Include/Library/NestedInterruptTplLib.h b/OvmfPkg/Include/Library/NestedInterruptTplLib.h new file mode 100644 index 0000000000..0ead6e4b34 --- /dev/null +++ b/OvmfPkg/Include/Library/NestedInterruptTplLib.h @@ -0,0 +1,87 @@ +/** @file + Handle raising and lowering TPL from within nested interrupt handlers. + + Allows interrupt handlers to safely raise and lower the TPL to + dispatch event notifications, correctly allowing for nested + interrupts to occur without risking stack exhaustion. + + Copyright (C) 2022, Fen Systems Ltd. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef __NESTED_INTERRUPT_TPL_LIB__ +#define __NESTED_INTERRUPT_TPL_LIB__ + +#include +#include +#include + +/// +/// State shared between all invocations of a nested interrupt handler. +/// +typedef struct { + /// + /// Highest TPL that is currently the target of a call to + /// RestoreTPL() by an instance of this interrupt handler. + /// + EFI_TPL InProgressRestoreTPL; + /// + /// Flag used to defer a call to RestoreTPL() from an inner instance + /// of the interrupt handler to an outer instance of the same + /// interrupt handler. + /// + BOOLEAN DeferredRestoreTPL; +} NESTED_INTERRUPT_STATE; + +/** + Raise the task priority level to TPL_HIGH_LEVEL. + + @param None. + + @return The task priority level at which the interrupt occurred. +**/ +EFI_TPL +EFIAPI +NestedInterruptRaiseTPL ( + VOID + ); + +/** + Lower the task priority back to the value at which the interrupt + occurred. + + This is unfortunately messy. UEFI requires us to support nested + interrupts, but provides no way for an interrupt handler to call + RestoreTPL() without implicitly re-enabling interrupts. In a + virtual machine, it is possible for a large burst of interrupts to + arrive. We must prevent such a burst from leading to stack + exhaustion, while continuing to allow nested interrupts to occur. + + Since nested interrupts are permitted, an interrupt handler may be + invoked as an inner interrupt handler while an outer instance of the + same interrupt handler is still inside its call to RestoreTPL(). + + To avoid stack exhaustion, this call may therefore (when provably + safe to do so) defer the actual TPL lowering to be performed by an + outer instance of the same interrupt handler. + + @param InterruptedTPL The task priority level at which the interrupt + occurred, as previously returned from + NestedInterruptRaiseTPL(). + + @param SystemContext A pointer to the system context when the + interrupt occurred. + + @param IsrState A pointer to the state shared between all + invocations of the nested interrupt handler. +**/ +VOID +EFIAPI +NestedInterruptRestoreTPL ( + IN EFI_TPL InterruptedTPL, + IN OUT EFI_SYSTEM_CONTEXT SystemContext, + IN OUT NESTED_INTERRUPT_STATE *IsrState + ); + +#endif // __NESTED_INTERRUPT_TPL_LIB__ diff --git a/OvmfPkg/Library/NestedInterruptTplLib/Iret.c b/OvmfPkg/Library/NestedInterruptTplLib/Iret.c new file mode 100644 index 0000000000..f6b2c51b6c --- /dev/null +++ b/OvmfPkg/Library/NestedInterruptTplLib/Iret.c @@ -0,0 +1,62 @@ +/** @file + Force interrupt handler to return with interrupts still disabled. + + Copyright (C) 2022, Fen Systems Ltd. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include + +#include "Iret.h" + +/** + Force interrupt handler to return with interrupts still disabled. + + @param SystemContext A pointer to the system context when the + interrupt occurred. +**/ +VOID +DisableInterruptsOnIret ( + IN OUT EFI_SYSTEM_CONTEXT SystemContext + ) +{ + #if defined (MDE_CPU_X64) + + IA32_EFLAGS32 Rflags; + + // + // Get flags from system context. + // + Rflags.UintN = SystemContext.SystemContextX64->Rflags; + ASSERT (Rflags.Bits.IF); + + // + // Clear interrupts-enabled flag. + // + Rflags.Bits.IF = 0; + SystemContext.SystemContextX64->Rflags = Rflags.UintN; + + #elif defined (MDE_CPU_IA32) + + IA32_EFLAGS32 Eflags; + + // + // Get flags from system context. + // + Eflags.UintN = SystemContext.SystemContextIa32->Eflags; + ASSERT (Eflags.Bits.IF); + + // + // Clear interrupts-enabled flag. + // + Eflags.Bits.IF = 0; + SystemContext.SystemContextIa32->Eflags = Eflags.UintN; + + #else + + #error "Unsupported CPU" + + #endif +} diff --git a/OvmfPkg/Library/NestedInterruptTplLib/Iret.h b/OvmfPkg/Library/NestedInterruptTplLib/Iret.h new file mode 100644 index 0000000000..278c1e22b3 --- /dev/null +++ b/OvmfPkg/Library/NestedInterruptTplLib/Iret.h @@ -0,0 +1,19 @@ +/** @file + Force interrupt handler to return with interrupts still disabled. + + Copyright (C) 2022, Fen Systems Ltd. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef _IRET_H_ +#define _IRET_H_ + +#include + +VOID +DisableInterruptsOnIret ( + IN OUT EFI_SYSTEM_CONTEXT SystemContext + ); + +#endif // _IRET_H_ diff --git a/OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf b/OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf new file mode 100644 index 0000000000..5eafb41978 --- /dev/null +++ b/OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf @@ -0,0 +1,35 @@ +## @file +# Handle raising and lowering TPL from within nested interrupt handlers. +# +# Allows interrupt handlers to safely raise and lower the TPL to +# dispatch event notifications, correctly allowing for nested +# interrupts to occur without risking stack exhaustion. +# +# Copyright (C) 2022, Fen Systems Ltd. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 1.29 + BASE_NAME = NestedInterruptTplLib + FILE_GUID = 8df39823-2f9e-4ef2-b971-243b44c32c67 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = NestedInterruptTplLib|DXE_DRIVER + +[Sources] + Tpl.c + Iret.c + +[Packages] + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + UefiBootServicesTableLib + +[Depex.common.DXE_DRIVER] + TRUE diff --git a/OvmfPkg/Library/NestedInterruptTplLib/Tpl.c b/OvmfPkg/Library/NestedInterruptTplLib/Tpl.c new file mode 100644 index 0000000000..e19d98878e --- /dev/null +++ b/OvmfPkg/Library/NestedInterruptTplLib/Tpl.c @@ -0,0 +1,216 @@ +/** @file + Handle raising and lowering TPL from within nested interrupt handlers. + + Allows interrupt handlers to safely raise and lower the TPL to + dispatch event notifications, correctly allowing for nested + interrupts to occur without risking stack exhaustion. + + Copyright (C) 2022, Fen Systems Ltd. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include +#include +#include + +#include "Iret.h" + +/** + Raise the task priority level to TPL_HIGH_LEVEL. + + @param None. + + @return The task priority level at which the interrupt occurred. +**/ +EFI_TPL +EFIAPI +NestedInterruptRaiseTPL ( + VOID + ) +{ + EFI_TPL InterruptedTPL; + + // + // Raise TPL and assert that we were called from within an interrupt + // handler (i.e. with TPL below TPL_HIGH_LEVEL but with interrupts + // disabled). + // + ASSERT (GetInterruptState () == FALSE); + InterruptedTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + ASSERT (InterruptedTPL < TPL_HIGH_LEVEL); + + return InterruptedTPL; +} + +/** + Lower the task priority back to the value at which the interrupt + occurred. + + This is unfortunately messy. UEFI requires us to support nested + interrupts, but provides no way for an interrupt handler to call + RestoreTPL() without implicitly re-enabling interrupts. In a + virtual machine, it is possible for a large burst of interrupts to + arrive. We must prevent such a burst from leading to stack + exhaustion, while continuing to allow nested interrupts to occur. + + Since nested interrupts are permitted, an interrupt handler may be + invoked as an inner interrupt handler while an outer instance of the + same interrupt handler is still inside its call to RestoreTPL(). + + To avoid stack exhaustion, this call may therefore (when provably + safe to do so) defer the actual TPL lowering to be performed by an + outer instance of the same interrupt handler. + + @param InterruptedTPL The task priority level at which the interrupt + occurred, as previously returned from + NestedInterruptRaiseTPL(). + + @param SystemContext A pointer to the system context when the + interrupt occurred. + + @param IsrState A pointer to the state shared between all + invocations of the nested interrupt handler. +**/ +VOID +EFIAPI +NestedInterruptRestoreTPL ( + IN EFI_TPL InterruptedTPL, + IN OUT EFI_SYSTEM_CONTEXT SystemContext, + IN OUT NESTED_INTERRUPT_STATE *IsrState + ) +{ + EFI_TPL SavedInProgressRestoreTPL; + BOOLEAN DeferredRestoreTPL; + + // + // If the TPL at which this interrupt occurred is equal to that of + // the in-progress RestoreTPL() for an outer instance of the same + // interrupt handler, then that outer handler's call to RestoreTPL() + // must have finished dispatching all event notifications. This + // interrupt must therefore have occurred at the point that the + // outer handler's call to RestoreTPL() had finished and was about + // to return to the outer handler. + // + // If we were to call RestoreTPL() at this point, then we would open + // up the possibility for unlimited stack consumption in the event + // of an interrupt storm. We therefore cannot safely call + // RestoreTPL() from within this stack frame (i.e. from within this + // instance of the interrupt handler). + // + // Instead, we arrange to return from this interrupt with the TPL + // still at TPL_HIGH_LEVEL and with interrupts disabled, and to + // defer our call to RestoreTPL() to the in-progress outer instance + // of the same interrupt handler. + // + if (InterruptedTPL == IsrState->InProgressRestoreTPL) { + // + // Trigger outer instance of this interrupt handler to perform the + // RestoreTPL() call that we cannot issue at this point without + // risking stack exhaustion. + // + ASSERT (IsrState->DeferredRestoreTPL == FALSE); + IsrState->DeferredRestoreTPL = TRUE; + + // + // DEFERRAL INVOCATION POINT + // + // Return from this interrupt handler with interrupts still + // disabled (by clearing the "interrupts-enabled" bit in the CPU + // flags that will be restored by the IRET or equivalent + // instruction). + // + // This ensures that no further interrupts may occur before + // control reaches the outer interrupt handler's RestoreTPL() loop + // at the point marked "DEFERRAL RETURN POINT" (see below). + // + DisableInterruptsOnIret (SystemContext); + return; + } + + // + // If the TPL at which this interrupt occurred is higher than that + // of the in-progress RestoreTPL() for an outer instance of the same + // interrupt handler, then that outer handler's call to RestoreTPL() + // must still be dispatching event notifications. + // + // We must therefore call RestoreTPL() at this point to allow more + // event notifications to be dispatched, since those event + // notification callback functions may themselves be waiting upon + // other events. + // + // We cannot avoid creating a new stack frame for this call to + // RestoreTPL(), but the total number of such stack frames is + // intrinsically limited by the number of distinct TPLs. + // + // We may need to issue the call to RestoreTPL() more than once, if + // an inner instance of the same interrupt handler needs to defer + // its RestoreTPL() call to be performed from within this stack + // frame (see above). + // + while (TRUE) { + // + // Check shared state loop invariants. + // + ASSERT (IsrState->InProgressRestoreTPL < InterruptedTPL); + ASSERT (IsrState->DeferredRestoreTPL == FALSE); + + // + // Record the in-progress RestoreTPL() value in the shared state + // where it will be visible to an inner instance of the same + // interrupt handler, in case a nested interrupt occurs during our + // call to RestoreTPL(). + // + SavedInProgressRestoreTPL = IsrState->InProgressRestoreTPL; + IsrState->InProgressRestoreTPL = InterruptedTPL; + + // + // Call RestoreTPL() to allow event notifications to be + // dispatched. This will implicitly re-enable interrupts. + // + gBS->RestoreTPL (InterruptedTPL); + + // + // Re-disable interrupts after the call to RestoreTPL() to ensure + // that we have exclusive access to the shared state. + // + DisableInterrupts (); + + // + // DEFERRAL RETURN POINT + // + // An inner instance of the same interrupt handler may have chosen + // to defer its RestoreTPL() call to be performed from within this + // stack frame. If so, it is guaranteed that no further event + // notifications or interrupts have been processed between the + // DEFERRAL INVOCATION POINT (see above) and this DEFERRAL RETURN + // POINT. + // + + // + // Restore the locally saved in-progress RestoreTPL() value in the + // shared state, now that our call to RestoreTPL() has returned + // and is therefore no longer in progress. + // + ASSERT (IsrState->InProgressRestoreTPL == InterruptedTPL); + IsrState->InProgressRestoreTPL = SavedInProgressRestoreTPL; + + // + // Check (and clear) the shared state to see if an inner instance + // of the same interrupt handler deferred its call to + // RestoreTPL(). + // + DeferredRestoreTPL = IsrState->DeferredRestoreTPL; + IsrState->DeferredRestoreTPL = FALSE; + + // + // If no inner interrupt handler deferred its call to + // RestoreTPL(), then the TPL has been successfully restored and + // we may return from the interrupt handler. + // + if (DeferredRestoreTPL == FALSE) { + return; + } + } +} diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index a350bb8f84..693925a1dc 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -38,6 +38,10 @@ # MemEncryptTdxLib|Include/Library/MemEncryptTdxLib.h + ## @libraryclass Handle TPL changes within nested interrupt handlers + # + NestedInterruptTplLib|Include/Library/NestedInterruptTplLib.h + ## @libraryclass Save and restore variables using a file # NvVarsFileLib|Include/Library/NvVarsFileLib.h From ab83797d416b35dea716463afa91bc1b93864ca8 Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Fri, 9 Dec 2022 10:20:27 +0000 Subject: [PATCH 0445/1529] OvmfPkg: Use NestedInterruptTplLib in nested interrupt handlers Prevent stack underrun in the event of a timer interrupt storm in LocalApicTimerDxe and 8254TimerDxe interrupt handlers by using the helper functions provided by NestedInterruptTplLib. This fixes the same problem as addressed in commit 239b50a86 ("OvmfPkg: End timer interrupt later to avoid stack overflow under load"), but does so without breaking nested timer interrupts. Cc: Paolo Bonzini Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=2815 Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4162 Signed-off-by: Michael Brown Acked-by: Laszlo Ersek --- OvmfPkg/8254TimerDxe/8254Timer.inf | 1 + OvmfPkg/8254TimerDxe/Timer.c | 9 ++++++--- OvmfPkg/AmdSev/AmdSevX64.dsc | 1 + OvmfPkg/CloudHv/CloudHvX64.dsc | 1 + OvmfPkg/IntelTdx/IntelTdxX64.dsc | 1 + OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c | 9 ++++++--- OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf | 1 + OvmfPkg/Microvm/MicrovmX64.dsc | 1 + OvmfPkg/OvmfPkgIa32.dsc | 1 + OvmfPkg/OvmfPkgIa32X64.dsc | 1 + OvmfPkg/OvmfPkgX64.dsc | 1 + OvmfPkg/OvmfXen.dsc | 1 + 12 files changed, 22 insertions(+), 6 deletions(-) diff --git a/OvmfPkg/8254TimerDxe/8254Timer.inf b/OvmfPkg/8254TimerDxe/8254Timer.inf index 8a07c8247e..8fbab896f0 100644 --- a/OvmfPkg/8254TimerDxe/8254Timer.inf +++ b/OvmfPkg/8254TimerDxe/8254Timer.inf @@ -24,6 +24,7 @@ UefiBootServicesTableLib BaseLib DebugLib + NestedInterruptTplLib UefiDriverEntryPoint IoLib diff --git a/OvmfPkg/8254TimerDxe/Timer.c b/OvmfPkg/8254TimerDxe/Timer.c index 7feaaaba2b..5382b01615 100644 --- a/OvmfPkg/8254TimerDxe/Timer.c +++ b/OvmfPkg/8254TimerDxe/Timer.c @@ -6,6 +6,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include + #include "Timer.h" // @@ -76,9 +78,10 @@ TimerInterruptHandler ( IN EFI_SYSTEM_CONTEXT SystemContext ) { - EFI_TPL OriginalTPL; + STATIC NESTED_INTERRUPT_STATE NestedInterruptState; + EFI_TPL OriginalTPL; - OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + OriginalTPL = NestedInterruptRaiseTPL (); mLegacy8259->EndOfInterrupt (mLegacy8259, Efi8259Irq0); @@ -89,7 +92,7 @@ TimerInterruptHandler ( mTimerNotifyFunction (mTimerPeriod); } - gBS->RestoreTPL (OriginalTPL); + NestedInterruptRestoreTPL (OriginalTPL, SystemContext, &NestedInterruptState); } /** diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 18c2922540..1cafe0d5b3 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -355,6 +355,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 98daf98f43..dc2509c39e 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -406,6 +406,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index ea538fd783..6ec64df918 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -315,6 +315,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c index 3e04b49d6b..67f4dcde37 100644 --- a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c +++ b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.c @@ -8,6 +8,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include + #include "LocalApicTimerDxe.h" // @@ -58,9 +60,10 @@ TimerInterruptHandler ( IN EFI_SYSTEM_CONTEXT SystemContext ) { - EFI_TPL OriginalTPL; + STATIC NESTED_INTERRUPT_STATE NestedInterruptState; + EFI_TPL OriginalTPL; - OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + OriginalTPL = NestedInterruptRaiseTPL (); SendApicEoi (); @@ -71,7 +74,7 @@ TimerInterruptHandler ( mTimerNotifyFunction (mTimerPeriod); } - gBS->RestoreTPL (OriginalTPL); + NestedInterruptRestoreTPL (OriginalTPL, SystemContext, &NestedInterruptState); } /** diff --git a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf index 3ad28a148c..b85965c75e 100644 --- a/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf +++ b/OvmfPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf @@ -27,6 +27,7 @@ UefiBootServicesTableLib BaseLib DebugLib + NestedInterruptTplLib UefiDriverEntryPoint LocalApicLib diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index de3b355254..f92a321fc2 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -405,6 +405,7 @@ PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index f617aa60ca..f232de13a7 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -410,6 +410,7 @@ !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index cbd5df63a1..f21b78299f 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -416,6 +416,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 2caa4d2ecc..e24bb442cb 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -436,6 +436,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index 2af4682b78..bfa08c08e3 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -341,6 +341,7 @@ PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf + NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf [LibraryClasses.common.UEFI_APPLICATION] From 0020eabe359918d603b524e0d6576853544b2bcc Mon Sep 17 00:00:00 2001 From: Pedro Falcato Date: Sat, 17 Dec 2022 03:50:20 +0800 Subject: [PATCH 0446/1529] BaseTools: Fix IA32 UINT64 alignment for CLANG toolchains Currently, UINT64 is not 8-byte aligned for CLANG* toolchains on IA32, which causes ABI differences between IA32 and X64 in such simple examples as: struct S {UINT32 A; UINT64 B;}; Pass -malign-double to align it to 8 bytes, as is done for GCC already. Signed-off-by: Pedro Falcato Cc: Marvin H?user Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Conf/tools_def.template | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index f1fd6a0030..805e903b23 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2616,15 +2616,15 @@ DEFINE CLANG38_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANG38_WARNIN *_CLANG38_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG38_IA32_TARGET) *_CLANG38_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_IA32_TARGET) -DEBUG_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g +DEBUG_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double DEBUG_CLANG38_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -flto -Wl,-Oz -Wl,-melf_i386 -Wl,--oformat=elf32-i386 DEBUG_CLANG38_IA32_DLINK2_FLAGS = DEF(GCC5_IA32_DLINK2_FLAGS) -O3 -RELEASE_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) +RELEASE_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -malign-double RELEASE_CLANG38_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -flto -Wl,-Oz -Wl,-melf_i386 -Wl,--oformat=elf32-i386 RELEASE_CLANG38_IA32_DLINK2_FLAGS = DEF(GCC5_IA32_DLINK2_FLAGS) -O3 -NOOPT_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g +NOOPT_CLANG38_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double NOOPT_CLANG38_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -Wl,-O0 -Wl,-melf_i386 -Wl,--oformat=elf32-i386 NOOPT_CLANG38_IA32_DLINK2_FLAGS = DEF(GCC5_IA32_DLINK2_FLAGS) -O0 @@ -2804,15 +2804,15 @@ DEFINE CLANGPDB_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANGPDB_WARN *_CLANGPDB_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANGPDB_IA32_TARGET) *_CLANGPDB_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANGPDB_IA32_TARGET) -DEBUG_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview +DEBUG_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview -malign-double DEBUG_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /MLLVM:-exception-model=wineh /lldmap DEBUG_CLANGPDB_IA32_DLINK2_FLAGS = -RELEASE_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) +RELEASE_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) -malign-double RELEASE_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /MERGE:.rdata=.data /MLLVM:-exception-model=wineh /lldmap RELEASE_CLANGPDB_IA32_DLINK2_FLAGS = -NOOPT_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview +NOOPT_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview -malign-double NOOPT_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /MLLVM:-exception-model=wineh /lldmap NOOPT_CLANGPDB_IA32_DLINK2_FLAGS = @@ -2905,15 +2905,15 @@ DEFINE CLANGDWARF_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x22 *_CLANGDWARF_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG38_IA32_TARGET) *_CLANGDWARF_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_IA32_TARGET) -DEBUG_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g +DEBUG_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double DEBUG_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -flto -Wl,-O3 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 DEBUG_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld -RELEASE_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) +RELEASE_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -malign-double RELEASE_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -flto -Wl,-O3 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 RELEASE_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld -NOOPT_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g +NOOPT_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double NOOPT_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -Wl,-O0 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 NOOPT_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O0 -fuse-ld=lld From 4d14120bbaf5065da680e5aa2e055a645d092166 Mon Sep 17 00:00:00 2001 From: Jake Garver Date: Tue, 20 Dec 2022 21:14:12 +0800 Subject: [PATCH 0447/1529] BaseTools: Use BUILD_CC when checking gcc version in DevicePath When checking the version in DevicePath's Makefile, use BUILD_CC instead of assuming "gcc". BUILD_CC is set in header.makefile and is the compiler that will actually be used to build DevicePath. It defaults to "gcc", but may be overridden. Signed-off-by: Jake Garver Reviewed-by: Bob Feng --- BaseTools/Source/C/DevicePath/GNUmakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile index 17f213879e..13b54ead65 100644 --- a/BaseTools/Source/C/DevicePath/GNUmakefile +++ b/BaseTools/Source/C/DevicePath/GNUmakefile @@ -13,7 +13,7 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o DevicePathUtili include $(MAKEROOT)/Makefiles/app.makefile -GCCVERSION = $(shell gcc -dumpversion | awk -F'.' '{print $$1}') +GCCVERSION = $(shell $(BUILD_CC) -dumpversion | awk -F'.' '{print $$1}') ifneq ("$(GCCVERSION)", "5") ifneq ($(CXX), llvm) ifneq ($(DARWIN),Darwin) From 1a15ba24cbd48889d57883fdabb7907e6d460597 Mon Sep 17 00:00:00 2001 From: "Jake Garver via groups.io" Date: Fri, 9 Dec 2022 00:22:11 +0800 Subject: [PATCH 0448/1529] BaseTools: Generate deps for Arm targets Prior to this change, deps were not generated for Arm and AARCH64 libraries when MODULE_TYPE was BASE, SEC, PEI_CORE, or PIEM. That resulted in bad incremental builds. Signed-off-by: Jake Garver Reviewed-by: Jeff Brasen Reviewed-by: Bob Feng --- BaseTools/Conf/build_rule.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index af4819de92..ec83638144 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -145,7 +145,7 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj - "$(CC)" $(CC_FLAGS) $(CC_XIPFLAGS) -c -o ${dst} $(INC) ${src} + "$(CC)" $(DEPS_FLAGS) $(CC_FLAGS) $(CC_XIPFLAGS) -c -o ${dst} $(INC) ${src} [C-Header-File] From b0640daac9ebc05cbc5cb43630fca77832f6d6ba Mon Sep 17 00:00:00 2001 From: "Tan, Dun" Date: Tue, 3 Jan 2023 13:56:17 +0800 Subject: [PATCH 0449/1529] UefiCpuPkg/PiSmmCpuDxeSmm:Fix PF issue caused by smm page table code When setting new page table pool to RO, only disable/enable WP when Cr0.WP has been set to 1 to fix potential PF caused by b822be1a20 (UefiCpuPkg/PiSmmCpuDxeSmm: Introduce page table pool mechanism). With previous code, if someone want to modify the page table and Cr0.WP has been cleared before modify page table, Cr0.WP may be set to 1 again since new pool may be generated during this process Then PF fault may happens. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar --- .../PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c index 4bb23f6920..834a756061 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c @@ -67,8 +67,10 @@ InitializePageTablePool ( IN UINTN PoolPages ) { - VOID *Buffer; - BOOLEAN CetEnabled; + VOID *Buffer; + BOOLEAN CetEnabled; + BOOLEAN WpEnabled; + IA32_CR0 Cr0; // // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for @@ -106,21 +108,32 @@ InitializePageTablePool ( // if (mIsReadOnlyPageTable) { CetEnabled = ((AsmReadCr4 () & CR4_CET_ENABLE) != 0) ? TRUE : FALSE; - if (CetEnabled) { - // - // CET must be disabled if WP is disabled. - // - DisableCet (); + Cr0.UintN = AsmReadCr0 (); + WpEnabled = (Cr0.Bits.WP != 0) ? TRUE : FALSE; + if (WpEnabled) { + if (CetEnabled) { + // + // CET must be disabled if WP is disabled. Disable CET before clearing CR0.WP. + // + DisableCet (); + } + + Cr0.Bits.WP = 0; + AsmWriteCr0 (Cr0.UintN); } - AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); SmmSetMemoryAttributes ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_PAGES_TO_SIZE (PoolPages), EFI_MEMORY_RO); - AsmWriteCr0 (AsmReadCr0 () | CR0_WP); - if (CetEnabled) { - // - // re-enable CET. - // - EnableCet (); + if (WpEnabled) { + Cr0.UintN = AsmReadCr0 (); + Cr0.Bits.WP = 1; + AsmWriteCr0 (Cr0.UintN); + + if (CetEnabled) { + // + // re-enable CET. + // + EnableCet (); + } } } From 2968e29f66b74e17f5b1ef51f7183e27fa3d18d2 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Tue, 27 Sep 2022 12:24:18 +0800 Subject: [PATCH 0450/1529] UnitTestFrameworkPkg: Add code coverage support for GCC In order to collect code coverage after running executable file, generate *.gcda and *.gcno file that require by lcov tool to generate code coverage report. Reviewed-by: Michael D Kinney Cc: Sean Brogan Cc: Bret Barkelew Reviewed-by: Michael Kubacki Signed-off-by: Gua Guo --- UnitTestFrameworkPkg/ReadMe.md | 41 +++++++++++++++++++ .../UnitTestFrameworkPkg.ci.yaml | 1 + .../UnitTestFrameworkPkgHost.dsc.inc | 3 +- 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 9ce04b7f3e..3fa4e1910f 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -583,6 +583,47 @@ GTEST_OUTPUT=xml: This mode is used by the test running plugin to aggregate the results for CI test status reporting in the web view. +### Code Coverage + +Host based Unit Tests will automatically enable coverage data. + +For Windows, This is primarily leverage for pipeline builds, but this can be leveraged locally using the +OpenCppCoverage windows tool to parse coverage data to cobertura xml format. + +- Windows Prerequisite + ```bash + Download and install https://github.com/OpenCppCoverage/OpenCppCoverage/releases + python -m pip install --upgrade -r ./pip-requirements.txt + stuart_ci_build -c .pytool/CISettings.py -t NOOPT TOOL_CHAIN_TAG=VS2019 -p MdeModulePkg + Open Build/coverage.xml + ``` + + - How to see code coverage data on IDE Visual Studio + ``` + Open Visual Studio VS2019 or above version + Click "Tools" -> "OpenCppCoverage Settings" + Fill your execute file into "Program to run:" + Click "Tools" -> "Run OpenCppCoverage" + ``` + + +For Linux, This is primarily leveraged for pipeline builds, but this can be leveraged locally using the +lcov linux tool, and parsed using the lcov_cobertura python tool to parse it to cobertura xml format. + +- Linux Prerequisite + ```bash + sudo apt-get install -y lcov + python -m pip install --upgrade -r ./pip-requirements.txt + stuart_ci_build -c .pytool/CISettings.py -t NOOPT TOOL_CHAIN_TAG=GCC5 -p MdeModulePkg + Open Build/coverage.xml + ``` + - How to see code coverage data on IDE Visual Studio Code + ``` + Download plugin "Coverage Gutters" + Press Hot Key "Ctrl + Shift + P" and click option "Coverage Gutters: Display Coverage" + ``` + + ### Important Note This works on both Windows and Linux but is currently limited to x64 architectures. Working on getting others, but we diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 072df6208c..d8f8e024c4 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -91,6 +91,7 @@ "pytools", "NOFAILURE", "cmockery", + "cobertura", "DHAVE", # build flag for cmocka in the INF "gtest", # file name in GoogleTestLib.inf "corthon", # Contact GitHub account in Readme diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 8009337552..7f5dfa30ed 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -27,7 +27,8 @@ GCC:*_*_*_CC_FLAGS = -D UNIT_TESTING_DEBUG=1 XCODE:*_*_*_CC_FLAGS = -D UNIT_TESTING_DEBUG=1 !endif - + GCC:*_GCC5_*_CC_FLAGS = --coverage + GCC:*_GCC5_*_DLINK_FLAGS = --coverage [BuildOptions.common.EDKII.HOST_APPLICATION] # # MSFT From 22b91eca655a08f56c83c98a9c6c3c7155fdcd2d Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Tue, 27 Sep 2022 12:25:17 +0800 Subject: [PATCH 0451/1529] BaseTools/Plugin: Add coverage support for Unit Test For GCC, use lcov to generate Unit Test code coverage report For VS2019, use OpenCppCoverage to generate code coverage report Cc: Bob Feng Cc: Bret Barkelew Cc: Liming Gao Reviewed-by: Michael D Kinney Cc: Sean Brogan Reviewed-by: Michael Kubacki Signed-off-by: Gua Guo --- .../HostBasedUnitTestRunner.py | 101 +++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index a8220aacd3..0e013c5f1a 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -94,7 +94,7 @@ def do_post_build(self, thebuilder): # Run the test. ret = RunCmd('"' + test + '"', "", workingdir=cp) - if(ret != 0): + if ret != 0: logging.error("UnitTest Execution Error: " + os.path.basename(test)) else: @@ -115,4 +115,103 @@ def do_post_build(self, thebuilder): " %s - %s" % (case.attrib['name'], result.text)) failure_count += 1 + if thebuilder.env.GetValue("CODE_COVERAGE") != "FALSE": + if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "GCC5": + self.gen_code_coverage_gcc(thebuilder) + elif thebuilder.env.GetValue("TOOL_CHAIN_TAG").startswith ("VS"): + self.gen_code_coverage_msvc(thebuilder) + else: + logging.info("Skipping code coverage. Currently, support GCC and MSVC compiler.") + return failure_count + + def gen_code_coverage_gcc(self, thebuilder): + logging.info("Generating UnitTest code coverage") + + buildOutputBase = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + workspace = thebuilder.env.GetValue("WORKSPACE") + + # Generate base code coverage for all source files + ret = RunCmd("lcov", f"--no-external --capture --initial --directory {buildOutputBase} --output-file {buildOutputBase}/cov-base.info --rc lcov_branch_coverage=1") + if ret != 0: + logging.error("UnitTest Coverage: Failed to build initial coverage data.") + return 1 + + # Coverage data for tested files only + ret = RunCmd("lcov", f"--capture --directory {buildOutputBase}/ --output-file {buildOutputBase}/coverage-test.info --rc lcov_branch_coverage=1") + if ret != 0: + logging.error("UnitTest Coverage: Failed to build coverage data for tested files.") + return 1 + + # Aggregate all coverage data + ret = RunCmd("lcov", f"--add-tracefile {buildOutputBase}/cov-base.info --add-tracefile {buildOutputBase}/coverage-test.info --output-file {buildOutputBase}/total-coverage.info --rc lcov_branch_coverage=1") + if ret != 0: + logging.error("UnitTest Coverage: Failed to aggregate coverage data.") + return 1 + + # Generate coverage XML + ret = RunCmd("lcov_cobertura",f"{buildOutputBase}/total-coverage.info -o {buildOutputBase}/compare.xml") + if ret != 0: + logging.error("UnitTest Coverage: Failed to generate coverage XML.") + return 1 + + # Filter out auto-generated and test code + ret = RunCmd("lcov_cobertura",f"{buildOutputBase}/total-coverage.info --excludes ^.*UnitTest\|^.*MU\|^.*Mock\|^.*DEBUG -o {buildOutputBase}/coverage.xml") + if ret != 0: + logging.error("UnitTest Coverage: Failed generate filtered coverage XML.") + return 1 + + # Generate all coverage file + testCoverageList = glob.glob (f"{workspace}/Build/**/total-coverage.info", recursive=True) + + coverageFile = "" + for testCoverage in testCoverageList: + coverageFile += " --add-tracefile " + testCoverage + ret = RunCmd("lcov", f"{coverageFile} --output-file {workspace}/Build/all-coverage.info --rc lcov_branch_coverage=1") + if ret != 0: + logging.error("UnitTest Coverage: Failed generate all coverage file.") + return 1 + + # Generate and XML file if requested.for all package + if os.path.isfile(f"{workspace}/Build/coverage.xml"): + os.remove(f"{workspace}/Build/coverage.xml") + ret = RunCmd("lcov_cobertura",f"{workspace}/Build/all-coverage.info --excludes ^.*UnitTest\|^.*MU\|^.*Mock\|^.*DEBUG -o {workspace}/Build/coverage.xml") + + return 0 + + + def gen_code_coverage_msvc(self, thebuilder): + logging.info("Generating UnitTest code coverage") + + + buildOutputBase = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + testList = glob.glob(os.path.join(buildOutputBase, "**","*Test*.exe"), recursive=True) + workspace = thebuilder.env.GetValue("WORKSPACE") + workspace = (workspace + os.sep) if workspace[-1] != os.sep else workspace + # Generate coverage file + coverageFile = "" + for testFile in testList: + ret = RunCmd("OpenCppCoverage", f"--source {workspace} --export_type binary:{testFile}.cov -- {testFile}") + coverageFile += " --input_coverage=" + testFile + ".cov" + if ret != 0: + logging.error("UnitTest Coverage: Failed to collect coverage data.") + return 1 + + # Generate and XML file if requested.by each package + ret = RunCmd("OpenCppCoverage", f"--export_type cobertura:{os.path.join(buildOutputBase, 'coverage.xml')} --working_dir={workspace}Build {coverageFile}") + if ret != 0: + logging.error("UnitTest Coverage: Failed to generate cobertura format xml in single package.") + return 1 + + # Generate total report XML file for all package + testCoverageList = glob.glob(os.path.join(workspace, "Build", "**","*Test*.exe.cov"), recursive=True) + coverageFile = "" + for testCoverage in testCoverageList: + coverageFile += " --input_coverage=" + testCoverage + + ret = RunCmd("OpenCppCoverage", f"--export_type cobertura:{workspace}Build/coverage.xml --working_dir={workspace}Build {coverageFile}") + if ret != 0: + logging.error("UnitTest Coverage: Failed to generate cobertura format xml.") + return 1 + + return 0 From d6512e5fe4191816562a37aa639992f38cfb8641 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Tue, 8 Nov 2022 16:38:49 +0800 Subject: [PATCH 0452/1529] .azurepipelines: Install code coverage tool For Windows add below tool for code coverage 1. OpenCppCoverage: parsing pdb file to generate coverage data 2. pycobertura: show up html format data for coverage data For Linux add below tool for code coverage 1. lcov: parsing gcda gcno file to generate coverage data 2. lcov-cobertura: convert coverage data to cobertura format 3. pycobertura: show up html format data for coverage data Cc: Sean Brogan Cc: Bret Barkelew Reviewed-by: Michael D Kinney Cc: Liming Gao Reviewed-by: Michael Kubacki Signed-off-by: Gua Guo --- .azurepipelines/Ubuntu-GCC5.yml | 5 ++- .azurepipelines/Windows-VS2019.yml | 5 +++ .../templates/pr-gate-build-job.yml | 36 +++++++++++++++++++ .azurepipelines/templates/pr-gate-steps.yml | 4 +++ pip-requirements.txt | 2 ++ 5 files changed, 51 insertions(+), 1 deletion(-) diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml index 1acd8d2a46..f83951eeaf 100644 --- a/.azurepipelines/Ubuntu-GCC5.yml +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -19,4 +19,7 @@ jobs: tool_chain_tag: 'GCC5' vm_image: 'ubuntu-latest' arch_list: "IA32,X64,ARM,AARCH64,RISCV64,LOONGARCH64" - + extra_install_step: + - bash: sudo apt-get install -y lcov + displayName: Install Code Coverage Tools + condition: and(gt(variables.pkg_count, 0), succeeded()) diff --git a/.azurepipelines/Windows-VS2019.yml b/.azurepipelines/Windows-VS2019.yml index e4bd4b1d22..c07e5bb434 100644 --- a/.azurepipelines/Windows-VS2019.yml +++ b/.azurepipelines/Windows-VS2019.yml @@ -18,3 +18,8 @@ jobs: tool_chain_tag: 'VS2019' vm_image: 'windows-2019' arch_list: "IA32,X64" + extra_install_step: + - powershell: choco install opencppcoverage; Write-Host "##vso[task.prependpath]C:\Program Files\OpenCppCoverage" + displayName: Install Code Coverage Tool + condition: and(gt(variables.pkg_count, 0), succeeded()) + diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 7f88b41dc8..840852b606 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -12,6 +12,7 @@ parameters: tool_chain_tag: '' vm_image: '' arch_list: '' + extra_install_step: [] # Build step jobs: @@ -77,3 +78,38 @@ jobs: build_pkgs: $(Build.Pkgs) build_targets: $(Build.Targets) build_archs: ${{ parameters.arch_list }} + extra_install_step: ${{ parameters.extra_install_step }} + +- job: Build_${{ parameters.tool_chain_tag }}_TARGET_CODE_COVERAGE + dependsOn: Build_${{ parameters.tool_chain_tag }} + workspace: + clean: all + + pool: + vmImage: 'windows-2019' + + steps: + - checkout: self + clean: true + fetchDepth: 1 + submodules: true + + - task: DownloadPipelineArtifact@2 + displayName: 'Download Build Artifacts' + inputs: + buildType: 'current' + targetPath: '$(Build.ArtifactStagingDirectory)' + + - task: CmdLine@2 + displayName: Create code coverage report + inputs: + script: | + dotnet tool install -g dotnet-reportgenerator-globaltool + reportgenerator -reports:$(Build.ArtifactStagingDirectory)/**/coverage.xml -targetdir:$(Build.ArtifactStagingDirectory)/Coverage -reporttypes:Cobertura -filefilters:-*Build*;-*UnitTest*;-*Mock*;-*usr* + + - task: PublishCodeCoverageResults@1 + displayName: 'Publish code coverage' + inputs: + codeCoverageTool: Cobertura + summaryFileLocation: '$(Build.ArtifactStagingDirectory)/Coverage/Cobertura.xml' + diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml index cb431e53fc..080f60aea6 100644 --- a/.azurepipelines/templates/pr-gate-steps.yml +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -12,6 +12,7 @@ parameters: build_pkgs: '' build_targets: '' build_archs: '' + extra_install_step: [] steps: - checkout: self @@ -37,6 +38,8 @@ steps: displayName: fetch target branch condition: eq(variables['Build.Reason'], 'PullRequest') +- ${{ parameters.extra_install_step }} + # trim the package list if this is a PR - task: CmdLine@1 displayName: Check if ${{ parameters.build_pkgs }} need testing @@ -125,6 +128,7 @@ steps: TestSuites.xml **/BUILD_TOOLS_REPORT.html **/OVERRIDELOG.TXT + coverage.xml flattenFolders: true condition: succeededOrFailed() diff --git a/pip-requirements.txt b/pip-requirements.txt index be8c7a1c37..4ffcadddd8 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -16,3 +16,5 @@ edk2-pytool-library==0.12.1 edk2-pytool-extensions~=0.20.0 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 +lcov-cobertura==2.0.2 + From cacae20d88e6a7a245848824ea10f9ddd0b4679c Mon Sep 17 00:00:00 2001 From: Sean Rhodes Date: Fri, 16 Dec 2022 12:24:18 +0000 Subject: [PATCH 0453/1529] MdeModulePkg/Bus/Pci/XhciDxe: Reset port if status change returns an error Force resetting the port by clearing the USB_PORT_STAT_C_RESET bit in PortChangeStatus when XhcPollPortStatusChange fails Signed-off-by: Sean Rhodes Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index 461b2cd9b5..d8fa41f68f 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -471,7 +471,16 @@ XhcGetRootHubPortStatus ( // For those devices behind hub, we get its attach/detach event by hooking Get_Port_Status request at control transfer for those hub. // ParentRouteChart.Dword = 0; - XhcPollPortStatusChange (Xhc, ParentRouteChart, PortNumber, PortStatus); + Status = XhcPollPortStatusChange (Xhc, ParentRouteChart, PortNumber, PortStatus); + + // + // Force resetting the port by clearing the USB_PORT_STAT_C_RESET bit in PortChangeStatus + // when XhcPollPortStatusChange fails + // + if (EFI_ERROR (Status)) { + PortStatus->PortChangeStatus &= ~(USB_PORT_STAT_C_RESET); + Status = EFI_SUCCESS; + } ON_EXIT: gBS->RestoreTPL (OldTpl); From 074ebbba97eef683a89d9a7a4648c35512236e6f Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Tue, 3 Jan 2023 16:02:41 +0100 Subject: [PATCH 0454/1529] OvmfPkg/QemuVideoDxe/VbeShim.sh: remove end-of-options delimiter for nasm Per my bisection: nasm broke the parsing of the "--" end-of-options delimiter in commit 55568c1193df ("nasm: scan the command line twice", 2016-10-03), part of the nasm-2.13 release. The parsing remains broken in at least nasm-2.15.03. The (invalid) error message is: "more than one input file specified". I've filed the following ticket for upstream nasm (and ndisasm): . Since the delimiter is not necessary in practice (due to $STEM being "VbeShim", i.e., not starting with a hyphen), simply remove the delimiter. Tested by enabling DEBUG in "VbeShim.asm", running the script, building OVMF, booting Windows 7, and checking the firmware log (debug console). Cc: Ard Biesheuvel Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Jordan Justen Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=3876 Signed-off-by: Laszlo Ersek Reviewed-by: Ard Biesheuvel --- OvmfPkg/QemuVideoDxe/VbeShim.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/QemuVideoDxe/VbeShim.sh b/OvmfPkg/QemuVideoDxe/VbeShim.sh index aea28be35f..7a0095a813 100755 --- a/OvmfPkg/QemuVideoDxe/VbeShim.sh +++ b/OvmfPkg/QemuVideoDxe/VbeShim.sh @@ -27,12 +27,15 @@ trap exit_handler EXIT # # Assemble the source file. +# (nasm doesn't recognize the "--" end-of-options delimiter; +# .) # -nasm -o "$STEM".bin -- "$STEM".asm +nasm -o "$STEM".bin "$STEM".asm # # Disassemble it, in order to get a binary dump associated with the source. -# (ndisasm doesn't recognize the "--" end-of-options delimiter.) +# (ndisasm doesn't recognize the "--" end-of-options delimiter; +# .) # ndisasm "$STEM".bin >"$STEM".disasm From 80d023a78135f971a111d78603b0a8e86be844e0 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Tue, 3 Jan 2023 16:02:42 +0100 Subject: [PATCH 0455/1529] OvmfPkg: raise DXEFV size to 13 MB in the traditional platform FDFs Similarly to the "cadence" mentioned in commit d272449d9e1e ("OvmfPkg: raise DXEFV size to 11 MB", 2018-05-29), it's been ~1.75 years since commit 5e75c4d1fe4f ("OvmfPkg: raise DXEFV size to 12 MB", 2020-03-11), and we've outgrown DXEFV again (with NOOPT builds). Increase the DXEFV size to 13MB now. Do not modify all platform FDF files under OvmfPkg. "BhyveX64.fdf" is still at 11MB, "OvmfXen.fdf" at 10MB. The "AmdSevX64.fdf", "CloudHvX64.fdf", "IntelTdxX64.fdf" and "MicrovmX64.fdf" flash devices could be modified similarly (from 12MB to 13MB), but I don't use or build those platforms. Tested on: - IA32, q35, SMM_REQUIRE, Fedora 30 guest - X64, pc (i440fx), no SMM, RHEL-7.9 guest - IA32X64, q35, SMM_REQUIRE, RHEL-7.9 guest Test steps: - configure 3 VCPUs - boot - run "taskset -c $I efibootmgr" with $I covering 0..2 - systemctl suspend - resume from virt-manager - run "taskset -c $I efibootmgr" with $I covering 0..2 Cc: Anthony Perard Cc: Ard Biesheuvel Cc: Brijesh Singh Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Jordan Justen Cc: Julien Grall Cc: Min Xu Cc: Peter Grehan Cc: Rebecca Cran Cc: Sebastien Boeuf Cc: Tom Lendacky Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4236 Signed-off-by: Laszlo Ersek Reviewed-by: Ard Biesheuvel --- OvmfPkg/OvmfPkgIa32.fdf | 6 +++--- OvmfPkg/OvmfPkgIa32X64.fdf | 6 +++--- OvmfPkg/OvmfPkgX64.fdf | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/OvmfPkgIa32.fdf b/OvmfPkg/OvmfPkgIa32.fdf index 72bce02cab..5451bfb845 100644 --- a/OvmfPkg/OvmfPkgIa32.fdf +++ b/OvmfPkg/OvmfPkgIa32.fdf @@ -62,10 +62,10 @@ FV = SECFV [FD.MEMFD] BaseAddress = $(MEMFD_BASE_ADDRESS) -Size = 0xD00000 +Size = 0xE00000 ErasePolarity = 1 BlockSize = 0x10000 -NumBlocks = 0xD0 +NumBlocks = 0xE0 0x000000|0x006000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize @@ -86,7 +86,7 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.P gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize FV = PEIFV -0x100000|0xC00000 +0x100000|0xD00000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize FV = DXEFV diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf index 576c985ae0..4c5bd0dbc3 100644 --- a/OvmfPkg/OvmfPkgIa32X64.fdf +++ b/OvmfPkg/OvmfPkgIa32X64.fdf @@ -62,10 +62,10 @@ FV = SECFV [FD.MEMFD] BaseAddress = $(MEMFD_BASE_ADDRESS) -Size = 0xD00000 +Size = 0xE00000 ErasePolarity = 1 BlockSize = 0x10000 -NumBlocks = 0xD0 +NumBlocks = 0xE0 0x000000|0x006000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize @@ -86,7 +86,7 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.P gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize FV = PEIFV -0x100000|0xC00000 +0x100000|0xD00000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize FV = DXEFV diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf index c4aa882431..8c02dfe11e 100644 --- a/OvmfPkg/OvmfPkgX64.fdf +++ b/OvmfPkg/OvmfPkgX64.fdf @@ -62,10 +62,10 @@ FV = SECFV [FD.MEMFD] BaseAddress = $(MEMFD_BASE_ADDRESS) -Size = 0xD00000 +Size = 0xE00000 ErasePolarity = 1 BlockSize = 0x10000 -NumBlocks = 0xD0 +NumBlocks = 0xE0 0x000000|0x006000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize @@ -101,7 +101,7 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.P gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize FV = PEIFV -0x100000|0xC00000 +0x100000|0xD00000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize FV = DXEFV From 6c1df60e26e11001a4f0a9babaa56329b8ba42cf Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Tue, 3 Jan 2023 16:02:43 +0100 Subject: [PATCH 0456/1529] UefiCpuPkg/SmmCpuFeaturesLib: drop obsolete API implementation Commit 0426115b6738 ("UefiCpuPkg: Remove unused API in SmmCpuFeaturesLib.h", 2022-12-21) removed the declaration of the function SmmCpuFeaturesAllocatePageTableMemory() from the "SmmCpuFeaturesLib.h" library class header. Remove the API's (null-)implementation from UefiCpuPkg/SmmCpuFeaturesLib as well. Build-tested with: build -a IA32 -a X64 -b NOOPT -p UefiCpuPkg/UefiCpuPkg.dsc -t GCC5 Cc: Eric Dong Cc: Gerd Hoffmann Cc: Rahul Kumar Cc: Ray Ni Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4235 Signed-off-by: Laszlo Ersek Reviewed-by: Ard Biesheuvel Acked-by: Dun Tan --- .../SmmCpuFeaturesLibCommon.c | 28 ------------------- 1 file changed, 28 deletions(-) diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c index 7777e52740..5498fda38d 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibCommon.c @@ -186,31 +186,3 @@ SmmCpuFeaturesCompleteSmmReadyToLock ( ) { } - -/** - This API provides a method for a CPU to allocate a specific region for storing page tables. - - This API can be called more once to allocate memory for page tables. - - Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the - allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL - is returned. If there is not enough memory remaining to satisfy the request, then NULL is - returned. - - This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM. - - @param Pages The number of 4 KB pages to allocate. - - @return A pointer to the allocated buffer for page tables. - @retval NULL Fail to allocate a specific region for storing page tables, - Or there is no preference on where the page tables are allocated in SMRAM. - -**/ -VOID * -EFIAPI -SmmCpuFeaturesAllocatePageTableMemory ( - IN UINTN Pages - ) -{ - return NULL; -} From 69ce3a06b910c88d08e9cddca466282f3a0176fd Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Tue, 3 Jan 2023 16:02:44 +0100 Subject: [PATCH 0457/1529] OvmfPkg/SmmCpuFeaturesLib: drop obsolete API implementation Commit 0426115b6738 ("UefiCpuPkg: Remove unused API in SmmCpuFeaturesLib.h", 2022-12-21) removed the declaration of the function SmmCpuFeaturesAllocatePageTableMemory() from the "SmmCpuFeaturesLib.h" library class header. Remove the API's (null-)implementation from OvmfPkg/SmmCpuFeaturesLib as well. Testing: OVMF builds, boots, and suspends/resumes (see earlier in this series). Cc: Ard Biesheuvel Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Jordan Justen Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4235 Signed-off-by: Laszlo Ersek Reviewed-by: Ard Biesheuvel --- .../SmmCpuFeaturesLib/SmmCpuFeaturesLib.c | 31 ------------------- 1 file changed, 31 deletions(-) diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c index 9297cc5fa9..6693666d04 100644 --- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c +++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c @@ -1348,34 +1348,3 @@ SmmCpuFeaturesCompleteSmmReadyToLock ( ) { } - -/** - This API provides a method for a CPU to allocate a specific region for - storing page tables. - - This API can be called more once to allocate memory for page tables. - - Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns - a pointer to the allocated buffer. The buffer returned is aligned on a 4KB - boundary. If Pages is 0, then NULL is returned. If there is not enough - memory remaining to satisfy the request, then NULL is returned. - - This function can also return NULL if there is no preference on where the - page tables are allocated in SMRAM. - - @param Pages The number of 4 KB pages to allocate. - - @return A pointer to the allocated buffer for page tables. - @retval NULL Fail to allocate a specific region for storing page tables, - Or there is no preference on where the page tables are - allocated in SMRAM. - -**/ -VOID * -EFIAPI -SmmCpuFeaturesAllocatePageTableMemory ( - IN UINTN Pages - ) -{ - return NULL; -} From 2b3753cdde54be5444f6b5d0a501e08dcc9faec2 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 15 Dec 2022 17:41:00 +0800 Subject: [PATCH 0458/1529] Maintainers.txt: Update NetworkPkg & MM modules Reviewer This is to change NetworkPkg & MM modules Reviewer. Reviewed-by: Eric Dong Reviewed-by: Ray Ni Cc: Maciej Rabeda Signed-off-by: Jiaxin Wu --- Maintainers.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Maintainers.txt b/Maintainers.txt index 13e1335a57..2464844c86 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -376,7 +376,7 @@ F: MdeModulePkg/*Smi*/ F: MdeModulePkg/*Smm*/ F: MdeModulePkg/Include/*Smi*.h F: MdeModulePkg/Include/*Smm*.h -R: Eric Dong [ydong10] +R: Jiaxin Wu [jiaxinwu] R: Ray Ni [niruiyu] MdeModulePkg: Pei Core @@ -432,7 +432,6 @@ NetworkPkg F: NetworkPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg M: Maciej Rabeda [mrabeda] -R: Jiaxin Wu [jiaxinwu] R: Siyuan Fu [sfu5] OvmfPkg From ae82702e15f9180a1a2e41c57a5aef1e16ee5854 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Thu, 5 Jan 2023 09:50:20 +0800 Subject: [PATCH 0459/1529] .azurepipelines: Skip CodeCoverage if coverage.xml not found Skip CodeCoverage if coverage.xml not found Cc: Liming Gao Signed-off-by: Gua Guo Reviewed-by: Sean Brogan Reviewed-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .azurepipelines/templates/pr-gate-build-job.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 840852b606..fff61a3193 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -100,16 +100,24 @@ jobs: buildType: 'current' targetPath: '$(Build.ArtifactStagingDirectory)' + - powershell: Write-Host "##vso[task.setvariable variable=is_code_coverage]0" + displayName: Give default value for whether CodeCoverage or not + + - powershell: if (Test-Path -Path $(Build.ArtifactStagingDirectory)/**/coverage.xml) {Write-Host "##vso[task.setvariable variable=is_code_coverage]1"} + displayName: Check coverage.xml exist or not + - task: CmdLine@2 displayName: Create code coverage report inputs: script: | dotnet tool install -g dotnet-reportgenerator-globaltool reportgenerator -reports:$(Build.ArtifactStagingDirectory)/**/coverage.xml -targetdir:$(Build.ArtifactStagingDirectory)/Coverage -reporttypes:Cobertura -filefilters:-*Build*;-*UnitTest*;-*Mock*;-*usr* + condition: eq(variables.is_code_coverage, 1) - task: PublishCodeCoverageResults@1 displayName: 'Publish code coverage' inputs: codeCoverageTool: Cobertura summaryFileLocation: '$(Build.ArtifactStagingDirectory)/Coverage/Cobertura.xml' + condition: eq(variables.is_code_coverage, 1) From 4211540bdda2613015b5ac174fb1c1888ee381b4 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Tue, 3 Jan 2023 17:05:39 +0100 Subject: [PATCH 0460/1529] Maintainers.txt: designate Gerd Hoffmann as UefiCpuPkg reviewer I suggest that Gerd be notified about all UefiCpuPkg patches, so he may take a quick look at, or (by his preference) even test, the proposed change, in a genuine QEMU/KVM environment. Assuming this patch is accepted -- subsequently, please *wait* for Gerd's approval on UefiCpuPkg patches, before merging them. Notes: - It's perfectly fine for a reviewer to give an A-b just so the review process be unblocked, if they don't have anything to add, or don't have time to review or test in detail. The point is that someone outside of Intel should *consistently get a chance* to raise concerns about UefiCpuPkg patches before they are merged. - My A-b's and R-b's on UefiCpuPkg patches were never supposed to be "sufficient", only "necessary", for merging. The intent is the same here, with Gerd's designation as a reviewer. Cc: Andrew Fish Cc: Eric Dong Cc: Gerd Hoffmann Cc: Leif Lindholm Cc: Michael D Kinney Cc: Rahul Kumar Cc: Ray Ni Signed-off-by: Laszlo Ersek Message-Id: <20230103160539.87830-1-lersek@redhat.com> Acked-by: Gerd Hoffmann Reviewed-by: Ray Ni --- Maintainers.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Maintainers.txt b/Maintainers.txt index 2464844c86..e785ec1f48 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -604,6 +604,7 @@ W: https://github.com/tianocore/tianocore.github.io/wiki/UefiCpuPkg M: Eric Dong [ydong10] M: Ray Ni [niruiyu] R: Rahul Kumar [rahul1-kumar] +R: Gerd Hoffmann [kraxel] UefiCpuPkg: Sec related modules F: UefiCpuPkg/SecCore/ From b96486329443ad0512fbc05f9600d8e283785541 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 4 Jan 2023 21:14:05 +0800 Subject: [PATCH 0461/1529] SecurityPkg: Move TdTcg2Dxe from OvmfPkg to SecurityPkg BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4194 The TdTcg2Dxe lives in the OvmfPkg instead of the SecurityPkg. Having the TdTcg2Dxe at the same place as Tcg2Dxe will be easier for platforms to consume. Definition of PcdCcEventlogAcpiTableLaml and PcdCcEventlogAcpiTableLasa are also moved from OvmfPkg.dec to SecurityPkg.dec. Cc: Jiewen Yao Cc: Jian J Wang Cc: Arti Gupta Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 2 +- OvmfPkg/IntelTdx/IntelTdxX64.fdf | 2 +- OvmfPkg/OvmfPkg.dec | 6 ------ SecurityPkg/SecurityPkg.dec | 6 ++++++ SecurityPkg/SecurityPkg.dsc | 5 +++++ .../Tcg}/TdTcg2Dxe/MeasureBootPeCoff.c | 0 {OvmfPkg/IntelTdx => SecurityPkg/Tcg}/TdTcg2Dxe/TdTcg2Dxe.c | 0 .../IntelTdx => SecurityPkg/Tcg}/TdTcg2Dxe/TdTcg2Dxe.inf | 5 ++--- 8 files changed, 15 insertions(+), 11 deletions(-) rename {OvmfPkg/IntelTdx => SecurityPkg/Tcg}/TdTcg2Dxe/MeasureBootPeCoff.c (100%) rename {OvmfPkg/IntelTdx => SecurityPkg/Tcg}/TdTcg2Dxe/TdTcg2Dxe.c (100%) rename {OvmfPkg/IntelTdx => SecurityPkg/Tcg}/TdTcg2Dxe/TdTcg2Dxe.inf (93%) diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 6ec64df918..5bd74639b4 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -774,7 +774,7 @@ # # Cc Measurement Protocol for Td guest # - OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf { + SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf { HashLib|SecurityPkg/Library/HashLibTdx/HashLibTdx.inf NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.fdf b/OvmfPkg/IntelTdx/IntelTdxX64.fdf index e79ad3e102..a57bbcee89 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.fdf +++ b/OvmfPkg/IntelTdx/IntelTdxX64.fdf @@ -298,7 +298,7 @@ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf # # EFI_CC_MEASUREMENT_PROTOCOL # -INF OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf +INF SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf ################################################################################ diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index 693925a1dc..e07546f4a7 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -459,12 +459,6 @@ # 2 - set by GOP Driver. gUefiOvmfPkgTokenSpaceGuid.PcdVideoResolutionSource|0|UINT8|0x64 - ## This PCD records LAML field in CC EVENTLOG ACPI table. - gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml|0|UINT32|0x66 - - ## This PCD records LASA field in CC EVENTLOG ACPI table. - gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa|0|UINT64|0x67 - [PcdsFeatureFlag] gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation|TRUE|BOOLEAN|0x1c gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderMmioTranslation|FALSE|BOOLEAN|0x1d diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 358b3dc543..8257f11d17 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -574,5 +574,11 @@ # @Prompt Tpm2AcpiTableLasa LASA field in TPM2 ACPI table. gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableLasa|0|UINT64|0x00010023 + ## This PCD records LAML field in CC EVENTLOG ACPI table. + gEfiSecurityPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml|0|UINT32|0x00010025 + + ## This PCD records LASA field in CC EVENTLOG ACPI table. + gEfiSecurityPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa|0|UINT64|0x00010026 + [UserExtensions.TianoCore."ExtraFiles"] SecurityPkgExtra.uni diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index 2f679c87a9..3bad5375c0 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -296,6 +296,11 @@ [Components.X64] SecurityPkg/Library/HashLibTdx/HashLibTdx.inf SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.inf + SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf { + + HashLib|SecurityPkg/Library/HashLibTdx/HashLibTdx.inf + NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf + } [Components.IA32, Components.X64] SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c b/SecurityPkg/Tcg/TdTcg2Dxe/MeasureBootPeCoff.c similarity index 100% rename from OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c rename to SecurityPkg/Tcg/TdTcg2Dxe/MeasureBootPeCoff.c diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c similarity index 100% rename from OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c rename to SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf similarity index 93% rename from OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf rename to SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf index 5efe7ef479..6861a1452d 100644 --- a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf +++ b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf @@ -31,7 +31,6 @@ MdeModulePkg/MdeModulePkg.dec SecurityPkg/SecurityPkg.dec CryptoPkg/CryptoPkg.dec - OvmfPkg/OvmfPkg.dec [LibraryClasses] MemoryAllocationLib @@ -85,8 +84,8 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTcg2NumberOfPCRBanks ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTcgLogAreaMinLen ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTcg2FinalLogAreaLen ## CONSUMES - gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml ## PRODUCES - gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa ## PRODUCES + gEfiSecurityPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml ## PRODUCES + gEfiSecurityPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa ## PRODUCES gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemId ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemTableId ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemRevision ## CONSUMES From 5e30bcafab4baf3a65af4947633474010134be97 Mon Sep 17 00:00:00 2001 From: Michael Roth Date: Thu, 22 Dec 2022 01:24:05 +0800 Subject: [PATCH 0462/1529] Maintainers.txt: Update reviewers for OVMF/Confidential Computing Add myself as a reviewer for OVMF/Confidential Computing patches. Remove Brijesh while at it, since he is no longer at AMD, and the email is no longer valid. Suggested-by: Tom Lendacky Signed-off-by: Michael Roth Acked-by: Jiewen Yao --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index e785ec1f48..68f603b483 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -484,12 +484,12 @@ F: OvmfPkg/Library/CcExitLib/ F: OvmfPkg/PlatformPei/AmdSev.c F: OvmfPkg/ResetVector/ F: OvmfPkg/Sec/ -R: Brijesh Singh [codomania] R: Erdem Aktas [ruleof2] R: James Bottomley [jejb] R: Jiewen Yao [jyao1] R: Min Xu [mxu9] R: Tom Lendacky [tlendacky] +R: Michael Roth [mdroth] OvmfPkg: FDT related modules F: OvmfPkg/Fdt From f2c2e1ec4d8a68a68980784f0f3d06f82d9483c7 Mon Sep 17 00:00:00 2001 From: KasimX Liu Date: Wed, 28 Dec 2022 15:57:23 +0800 Subject: [PATCH 0463/1529] UefiPayloadPkg: Move RTC PCD to dynamic PCD REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4193 In order to remove RTC_INDEX/RTC_TARGET from the UplBuild macro list,change the RTC_INDEX /RTC_TARGET type from PcdsFixedAtBuild to PcdsDynamicEx Reviewed-by: Guo Dong Cc: Ray Ni Cc: James Lu Reviewed-by: Gua Guo Signed-off-by: KasimX Liu --- UefiPayloadPkg/UefiPayloadPkg.dsc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 12e80a9e74..a1a3c74290 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -472,8 +472,6 @@ !endif [PcdsPatchableInModule.X64] - gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister|$(RTC_INDEX_REGISTER) - gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister|$(RTC_TARGET_REGISTER) !if $(NETWORK_DRIVER_ENABLE) == TRUE gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections|TRUE !endif @@ -580,6 +578,9 @@ gUefiCpuPkgTokenSpaceGuid.PcdSevEsIsEnabled|0 gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister|$(RTC_INDEX_REGISTER) + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister|$(RTC_TARGET_REGISTER) + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform. From 128df24bac984d2256785683331a0e8840e6456e Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Mon, 9 Jan 2023 11:37:21 +0800 Subject: [PATCH 0464/1529] Revert "UefiCpuPkg: Has APs in 64 bit long-mode before booting to OS." This reverts commit 73ccde8f6d04a246377cabaed2875e69d4b6b719 since it results in a hang of the IA32 processor and needs further clean-up. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4234 Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Reviewed-by: Laszlo Ersek Signed-off-by: Yuanhao Xie --- UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 7 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 84 +++++---- .../Library/MpInitLib/Ia32/CreatePageTable.c | 27 --- UefiCpuPkg/Library/MpInitLib/MpLib.h | 19 +- .../Library/MpInitLib/X64/CreatePageTable.c | 75 -------- UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 171 +++++++++++++++--- UefiCpuPkg/UefiCpuPkg.dsc | 1 - 7 files changed, 200 insertions(+), 184 deletions(-) delete mode 100644 UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c delete mode 100644 UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index 8c8b81d933..cd07de3a3c 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -1,7 +1,7 @@ ## @file # MP Initialize Library instance for DXE driver. # -# Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -24,11 +24,9 @@ [Sources.IA32] Ia32/AmdSev.c Ia32/MpFuncs.nasm - Ia32/CreatePageTable.c [Sources.X64] X64/AmdSev.c - X64/CreatePageTable.c X64/MpFuncs.nasm [Sources.common] @@ -59,9 +57,6 @@ CcExitLib MicrocodeLib -[LibraryClasses.X64] - CpuPageTableLib - [Protocols] gEfiTimerArchProtocolGuid ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index beab06a5b1..445e0853d2 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -28,7 +28,6 @@ volatile BOOLEAN mStopCheckAllApsStatus = TRUE; VOID *mReservedApLoopFunc = NULL; UINTN mReservedTopOfApStack; volatile UINT32 mNumberToFinish = 0; -UINTN mApPageTable; // // Begin wakeup buffer allocation below 0x88000 @@ -408,9 +407,12 @@ RelocateApLoop ( AsmRelocateApLoopFunc ( MwaitSupport, CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, (UINTN)&mNumberToFinish, - mApPageTable + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer ); } @@ -475,6 +477,7 @@ InitMpGlobalData ( ) { EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS Address; UINTN ApSafeBufferSize; UINTN Index; EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; @@ -542,45 +545,60 @@ InitMpGlobalData ( // Allocating it in advance since memory services are not available in // Exit Boot Services callback function. // - // +------------+ - // | Ap Loop | - // +------------+ - // | Stack * N | - // +------------+ (low address) - // ApSafeBufferSize = EFI_PAGES_TO_SIZE ( EFI_SIZE_TO_PAGES ( - CpuMpData->CpuCount * AP_SAFE_STACK_SIZE - + CpuMpData->AddressMap.RelocateApLoopFuncSize + CpuMpData->AddressMap.RelocateApLoopFuncSize ) ); + Address = BASE_4GB - 1; + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiReservedMemoryType, + EFI_SIZE_TO_PAGES (ApSafeBufferSize), + &Address + ); + ASSERT_EFI_ERROR (Status); - mReservedTopOfApStack = (UINTN)AllocateReservedPages (EFI_SIZE_TO_PAGES (ApSafeBufferSize)); - ASSERT (mReservedTopOfApStack != 0); - ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); - ASSERT ((AP_SAFE_STACK_SIZE & (CPU_STACK_ALIGNMENT - 1)) == 0); - - mReservedApLoopFunc = (VOID *)(mReservedTopOfApStack + CpuMpData->CpuCount * AP_SAFE_STACK_SIZE); - if (StandardSignatureIsAuthenticAMD ()) { - CopyMem ( - mReservedApLoopFunc, - CpuMpData->AddressMap.RelocateApLoopFuncAddressAmd, - CpuMpData->AddressMap.RelocateApLoopFuncSizeAmd - ); - } else { - CopyMem ( - mReservedApLoopFunc, - CpuMpData->AddressMap.RelocateApLoopFuncAddress, - CpuMpData->AddressMap.RelocateApLoopFuncSize - ); + mReservedApLoopFunc = (VOID *)(UINTN)Address; + ASSERT (mReservedApLoopFunc != NULL); - mApPageTable = CreatePageTable ( - mReservedTopOfApStack, - ApSafeBufferSize - ); + // + // Make sure that the buffer memory is executable if NX protection is enabled + // for EfiReservedMemoryType. + // + // TODO: Check EFI_MEMORY_XP bit set or not once it's available in DXE GCD + // service. + // + Status = gDS->GetMemorySpaceDescriptor (Address, &MemDesc); + if (!EFI_ERROR (Status)) { + gDS->SetMemorySpaceAttributes ( + Address, + ApSafeBufferSize, + MemDesc.Attributes & (~EFI_MEMORY_XP) + ); } - mReservedTopOfApStack += CpuMpData->CpuCount * AP_SAFE_STACK_SIZE; + ApSafeBufferSize = EFI_PAGES_TO_SIZE ( + EFI_SIZE_TO_PAGES ( + CpuMpData->CpuCount * AP_SAFE_STACK_SIZE + ) + ); + Address = BASE_4GB - 1; + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiReservedMemoryType, + EFI_SIZE_TO_PAGES (ApSafeBufferSize), + &Address + ); + ASSERT_EFI_ERROR (Status); + + mReservedTopOfApStack = (UINTN)Address + ApSafeBufferSize; + ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); + CopyMem ( + mReservedApLoopFunc, + CpuMpData->AddressMap.RelocateApLoopFuncAddress, + CpuMpData->AddressMap.RelocateApLoopFuncSize + ); Status = gBS->CreateEvent ( EVT_TIMER | EVT_NOTIFY_SIGNAL, diff --git a/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c deleted file mode 100644 index 525885b77d..0000000000 --- a/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c +++ /dev/null @@ -1,27 +0,0 @@ -/** @file - Function to create page talbe. - Only create page table for x64, and leave the CreatePageTable empty for Ia32. - - Copyright (c) 2022, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -/** - Only create page table for x64, and leave the CreatePageTable empty for Ia32. - - @param[in] LinearAddress The start of the linear address range. - @param[in] Length The length of the linear address range. - - @return The page table to be created. -**/ -UINTN -CreatePageTable ( - IN UINTN Address, - IN UINTN Length - ) -{ - return 0; -} diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 13d515c2df..1102003a93 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -392,9 +392,12 @@ typedef (EFIAPI *ASM_RELOCATE_AP_LOOP)( IN BOOLEAN MwaitSupport, IN UINTN ApTargetCState, + IN UINTN PmCodeSegment, IN UINTN TopOfApStack, IN UINTN NumberToFinish, - IN UINTN Cr3 + IN UINTN Pm16CodeSegment, + IN UINTN SevEsAPJumpTable, + IN UINTN WakeupBuffer ); /** @@ -509,20 +512,6 @@ WakeUpAP ( IN BOOLEAN WakeUpDisabledAps ); -/** - Create 1:1 mapping page table in reserved memory to map the specified address range. - - @param[in] LinearAddress The start of the linear address range. - @param[in] Length The length of the linear address range. - - @return The page table to be created. -**/ -UINTN -CreatePageTable ( - IN UINTN Address, - IN UINTN Length - ); - /** Initialize global data for MP support. diff --git a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c deleted file mode 100644 index 548ef3f2c8..0000000000 --- a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c +++ /dev/null @@ -1,75 +0,0 @@ -/** @file - Function to create page talbe. - Only create page table for x64, and leave the CreatePageTable empty for Ia32. - - Copyright (c) 2022, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ -#include -#include -#include -#include -#include - -/** - Create 1:1 mapping page table in reserved memory to map the specified address range. - - @param[in] LinearAddress The start of the linear address range. - @param[in] Length The length of the linear address range. - - @return The page table to be created. -**/ -UINTN -CreatePageTable ( - IN UINTN Address, - IN UINTN Length - ) -{ - EFI_STATUS Status; - VOID *PageTableBuffer; - UINTN PageTableBufferSize; - UINTN PageTable; - - IA32_MAP_ATTRIBUTE MapAttribute; - IA32_MAP_ATTRIBUTE MapMask; - - MapAttribute.Uint64 = Address; - MapAttribute.Bits.Present = 1; - MapAttribute.Bits.ReadWrite = 1; - - MapMask.Bits.PageTableBaseAddress = 1; - MapMask.Bits.Present = 1; - MapMask.Bits.ReadWrite = 1; - - PageTable = 0; - PageTableBufferSize = 0; - - Status = PageTableMap ( - &PageTable, - Paging4Level, - NULL, - &PageTableBufferSize, - Address, - Length, - &MapAttribute, - &MapMask - ); - ASSERT (Status == EFI_BUFFER_TOO_SMALL); - DEBUG ((DEBUG_INFO, "AP Page Table Buffer Size = %x\n", PageTableBufferSize)); - - PageTableBuffer = AllocateReservedPages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - ASSERT (PageTableBuffer != NULL); - Status = PageTableMap ( - &PageTable, - Paging4Level, - PageTableBuffer, - &PageTableBufferSize, - Address, - Length, - &MapAttribute, - &MapMask - ); - ASSERT_EFI_ERROR (Status); - return PageTable; -} diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 8ae287dd8d..39c3e8606a 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -279,42 +279,120 @@ CProcedureInvoke: RendezvousFunnelProcEnd: ;------------------------------------------------------------------------------------- -; AsmRelocateApLoop (MwaitSupport, ApTargetCState, TopOfApStack, CountTofinish, Cr3); -; This function is called during the finalizaiton of Mp initialization before booting -; to OS, and aim to put Aps either in Mwait or HLT. +; AsmRelocateApLoop (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); ;------------------------------------------------------------------------------------- -; +----------------+ -; | Cr3 | rsp+40 -; +----------------+ -; | CountTofinish | r9 -; +----------------+ -; | TopOfApStack | r8 -; +----------------+ -; | ApTargetCState | rdx -; +----------------+ -; | MwaitSupport | rcx -; +----------------+ -; | the return | -; +----------------+ low address - AsmRelocateApLoopStart: - mov rax, r9 ; CountTofinish +BITS 64 + cmp qword [rsp + 56], 0 ; SevEsAPJumpTable + je NoSevEs + + ; + ; Perform some SEV-ES related setup before leaving 64-bit mode + ; + push rcx + push rdx + + ; + ; Get the RDX reset value using CPUID + ; + mov rax, 1 + cpuid + mov rsi, rax ; Save off the reset value for RDX + + ; + ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call + ; - Must be done while in 64-bit long mode so that writes to + ; the GHCB memory will be unencrypted. + ; - No NAE events can be generated once this is set otherwise + ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. + ; + mov rcx, 0xc0010130 + rdmsr ; Retrieve current GHCB address + shl rdx, 32 + or rdx, rax + + mov rdi, rdx + xor rax, rax + mov rcx, 0x800 + shr rcx, 3 + rep stosq ; Clear the GHCB + + mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD + mov [rdx + 0x390], rax + mov rax, 114 ; Set SwExitCode valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo1 valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo2 valid bit + bts [rdx + 0x3f0], rax + + pop rdx + pop rcx + +NoSevEs: + cli ; Disable interrupt before switching to 32-bit mode + mov rax, [rsp + 40] ; CountTofinish lock dec dword [rax] ; (*CountTofinish)-- - mov rax, [rsp + 40] ; Cr3 - ; Do not push on old stack, since old stack is not mapped - ; in the page table pointed by cr3 - mov cr3, rax - mov rsp, r8 ; TopOfApStack + mov r10, [rsp + 48] ; Pm16CodeSegment + mov rax, [rsp + 56] ; SevEsAPJumpTable + mov rbx, [rsp + 64] ; WakeupBuffer + mov rsp, r9 ; TopOfApStack + + push rax ; Save SevEsAPJumpTable + push rbx ; Save WakeupBuffer + push r10 ; Save Pm16CodeSegment + push rcx ; Save MwaitSupport + push rdx ; Save ApTargetCState + + lea rax, [PmEntry] ; rax <- The start address of transition code + + push r8 + push rax + + ; + ; Clear R8 - R15, for reset, before going into 32-bit mode + ; + xor r8, r8 + xor r9, r9 + xor r10, r10 + xor r11, r11 + xor r12, r12 + xor r13, r13 + xor r14, r14 + xor r15, r15 + + ; + ; Far return into 32-bit mode + ; + retfq + +BITS 32 +PmEntry: + mov eax, cr0 + btr eax, 31 ; Clear CR0.PG + mov cr0, eax ; Disable paging and caches + + mov ecx, 0xc0000080 + rdmsr + and ah, ~ 1 ; Clear LME + wrmsr + mov eax, cr4 + and al, ~ (1 << 5) ; Clear PAE + mov cr4, eax + + pop edx + add esp, 4 + pop ecx, + add esp, 4 MwaitCheck: cmp cl, 1 ; Check mwait-monitor support jnz HltLoop - mov rbx, rdx ; Save C-State to ebx - + mov ebx, edx ; Save C-State to ebx MwaitLoop: cli - mov rax, rsp ; Set Monitor Address + mov eax, esp ; Set Monitor Address xor ecx, ecx ; ecx = 0 xor edx, edx ; edx = 0 monitor @@ -324,10 +402,49 @@ MwaitLoop: jmp MwaitLoop HltLoop: + pop edx ; PM16CodeSegment + add esp, 4 + pop ebx ; WakeupBuffer + add esp, 4 + pop eax ; SevEsAPJumpTable + add esp, 4 + cmp eax, 0 ; Check for SEV-ES + je DoHlt + + cli + ; + ; SEV-ES is enabled, use VMGEXIT (GHCB information already + ; set by caller) + ; +BITS 64 + rep vmmcall +BITS 32 + + ; + ; Back from VMGEXIT AP_HLT_LOOP + ; Push the FLAGS/CS/IP values to use + ; + push word 0x0002 ; EFLAGS + xor ecx, ecx + mov cx, [eax + 2] ; CS + push cx + mov cx, [eax] ; IP + push cx + push word 0x0000 ; For alignment, will be discarded + + push edx + push ebx + + mov edx, esi ; Restore RDX reset value + + retf + +DoHlt: cli hlt - jmp HltLoop + jmp DoHlt +BITS 64 AsmRelocateApLoopEnd: ;------------------------------------------------------------------------------------- diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index 781acedfc5..f9a46089d2 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -94,7 +94,6 @@ MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf RegisterCpuFeaturesLib|UefiCpuPkg/Library/RegisterCpuFeaturesLib/DxeRegisterCpuFeaturesLib.inf CpuCacheInfoLib|UefiCpuPkg/Library/CpuCacheInfoLib/DxeCpuCacheInfoLib.inf From af0a00a800fd8e3e84faff423895aa528e4493c6 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Mon, 9 Jan 2023 11:37:22 +0800 Subject: [PATCH 0465/1529] Revert "UefiPayloadPkg: Add CpuPageTableLib required by MpInitLib." This reverts commit 3f378450dfafc11754bfdb64af28060ec8466acb, since the commit 73ccde8 introduced CpuPageTableLib dependency which resolved for UefiPayloadPkg need to be reverted. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4234 Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Reviewed-by: Gua Guo Reviewed-by: Laszlo Ersek Signed-off-by: Yuanhao Xie --- UefiPayloadPkg/UefiPayloadPkg.dsc | 1 - 1 file changed, 1 deletion(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index a1a3c74290..2dbd875f37 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -340,7 +340,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf !if $(PERFORMANCE_MEASUREMENT_ENABLE) PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf From de8b0b551f55f15f2868d7ec56d2bf13f8526216 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Mon, 9 Jan 2023 11:37:23 +0800 Subject: [PATCH 0466/1529] Revert "OvmfPkg: Add CpuPageTableLib required by MpInitLib." This reverts commit 4a8642422460635462d315defe4ca84bf6d33351 as the commit 73ccde8 introduced CpuPageTableLib dependency which resolved for OvmfPkg is to be reverted. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4234 Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Reviewed-by: Laszlo Ersek Signed-off-by: Yuanhao Xie --- OvmfPkg/AmdSev/AmdSevX64.dsc | 3 +-- OvmfPkg/CloudHv/CloudHvX64.dsc | 1 - OvmfPkg/IntelTdx/IntelTdxX64.dsc | 4 +--- OvmfPkg/Microvm/MicrovmX64.dsc | 3 +-- OvmfPkg/OvmfPkgIa32X64.dsc | 1 - OvmfPkg/OvmfPkgX64.dsc | 2 -- OvmfPkg/OvmfXen.dsc | 3 +-- 7 files changed, 4 insertions(+), 13 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 1cafe0d5b3..36100f5fdc 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -3,7 +3,7 @@ # virtual machine remote attestation and secret injection # # Copyright (c) 2020 James Bottomley, IBM Corporation. -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -353,7 +353,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index dc2509c39e..03b7a5cc6b 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -404,7 +404,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 5bd74639b4..81511e3556 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -313,7 +313,6 @@ CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf @@ -579,7 +578,6 @@ UefiCpuPkg/CpuDxe/CpuDxe.inf { - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf # # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index f92a321fc2..d5bdcbb983 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -403,7 +403,6 @@ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf PciPcdProducerLib|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index f21b78299f..a9d422bd91 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -414,7 +414,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index e24bb442cb..8401d73900 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -434,7 +434,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf @@ -815,7 +814,6 @@ UefiCpuPkg/CpuDxe/CpuDxe.inf { - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf # # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index bfa08c08e3..c328987e84 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) 2019, Citrix Systems, Inc. # Copyright (c) Microsoft Corporation. @@ -339,7 +339,6 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf - CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf From b08dd3a16e7165907fc1984e0a2bf62724b22789 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Mon, 9 Jan 2023 11:37:24 +0800 Subject: [PATCH 0467/1529] Revert "UefiCpuPkg: Duplicated AsmRelocateApLoop as AsmRelocateApLoopAmd" This reverts commit 7bda8c648192d76f7b3f7cee54bd7b1c86a6a84f. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4234 Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Reviewed-by: Laszlo Ersek Signed-off-by: Yuanhao Xie --- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 52 +++--- UefiCpuPkg/Library/MpInitLib/MpEqu.inc | 2 - UefiCpuPkg/Library/MpInitLib/MpLib.h | 27 --- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm | 169 ------------------ UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 5 - 5 files changed, 20 insertions(+), 235 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index 445e0853d2..a84e9e33ba 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -1,7 +1,7 @@ /** @file MP initialize support functions for DXE phase. - Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -378,44 +378,32 @@ RelocateApLoop ( IN OUT VOID *Buffer ) { - CPU_MP_DATA *CpuMpData; - BOOLEAN MwaitSupport; - ASM_RELOCATE_AP_LOOP AsmRelocateApLoopFunc; - ASM_RELOCATE_AP_LOOP_AMD AsmRelocateApLoopFuncAmd; - UINTN ProcessorNumber; - UINTN StackStart; + CPU_MP_DATA *CpuMpData; + BOOLEAN MwaitSupport; + ASM_RELOCATE_AP_LOOP AsmRelocateApLoopFunc; + UINTN ProcessorNumber; + UINTN StackStart; MpInitLibWhoAmI (&ProcessorNumber); CpuMpData = GetCpuMpData (); MwaitSupport = IsMwaitSupport (); - if (StandardSignatureIsAuthenticAMD ()) { - StackStart = CpuMpData->UseSevEsAPMethod ? CpuMpData->SevEsAPResetStackStart : mReservedTopOfApStack; - AsmRelocateApLoopFuncAmd = (ASM_RELOCATE_AP_LOOP_AMD)(UINTN)mReservedApLoopFunc; - AsmRelocateApLoopFuncAmd ( - MwaitSupport, - CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, - StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, - (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer - ); + if (CpuMpData->UseSevEsAPMethod) { + StackStart = CpuMpData->SevEsAPResetStackStart; } else { - StackStart = mReservedTopOfApStack; - AsmRelocateApLoopFunc = (ASM_RELOCATE_AP_LOOP)(UINTN)mReservedApLoopFunc; - AsmRelocateApLoopFunc ( - MwaitSupport, - CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, - StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, - (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer - ); + StackStart = mReservedTopOfApStack; } + AsmRelocateApLoopFunc = (ASM_RELOCATE_AP_LOOP)(UINTN)mReservedApLoopFunc; + AsmRelocateApLoopFunc ( + MwaitSupport, + CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, + StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, + (UINTN)&mNumberToFinish, + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer + ); // // It should never reach here // diff --git a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc index ea202d4aef..ebadcc6fb3 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc +++ b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc @@ -26,8 +26,6 @@ struc MP_ASSEMBLY_ADDRESS_MAP .RendezvousFunnelSize CTYPE_UINTN 1 .RelocateApLoopFuncAddress CTYPE_UINTN 1 .RelocateApLoopFuncSize CTYPE_UINTN 1 - .RelocateApLoopFuncAddressAmd CTYPE_UINTN 1 - .RelocateApLoopFuncSizeAmd CTYPE_UINTN 1 .ModeTransitionOffset CTYPE_UINTN 1 .SwitchToRealNoNxOffset CTYPE_UINTN 1 .SwitchToRealPM16ModeOffset CTYPE_UINTN 1 diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 1102003a93..f5086e497e 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -179,8 +179,6 @@ typedef struct { UINTN RendezvousFunnelSize; UINT8 *RelocateApLoopFuncAddress; UINTN RelocateApLoopFuncSize; - UINT8 *RelocateApLoopFuncAddressAmd; - UINTN RelocateApLoopFuncSizeAmd; UINTN ModeTransitionOffset; UINTN SwitchToRealNoNxOffset; UINTN SwitchToRealPM16ModeOffset; @@ -348,31 +346,6 @@ typedef extern EFI_GUID mCpuInitMpLibHobGuid; -/** - Assembly code to place AP into safe loop mode for Amd. - Place AP into targeted C-State if MONITOR is supported, otherwise - place AP into hlt state. - Place AP in protected mode if the current is long mode. Due to AP maybe - wakeup by some hardware event. It could avoid accessing page table that - may not available during booting to OS. - @param[in] MwaitSupport TRUE indicates MONITOR is supported. - FALSE indicates MONITOR is not supported. - @param[in] ApTargetCState Target C-State value. - @param[in] PmCodeSegment Protected mode code segment value. -**/ -typedef - VOID -(EFIAPI *ASM_RELOCATE_AP_LOOP_AMD)( - IN BOOLEAN MwaitSupport, - IN UINTN ApTargetCState, - IN UINTN PmCodeSegment, - IN UINTN TopOfApStack, - IN UINTN NumberToFinish, - IN UINTN Pm16CodeSegment, - IN UINTN SevEsAPJumpTable, - IN UINTN WakeupBuffer - ); - /** Assembly code to place AP into safe loop mode. diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm index b2d95adf6d..7c2469f9c5 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm @@ -346,172 +346,3 @@ PM16Mode: iret SwitchToRealProcEnd: -;------------------------------------------------------------------------------------- -; AsmRelocateApLoopAmd (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); -;------------------------------------------------------------------------------------- - -AsmRelocateApLoopStartAmd: -BITS 64 - cmp qword [rsp + 56], 0 ; SevEsAPJumpTable - je NoSevEsAmd - - ; - ; Perform some SEV-ES related setup before leaving 64-bit mode - ; - push rcx - push rdx - - ; - ; Get the RDX reset value using CPUID - ; - mov rax, 1 - cpuid - mov rsi, rax ; Save off the reset value for RDX - - ; - ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call - ; - Must be done while in 64-bit long mode so that writes to - ; the GHCB memory will be unencrypted. - ; - No NAE events can be generated once this is set otherwise - ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. - ; - mov rcx, 0xc0010130 - rdmsr ; Retrieve current GHCB address - shl rdx, 32 - or rdx, rax - - mov rdi, rdx - xor rax, rax - mov rcx, 0x800 - shr rcx, 3 - rep stosq ; Clear the GHCB - - mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD - mov [rdx + 0x390], rax - mov rax, 114 ; Set SwExitCode valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo1 valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo2 valid bit - bts [rdx + 0x3f0], rax - - pop rdx - pop rcx - -NoSevEsAmd: - cli ; Disable interrupt before switching to 32-bit mode - mov rax, [rsp + 40] ; CountTofinish - lock dec dword [rax] ; (*CountTofinish)-- - - mov r10, [rsp + 48] ; Pm16CodeSegment - mov rax, [rsp + 56] ; SevEsAPJumpTable - mov rbx, [rsp + 64] ; WakeupBuffer - mov rsp, r9 ; TopOfApStack - - push rax ; Save SevEsAPJumpTable - push rbx ; Save WakeupBuffer - push r10 ; Save Pm16CodeSegment - push rcx ; Save MwaitSupport - push rdx ; Save ApTargetCState - - lea rax, [PmEntryAmd] ; rax <- The start address of transition code - - push r8 - push rax - - ; - ; Clear R8 - R15, for reset, before going into 32-bit mode - ; - xor r8, r8 - xor r9, r9 - xor r10, r10 - xor r11, r11 - xor r12, r12 - xor r13, r13 - xor r14, r14 - xor r15, r15 - - ; - ; Far return into 32-bit mode - ; -o64 retf - -BITS 32 -PmEntryAmd: - mov eax, cr0 - btr eax, 31 ; Clear CR0.PG - mov cr0, eax ; Disable paging and caches - - mov ecx, 0xc0000080 - rdmsr - and ah, ~ 1 ; Clear LME - wrmsr - mov eax, cr4 - and al, ~ (1 << 5) ; Clear PAE - mov cr4, eax - - pop edx - add esp, 4 - pop ecx, - add esp, 4 - -MwaitCheckAmd: - cmp cl, 1 ; Check mwait-monitor support - jnz HltLoopAmd - mov ebx, edx ; Save C-State to ebx -MwaitLoopAmd: - cli - mov eax, esp ; Set Monitor Address - xor ecx, ecx ; ecx = 0 - xor edx, edx ; edx = 0 - monitor - mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] - shl eax, 4 - mwait - jmp MwaitLoopAmd - -HltLoopAmd: - pop edx ; PM16CodeSegment - add esp, 4 - pop ebx ; WakeupBuffer - add esp, 4 - pop eax ; SevEsAPJumpTable - add esp, 4 - cmp eax, 0 ; Check for SEV-ES - je DoHltAmd - - cli - ; - ; SEV-ES is enabled, use VMGEXIT (GHCB information already - ; set by caller) - ; -BITS 64 - rep vmmcall -BITS 32 - - ; - ; Back from VMGEXIT AP_HLT_LOOP - ; Push the FLAGS/CS/IP values to use - ; - push word 0x0002 ; EFLAGS - xor ecx, ecx - mov cx, [eax + 2] ; CS - push cx - mov cx, [eax] ; IP - push cx - push word 0x0000 ; For alignment, will be discarded - - push edx - push ebx - - mov edx, esi ; Restore RDX reset value - - retf - -DoHltAmd: - cli - hlt - jmp DoHltAmd - -BITS 64 -AsmRelocateApLoopEndAmd: diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 39c3e8606a..5d71995bf8 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -460,11 +460,6 @@ ASM_PFX(AsmGetAddressMap): mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddress], rax mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSize], AsmRelocateApLoopEnd - AsmRelocateApLoopStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.ModeTransitionOffset], Flat32Start - RendezvousFunnelProcStart - - lea rax, [AsmRelocateApLoopStartAmd] - mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressAmd], rax - mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeAmd], AsmRelocateApLoopEndAmd - AsmRelocateApLoopStartAmd - mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealNoNxOffset], SwitchToRealProcStart - Flat32Start mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeOffset], PM16Mode - RendezvousFunnelProcStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeSize], SwitchToRealProcEnd - PM16Mode From 48ed341ac0d4abe745e24ba816ff6b62d7872d4f Mon Sep 17 00:00:00 2001 From: Ning Feng Date: Mon, 9 Jan 2023 07:28:09 -0500 Subject: [PATCH 0468/1529] UefiPayloadPkg: Fix debug print error level hob not save correct REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4264 Fix debug print error level hob not save correct DebugPrintErrorlevel Should cover the case: Header.Length == UNIVERSAL_PAYLOAD_SIZEOF_THROUGH_FIELD () Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Ning Feng Reviewed-by: Gua Guo --- .../DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiPayloadPkg/Library/DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.c b/UefiPayloadPkg/Library/DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.c index 4f6b4ef1fb..10bdbe2bbc 100644 --- a/UefiPayloadPkg/Library/DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.c +++ b/UefiPayloadPkg/Library/DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.c @@ -46,7 +46,7 @@ GetDebugPrintErrorLevel ( { if (GenericHeader->Revision == UEFI_PAYLOAD_DEBUG_PRINT_ERROR_LEVEL_REVISION) { DebugPrintErrorLevel = (UEFI_PAYLOAD_DEBUG_PRINT_ERROR_LEVEL *)GET_GUID_HOB_DATA (GuidHob); - if (DebugPrintErrorLevel->Header.Length > UNIVERSAL_PAYLOAD_SIZEOF_THROUGH_FIELD (UEFI_PAYLOAD_DEBUG_PRINT_ERROR_LEVEL, ErrorLevel)) { + if (DebugPrintErrorLevel->Header.Length >= UNIVERSAL_PAYLOAD_SIZEOF_THROUGH_FIELD (UEFI_PAYLOAD_DEBUG_PRINT_ERROR_LEVEL, ErrorLevel)) { gDebugPrintErrorLevel = DebugPrintErrorLevel->ErrorLevel; } } From feec35d07c2cb9b236f2db9dfa72be3c5c55d3f7 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Fri, 30 Dec 2022 16:17:58 +0800 Subject: [PATCH 0469/1529] BaseTools: Reduce the LoongArch64 compiler size The LoongArch64 cross compiler size is too large after decompression, using the new compiler, there is no system library and glibc. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4233 Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Reviewed-by: Liming Gao Reviewed-by: Rebecca Cran Signed-off-by: Chao Li --- BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml index fe9a244853..6ebc93a07c 100644 --- a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml +++ b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml @@ -12,9 +12,9 @@ "scope": "gcc_loongarch64_unknown_linux", "type": "web", "name": "gcc_loongarch64_unknown_linux", - "source":"https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-gcc-full.tar.xz", + "source":"https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-c-only.tar.xz", "version": "13.0.0", - "sha256":"27a43c5bb127794f091d0e75da0003c4d0eec28a958d8f2cc7cd290a6e6133ab", + "sha256":"744cbb50c6ef07c96551bddf07a8b85cee3250bb18b6040f6ed051e389514951", "compression_type": "tar", "internal_path": "/cross-tools/", "flags": ["set_shell_var", ], From f23ecfdaabffac0980d5b419140a8921284a7126 Mon Sep 17 00:00:00 2001 From: Moritz Fischer Date: Mon, 9 Jan 2023 08:42:18 -0800 Subject: [PATCH 0470/1529] DynamicTablesPkg: FdtHwInfoParserLib: Fix compatible string Linux's cpu DT bindings call out arm,armv8 while the code previously used arm,arm-v8, add second entry to support the arm,armv8 case. Cc: Sami Mujawar Fixes: e366a41ef0 ("DynamicTablesPkg: FdtHwInfoParser: Add GICC parser") Signed-off-by: Moritz Fischer Reviewed-by: Sami Mujawar --- DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c | 1 + 1 file changed, 1 insertion(+) diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c index 2c72bd0c58..ee82f7a0b4 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Gic/ArmGicCParser.c @@ -23,6 +23,7 @@ STATIC CONST COMPATIBILITY_STR CpuCompatibleStr[] = { { "arm,arm-v7" }, { "arm,arm-v8" }, + { "arm,armv8" }, { "arm,cortex-a15" }, { "arm,cortex-a7" }, { "arm,cortex-a57" } From 533865d7acdb75bd110768216daeb70176376f51 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 5 Jan 2023 14:43:14 +0100 Subject: [PATCH 0471/1529] ArmVirtPkg/ArmPlatformLibQemu: Ensure that VFP is on before running C code Now that we build the early code without strict alignment and without suppressing the use of SIMD registers, ensure that the VFP unit is on before entering C code. While at it, simplyify the mov_i macro, which is only used for 32-bit quantities. Signed-off-by: Ard Biesheuvel Tested-by: dann frazier --- .../ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S index 05ccc7f9f0..1787d52fbf 100644 --- a/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S @@ -8,9 +8,7 @@ #include .macro mov_i, reg:req, imm:req - movz \reg, :abs_g3:\imm - movk \reg, :abs_g2_nc:\imm - movk \reg, :abs_g1_nc:\imm + movz \reg, :abs_g1:\imm movk \reg, :abs_g0_nc:\imm .endm @@ -45,10 +43,9 @@ ASM_FUNC(ArmPlatformPeiBootAction) mrs x0, CurrentEL // check current exception level - tbz x0, #3, 0f // bail if above EL1 - ret + tbnz x0, #3, 0f // omit early ID map if above EL1 -0:mov_i x0, mairval + mov_i x0, mairval mov_i x1, tcrval adrp x2, idmap orr x2, x2, #0xff << 48 // set non-zero ASID @@ -87,7 +84,8 @@ ASM_FUNC(ArmPlatformPeiBootAction) msr sctlr_el1, x3 // enable MMU and caches isb - ret + +0:b ArmEnableVFP // enable SIMD before entering C code //UINTN //ArmPlatformGetCorePosition ( From 8f4374ec46e8e60335544fd085f8a02418d61819 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 4 Jan 2023 16:51:35 +0100 Subject: [PATCH 0472/1529] ArmVirtPkg/ArmVirtQemu: Avoid early ID map on ThunderX The early ID map used by ArmVirtQemu uses ASID scoped non-global mappings, as this allows us to switch to the permanent ID map seamlessly without the need for explicit TLB maintenance. However, this triggers a known erratum on ThunderX, which does not tolerate non-global mappings that are executable at EL1, as this appears to result in I-cache corruption. (Linux disables the KPTI based Meltdown mitigation on ThunderX for the same reason) So work around this, by detecting the CPU implementor and part number, and proceeding without the early ID map if a ThunderX CPU is detected. Note that this requires the C code to be built with strict alignment again, as we may end up executing it with the MMU and caches off. Signed-off-by: Ard Biesheuvel Acked-by: Laszlo Ersek Tested-by: dann frazier --- ArmVirtPkg/ArmVirtQemu.dsc | 5 +++++ .../AArch64/ArmPlatformHelper.S | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index f77443229e..5dd8b6104c 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -31,6 +31,7 @@ DEFINE SECURE_BOOT_ENABLE = FALSE DEFINE TPM2_ENABLE = FALSE DEFINE TPM2_CONFIG_ENABLE = FALSE + DEFINE CAVIUM_ERRATUM_27456 = FALSE # # Network definition @@ -117,7 +118,11 @@ UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf [BuildOptions] +!if $(CAVIUM_ERRATUM_27456) == TRUE + GCC:*_*_AARCH64_PP_FLAGS = -DCAVIUM_ERRATUM_27456 +!else GCC:*_*_AARCH64_CC_XIPFLAGS == +!endif !include NetworkPkg/NetworkBuildOptions.dsc.inc diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S index 1787d52fbf..5ac7c732f6 100644 --- a/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/AArch64/ArmPlatformHelper.S @@ -42,6 +42,21 @@ ASM_FUNC(ArmPlatformPeiBootAction) +#ifdef CAVIUM_ERRATUM_27456 + /* + * On Cavium ThunderX, using non-global mappings that are executable at EL1 + * results in I-cache corruption. So just avoid the early ID mapping there. + * + * MIDR implementor 0x43 + * MIDR part numbers 0xA1 0xA2 (but not 0xAF) + */ + mrs x0, midr_el1 // read the MIDR into X0 + ubfx x1, x0, #24, #8 // grab implementor id + ubfx x0, x0, #7, #9 // grab part number bits [11:3] + cmp x1, #0x43 // compare implementor id + ccmp x0, #0xA0 >> 3, #0, eq // compare part# bits [11:3] + b.eq 0f +#endif mrs x0, CurrentEL // check current exception level tbnz x0, #3, 0f // omit early ID map if above EL1 From 0839ea7de83fa809e2b45b02f2b5d1c58fff90ee Mon Sep 17 00:00:00 2001 From: Zachary Clark-Williams Date: Wed, 10 Aug 2022 15:32:11 -0700 Subject: [PATCH 0473/1529] NetworkPkg: Add WiFi profile sync protocol support REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3845 Enables KVM and One Click Recovery WLAN capability with WiFi Profile Sync feature and protocol. Adding WiFiProfileSyncProtocol, which supports the profilesync driver operations for transferring WiFi profiles from AMT to the Supplicant. WiFiConnectionManager will check for the WifiProfileSyncProtocol and if found will operate on the premise of a One Click Recovery, or KVM flow with a Wifi profile provided by AMT. Cc: Maciej Rabeda Cc: Wu Jiaxin Cc: Andrei Otcheretianski Signed-off-by: Zachary Clark-Williams Acked-by: Michael D Kinney Reviewed-by: Jiaxin Wu --- .../Protocol/WiFiProfileSyncProtocol.h | 93 ++++++++ NetworkPkg/NetworkPkg.dec | 3 + .../WifiConnectionManagerDxe.inf | 3 +- .../WifiConnectionMgrConfigNVDataStruct.h | 2 +- .../WifiConnectionMgrDriver.c | 126 ++++++---- .../WifiConnectionMgrDxe.h | 4 +- .../WifiConnectionMgrImpl.c | 219 +++++++++++++++--- .../WifiConnectionMgrMisc.c | 13 ++ 8 files changed, 390 insertions(+), 73 deletions(-) create mode 100644 NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h diff --git a/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h new file mode 100644 index 0000000000..c6d1fda2b5 --- /dev/null +++ b/NetworkPkg/Include/Protocol/WiFiProfileSyncProtocol.h @@ -0,0 +1,93 @@ +/** @file + WiFi profile sync protocol. Supports One Click Recovery or KVM OS recovery + boot flow over WiFi. This protocol will hold the WiFi profile provided by AMT + in its original structure, then convert the profile when the WifiConnectionManager + is attempting a connection during a system recovery reboot, OCR or KVM. These + converstion and operations are found in the WifiProfileSync driver and in + the link provided below. + + This protocol facilitates the reporting and storing of the connection state + incase of failure, to which a connection attempt will rety a maximum of 3 times. + + Pulbic links to speficiation document for KVM and One Click Recovery feature. + https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=WordDocuments%2Foneclickrecovery.htm + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef WIFI_PROFILE_SYNC_PROTOCOL_H_ +#define WIFI_PROFILE_SYNC_PROTOCOL_H_ + +#include + +// +// WiFi Profile Sync Protocol GUID variable. +// +extern EFI_GUID gEdkiiWiFiProfileSyncProtocolGuid; + +/** + Used by the WiFi connection manager to get the WiFi profile that AMT shared + and was stored in WiFi profile protocol. Aligns the AMT WiFi profile data to + the WiFi connection manager profile structure fo connection use. + + @param[in, out] WcmProfile WiFi Connection Manager profile structure + @param[in, out] MacAddress MAC address from AMT saved to NiC MAC address + + @retval EFI_SUCCESS Stored WiFi profile converted and returned succefully + @retval EFI_UNSUPPORTED Profile protocol sharing not supported or enabled + @retval EFI_NOT_FOUND No profiles to returned + @retval Others Error Occurred +**/ +typedef +EFI_STATUS +(EFIAPI *WIFI_PROFILE_GET)( + IN OUT WIFI_MGR_NETWORK_PROFILE *Profile, + IN OUT EFI_80211_MAC_ADDRESS MacAddress + ); + +/** + Saves the WiFi connection status recieved by the WiFiConnectionManager when + in a KVM OR One Click Recovery WLAN recovery flow. Input as + EFI_80211_CONNECT_NETWORK_RESULT_CODE then converted and stored as EFI_STATUS type. + + @param[in] ConnectionStatus WiFi connection attempt results +**/ +typedef +VOID +(EFIAPI *WIFI_SET_CONNECT_STATE)( + IN EFI_80211_CONNECT_NETWORK_RESULT_CODE ConnectionStatus + ); + +/** + Retrieves the stored WiFi connection status when in either KVM OR One Click + Recovery WLAN recovery flow. + + @retval EFI_SUCCESS WiFi connection completed succesfully + @retval Others Connection failure occurred +**/ +typedef +EFI_STATUS +(EFIAPI *WIFI_GET_CONNECT_STATE)( + VOID + ); + +// +// WiFi Profile Sync Protocol structure. +// +typedef struct { + UINT32 Revision; + WIFI_SET_CONNECT_STATE SetConnectState; + WIFI_GET_CONNECT_STATE GetConnectState; + WIFI_PROFILE_GET GetProfile; +} EDKII_WIFI_PROFILE_SYNC_PROTOCOL; + +/** + WiFi Profile Protocol revision number. + + Revision 1: Initial version +**/ +#define EDKII_WIFI_PROFILE_SYNC_PROTOCOL_REVISION 1 + +#endif // WIFI_PROFILE_SYNC_PROTOCOL_H_ diff --git a/NetworkPkg/NetworkPkg.dec b/NetworkPkg/NetworkPkg.dec index 5e43ebf8c5..e06f35e774 100644 --- a/NetworkPkg/NetworkPkg.dec +++ b/NetworkPkg/NetworkPkg.dec @@ -91,6 +91,9 @@ ## Include/Protocol/HttpCallback.h gEdkiiHttpCallbackProtocolGuid = {0x611114f1, 0xa37b, 0x4468, {0xa4, 0x36, 0x5b, 0xdd, 0xa1, 0x6a, 0xa2, 0x40}} + ## Include/Protocol/WiFiProfileSyncProtocol.h + gEdkiiWiFiProfileSyncProtocolGuid = {0x399a2b8a, 0xc267, 0x44aa, {0x9a, 0xb4, 0x30, 0x58, 0x8c, 0xd2, 0x2d, 0xcc}} + [PcdsFixedAtBuild] ## The max attempt number will be created by iSCSI driver. # @Prompt Max attempt number. diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf index 4394b6f4bb..47901d75ab 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionManagerDxe.inf @@ -9,7 +9,7 @@ # 2). WPA2 Personal Network # 3). EAP Networks (EAP-TLS, EAP-TTLS/MSCHAPv2 and PEAPv0/MSCHAPv2) # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2022, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -71,6 +71,7 @@ gEfiAdapterInformationProtocolGuid ## SOMETIMES_CONSUMES gEfiSupplicantProtocolGuid ## SOMETIMES_CONSUMES gEfiEapConfigurationProtocolGuid ## SOMETIMES_CONSUMES + gEdkiiWiFiProfileSyncProtocolGuid ## SOMETIMES_CONSUMES [Guids] gWifiConfigGuid ## PRODUCES ## GUID diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h index b5518a74d8..dcc4bf7e27 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrConfigNVDataStruct.h @@ -25,7 +25,7 @@ #define PASSWORD_MIN_LEN 8 #define PASSWORD_MAX_LEN 63 -#define PASSWORD_STORAGE_SIZE 64 +#define PASSWORD_STORAGE_SIZE 65 #define EAP_IDENTITY_LEN 63 #define EAP_IDENTITY_SIZE 64 diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c index 67a01ca058..36c467025f 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDriver.c @@ -1,7 +1,7 @@ /** @file The driver binding protocol for the WiFi Connection Manager. - Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2022, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -39,6 +39,11 @@ EFI_GUID mWifiConfigNetworkListRefreshGuid = WIFI_CONFIG_NETWORK_LIST_REFRESH_G EFI_GUID mWifiConfigConnectFormRefreshGuid = WIFI_CONFIG_CONNECT_FORM_REFRESH_GUID; EFI_GUID mWifiConfigMainFormRefreshGuid = WIFI_CONFIG_MAIN_FORM_REFRESH_GUID; +// +// Wifi connection attempt counter for retries +// +extern UINT8 mWifiConnectionCount; + /** Tests to see if this driver supports a given controller. If a child device is provided, it further tests to see if this driver supports creating a handle for the specified child device. @@ -167,8 +172,10 @@ WifiMgrDxeDriverBindingStart ( EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp; EFI_SUPPLICANT_PROTOCOL *Supplicant; EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig; + EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol; - Nic = NULL; + mWifiConnectionCount = 0; + Nic = NULL; // // Open Protocols @@ -236,47 +243,73 @@ WifiMgrDxeDriverBindingStart ( InitializeListHead (&Nic->ProfileList); // - // Record the MAC address of the incoming NIC. + // WiFi profile sync protocol installation check for OS recovery flow. // - Status = NetLibGetMacAddress ( - ControllerHandle, - (EFI_MAC_ADDRESS *)&Nic->MacAddress, - &AddressSize - ); - if (EFI_ERROR (Status)) { - goto ERROR2; - } - - // - // Create and start the timer for the status check - // - Status = gBS->CreateEvent ( - EVT_NOTIFY_SIGNAL | EVT_TIMER, - TPL_CALLBACK, - WifiMgrOnTimerTick, - Nic, - &Nic->TickTimer + Status = gBS->LocateProtocol ( + &gEdkiiWiFiProfileSyncProtocolGuid, + NULL, + (VOID **)&WiFiProfileSyncProtocol ); - if (EFI_ERROR (Status)) { - goto ERROR2; - } + if (!EFI_ERROR (Status)) { + Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE)); + if (Nic->ConnectPendingNetwork == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto ERROR1; + } - Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500)); - if (EFI_ERROR (Status)) { - goto ERROR3; - } + WiFiProfileSyncProtocol->GetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress); + if (Nic->ConnectPendingNetwork != NULL) { + Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork); + if (!EFI_ERROR (Status)) { + goto ERROR1; + } + + WiFiProfileSyncProtocol->SetConnectState (Status); + } + } else { + // + // Record the MAC address of the incoming NIC. + // + Status = NetLibGetMacAddress ( + ControllerHandle, + (EFI_MAC_ADDRESS *)&Nic->MacAddress, + &AddressSize + ); + if (EFI_ERROR (Status)) { + goto ERROR2; + } - Nic->ConnectState = WifiMgrDisconnected; - Nic->ScanState = WifiMgrScanFinished; + // + // Create and start the timer for the status check + // + Status = gBS->CreateEvent ( + EVT_NOTIFY_SIGNAL | EVT_TIMER, + TPL_CALLBACK, + WifiMgrOnTimerTick, + Nic, + &Nic->TickTimer + ); + if (EFI_ERROR (Status)) { + goto ERROR2; + } - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - InsertTailList (&mPrivate->NicList, &Nic->Link); - Nic->NicIndex = mPrivate->NicCount++; - if (mPrivate->CurrentNic == NULL) { - mPrivate->CurrentNic = Nic; - } + Status = gBS->SetTimer (Nic->TickTimer, TimerPeriodic, EFI_TIMER_PERIOD_MILLISECONDS (500)); + if (EFI_ERROR (Status)) { + goto ERROR3; + } - gBS->RestoreTPL (OldTpl); + Nic->ConnectState = WifiMgrDisconnected; + Nic->ScanState = WifiMgrScanFinished; + + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + InsertTailList (&mPrivate->NicList, &Nic->Link); + Nic->NicIndex = mPrivate->NicCount++; + if (mPrivate->CurrentNic == NULL) { + mPrivate->CurrentNic = Nic; + } + + gBS->RestoreTPL (OldTpl); + } Status = gBS->InstallProtocolInterface ( &ControllerHandle, @@ -385,10 +418,11 @@ WifiMgrDxeDriverBindingStop ( IN EFI_HANDLE *ChildHandleBuffer OPTIONAL ) { - EFI_STATUS Status; - EFI_TPL OldTpl; - WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier; - WIFI_MGR_DEVICE_DATA *Nic; + EFI_STATUS Status; + EFI_TPL OldTpl; + WIFI_MGR_PRIVATE_PROTOCOL *WifiMgrIdentifier; + WIFI_MGR_DEVICE_DATA *Nic; + EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol; Status = gBS->OpenProtocol ( ControllerHandle, @@ -481,7 +515,15 @@ WifiMgrDxeDriverBindingStop ( // OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - RemoveEntryList (&Nic->Link); + Status = gBS->LocateProtocol ( + &gEdkiiWiFiProfileSyncProtocolGuid, + NULL, + (VOID **)&WiFiProfileSyncProtocol + ); + if (EFI_ERROR (Status)) { + RemoveEntryList (&Nic->Link); + } + mPrivate->NicCount--; if (mPrivate->CurrentNic == Nic) { mPrivate->CurrentNic = NULL; diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h index 7b2e41e155..047f85dbc2 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrDxe.h @@ -47,6 +47,7 @@ #include #include #include +#include // // Produced Protocols @@ -73,7 +74,8 @@ // #define WIFI_MGR_DXE_VERSION 0xb -#define OUI_IEEE_80211I 0xAC0F00 +#define OUI_IEEE_80211I 0xAC0F00 +#define MAX_WIFI_CONNETION_ATTEMPTS 3 typedef enum { Ieee80211PairwiseCipherSuiteUseGroupCipherSuite = 0, diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c index 59bac48c42..2e596c1981 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrImpl.c @@ -19,6 +19,8 @@ EFI_EAP_TYPE mEapSecondAuthMethod[] = { EFI_EAP_TYPE_MSCHAPV2 }; +UINT8 mWifiConnectionCount = 0; + /** The callback function for scan operation. This function updates networks according to the latest scan result, and trigger UI refresh. @@ -424,18 +426,26 @@ WifiMgrConfigPassword ( return EFI_NOT_FOUND; } - AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) * sizeof (UINT8)); + if (StrLen (Profile->Password) >= PASSWORD_STORAGE_SIZE) { + ASSERT (EFI_INVALID_PARAMETER); + return EFI_INVALID_PARAMETER; + } + + AsciiPassword = AllocateZeroPool ((StrLen (Profile->Password) + 1) * sizeof (CHAR8)); if (AsciiPassword == NULL) { return EFI_OUT_OF_RESOURCES; } - UnicodeStrToAsciiStrS (Profile->Password, (CHAR8 *)AsciiPassword, PASSWORD_STORAGE_SIZE); - Status = Supplicant->SetData ( - Supplicant, - EfiSupplicant80211PskPassword, - AsciiPassword, - (StrLen (Profile->Password) + 1) * sizeof (UINT8) - ); + Status = UnicodeStrToAsciiStrS (Profile->Password, (CHAR8 *)AsciiPassword, (StrLen (Profile->Password) + 1)); + if (!EFI_ERROR (Status)) { + Status = Supplicant->SetData ( + Supplicant, + EfiSupplicant80211PskPassword, + AsciiPassword, + (StrLen (Profile->Password) + 1) * sizeof (CHAR8) + ); + } + ZeroMem (AsciiPassword, AsciiStrLen ((CHAR8 *)AsciiPassword) + 1); FreePool (AsciiPassword); @@ -465,19 +475,20 @@ WifiMgrConfigEap ( IN WIFI_MGR_NETWORK_PROFILE *Profile ) { - EFI_STATUS Status; - EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig; - EFI_EAP_TYPE EapAuthMethod; - EFI_EAP_TYPE EapSecondAuthMethod; - EFI_EAP_TYPE *AuthMethodList; - CHAR8 *Identity; - UINTN IdentitySize; - CHAR16 *Password; - UINTN PasswordSize; - UINTN EncryptPasswordLen; - CHAR8 *AsciiEncryptPassword; - UINTN AuthMethodListSize; - UINTN Index; + EFI_STATUS Status; + EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol; + EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig; + EFI_EAP_TYPE EapAuthMethod; + EFI_EAP_TYPE EapSecondAuthMethod; + EFI_EAP_TYPE *AuthMethodList; + CHAR8 *Identity; + UINTN IdentitySize; + CHAR16 *Password; + UINTN PasswordSize; + UINTN EncryptPasswordLen; + CHAR8 *AsciiEncryptPassword; + UINTN AuthMethodListSize; + UINTN Index; if ((Nic == NULL) || (Nic->EapConfig == NULL) || (Profile == NULL)) { return EFI_INVALID_PARAMETER; @@ -567,7 +578,13 @@ WifiMgrConfigEap ( return EFI_OUT_OF_RESOURCES; } - UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize); + Status = gBS->LocateProtocol (&gEdkiiWiFiProfileSyncProtocolGuid, NULL, (VOID **)&WiFiProfileSyncProtocol); + if (!EFI_ERROR (Status)) { + CopyMem (Identity, &Profile->EapIdentity, IdentitySize); + } else { + UnicodeStrToAsciiStrS (Profile->EapIdentity, Identity, IdentitySize); + } + Status = EapConfig->SetData ( EapConfig, EFI_EAP_TYPE_IDENTITY, @@ -892,6 +909,133 @@ WifiMgrPrepareConnection ( return EFI_SUCCESS; } +/** + Will reset NiC data, get profile from profile sync driver, and send for + another connection attempt.This function should not be called more than + 3 times. + + @param[in] WiFiProfileSyncProtocol The target network profile to connect. + + @retval EFI_SUCCESS The operation is completed. + @retval other Operation failure. + +**/ +EFI_STATUS +ConnectionRetry ( + IN EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol + ) +{ + EFI_STATUS Status; + WIFI_MGR_DEVICE_DATA *Nic; + EFI_WIRELESS_MAC_CONNECTION_II_PROTOCOL *Wmp; + EFI_SUPPLICANT_PROTOCOL *Supplicant; + EFI_EAP_CONFIGURATION_PROTOCOL *EapConfig; + + Nic = NULL; + + Status = gBS->LocateProtocol ( + &gEfiWiFi2ProtocolGuid, + NULL, + (VOID **)&Wmp + ); + if (EFI_ERROR (Status)) { + return Status; + } + + Status = gBS->LocateProtocol ( + &gEfiSupplicantProtocolGuid, + NULL, + (VOID **)&Supplicant + ); + if (EFI_ERROR (Status)) { + Supplicant = NULL; + } + + Status = gBS->LocateProtocol ( + &gEfiEapConfigurationProtocolGuid, + NULL, + (VOID **)&EapConfig + ); + if (EFI_ERROR (Status)) { + EapConfig = NULL; + } + + // + // Initialize Nic device data + // + Nic = AllocateZeroPool (sizeof (WIFI_MGR_DEVICE_DATA)); + if (Nic == NULL) { + Status = EFI_OUT_OF_RESOURCES; + return Status; + } + + Nic->Signature = WIFI_MGR_DEVICE_DATA_SIGNATURE; + Nic->Private = mPrivate; + Nic->Wmp = Wmp; + Nic->Supplicant = Supplicant; + Nic->EapConfig = EapConfig; + Nic->UserSelectedProfile = NULL; + Nic->OneTimeScanRequest = FALSE; + + if (Nic->Supplicant != NULL) { + Status = WifiMgrGetSupportedSuites (Nic); + } + + if (!EFI_ERROR (Status)) { + InitializeListHead (&Nic->ProfileList); + + Nic->ConnectPendingNetwork = (WIFI_MGR_NETWORK_PROFILE *)AllocateZeroPool (sizeof (WIFI_MGR_NETWORK_PROFILE)); + if (Nic->ConnectPendingNetwork == NULL) { + Status = EFI_OUT_OF_RESOURCES; + DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to allocate memory for ConnectPendingNetwork\n")); + goto ERROR; + } + + Status = WiFiProfileSyncProtocol->GetProfile (Nic->ConnectPendingNetwork, Nic->MacAddress); + if (!EFI_ERROR (Status) && (Nic->ConnectPendingNetwork != NULL)) { + Status = WifiMgrConnectToNetwork (Nic, Nic->ConnectPendingNetwork); + if (!EFI_ERROR (Status)) { + return Status; + } + } else { + DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get WiFi profile with status %r\n", Status)); + } + } else { + DEBUG ((DEBUG_ERROR, "[WiFi Connection Manager] Failed to get Supported suites with status %r\n", Status)); + } + + if (Nic->ConnectPendingNetwork != NULL) { + if (Nic->ConnectPendingNetwork->Network.AKMSuite != NULL) { + FreePool (Nic->ConnectPendingNetwork->Network.AKMSuite); + } + + if (Nic->ConnectPendingNetwork->Network.CipherSuite != NULL) { + FreePool (Nic->ConnectPendingNetwork->Network.CipherSuite); + } + + FreePool (Nic->ConnectPendingNetwork); + } + +ERROR: + if (Nic->Supplicant != NULL) { + if (Nic->SupportedSuites.SupportedAKMSuites != NULL) { + FreePool (Nic->SupportedSuites.SupportedAKMSuites); + } + + if (Nic->SupportedSuites.SupportedSwCipherSuites != NULL) { + FreePool (Nic->SupportedSuites.SupportedSwCipherSuites); + } + + if (Nic->SupportedSuites.SupportedHwCipherSuites != NULL) { + FreePool (Nic->SupportedSuites.SupportedHwCipherSuites); + } + } + + FreePool (Nic); + + return Status; +} + /** The callback function for connect operation. @@ -908,12 +1052,13 @@ WifiMgrOnConnectFinished ( IN VOID *Context ) { - EFI_STATUS Status; - WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken; - WIFI_MGR_NETWORK_PROFILE *ConnectedProfile; - UINT8 SecurityType; - UINT8 SSIdLen; - CHAR8 *AsciiSSId; + EFI_STATUS Status; + WIFI_MGR_MAC_CONFIG_TOKEN *ConfigToken; + WIFI_MGR_NETWORK_PROFILE *ConnectedProfile; + UINT8 SecurityType; + UINT8 SSIdLen; + CHAR8 *AsciiSSId; + EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol; ASSERT (Context != NULL); @@ -925,6 +1070,24 @@ WifiMgrOnConnectFinished ( ASSERT (ConfigToken->Type == TokenTypeConnectNetworkToken); ASSERT (ConfigToken->Token.ConnectNetworkToken != NULL); + + Status = gBS->LocateProtocol (&gEdkiiWiFiProfileSyncProtocolGuid, NULL, (VOID **)&WiFiProfileSyncProtocol); + if (!EFI_ERROR (Status)) { + WiFiProfileSyncProtocol->SetConnectState (ConfigToken->Token.ConnectNetworkToken->ResultCode); + if ((mWifiConnectionCount < MAX_WIFI_CONNETION_ATTEMPTS) && + (ConfigToken->Token.ConnectNetworkToken->ResultCode != ConnectSuccess)) + { + mWifiConnectionCount++; + gBS->CloseEvent (Event); + Status = ConnectionRetry (WiFiProfileSyncProtocol); + if (!EFI_ERROR (Status)) { + return; + } + + WiFiProfileSyncProtocol->SetConnectState (Status); + } + } + if (ConfigToken->Token.ConnectNetworkToken->Status != EFI_SUCCESS) { if (ConfigToken->Nic->OneTimeConnectRequest) { // diff --git a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c index 4ad5643c24..154f2968c7 100644 --- a/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c +++ b/NetworkPkg/WifiConnectionManagerDxe/WifiConnectionMgrMisc.c @@ -672,10 +672,23 @@ WifiMgrCleanProfileSecrets ( IN WIFI_MGR_NETWORK_PROFILE *Profile ) { + EFI_STATUS Status; + EDKII_WIFI_PROFILE_SYNC_PROTOCOL *WiFiProfileSyncProtocol; + ZeroMem (Profile->Password, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE); ZeroMem (Profile->EapPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE); ZeroMem (Profile->PrivateKeyPassword, sizeof (CHAR16) * PASSWORD_STORAGE_SIZE); + // + // When EFI WiFi profile sync protocol is found the system is performing a recovery boot in secure + // boot mode. The profile sync driver will manage the CA certificate, client certificate, and key + // data, cleaning them at exit boot services. + // + Status = gBS->LocateProtocol (&gEdkiiWiFiProfileSyncProtocolGuid, NULL, (VOID **)&WiFiProfileSyncProtocol); + if (!EFI_ERROR (Status)) { + return; + } + if (Profile->CACertData != NULL) { ZeroMem (Profile->CACertData, Profile->CACertSize); FreePool (Profile->CACertData); From eb206d8e4af486cd329b48a81ea4d17b1ba85788 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 12 Jan 2023 08:45:29 +0100 Subject: [PATCH 0474/1529] OvmfPkg/PlatformInitLib: fix comment about uncacheable MTRRs In commit 49edde15230a ("OvmfPkg/PlatformPei: set 32-bit UC area at PciBase / PciExBarBase (pc/q35)", 2019-06-03), I forgot to update the comment. Do it now. Fixes: 49edde15230a5bfd6746225eb95535eaa2ec1ba4 Signed-off-by: Laszlo Ersek Reviewed-by: Ard Biesheuvel --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 0c49568526..882805269b 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -968,7 +968,7 @@ PlatformQemuInitializeRam ( // // We'd like to keep the following ranges uncached: // - [640 KB, 1 MB) - // - [LowerMemorySize, 4 GB) + // - [Uc32Base, 4 GB) // // Everything else should be WB. Unfortunately, programming the inverse (ie. // keeping the default UC, and configuring the complement set of the above as From 86523a8daaf5b35e325815ac72e5e36942b9b808 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 11 Jan 2023 19:00:23 +0100 Subject: [PATCH 0475/1529] OvmfPkg/VirtNorFlashDxe: map flash memory as uncacheable Switching from the ArmPlatformPkg/NorFlashDxe driver to the OvmfPkg/VirtNorFlashDxe driver had the side effect that flash address space got registered as EFI_MEMORY_WC instead of EFI_MEMORY_UC. That confuses the linux kernel's numa code, seems this makes kernel consider the flash being node memory. "lsmem" changes from ... RANGE SIZE STATE REMOVABLE BLOCK 0x0000000040000000-0x000000013fffffff 4G online yes 8-39 ... to ... RANGE SIZE STATE REMOVABLE BLOCK 0x0000000000000000-0x0000000007ffffff 128M online yes 0 0x0000000040000000-0x000000013fffffff 4G online yes 8-39 ... and in the kernel log got new error lines: NUMA: Warning: invalid memblk node 512 [mem 0x0000000004000000-0x0000000007ffffff] NUMA: Faking a node at [mem 0x0000000004000000-0x000000013fffffff] Changing the attributes back to EFI_MEMORY_UC fixes this. Fixes: b92298af8218 ("ArmVirtPkg/ArmVirtQemu: migrate to OVMF's VirtNorFlashDxe") Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index ff3121af2a..f9a41f6aab 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -394,14 +394,14 @@ NorFlashFvbInitialize ( EfiGcdMemoryTypeMemoryMappedIo, Instance->DeviceBaseAddress, RuntimeMmioRegionSize, - EFI_MEMORY_WC | EFI_MEMORY_RUNTIME + EFI_MEMORY_UC | EFI_MEMORY_RUNTIME ); ASSERT_EFI_ERROR (Status); Status = gDS->SetMemorySpaceAttributes ( Instance->DeviceBaseAddress, RuntimeMmioRegionSize, - EFI_MEMORY_WC | EFI_MEMORY_RUNTIME + EFI_MEMORY_UC | EFI_MEMORY_RUNTIME ); ASSERT_EFI_ERROR (Status); From 2d8075df80ae8bce6a3dfe8b02c4599fce1cfce2 Mon Sep 17 00:00:00 2001 From: Sophia Wolf Date: Tue, 8 Nov 2022 16:46:14 +0000 Subject: [PATCH 0476/1529] OvmfPkg: Realize EfiMemoryAcceptProtocol in AmdSevDxe When a guest OS does not support unaccepted memory, the unaccepted memory must be accepted before returning a memory map to the caller. EfiMemoryAcceptProtocol is defined in MdePkg and is implemented / Installed in AmdSevDxe for AMD SEV-SNP memory acceptance. Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Tom Lendacky Acked-by: Jiewen Yao Signed-off-by: Dionna Glaze Message-Id: <20221108164616.3251967-2-dionnaglaze@google.com> --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 55 +++++++++++++++++-- OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 3 + .../X64/DxeSnpSystemRamValidate.c | 24 ++++++-- 3 files changed, 74 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 662d3c4ccb..f7600c3c81 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -20,6 +20,7 @@ #include #include #include +#include STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { SIGNATURE_32 ('A', 'M', 'D', 'E'), @@ -31,6 +32,40 @@ STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { FixedPcdGet32 (PcdOvmfCpuidSize), }; +STATIC EFI_HANDLE mAmdSevDxeHandle = NULL; + +#define IS_ALIGNED(x, y) ((((x) & ((y) - 1)) == 0)) + +STATIC +EFI_STATUS +EFIAPI +AmdSevMemoryAccept ( + IN EDKII_MEMORY_ACCEPT_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS StartAddress, + IN UINTN Size + ) +{ + // + // The StartAddress must be page-aligned, and the Size must be a positive + // multiple of SIZE_4KB. Use an assert instead of returning an erros since + // this is an EDK2-internal protocol. + // + ASSERT (IS_ALIGNED (StartAddress, SIZE_4KB)); + ASSERT (IS_ALIGNED (Size, SIZE_4KB)); + ASSERT (Size != 0); + + MemEncryptSevSnpPreValidateSystemRam ( + StartAddress, + EFI_SIZE_TO_PAGES (Size) + ); + + return EFI_SUCCESS; +} + +STATIC EDKII_MEMORY_ACCEPT_PROTOCOL mMemoryAcceptProtocol = { + AmdSevMemoryAccept +}; + EFI_STATUS EFIAPI AmdSevDxeEntryPoint ( @@ -147,11 +182,23 @@ AmdSevDxeEntryPoint ( } } - // - // If its SEV-SNP active guest then install the CONFIDENTIAL_COMPUTING_SEV_SNP_BLOB. - // It contains the location for both the Secrets and CPUID page. - // if (MemEncryptSevSnpIsEnabled ()) { + // + // Memory acceptance began being required in SEV-SNP, so install the + // memory accept protocol implementation for a SEV-SNP active guest. + // + Status = gBS->InstallProtocolInterface ( + &mAmdSevDxeHandle, + &gEdkiiMemoryAcceptProtocolGuid, + EFI_NATIVE_INTERFACE, + &mMemoryAcceptProtocol + ); + ASSERT_EFI_ERROR (Status); + + // + // If its SEV-SNP active guest then install the CONFIDENTIAL_COMPUTING_SEV_SNP_BLOB. + // It contains the location for both the Secrets and CPUID page. + // return gBS->InstallConfigurationTable ( &gConfidentialComputingSevSnpBlobGuid, &mSnpBootDxeTable diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf index 9acf860cf2..cd1b686c53 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf @@ -47,6 +47,9 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSnpSecretsBase gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSnpSecretsSize +[Protocols] + gEdkiiMemoryAcceptProtocolGuid + [Guids] gConfidentialComputingSevSnpBlobGuid diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/DxeSnpSystemRamValidate.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/DxeSnpSystemRamValidate.c index d3a95e4913..cbcdd46f52 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/DxeSnpSystemRamValidate.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/DxeSnpSystemRamValidate.c @@ -14,6 +14,7 @@ #include #include "SnpPageStateChange.h" +#include "VirtualMemory.h" /** Pre-validate the system RAM when SEV-SNP is enabled in the guest VM. @@ -29,12 +30,27 @@ MemEncryptSevSnpPreValidateSystemRam ( IN UINTN NumPages ) { + EFI_STATUS Status; + if (!MemEncryptSevSnpIsEnabled ()) { return; } - // - // All the pre-validation must be completed in the PEI phase. - // - ASSERT (FALSE); + // DXE pre-validation may happen with the memory accept protocol. + // The protocol should only be called outside the prevalidated ranges + // that the PEI stage code explicitly skips. Specifically, only memory + // ranges that are classified as unaccepted. + if (BaseAddress >= SIZE_4GB) { + Status = InternalMemEncryptSevCreateIdentityMap1G ( + 0, + BaseAddress, + EFI_PAGES_TO_SIZE (NumPages) + ); + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + CpuDeadLoop (); + } + } + + InternalSetPageState (BaseAddress, NumPages, SevSnpPagePrivate, TRUE); } From a8f6e0c97bcee6167960f6a130ec3ac6e2a19285 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Tue, 8 Nov 2022 16:46:15 +0000 Subject: [PATCH 0477/1529] MdePkg: Add EFI_EVENT_BEFORE_EXIT_BOOT_SERVICES_GUID Event group as defined in UEFI standard v2.9. Cc: Ard Biescheuvel Cc: "Min M. Xu" Cc: Gerd Hoffmann Cc: James Bottomley Cc: Tom Lendacky Cc: Jiewen Yao Cc: Erdem Aktas Acked-by: Jiewen Yao Reviewed-by: Michael D Kinney Signed-off-by: Dionna Glaze Message-Id: <20221108164616.3251967-3-dionnaglaze@google.com> --- MdePkg/Include/Guid/EventGroup.h | 5 +++++ MdePkg/MdePkg.dec | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/Guid/EventGroup.h b/MdePkg/Include/Guid/EventGroup.h index 063d1f7157..64bfd4bab9 100644 --- a/MdePkg/Include/Guid/EventGroup.h +++ b/MdePkg/Include/Guid/EventGroup.h @@ -14,6 +14,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent extern EFI_GUID gEfiEventExitBootServicesGuid; +#define EFI_EVENT_GROUP_BEFORE_EXIT_BOOT_SERVICES \ + { 0x8be0e274, 0x3970, 0x4b44, { 0x80, 0xc5, 0x1a, 0xb9, 0x50, 0x2f, 0x3b, 0xfc } } + +extern EFI_GUID gEfiEventBeforeExitBootServicesGuid; + #define EFI_EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE \ { 0x13fa7698, 0xc831, 0x49c7, { 0x87, 0xea, 0x8f, 0x43, 0xfc, 0xc2, 0x51, 0x96 } } diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index e49b2d5b5f..3d08f20d15 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -417,7 +417,10 @@ gEfiEventMemoryMapChangeGuid = { 0x78BEE926, 0x692F, 0x48FD, { 0x9E, 0xDB, 0x01, 0x42, 0x2E, 0xF0, 0xD7, 0xAB }} ## Include/Guid/EventGroup.h - gEfiEventVirtualAddressChangeGuid = { 0x13FA7698, 0xC831, 0x49C7, { 0x87, 0xEA, 0x8F, 0x43, 0xFC, 0xC2, 0x51, 0x96 }} + gEfiEventVirtualAddressChangeGuid = { 0x13FA7698, 0xC831, 0x49C7, { 0x87, 0xEA, 0x8F, 0x43, 0xFC, 0xC2, 0x51, 0x96 }} + + ## Include/Guid/EventGroup.h + gEfiEventBeforeExitBootServicesGuid = { 0x8BE0E274, 0x3970, 0x4B44, { 0x80, 0xC5, 0x1A, 0xB9, 0x50, 0x2F, 0x3B, 0xFC }} ## Include/Guid/EventGroup.h gEfiEventExitBootServicesGuid = { 0x27ABF055, 0xB1B8, 0x4C26, { 0x80, 0x48, 0x74, 0x8F, 0x37, 0xBA, 0xA2, 0xDF }} From 7be267315415079b6ce3c93d76094363eceaf530 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Tue, 8 Nov 2022 16:46:16 +0000 Subject: [PATCH 0478/1529] MdeModulePkg: Notify BeforeExitBootServices in CoreExitBootServices Location of notification is has been specified in UEFI v2.9. Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Ard Biesheuvel Cc: "Min M. Xu" Cc: Andrew Fish Cc: "Michael D. Kinney" Cc: Ray Ni Acked-by: Jiewen Yao Reviewed-by: Michael D Kinney Signed-off-by: Dionna Glaze Message-Id: <20221108164616.3251967-4-dionnaglaze@google.com> --- MdeModulePkg/Core/Dxe/DxeMain.inf | 1 + MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/MdeModulePkg/Core/Dxe/DxeMain.inf b/MdeModulePkg/Core/Dxe/DxeMain.inf index e4bca89577..35d5bf0dee 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain.inf +++ b/MdeModulePkg/Core/Dxe/DxeMain.inf @@ -100,6 +100,7 @@ gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event ## CONSUMES ## Event ## PRODUCES ## Event + gEfiEventBeforeExitBootServicesGuid gEfiEventExitBootServicesGuid gEfiHobMemoryAllocModuleGuid ## SOMETIMES_CONSUMES ## HOB gEfiFirmwareFileSystem2Guid ## CONSUMES ## GUID # Used to compare with FV's file system guid and get the FV's file system format diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c index 5733f0c8ec..4683016ed7 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c +++ b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c @@ -763,6 +763,12 @@ CoreExitBootServices ( { EFI_STATUS Status; + // + // Notify other drivers of their last chance to use boot services + // before the memory map is terminated. + // + CoreNotifySignalList (&gEfiEventBeforeExitBootServicesGuid); + // // Disable Timer // From e43c98fd52e1eac447b0d420ed98431bc6a70fa0 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 12 Jan 2023 23:41:02 +0800 Subject: [PATCH 0479/1529] OvmfPkg: fix OvmfTpmSecurityStub.dsc.inc include TPM support is independent from secure boot support. Move the TPM include snipped out of the secure boot !if block. Fixes: b47575801e19 ("OvmfPkg: move tcg configuration to dsc and fdf include files") Bugzilla: https://bugzilla.tianocore.org//show_bug.cgi?id=4290 Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/CloudHv/CloudHvX64.dsc | 2 +- OvmfPkg/Microvm/MicrovmX64.dsc | 2 +- OvmfPkg/OvmfPkgX64.dsc | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 03b7a5cc6b..7326417eab 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -716,8 +716,8 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index d5bdcbb983..2d53b5c295 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -705,8 +705,8 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 8401d73900..3f970a79a0 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -805,8 +805,8 @@ !if $(SECURE_BOOT_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf -!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc !endif +!include OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc } MdeModulePkg/Universal/EbcDxe/EbcDxe.inf From e1feecf51f3d3e96aa57a895795de2098f9c6879 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:30 +0800 Subject: [PATCH 0480/1529] OvmfPkg/AcpiPlatformDxe: Remove QEMU_ACPI_TABLE_NOTIFY_PROTOCOL BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 The QEMU_ACPI_TABLE_NOTIFY_PROTOCOL structure is superfluous because NULL protocol interfaces have been used in edk2 repeatedly. A protocol instance can exist in the protocol database with a NULL associated interface. Therefore the QEMU_ACPI_TABLE_NOTIFY_PROTOCOL type, the "QemuAcpiTableNotify.h" header, and the "mAcpiNotifyProtocol" global variable can be removed. Cc: Laszlo Ersek Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Sebastien Boeuf Reported-by: Laszlo Ersek Reviewed-by: Laszlo Ersek Signed-off-by: Min Xu Message-Id: <20230111012235.189-2-min.m.xu@intel.com> Reviewed-by: Sebastien Boeuf --- OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c | 7 ++--- OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 6 ++--- .../Include/Protocol/QemuAcpiTableNotify.h | 27 ------------------- 3 files changed, 4 insertions(+), 36 deletions(-) delete mode 100644 OvmfPkg/Include/Protocol/QemuAcpiTableNotify.h diff --git a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c index cbe8bb9b0c..ad39e42534 100644 --- a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c @@ -15,15 +15,12 @@ #include // PcdGet32() #include // GetFirstGuidHob(), GetNextGuidHob() #include // gBS - #include #include -#include // QEMU_ACPI_TABLE_NOTIFY_PROTOCOL #include "AcpiPlatform.h" -EFI_HANDLE mChAcpiHandle = NULL; -QEMU_ACPI_TABLE_NOTIFY_PROTOCOL mChAcpiNotifyProtocol; +EFI_HANDLE mChAcpiHandle = NULL; EFI_STATUS EFIAPI @@ -96,7 +93,7 @@ InstallCloudHvTablesTdx ( &mChAcpiHandle, &gQemuAcpiTableNotifyProtocolGuid, EFI_NATIVE_INTERFACE, - &mChAcpiNotifyProtocol + NULL ); return EFI_SUCCESS; diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index c8dee17c13..1a3852904d 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -19,10 +19,8 @@ #include // QemuFwCfgS3Enabled() #include // gBS -#include #include "AcpiPlatform.h" -EFI_HANDLE mQemuAcpiHandle = NULL; -QEMU_ACPI_TABLE_NOTIFY_PROTOCOL mAcpiNotifyProtocol; +EFI_HANDLE mQemuAcpiHandle = NULL; // // The user structure for the ordered collection that will track the fw_cfg @@ -1284,7 +1282,7 @@ InstallQemuFwCfgTables ( &mQemuAcpiHandle, &gQemuAcpiTableNotifyProtocolGuid, EFI_NATIVE_INTERFACE, - &mAcpiNotifyProtocol + NULL ); } diff --git a/OvmfPkg/Include/Protocol/QemuAcpiTableNotify.h b/OvmfPkg/Include/Protocol/QemuAcpiTableNotify.h deleted file mode 100644 index a3dd2fc1dc..0000000000 --- a/OvmfPkg/Include/Protocol/QemuAcpiTableNotify.h +++ /dev/null @@ -1,27 +0,0 @@ -/** @file - - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef QEMU_ACPI_TABLE_NOTIFY_H_ -#define QEMU_ACPI_TABLE_NOTIFY_H_ - -#define QEMU_ACPI_TABLE_NOTIFY_GUID \ - { 0x928939b2, 0x4235, 0x462f, { 0x95, 0x80, 0xf6, 0xa2, 0xb2, 0xc2, 0x1a, 0x4f } }; - -/// -/// Forward declaration -/// -typedef struct _QEMU_ACPI_TABLE_NOTIFY_PROTOCOL QEMU_ACPI_TABLE_NOTIFY_PROTOCOL; - -/// -/// Protocol structure -/// -struct _QEMU_ACPI_TABLE_NOTIFY_PROTOCOL { - UINT8 Notify; -}; - -extern EFI_GUID gQemuAcpiTableNotifyProtocolGuid; - -#endif From 05f9e76b332b3388b70db14336970e38d988b494 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:31 +0800 Subject: [PATCH 0481/1529] OvmfPkg/AcpiPlatformDxe: Use local variable in CloudHvAcpi.c BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 The handle of mChAcpiHandle is not needed for anything, beyond the scope of the InstallCloudHvTablesTdx (). A local variable (ChAcpiHandle) suffices for storing the handle. Cc: Laszlo Ersek Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Sebastien Boeuf Reported-by: Laszlo Ersek Signed-off-by: Min Xu Message-Id: <20230111012235.189-3-min.m.xu@intel.com> Reviewed-by: Sebastien Boeuf --- OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c index ad39e42534..8f90ea2399 100644 --- a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c @@ -20,8 +20,6 @@ #include "AcpiPlatform.h" -EFI_HANDLE mChAcpiHandle = NULL; - EFI_STATUS EFIAPI InstallCloudHvTablesTdx ( @@ -30,6 +28,7 @@ InstallCloudHvTablesTdx ( { EFI_STATUS Status; UINTN TableHandle; + EFI_HANDLE ChAcpiHandle; EFI_PEI_HOB_POINTERS Hob; EFI_ACPI_DESCRIPTION_HEADER *CurrentTable; @@ -89,8 +88,9 @@ InstallCloudHvTablesTdx ( // Install a protocol to notify that the ACPI table provided by CH is // ready. // + ChAcpiHandle = NULL; gBS->InstallProtocolInterface ( - &mChAcpiHandle, + &ChAcpiHandle, &gQemuAcpiTableNotifyProtocolGuid, EFI_NATIVE_INTERFACE, NULL From 714ed98732c3793d1a95d781540fcff6bd6a22fe Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:32 +0800 Subject: [PATCH 0482/1529] OvmfPkg/AcpiPlatformDxe: Use local variable in QemuFwCfgAcpi.c BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 The handle of mQemuAcpiHandle is not needed for anything, beyond the scope of the InstallQemuFwCfgTables(). So a local variable will suffice for storing the handle. Cc: Laszlo Ersek Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Reported-by: Laszlo Ersek Reviewed-by: Laszlo Ersek Signed-off-by: Min Xu Message-Id: <20230111012235.189-4-min.m.xu@intel.com> --- OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index 1a3852904d..9711335c6c 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -20,7 +20,6 @@ #include // gBS #include "AcpiPlatform.h" -EFI_HANDLE mQemuAcpiHandle = NULL; // // The user structure for the ordered collection that will track the fw_cfg @@ -1101,6 +1100,7 @@ InstallQemuFwCfgTables ( ORDERED_COLLECTION_ENTRY *TrackerEntry, *TrackerEntry2; ORDERED_COLLECTION *SeenPointers; ORDERED_COLLECTION_ENTRY *SeenPointerEntry, *SeenPointerEntry2; + EFI_HANDLE QemuAcpiHandle; Status = QemuFwCfgFindFile ("etc/table-loader", &FwCfgItem, &FwCfgSize); if (EFI_ERROR (Status)) { @@ -1278,8 +1278,9 @@ InstallQemuFwCfgTables ( // Install a protocol to notify that the ACPI table provided by Qemu is // ready. // + QemuAcpiHandle = NULL; gBS->InstallProtocolInterface ( - &mQemuAcpiHandle, + &QemuAcpiHandle, &gQemuAcpiTableNotifyProtocolGuid, EFI_NATIVE_INTERFACE, NULL From 352ff877d0853091ab79f58065f96c8b71e56291 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:33 +0800 Subject: [PATCH 0483/1529] OvmfPkg/AcpiPlatformDxe: Add log to show the installed tables BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 Commit 9fdc70af6ba8 wrongly removed the log from InstallQemuFwCfgTables after ACPI tables are successfully installed. This patch add the log back after all operations succeed. Cc: Laszlo Ersek Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Reported-by: Laszlo Ersek Reviewed-by: Laszlo Ersek Signed-off-by: Min Xu Message-Id: <20230111012235.189-5-min.m.xu@intel.com> --- OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index 9711335c6c..4629214666 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -1264,6 +1264,8 @@ InstallQemuFwCfgTables ( S3Context = NULL; } + DEBUG ((DEBUG_INFO, "%a: installed %d tables\n", __FUNCTION__, Installed)); + UninstallAcpiTables: if (EFI_ERROR (Status)) { // From f1ec7f481d0d9cc377299ca2311392196bb3179b Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:34 +0800 Subject: [PATCH 0484/1529] OvmfPkg/AcpiPlatformDxe: Refactor QemuAcpiTableNotifyProtocol BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 Commit 9fdc70af6ba8 install the QemuAcpiTableNotifyProtocol at a wrong positioin. It should be called before TransferS3ContextToBootScript because TransferS3ContextToBootScript is the last operation in InstallQemuFwCfgTables(). Another error is that we should check the returned value after installing the QemuAcpiTableNotifyProtocol. This patch refactors the installation and error handling of QemuAcpiTableNotifyProtocol in InstallQemuFwCfgTables (). Cc: Laszlo Ersek Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Reported-by: Laszlo Ersek Signed-off-by: Min Xu Message-Id: <20230111012235.189-6-min.m.xu@intel.com> Reviewed-by: Laszlo Ersek --- OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 38 ++++++++++++++++--------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index 4629214666..f0d81d6fd7 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -1247,6 +1247,21 @@ InstallQemuFwCfgTables ( } } + // + // Install a protocol to notify that the ACPI table provided by Qemu is + // ready. + // + QemuAcpiHandle = NULL; + Status = gBS->InstallProtocolInterface ( + &QemuAcpiHandle, + &gQemuAcpiTableNotifyProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); + if (EFI_ERROR (Status)) { + goto UninstallAcpiTables; + } + // // Translating the condensed QEMU_LOADER_WRITE_POINTER commands to ACPI S3 // Boot Script opcodes has to be the last operation in this function, because @@ -1255,7 +1270,7 @@ InstallQemuFwCfgTables ( if (S3Context != NULL) { Status = TransferS3ContextToBootScript (S3Context); if (EFI_ERROR (Status)) { - goto UninstallAcpiTables; + goto UninstallQemuAcpiTableNotifyProtocol; } // @@ -1266,6 +1281,15 @@ InstallQemuFwCfgTables ( DEBUG ((DEBUG_INFO, "%a: installed %d tables\n", __FUNCTION__, Installed)); +UninstallQemuAcpiTableNotifyProtocol: + if (EFI_ERROR (Status)) { + gBS->UninstallProtocolInterface ( + QemuAcpiHandle, + &gQemuAcpiTableNotifyProtocolGuid, + NULL + ); + } + UninstallAcpiTables: if (EFI_ERROR (Status)) { // @@ -1275,18 +1299,6 @@ InstallQemuFwCfgTables ( --Installed; AcpiProtocol->UninstallAcpiTable (AcpiProtocol, InstalledKey[Installed]); } - } else { - // - // Install a protocol to notify that the ACPI table provided by Qemu is - // ready. - // - QemuAcpiHandle = NULL; - gBS->InstallProtocolInterface ( - &QemuAcpiHandle, - &gQemuAcpiTableNotifyProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); } for (SeenPointerEntry = OrderedCollectionMin (SeenPointers); From 39a3b351d6a746e6947305dd64d9529b6d766abc Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 11 Jan 2023 09:22:35 +0800 Subject: [PATCH 0485/1529] OvmfPkg/AcpiPlatformDxe: Return error if installing NotifyProtocol failed BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4237 Installation of gQemuAcpiTableNotifyProtocol may fail. The error code should be returned so that the caller can handle it. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Sebastien Boeuf Signed-off-by: Min Xu Message-Id: <20230111012235.189-7-min.m.xu@intel.com> Reviewed-by: Sebastien Boeuf --- OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c index 8f90ea2399..d56eb074a9 100644 --- a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c @@ -89,12 +89,16 @@ InstallCloudHvTablesTdx ( // ready. // ChAcpiHandle = NULL; - gBS->InstallProtocolInterface ( - &ChAcpiHandle, - &gQemuAcpiTableNotifyProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = gBS->InstallProtocolInterface ( + &ChAcpiHandle, + &gQemuAcpiTableNotifyProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return Status; + } return EFI_SUCCESS; } From 251f310be5e8a280d4f32ba7535fe63c6e445049 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Wed, 11 Jan 2023 11:10:06 +0800 Subject: [PATCH 0486/1529] MdeModulePkg/Xhci: Initial XHCI DCI slot's Context value Initialize XHCI DCI slot's context entries value. Signed-off-by: Jiangang He Cc: Hao A Wu Cc: Ray Ni Cc: Garrett Kirkendall Cc: Abner Chang Cc: Kuei-Hung Lin Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 7 +++++++ MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index 13247f7b0d..4b7462704a 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -4,6 +4,7 @@ Copyright (c) 2011 - 2020, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation.
+Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -2807,6 +2808,9 @@ XhcInitializeEndpointContext ( MaxDci = 0; NumEp = IfDesc->NumEndpoints; + if (NumEp == 0) { + MaxDci = 1; + } EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { @@ -3006,6 +3010,9 @@ XhcInitializeEndpointContext64 ( MaxDci = 0; NumEp = IfDesc->NumEndpoints; + if (NumEp == 0) { + MaxDci = 1; + } EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c index cc597a4371..8400c90f7a 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c @@ -3,6 +3,7 @@ PEIM to produce gPeiUsb2HostControllerPpiGuid based on gPeiUsbControllerPpiGuid which is used to enable recovery function from USB Drivers. Copyright (c) 2014 - 2017, Intel Corporation. All rights reserved.
+Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -1752,6 +1753,9 @@ XhcPeiSetConfigCmd ( } NumEp = IfDesc->NumEndpoints; + if ((NumEp == 0) && (MaxDci == 0)) { + MaxDci = 1; + } EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { @@ -1974,6 +1978,9 @@ XhcPeiSetConfigCmd64 ( } NumEp = IfDesc->NumEndpoints; + if ((NumEp == 0) && (MaxDci == 0)) { + MaxDci = 1; + } EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { From 5bd938506dcf8b8efdbe30ebd2513b6dafe9e927 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Wed, 11 Jan 2023 11:10:07 +0800 Subject: [PATCH 0487/1529] MdeModulePkg/Usb: Read a large number of blocks Changes to allow reading blocks that greater than 65535 sectors. Signed-off-by: Jiangang He Cc: Hao A Wu Cc: Ray Ni Cc: Garrett Kirkendall Cc: Abner Chang Cc: Kuei-Hung Lin Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c | 25 +++++++++++------------ 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c index 422ac5fec9..5111e4579e 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c @@ -2,6 +2,7 @@ Pei USB ATAPI command implementations. Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.
+Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -382,14 +383,14 @@ PeiUsbRead10 ( ATAPI_PACKET_COMMAND Packet; ATAPI_READ10_CMD *Read10Packet; UINT16 MaxBlock; - UINT16 BlocksRemaining; - UINT16 SectorCount; + UINT32 BlocksRemaining; + UINT32 SectorCount; UINT32 Lba32; UINT32 BlockSize; UINT32 ByteCount; VOID *PtrBuffer; EFI_STATUS Status; - UINT16 TimeOut; + UINT32 TimeOut; // // prepare command packet for the Inquiry Packet Command. @@ -401,16 +402,13 @@ PeiUsbRead10 ( BlockSize = (UINT32)PeiBotDevice->Media.BlockSize; - MaxBlock = (UINT16)(65535 / BlockSize); - BlocksRemaining = (UINT16)NumberOfBlocks; + MaxBlock = (UINT16)(MAX_UINT16 / BlockSize); + ASSERT (NumberOfBlocks < MAX_UINT32); + BlocksRemaining = (UINT32)NumberOfBlocks; Status = EFI_SUCCESS; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { - SectorCount = BlocksRemaining; - } else { - SectorCount = MaxBlock; - } + SectorCount = MIN (BlocksRemaining, MaxBlock); // // fill the Packet data structure @@ -435,7 +433,7 @@ PeiUsbRead10 ( ByteCount = SectorCount * BlockSize; - TimeOut = (UINT16)(SectorCount * 2000); + TimeOut = SectorCount * 2000; // // send command packet @@ -448,16 +446,17 @@ PeiUsbRead10 ( (VOID *)PtrBuffer, ByteCount, EfiUsbDataIn, - TimeOut + (UINT16)MIN (TimeOut, MAX_UINT16) ); if (Status != EFI_SUCCESS) { return Status; } + ASSERT (Lba32 <= (MAX_UINT32-SectorCount)); Lba32 += SectorCount; PtrBuffer = (UINT8 *)PtrBuffer + SectorCount * BlockSize; - BlocksRemaining = (UINT16)(BlocksRemaining - SectorCount); + BlocksRemaining = BlocksRemaining - SectorCount; } return Status; From b664074bceeaf1e0460d3284520684ea2c1e1d85 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Wed, 11 Jan 2023 11:10:08 +0800 Subject: [PATCH 0488/1529] MdeModulePkg/XhciPei: Unlinked XhciPei memory block Unlink the XhciPei memory block when it has been freed. Signed-off-by: Jiangang He Cc: Hao A Wu Cc: Ray Ni Cc: Garrett Kirkendall Cc: Abner Chang Cc: Kuei-Hung Lin Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c | 31 +++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c index c64b38fcfc..e779a31138 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c @@ -3,6 +3,7 @@ PEIM to produce gPeiUsb2HostControllerPpiGuid based on gPeiUsbControllerPpiGuid which is used to enable recovery function from USB Drivers. Copyright (c) 2014 - 2016, Intel Corporation. All rights reserved.
+Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -365,6 +366,32 @@ UsbHcInitMemPool ( return Pool; } +/** + Unlink the memory block from the pool's list. + + @param Head The block list head of the memory's pool. + @param BlockToUnlink The memory block to unlink. + +**/ +VOID +UsbHcUnlinkMemBlock ( + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *BlockToUnlink + ) +{ + USBHC_MEM_BLOCK *Block; + + ASSERT ((Head != NULL) && (BlockToUnlink != NULL)); + + for (Block = Head; Block != NULL; Block = Block->Next) { + if (Block->Next == BlockToUnlink) { + Block->Next = BlockToUnlink->Next; + BlockToUnlink->Next = NULL; + break; + } + } +} + /** Release the memory management pool. @@ -386,7 +413,7 @@ UsbHcFreeMemPool ( // first block. // for (Block = Pool->Head->Next; Block != NULL; Block = Pool->Head->Next) { - // UsbHcUnlinkMemBlock (Pool->Head, Block); + UsbHcUnlinkMemBlock (Pool->Head, Block); UsbHcFreeMemBlock (Pool, Block); } @@ -532,7 +559,7 @@ UsbHcFreeMem ( // Release the current memory block if it is empty and not the head // if ((Block != Head) && UsbHcIsMemBlockEmpty (Block)) { - // UsbHcUnlinkMemBlock (Head, Block); + UsbHcUnlinkMemBlock (Head, Block); UsbHcFreeMemBlock (Pool, Block); } } From 2c6c4041645d5c431a667e4834b12eb96e6b6e94 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Mon, 16 Jan 2023 10:46:39 +0100 Subject: [PATCH 0489/1529] ArmVirt: don't use unaligned CopyMem () on NOR flash Commit 789a72328553 reclassified the NOR flash region as EFI_MEMORY_WC in the OS visible EFI memory map, and dropped the explicit aligned CopyMem() implementation, in the assumption that EFI_MEMORY_WC will be honored by the OS, and that the region will be mapped in a way that tolerates misaligned accesseses. However, Linux today uses device attributes for all EFI MMIO regions, in spite of the memory type attributes, and so using misaligned accesses is never safe. So instead, switch to the generic CopyMem() implementation entirely, just like we already did for VariableRuntimeDxe. Fixes: 789a72328553 ("OvmfPkg/VirtNorFlashDxe: use EFI_MEMORY_WC and drop AlignedCopyMem()") Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtKvmTool.dsc | 6 +++++- ArmVirtPkg/ArmVirtQemu.dsc | 6 +++++- ArmVirtPkg/ArmVirtQemuKernel.dsc | 6 +++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/ArmVirtPkg/ArmVirtKvmTool.dsc b/ArmVirtPkg/ArmVirtKvmTool.dsc index 2ba00bd08f..d0afe1b49e 100644 --- a/ArmVirtPkg/ArmVirtKvmTool.dsc +++ b/ArmVirtPkg/ArmVirtKvmTool.dsc @@ -296,7 +296,11 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf { + + # don't use unaligned CopyMem () on the UEFI varstore NOR flash region + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + } MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 5dd8b6104c..0f1c639548 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -428,7 +428,11 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf { + + # don't use unaligned CopyMem () on the UEFI varstore NOR flash region + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + } MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf # diff --git a/ArmVirtPkg/ArmVirtQemuKernel.dsc b/ArmVirtPkg/ArmVirtQemuKernel.dsc index f5db3ac432..807c85d482 100644 --- a/ArmVirtPkg/ArmVirtQemuKernel.dsc +++ b/ArmVirtPkg/ArmVirtQemuKernel.dsc @@ -331,7 +331,11 @@ NULL|ArmVirtPkg/Library/ArmVirtTimerFdtClientLib/ArmVirtTimerFdtClientLib.inf } - OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf { + + # don't use unaligned CopyMem () on the UEFI varstore NOR flash region + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + } MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf # From 1d3096f6843da8f493716fa6387cc9d0f9b84a33 Mon Sep 17 00:00:00 2001 From: Konstantin Aladyshev Date: Wed, 14 Dec 2022 00:22:22 +0800 Subject: [PATCH 0490/1529] Fix cyclic dependency error on OptionROM build EDKII build system supports OptionROM generation if particular PCI_* defines are present in the module INF file: ``` [Defines] ... PCI_VENDOR_ID = <...> PCI_DEVICE_ID = <...> PCI_CLASS_CODE = <...> PCI_REVISION = <...> ``` Although after the commit d372ab585a2cdc5348af5f701c56c631235fe698 ("BaseTools/Conf: Fix Dynamic-Library-File template") it is no longer possible. The build system fails with the error: ``` Cyclic dependency detected while generating rule for "<...>/DEBUG/<...>.efi" file ``` Remove "$(DEBUG_DIR)(+)$(MODULE_NAME).efi" from the 'dll' output files to fix the cyclic dependency. Signed-off-by: Konstantin Aladyshev Reviewed-by: Bob Feng --- BaseTools/Conf/build_rule.template | 1 - 1 file changed, 1 deletion(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index ec83638144..d42e7937cc 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -342,7 +342,6 @@ $(OUTPUT_DIR)(+)$(MODULE_NAME).efi - $(DEBUG_DIR)(+)$(MODULE_NAME).efi $(OUTPUT_DIR)(+)$(MODULE_NAME).map From dc4773453856cd43897101a8008395fc7a8bee4b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 5 Jan 2023 15:29:39 +0100 Subject: [PATCH 0491/1529] BaseTools/tools_def RISCV: Make OpenSBI references RISCV-only The global GCC_PP_FLAGS tools_def variable now contains a reference to OpenSBI specific C preprocessor variables, which means they are added to the command line on every architecture, not just RISC-V. This does not currently result in any issues, but it is a bit sloppy so let's clean this up. Given that the GCC_PP_FLAGS definition appears twice, drop the one that carries the OpenSBI reference, and move that reference to a new RISC-V specific variable. Acked-by: Abner Chang Reviewed-by: Sunil V L Signed-off-by: Ard Biesheuvel --- BaseTools/Conf/tools_def.template | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 805e903b23..4733040e3e 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1979,8 +1979,6 @@ DEFINE GCC5_LOONGARCH64_ASLDLINK_FLAGS = DEF(GCC_LOONGARCH64_ASLDLINK_FLAGS) DEFINE GCC5_LOONGARCH64_ASM_FLAGS = -x assembler-with-cpp -mabi=lp64d -march=loongarch64 -fno-builtin -c -Wall -mno-explicit-relocs DEFINE GCC5_LOONGARCH64_PP_FLAGS = -mabi=lp64d -march=loongarch64 DEF(GCC_PP_FLAGS) -DEFINE GCC_PP_FLAGS = -E -x assembler-with-cpp -include AutoGen.h DEF(GCC5_RISCV_OPENSBI_TYPES) - #################################################################################### # # GCC 4.8 - This configuration is used to compile under Linux to produce @@ -2456,6 +2454,7 @@ RELEASE_GCC5_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_GCC5_RISCV64_RC_FLAGS = DEF(GCC_RISCV64_RC_FLAGS) *_GCC5_RISCV64_OBJCOPY_FLAGS = *_GCC5_RISCV64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) +*_GCC5_RISCV64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(GCC5_RISCV_OPENSBI_TYPES) ################## # GCC5 LOONGARCH64 definitions From faaa699f9868f24daea32fb6534677fad8154d9c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 5 Jan 2023 15:20:16 +0100 Subject: [PATCH 0492/1529] BaseTools/tools_def ARM AARCH64: Get rid of ARCHCC and ARCHASM flags ARCHCC_FLAGS and ARCHASM_FLAGS no longer serve a useful purpose so drop all the definitions and references. Signed-off-by: Ard Biesheuvel --- BaseTools/Conf/tools_def.template | 89 ++++++++++++++----------------- 1 file changed, 41 insertions(+), 48 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 4733040e3e..fe8d5a8ea5 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1896,11 +1896,11 @@ DEFINE GCC48_IA32_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 DEF DEFINE GCC48_X64_DLINK_FLAGS = DEF(GCC48_IA32_X64_DLINK_FLAGS) -Wl,-melf_x86_64,--oformat=elf64-x86-64,-pie DEFINE GCC48_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x228 DEF(GCC_DLINK2_FLAGS_COMMON) DEFINE GCC48_ASM_FLAGS = DEF(GCC_ASM_FLAGS) -DEFINE GCC48_ARM_ASM_FLAGS = $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_ASM_FLAGS) -mlittle-endian -DEFINE GCC48_AARCH64_ASM_FLAGS = $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_ASM_FLAGS) -mlittle-endian -DEFINE GCC48_ARM_CC_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_ARM_CC_FLAGS) -fstack-protector -mword-relocations +DEFINE GCC48_ARM_ASM_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_ASM_FLAGS) -mlittle-endian +DEFINE GCC48_AARCH64_ASM_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_ASM_FLAGS) -mlittle-endian +DEFINE GCC48_ARM_CC_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_ARM_CC_FLAGS) -fstack-protector -mword-relocations DEFINE GCC48_ARM_CC_XIPFLAGS = DEF(GCC_ARM_CC_XIPFLAGS) -DEFINE GCC48_AARCH64_CC_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -mcmodel=large DEF(GCC_AARCH64_CC_FLAGS) +DEFINE GCC48_AARCH64_CC_FLAGS = $(PLATFORM_FLAGS) -mcmodel=large DEF(GCC_AARCH64_CC_FLAGS) DEFINE GCC48_AARCH64_CC_XIPFLAGS = DEF(GCC_AARCH64_CC_XIPFLAGS) DEFINE GCC48_ARM_DLINK_FLAGS = DEF(GCC_ARM_DLINK_FLAGS) -Wl,--oformat=elf32-littlearm DEFINE GCC48_ARM_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 @@ -1923,7 +1923,7 @@ DEFINE GCC49_ARM_ASM_FLAGS = DEF(GCC48_ARM_ASM_FLAGS) DEFINE GCC49_AARCH64_ASM_FLAGS = DEF(GCC48_AARCH64_ASM_FLAGS) DEFINE GCC49_ARM_CC_FLAGS = DEF(GCC48_ARM_CC_FLAGS) DEFINE GCC49_ARM_CC_XIPFLAGS = DEF(GCC48_ARM_CC_XIPFLAGS) -DEFINE GCC49_AARCH64_CC_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC48_ALL_CC_FLAGS) DEF(GCC_AARCH64_CC_FLAGS) -mcmodel=small +DEFINE GCC49_AARCH64_CC_FLAGS = $(PLATFORM_FLAGS) DEF(GCC48_ALL_CC_FLAGS) DEF(GCC_AARCH64_CC_FLAGS) -mcmodel=small DEFINE GCC49_AARCH64_CC_XIPFLAGS = DEF(GCC48_AARCH64_CC_XIPFLAGS) DEFINE GCC49_ARM_DLINK_FLAGS = DEF(GCC48_ARM_DLINK_FLAGS) DEFINE GCC49_ARM_DLINK2_FLAGS = DEF(GCC48_ARM_DLINK2_FLAGS) @@ -2070,9 +2070,6 @@ RELEASE_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -Os -Wno-unused-but-s *_GCC48_ARM_ASLPP_PATH = ENV(GCC48_ARM_PREFIX)gcc *_GCC48_ARM_RC_PATH = ENV(GCC48_ARM_PREFIX)objcopy -*_GCC48_ARM_ARCHCC_FLAGS = -mthumb -*_GCC48_ARM_PLATFORM_FLAGS = -march=armv7-a - *_GCC48_ARM_ASLCC_FLAGS = DEF(GCC48_ASLCC_FLAGS) *_GCC48_ARM_ASLDLINK_FLAGS = DEF(GCC48_ARM_ASLDLINK_FLAGS) *_GCC48_ARM_ASM_FLAGS = DEF(GCC48_ARM_ASM_FLAGS) @@ -2080,9 +2077,9 @@ RELEASE_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -Os -Wno-unused-but-s *_GCC48_ARM_DLINK2_FLAGS = DEF(GCC48_ARM_DLINK2_FLAGS) *_GCC48_ARM_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC48_ARM_PLATFORM_FLAGS = -march=armv7-a -*_GCC48_ARM_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC48_ARM_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC48_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) -*_GCC48_ARM_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC48_ARM_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC48_ARM_CC_XIPFLAGS = DEF(GCC48_ARM_CC_XIPFLAGS) DEBUG_GCC48_ARM_CC_FLAGS = DEF(GCC48_ARM_CC_FLAGS) -O0 @@ -2110,9 +2107,9 @@ RELEASE_GCC48_ARM_CC_FLAGS = DEF(GCC48_ARM_CC_FLAGS) -Wno-unused-but-set-v *_GCC48_AARCH64_DLINK2_FLAGS = DEF(GCC48_AARCH64_DLINK2_FLAGS) *_GCC48_AARCH64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC48_AARCH64_PLATFORM_FLAGS = -*_GCC48_AARCH64_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC48_AARCH64_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC48_AARCH64_RC_FLAGS = DEF(GCC_AARCH64_RC_FLAGS) -*_GCC48_AARCH64_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC48_AARCH64_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC48_AARCH64_CC_XIPFLAGS = DEF(GCC48_AARCH64_CC_XIPFLAGS) DEBUG_GCC48_AARCH64_CC_FLAGS = DEF(GCC48_AARCH64_CC_FLAGS) -O0 @@ -2210,9 +2207,6 @@ RELEASE_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -Os -Wno-unused-but-s *_GCC49_ARM_ASLPP_PATH = ENV(GCC49_ARM_PREFIX)gcc *_GCC49_ARM_RC_PATH = ENV(GCC49_ARM_PREFIX)objcopy -*_GCC49_ARM_ARCHCC_FLAGS = -mthumb -*_GCC49_ARM_PLATFORM_FLAGS = -march=armv7-a - *_GCC49_ARM_ASLCC_FLAGS = DEF(GCC49_ASLCC_FLAGS) *_GCC49_ARM_ASLDLINK_FLAGS = DEF(GCC49_ARM_ASLDLINK_FLAGS) *_GCC49_ARM_ASM_FLAGS = DEF(GCC49_ARM_ASM_FLAGS) @@ -2220,9 +2214,9 @@ RELEASE_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -Os -Wno-unused-but-s *_GCC49_ARM_DLINK2_FLAGS = DEF(GCC49_ARM_DLINK2_FLAGS) *_GCC49_ARM_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC49_ARM_PLATFORM_FLAGS = -march=armv7-a -*_GCC49_ARM_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC49_ARM_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC49_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) -*_GCC49_ARM_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC49_ARM_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC49_ARM_CC_XIPFLAGS = DEF(GCC49_ARM_CC_XIPFLAGS) DEBUG_GCC49_ARM_CC_FLAGS = DEF(GCC49_ARM_CC_FLAGS) -O0 @@ -2249,9 +2243,9 @@ RELEASE_GCC49_ARM_CC_FLAGS = DEF(GCC49_ARM_CC_FLAGS) -Wno-unused-but-set-v *_GCC49_AARCH64_DLINK2_FLAGS = DEF(GCC49_AARCH64_DLINK2_FLAGS) *_GCC49_AARCH64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC49_AARCH64_PLATFORM_FLAGS = -*_GCC49_AARCH64_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC49_AARCH64_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC49_AARCH64_RC_FLAGS = DEF(GCC_AARCH64_RC_FLAGS) -*_GCC49_AARCH64_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC49_AARCH64_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC49_AARCH64_CC_XIPFLAGS = DEF(GCC49_AARCH64_CC_XIPFLAGS) DEBUG_GCC49_AARCH64_CC_FLAGS = DEF(GCC49_AARCH64_CC_FLAGS) -O0 @@ -2365,16 +2359,15 @@ RELEASE_GCC5_X64_DLINK_FLAGS = DEF(GCC5_X64_DLINK_FLAGS) -flto -Os *_GCC5_ARM_ASLPP_PATH = ENV(GCC5_ARM_PREFIX)gcc *_GCC5_ARM_RC_PATH = ENV(GCC5_ARM_PREFIX)objcopy -*_GCC5_ARM_ARCHCC_FLAGS = -mthumb *_GCC5_ARM_ASLCC_FLAGS = DEF(GCC5_ASLCC_FLAGS) *_GCC5_ARM_ASLDLINK_FLAGS = DEF(GCC5_ARM_ASLDLINK_FLAGS) *_GCC5_ARM_ASM_FLAGS = DEF(GCC5_ARM_ASM_FLAGS) *_GCC5_ARM_DLINK2_FLAGS = DEF(GCC5_ARM_DLINK2_FLAGS) *_GCC5_ARM_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC5_ARM_PLATFORM_FLAGS = -march=armv7-a -*_GCC5_ARM_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC5_ARM_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC5_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) -*_GCC5_ARM_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC5_ARM_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC5_ARM_CC_XIPFLAGS = DEF(GCC5_ARM_CC_XIPFLAGS) DEBUG_GCC5_ARM_CC_FLAGS = DEF(GCC5_ARM_CC_FLAGS) -flto -Wno-unused-but-set-variable -Wno-unused-const-variable @@ -2406,9 +2399,9 @@ RELEASE_GCC5_ARM_DLINK_FLAGS = DEF(GCC5_ARM_DLINK_FLAGS) -flto -Os -L$(WORKS *_GCC5_AARCH64_DLINK2_FLAGS = DEF(GCC5_AARCH64_DLINK2_FLAGS) *_GCC5_AARCH64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) *_GCC5_AARCH64_PLATFORM_FLAGS = -*_GCC5_AARCH64_PP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) +*_GCC5_AARCH64_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC5_AARCH64_RC_FLAGS = DEF(GCC_AARCH64_RC_FLAGS) -*_GCC5_AARCH64_VFRPP_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) +*_GCC5_AARCH64_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) *_GCC5_AARCH64_CC_XIPFLAGS = DEF(GCC5_AARCH64_CC_XIPFLAGS) DEBUG_GCC5_AARCH64_CC_FLAGS = DEF(GCC5_AARCH64_CC_FLAGS) -flto -Wno-unused-but-set-variable -Wno-unused-const-variable @@ -2529,19 +2522,19 @@ DEFINE CLANG35_AARCH64_CC_FLAGS = DEF(GCC_AARCH64_CC_FLAGS) DEF(CLANG35_AARCH64 *_CLANG35_ARM_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) *_CLANG35_ARM_ASLDLINK_FLAGS = DEF(CLANG35_ARM_TARGET) DEF(GCC_ARM_ASLDLINK_FLAGS) -*_CLANG35_ARM_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG35_ARM_TARGET) $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) -Qunused-arguments +*_CLANG35_ARM_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG35_ARM_TARGET) $(PLATFORM_FLAGS) -Qunused-arguments *_CLANG35_ARM_DLINK_FLAGS = DEF(CLANG35_ARM_TARGET) DEF(GCC_ARM_DLINK_FLAGS) *_CLANG35_ARM_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 *_CLANG35_ARM_PLATFORM_FLAGS = -march=armv7-a -mkernel -Qunused-arguments -*_CLANG35_ARM_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG35_ARM_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG35_ARM_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG35_ARM_TARGET) $(PLATFORM_FLAGS) *_CLANG35_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) -*_CLANG35_ARM_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG35_ARM_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG35_ARM_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG35_ARM_TARGET) $(PLATFORM_FLAGS) *_CLANG35_ARM_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG35_ARM_TARGET) *_CLANG35_ARM_CC_XIPFLAGS = DEF(GCC_ARM_CC_XIPFLAGS) - DEBUG_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O1 -RELEASE_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -Oz - NOOPT_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O0 + DEBUG_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -O1 +RELEASE_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -Oz + NOOPT_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -O0 ################## # CLANG35 AARCH64 definitions @@ -2551,20 +2544,20 @@ RELEASE_CLANG35_ARM_CC_FLAGS = DEF(CLANG35_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(P *_CLANG35_AARCH64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) *_CLANG35_AARCH64_ASLDLINK_FLAGS = DEF(CLANG35_AARCH64_TARGET) DEF(GCC_AARCH64_ASLDLINK_FLAGS) -*_CLANG35_AARCH64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) -Qunused-arguments +*_CLANG35_AARCH64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(PLATFORM_FLAGS) -Qunused-arguments *_CLANG35_AARCH64_DLINK_FLAGS = DEF(CLANG35_AARCH64_TARGET) DEF(GCC_AARCH64_DLINK_FLAGS) -z common-page-size=0x1000 *_CLANG35_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_CLANG35_AARCH64_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x228 *_CLANG35_AARCH64_PLATFORM_FLAGS = -*_CLANG35_AARCH64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG35_AARCH64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(PLATFORM_FLAGS) *_CLANG35_AARCH64_RC_FLAGS = DEF(GCC_AARCH64_RC_FLAGS) -*_CLANG35_AARCH64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG35_AARCH64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG35_AARCH64_TARGET) $(PLATFORM_FLAGS) *_CLANG35_AARCH64_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG35_AARCH64_TARGET) *_CLANG35_AARCH64_CC_XIPFLAGS = DEF(GCC_AARCH64_CC_XIPFLAGS) - DEBUG_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O1 -RELEASE_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -Oz - NOOPT_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O0 + DEBUG_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -O1 +RELEASE_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -Oz + NOOPT_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -O0 #################################################################################### # @@ -2692,20 +2685,20 @@ DEFINE CLANG38_ARM_DLINK_FLAGS = DEF(CLANG38_ARM_TARGET) DEF(GCC_ARM_DLINK_FLA *_CLANG38_ARM_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -fno-lto *_CLANG38_ARM_ASLDLINK_FLAGS = DEF(CLANG38_ARM_TARGET) DEF(GCC_ARM_ASLDLINK_FLAGS) -*_CLANG38_ARM_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG38_ARM_TARGET) $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) -Qunused-arguments +*_CLANG38_ARM_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG38_ARM_TARGET) $(PLATFORM_FLAGS) -Qunused-arguments *_CLANG38_ARM_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 *_CLANG38_ARM_PLATFORM_FLAGS = -march=armv7-a -*_CLANG38_ARM_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG38_ARM_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG38_ARM_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG38_ARM_TARGET) $(PLATFORM_FLAGS) *_CLANG38_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) -*_CLANG38_ARM_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_ARM_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG38_ARM_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_ARM_TARGET) $(PLATFORM_FLAGS) *_CLANG38_ARM_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG38_ARM_TARGET) *_CLANG38_ARM_CC_XIPFLAGS = DEF(GCC_ARM_CC_XIPFLAGS) - DEBUG_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -flto -O1 + DEBUG_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -flto -O1 DEBUG_CLANG38_ARM_DLINK_FLAGS = DEF(CLANG38_ARM_DLINK_FLAGS) -flto -Wl,-O1 -L$(WORKSPACE)/ArmPkg/Library/GccLto -llto-arm -Wl,-plugin-opt=-pass-through=-llto-arm - NOOPT_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O0 + NOOPT_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -O0 NOOPT_CLANG38_ARM_DLINK_FLAGS = DEF(CLANG38_ARM_DLINK_FLAGS) -RELEASE_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -flto -O3 +RELEASE_CLANG38_ARM_CC_FLAGS = DEF(CLANG38_ARM_CC_FLAGS) $(PLATFORM_FLAGS) -flto -O3 RELEASE_CLANG38_ARM_DLINK_FLAGS = DEF(CLANG38_ARM_DLINK_FLAGS) -flto -Wl,-O3 -L$(WORKSPACE)/ArmPkg/Library/GccLto -llto-arm -Wl,-plugin-opt=-pass-through=-llto-arm ################## @@ -2736,22 +2729,22 @@ DEFINE CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_TARGET) DEF(GCC_AARCH6 *_CLANG38_AARCH64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -fno-lto *_CLANG38_AARCH64_ASLDLINK_FLAGS = DEF(CLANG38_AARCH64_TARGET) DEF(GCC_AARCH64_ASLDLINK_FLAGS) -*_CLANG38_AARCH64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(ARCHASM_FLAGS) $(PLATFORM_FLAGS) -Qunused-arguments +*_CLANG38_AARCH64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(PLATFORM_FLAGS) -Qunused-arguments *_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_TARGET) DEF(GCC_AARCH64_DLINK_FLAGS) -z common-page-size=0x1000 *_CLANG38_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_CLANG38_AARCH64_DLINK2_FLAGS = DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0x228 *_CLANG38_AARCH64_PLATFORM_FLAGS = -*_CLANG38_AARCH64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG38_AARCH64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(PLATFORM_FLAGS) *_CLANG38_AARCH64_RC_FLAGS = DEF(GCC_AARCH64_RC_FLAGS) -*_CLANG38_AARCH64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) +*_CLANG38_AARCH64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_AARCH64_TARGET) $(PLATFORM_FLAGS) *_CLANG38_AARCH64_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG38_AARCH64_TARGET) *_CLANG38_AARCH64_CC_XIPFLAGS = DEF(GCC_AARCH64_CC_XIPFLAGS) - DEBUG_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -flto -O1 + DEBUG_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -flto -O1 DEBUG_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_DLINK_FLAGS) -flto -Wl,-O1 -L$(WORKSPACE)/ArmPkg/Library/GccLto -llto-aarch64 -Wl,-plugin-opt=-pass-through=-llto-aarch64 - NOOPT_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -O0 + NOOPT_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -O0 NOOPT_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_DLINK_FLAGS) -RELEASE_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) -flto -O3 +RELEASE_CLANG38_AARCH64_CC_FLAGS = DEF(CLANG38_AARCH64_CC_FLAGS) $(PLATFORM_FLAGS) -flto -O3 RELEASE_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_DLINK_FLAGS) -flto -Wl,-O3 -L$(WORKSPACE)/ArmPkg/Library/GccLto -llto-aarch64 -Wl,-plugin-opt=-pass-through=-llto-aarch64 #################################################################################### From f96c4990326266b0a1f0a85ace793d4ddec072b6 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 5 Jan 2023 16:43:54 +0100 Subject: [PATCH 0493/1529] BaseTools/tools_def ARM: Make choice for soft float ABI explicit Recent GCC for ARM will complain when selecting the hard float ABI without specifying the FPU implementation, even when just running the preprocessor. This all happens under the hood, and we never bothered in the past, given that we don't emit floating point code anyway. However, to placate newer compilers, make it explicit that the floating point ABI is always the softfloat one, by moving the -msoft-float compiler option to PLATFORM_FLAGS. Signed-off-by: Ard Biesheuvel --- BaseTools/Conf/tools_def.template | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index fe8d5a8ea5..9bf771385e 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1850,7 +1850,7 @@ NOOPT_*_*_OBJCOPY_ADDDEBUGFLAG = --add-gnu-debuglink=$(DEBUG_DIR)/$(MODULE_N *_*_*_DTC_PATH = DEF(DTC_BIN) DEFINE GCC_ALL_CC_FLAGS = -g -Os -fshort-wchar -fno-builtin -fno-strict-aliasing -Wall -Werror -Wno-array-bounds -include AutoGen.h -fno-common -DEFINE GCC_ARM_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -mabi=aapcs -fno-short-enums -funsigned-char -ffunction-sections -fdata-sections -fomit-frame-pointer -Wno-address -mthumb -mfloat-abi=soft -fno-pic -fno-pie +DEFINE GCC_ARM_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -mabi=aapcs -fno-short-enums -funsigned-char -ffunction-sections -fdata-sections -fomit-frame-pointer -Wno-address -mthumb -fno-pic -fno-pie DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mabi=lp64d -fno-asynchronous-unwind-tables -fno-plt -Wno-address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections DEFINE GCC_ARM_CC_XIPFLAGS = -mno-unaligned-access DEFINE GCC_AARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-endian -fno-short-enums -fverbose-asm -funsigned-char -ffunction-sections -fdata-sections -Wno-address -fno-asynchronous-unwind-tables -fno-unwind-tables -fno-pic -fno-pie -ffixed-x18 @@ -2364,7 +2364,7 @@ RELEASE_GCC5_X64_DLINK_FLAGS = DEF(GCC5_X64_DLINK_FLAGS) -flto -Os *_GCC5_ARM_ASM_FLAGS = DEF(GCC5_ARM_ASM_FLAGS) *_GCC5_ARM_DLINK2_FLAGS = DEF(GCC5_ARM_DLINK2_FLAGS) *_GCC5_ARM_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS) -*_GCC5_ARM_PLATFORM_FLAGS = -march=armv7-a +*_GCC5_ARM_PLATFORM_FLAGS = -march=armv7-a -mfloat-abi=soft *_GCC5_ARM_PP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_PP_FLAGS) *_GCC5_ARM_RC_FLAGS = DEF(GCC_ARM_RC_FLAGS) *_GCC5_ARM_VFRPP_FLAGS = $(PLATFORM_FLAGS) DEF(GCC_VFRPP_FLAGS) From e073795f8f7765f23b528cbcb165d2206a8a83b6 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 5 Jan 2023 16:53:33 +0100 Subject: [PATCH 0494/1529] BaseTools/tools_def CLANG38: Suppress unaligned access warning Even though the presence of the 'packed' pragma should be a strong hint that the misaligned placement of a GUID in a struct is intentional, recent Clang versions will object nonetheless, and break the build due to the presence of such GUIDs in the FPDT ACPI tables. This is obviously not something we can fix in the code, so let's just suppress the warning/error instead. Signed-off-by: Ard Biesheuvel --- BaseTools/Conf/tools_def.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 9bf771385e..380d458733 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2580,7 +2580,7 @@ DEFINE CLANG38_X64_PREFIX = ENV(CLANG38_BIN) DEFINE CLANG38_IA32_TARGET = -target i686-pc-linux-gnu DEFINE CLANG38_X64_TARGET = -target x86_64-pc-linux-gnu -DEFINE CLANG38_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-tautological-compare -Wno-tautological-constant-out-of-range-compare -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-unused-but-set-variable -Wno-unused-const-variable +DEFINE CLANG38_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-tautological-compare -Wno-tautological-constant-out-of-range-compare -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-unused-but-set-variable -Wno-unused-const-variable -Wno-unaligned-access DEFINE CLANG38_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANG38_WARNING_OVERRIDES) -fno-stack-protector -mms-bitfields -Wno-address -Wno-shift-negative-value -Wno-unknown-pragmas -Wno-incompatible-library-redeclaration -fno-asynchronous-unwind-tables -mno-sse -mno-mmx -msoft-float -mno-implicit-float -ftrap-function=undefined_behavior_has_been_optimized_away_by_clang -funsigned-char -fno-ms-extensions -Wno-null-dereference ########################### From 7ad9650e145552263252a639e3634fc57eab78f0 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 17 Jan 2023 13:16:25 +0100 Subject: [PATCH 0495/1529] OvmfPkg/PlatformInitLib: Add PlatformScanE820 and GetFirstNonAddressCB First step replacing the PlatformScanOrAdd64BitE820Ram() function. Add a PlatformScanE820() function which loops over the e280 entries from FwCfg and calls a callback for each of them. Add a GetFirstNonAddressCB() function which will store the first free address (right after the last RAM block) in PlatformInfoHob->FirstNonAddress. This replaces calls to PlatformScanOrAdd64BitE820Ram() with non-NULL MaxAddress. Write any actions done (setting FirstNonAddress) to the firmware log with INFO loglevel. Also drop local FirstNonAddress variables and use PlatformInfoHob->FirstNonAddress instead everywhere. Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 116 ++++++++++++++++---- 1 file changed, 93 insertions(+), 23 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 882805269b..fdfe134247 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -251,6 +251,84 @@ PlatformScanOrAdd64BitE820Ram ( return EFI_SUCCESS; } +typedef VOID (*E820_SCAN_CALLBACK) ( + EFI_E820_ENTRY64 *E820Entry, + EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ); + +/** + Store first address not used by e820 RAM entries in + PlatformInfoHob->FirstNonAddress +**/ +STATIC +VOID +PlatformGetFirstNonAddressCB ( + IN EFI_E820_ENTRY64 *E820Entry, + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + UINT64 Candidate; + + if (E820Entry->Type != EfiAcpiAddressRangeMemory) { + return; + } + + Candidate = E820Entry->BaseAddr + E820Entry->Length; + if (PlatformInfoHob->FirstNonAddress < Candidate) { + DEBUG ((DEBUG_INFO, "%a: FirstNonAddress=0x%Lx\n", __FUNCTION__, Candidate)); + PlatformInfoHob->FirstNonAddress = Candidate; + } +} + +/** + Iterate over the entries in QEMU's fw_cfg E820 RAM map, call the + passed callback for each entry. + + @param[in] Callback The callback function to be called. + + @param[in out] PlatformInfoHob PlatformInfo struct which is passed + through to the callback. + + @retval EFI_SUCCESS The fw_cfg E820 RAM map was found and processed. + + @retval EFI_PROTOCOL_ERROR The RAM map was found, but its size wasn't a + whole multiple of sizeof(EFI_E820_ENTRY64). No + RAM entry was processed. + + @return Error codes from QemuFwCfgFindFile(). No RAM + entry was processed. +**/ +STATIC +EFI_STATUS +PlatformScanE820 ( + IN E820_SCAN_CALLBACK Callback, + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + EFI_STATUS Status; + FIRMWARE_CONFIG_ITEM FwCfgItem; + UINTN FwCfgSize; + EFI_E820_ENTRY64 E820Entry; + UINTN Processed; + + Status = QemuFwCfgFindFile ("etc/e820", &FwCfgItem, &FwCfgSize); + if (EFI_ERROR (Status)) { + return Status; + } + + if (FwCfgSize % sizeof E820Entry != 0) { + return EFI_PROTOCOL_ERROR; + } + + QemuFwCfgSelectItem (FwCfgItem); + for (Processed = 0; Processed < FwCfgSize; Processed += sizeof E820Entry) { + QemuFwCfgReadBytes (sizeof E820Entry, &E820Entry); + Callback (&E820Entry, PlatformInfoHob); + } + + return EFI_SUCCESS; +} + /** Returns PVH memmap @@ -384,23 +462,17 @@ PlatformGetSystemMemorySizeAbove4gb ( Return the highest address that DXE could possibly use, plus one. **/ STATIC -UINT64 +VOID PlatformGetFirstNonAddress ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - UINT64 FirstNonAddress; UINT32 FwCfgPciMmio64Mb; EFI_STATUS Status; FIRMWARE_CONFIG_ITEM FwCfgItem; UINTN FwCfgSize; UINT64 HotPlugMemoryEnd; - // - // set FirstNonAddress to suppress incorrect compiler/analyzer warnings - // - FirstNonAddress = 0; - // // If QEMU presents an E820 map, then get the highest exclusive >=4GB RAM // address from it. This can express an address >= 4GB+1TB. @@ -408,9 +480,10 @@ PlatformGetFirstNonAddress ( // Otherwise, get the flat size of the memory above 4GB from the CMOS (which // can only express a size smaller than 1TB), and add it to 4GB. // - Status = PlatformScanOrAdd64BitE820Ram (FALSE, NULL, &FirstNonAddress); + PlatformInfoHob->FirstNonAddress = BASE_4GB; + Status = PlatformScanE820 (PlatformGetFirstNonAddressCB, PlatformInfoHob); if (EFI_ERROR (Status)) { - FirstNonAddress = BASE_4GB + PlatformGetSystemMemorySizeAbove4gb (); + PlatformInfoHob->FirstNonAddress = BASE_4GB + PlatformGetSystemMemorySizeAbove4gb (); } // @@ -420,7 +493,7 @@ PlatformGetFirstNonAddress ( // #ifdef MDE_CPU_IA32 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { - return FirstNonAddress; + return; } #endif @@ -473,7 +546,7 @@ PlatformGetFirstNonAddress ( // determines the highest address plus one. The memory hotplug area (see // below) plays no role for the firmware in this case. // - return FirstNonAddress; + return; } // @@ -497,15 +570,15 @@ PlatformGetFirstNonAddress ( HotPlugMemoryEnd )); - ASSERT (HotPlugMemoryEnd >= FirstNonAddress); - FirstNonAddress = HotPlugMemoryEnd; + ASSERT (HotPlugMemoryEnd >= PlatformInfoHob->FirstNonAddress); + PlatformInfoHob->FirstNonAddress = HotPlugMemoryEnd; } // // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so // that the host can map it with 1GB hugepages. Follow suit. // - PlatformInfoHob->PcdPciMmio64Base = ALIGN_VALUE (FirstNonAddress, (UINT64)SIZE_1GB); + PlatformInfoHob->PcdPciMmio64Base = ALIGN_VALUE (PlatformInfoHob->FirstNonAddress, (UINT64)SIZE_1GB); PlatformInfoHob->PcdPciMmio64Size = ALIGN_VALUE (PlatformInfoHob->PcdPciMmio64Size, (UINT64)SIZE_1GB); // @@ -519,8 +592,8 @@ PlatformGetFirstNonAddress ( // // The useful address space ends with the 64-bit PCI host aperture. // - FirstNonAddress = PlatformInfoHob->PcdPciMmio64Base + PlatformInfoHob->PcdPciMmio64Size; - return FirstNonAddress; + PlatformInfoHob->FirstNonAddress = PlatformInfoHob->PcdPciMmio64Base + PlatformInfoHob->PcdPciMmio64Size; + return; } /* @@ -781,7 +854,6 @@ PlatformAddressWidthInitialization ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - UINT64 FirstNonAddress; UINT8 PhysMemAddressWidth; EFI_STATUS Status; @@ -794,7 +866,7 @@ PlatformAddressWidthInitialization ( // First scan host-provided hardware information to assess if the address // space is already known. If so, guest must use those values. // - Status = PlatformScanHostProvided64BitPciMmioEnd (&FirstNonAddress); + Status = PlatformScanHostProvided64BitPciMmioEnd (&PlatformInfoHob->FirstNonAddress); if (EFI_ERROR (Status)) { // @@ -806,13 +878,12 @@ PlatformAddressWidthInitialization ( // The DXL IPL keys off of the physical address bits advertized in the CPU // HOB. To conserve memory, we calculate the minimum address width here. // - FirstNonAddress = PlatformGetFirstNonAddress (PlatformInfoHob); + PlatformGetFirstNonAddress (PlatformInfoHob); } PlatformAddressWidthFromCpuid (PlatformInfoHob, TRUE); if (PlatformInfoHob->PhysMemAddressWidth != 0) { // physical address width is known - PlatformInfoHob->FirstNonAddress = FirstNonAddress; PlatformDynamicMmioWindow (PlatformInfoHob); return; } @@ -823,13 +894,13 @@ PlatformAddressWidthInitialization ( // -> try be conservstibe to stay below the guaranteed minimum of // 36 phys bits (aka 64 GB). // - PhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress); + PhysMemAddressWidth = (UINT8)HighBitSet64 (PlatformInfoHob->FirstNonAddress); // // If FirstNonAddress is not an integral power of two, then we need an // additional bit. // - if ((FirstNonAddress & (FirstNonAddress - 1)) != 0) { + if ((PlatformInfoHob->FirstNonAddress & (PlatformInfoHob->FirstNonAddress - 1)) != 0) { ++PhysMemAddressWidth; } @@ -857,7 +928,6 @@ PlatformAddressWidthInitialization ( ASSERT (PhysMemAddressWidth <= 48); #endif - PlatformInfoHob->FirstNonAddress = FirstNonAddress; PlatformInfoHob->PhysMemAddressWidth = PhysMemAddressWidth; } From 3726bc68ca8d839b2419552da60746b62d193557 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 17 Jan 2023 13:16:26 +0100 Subject: [PATCH 0496/1529] OvmfPkg/PlatformInitLib: Add PlatformGetLowMemoryCB Add PlatformGetLowMemoryCB() callback function for use with PlatformScanE820(). It stores the low memory size in PlatformInfoHob->LowMemory. This replaces calls to PlatformScanOrAdd64BitE820Ram() with non-NULL LowMemory. Write any actions done (setting LowMemory) to the firmware log with INFO loglevel. Also change PlatformGetSystemMemorySizeBelow4gb() to likewise set PlatformInfoHob->LowMemory instead of returning the value. Update all Callers to the new convention. Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek --- OvmfPkg/Include/Library/PlatformInitLib.h | 3 +- OvmfPkg/Library/PeilessStartupLib/Hob.c | 3 +- .../PeilessStartupLib/PeilessStartup.c | 7 +- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 70 +++++++++++++------ OvmfPkg/Library/PlatformInitLib/Platform.c | 7 +- OvmfPkg/PlatformPei/MemDetect.c | 3 +- 6 files changed, 60 insertions(+), 33 deletions(-) diff --git a/OvmfPkg/Include/Library/PlatformInitLib.h b/OvmfPkg/Include/Library/PlatformInitLib.h index bf6f90a576..051b311911 100644 --- a/OvmfPkg/Include/Library/PlatformInitLib.h +++ b/OvmfPkg/Include/Library/PlatformInitLib.h @@ -26,6 +26,7 @@ typedef struct { BOOLEAN Q35SmramAtDefaultSmbase; UINT16 Q35TsegMbytes; + UINT32 LowMemory; UINT64 FirstNonAddress; UINT8 PhysMemAddressWidth; UINT32 Uc32Base; @@ -144,7 +145,7 @@ PlatformQemuUc32BaseInitialization ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); -UINT32 +VOID EFIAPI PlatformGetSystemMemorySizeBelow4gb ( IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob diff --git a/OvmfPkg/Library/PeilessStartupLib/Hob.c b/OvmfPkg/Library/PeilessStartupLib/Hob.c index 630ce445eb..318b74c95d 100644 --- a/OvmfPkg/Library/PeilessStartupLib/Hob.c +++ b/OvmfPkg/Library/PeilessStartupLib/Hob.c @@ -42,7 +42,8 @@ ConstructSecHobList ( ZeroMem (&PlatformInfoHob, sizeof (PlatformInfoHob)); PlatformInfoHob.HostBridgeDevId = PciRead16 (OVMF_HOSTBRIDGE_DID); - LowMemorySize = PlatformGetSystemMemorySizeBelow4gb (&PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (&PlatformInfoHob); + LowMemorySize = PlatformInfoHob.LowMemory; ASSERT (LowMemorySize != 0); LowMemoryStart = FixedPcdGet32 (PcdOvmfDxeMemFvBase) + FixedPcdGet32 (PcdOvmfDxeMemFvSize); LowMemorySize -= LowMemoryStart; diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c index 380e715972..928120d183 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c @@ -41,8 +41,7 @@ InitializePlatform ( EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - UINT32 LowerMemorySize; - VOID *VariableStore; + VOID *VariableStore; DEBUG ((DEBUG_INFO, "InitializePlatform in Pei-less boot\n")); PlatformDebugDumpCmos (); @@ -70,14 +69,14 @@ InitializePlatform ( PlatformInfoHob->PcdCpuBootLogicalProcessorNumber )); - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); PlatformQemuUc32BaseInitialization (PlatformInfoHob); DEBUG (( DEBUG_INFO, "Uc32Base = 0x%x, Uc32Size = 0x%x, LowerMemorySize = 0x%x\n", PlatformInfoHob->Uc32Base, PlatformInfoHob->Uc32Size, - LowerMemorySize + PlatformInfoHob->LowMemory )); VariableStore = PlatformReserveEmuVariableNvStore (); diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index fdfe134247..57feeb6dab 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -51,18 +51,16 @@ PlatformQemuUc32BaseInitialization ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - UINT32 LowerMemorySize; - if (PlatformInfoHob->HostBridgeDevId == 0xffff /* microvm */) { return; } if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); ASSERT (PcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32); - ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= LowerMemorySize); + ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= PlatformInfoHob->LowMemory); - if (LowerMemorySize <= BASE_2GB) { + if (PlatformInfoHob->LowMemory <= BASE_2GB) { // Newer qemu with gigabyte aligned memory, // 32-bit pci mmio window is 2G -> 4G then. PlatformInfoHob->Uc32Base = BASE_2GB; @@ -92,8 +90,8 @@ PlatformQemuUc32BaseInitialization ( // variable MTRR suffices by truncating the size to a whole power of two, // while keeping the end affixed to 4GB. This will round the base up. // - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); - PlatformInfoHob->Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - LowerMemorySize)); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformInfoHob->Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - PlatformInfoHob->LowMemory)); PlatformInfoHob->Uc32Base = (UINT32)(SIZE_4GB - PlatformInfoHob->Uc32Size); // // Assuming that LowerMemorySize is at least 1 byte, Uc32Size is at most 2GB. @@ -101,13 +99,13 @@ PlatformQemuUc32BaseInitialization ( // ASSERT (PlatformInfoHob->Uc32Base >= BASE_2GB); - if (PlatformInfoHob->Uc32Base != LowerMemorySize) { + if (PlatformInfoHob->Uc32Base != PlatformInfoHob->LowMemory) { DEBUG (( DEBUG_VERBOSE, "%a: rounded UC32 base from 0x%x up to 0x%x, for " "an UC32 size of 0x%x\n", __FUNCTION__, - LowerMemorySize, + PlatformInfoHob->LowMemory, PlatformInfoHob->Uc32Base, PlatformInfoHob->Uc32Size )); @@ -280,6 +278,34 @@ PlatformGetFirstNonAddressCB ( } } +/** + Store the low (below 4G) memory size in + PlatformInfoHob->LowMemory +**/ +STATIC +VOID +PlatformGetLowMemoryCB ( + IN EFI_E820_ENTRY64 *E820Entry, + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + UINT64 Candidate; + + if (E820Entry->Type != EfiAcpiAddressRangeMemory) { + return; + } + + Candidate = E820Entry->BaseAddr + E820Entry->Length; + if (Candidate >= BASE_4GB) { + return; + } + + if (PlatformInfoHob->LowMemory < Candidate) { + DEBUG ((DEBUG_INFO, "%a: LowMemory=0x%Lx\n", __FUNCTION__, Candidate)); + PlatformInfoHob->LowMemory = (UINT32)Candidate; + } +} + /** Iterate over the entries in QEMU's fw_cfg E820 RAM map, call the passed callback for each entry. @@ -396,14 +422,13 @@ GetHighestSystemMemoryAddressFromPvhMemmap ( return HighestAddress; } -UINT32 +VOID EFIAPI PlatformGetSystemMemorySizeBelow4gb ( IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { EFI_STATUS Status; - UINT64 LowerMemorySize = 0; UINT8 Cmos0x34; UINT8 Cmos0x35; @@ -411,12 +436,13 @@ PlatformGetSystemMemorySizeBelow4gb ( (CcProbe () != CcGuestTypeIntelTdx)) { // Get the information from PVH memmap - return (UINT32)GetHighestSystemMemoryAddressFromPvhMemmap (TRUE); + PlatformInfoHob->LowMemory = (UINT32)GetHighestSystemMemoryAddressFromPvhMemmap (TRUE); + return; } - Status = PlatformScanOrAdd64BitE820Ram (FALSE, &LowerMemorySize, NULL); - if ((Status == EFI_SUCCESS) && (LowerMemorySize > 0)) { - return (UINT32)LowerMemorySize; + Status = PlatformScanE820 (PlatformGetLowMemoryCB, PlatformInfoHob); + if (!EFI_ERROR (Status) && (PlatformInfoHob->LowMemory > 0)) { + return; } // @@ -431,7 +457,7 @@ PlatformGetSystemMemorySizeBelow4gb ( Cmos0x34 = (UINT8)PlatformCmosRead8 (0x34); Cmos0x35 = (UINT8)PlatformCmosRead8 (0x35); - return (UINT32)(((UINTN)((Cmos0x35 << 8) + Cmos0x34) << 16) + SIZE_16MB); + PlatformInfoHob->LowMemory = (UINT32)(((UINTN)((Cmos0x35 << 8) + Cmos0x34) << 16) + SIZE_16MB); } STATIC @@ -967,7 +993,6 @@ PlatformQemuInitializeRam ( IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob ) { - UINT64 LowerMemorySize; UINT64 UpperMemorySize; MTRR_SETTINGS MtrrSettings; EFI_STATUS Status; @@ -977,7 +1002,7 @@ PlatformQemuInitializeRam ( // // Determine total memory size available // - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); if (PlatformInfoHob->BootMode == BOOT_ON_S3_RESUME) { // @@ -1011,14 +1036,14 @@ PlatformQemuInitializeRam ( UINT32 TsegSize; TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB; - PlatformAddMemoryRangeHob (BASE_1MB, LowerMemorySize - TsegSize); + PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory - TsegSize); PlatformAddReservedMemoryBaseSizeHob ( - LowerMemorySize - TsegSize, + PlatformInfoHob->LowMemory - TsegSize, TsegSize, TRUE ); } else { - PlatformAddMemoryRangeHob (BASE_1MB, LowerMemorySize); + PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory); } // @@ -1196,9 +1221,10 @@ PlatformQemuInitializeRamForS3 ( // Make sure the TSEG area that we reported as a reserved memory resource // cannot be used for reserved memory allocations. // + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB; BuildMemoryAllocationHob ( - PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob) - TsegSize, + PlatformInfoHob->LowMemory - TsegSize, TsegSize, EfiReservedMemoryType ); diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 3e13c5d4b3..9ab0342fd8 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -128,7 +128,6 @@ PlatformMemMapInitialization ( { UINT64 PciIoBase; UINT64 PciIoSize; - UINT32 TopOfLowRam; UINT64 PciExBarBase; UINT32 PciBase; UINT32 PciSize; @@ -150,7 +149,7 @@ PlatformMemMapInitialization ( return; } - TopOfLowRam = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); PciExBarBase = 0; if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { // @@ -158,11 +157,11 @@ PlatformMemMapInitialization ( // the base of the 32-bit PCI host aperture. // PciExBarBase = PcdGet64 (PcdPciExpressBaseAddress); - ASSERT (TopOfLowRam <= PciExBarBase); + ASSERT (PlatformInfoHob->LowMemory <= PciExBarBase); ASSERT (PciExBarBase <= MAX_UINT32 - SIZE_256MB); PciBase = (UINT32)(PciExBarBase + SIZE_256MB); } else { - ASSERT (TopOfLowRam <= PlatformInfoHob->Uc32Base); + ASSERT (PlatformInfoHob->LowMemory <= PlatformInfoHob->Uc32Base); PciBase = PlatformInfoHob->Uc32Base; } diff --git a/OvmfPkg/PlatformPei/MemDetect.c b/OvmfPkg/PlatformPei/MemDetect.c index 3d8375320d..41d186986b 100644 --- a/OvmfPkg/PlatformPei/MemDetect.c +++ b/OvmfPkg/PlatformPei/MemDetect.c @@ -271,7 +271,8 @@ PublishPeiMemory ( UINT32 S3AcpiReservedMemoryBase; UINT32 S3AcpiReservedMemorySize; - LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + LowerMemorySize = PlatformInfoHob->LowMemory; if (PlatformInfoHob->SmmSmramRequire) { // // TSEG is chipped from the end of low RAM From 4f7372514e703e1f042305e8df204f76419435cd Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 17 Jan 2023 13:16:27 +0100 Subject: [PATCH 0497/1529] OvmfPkg/PlatformInitLib: Add PlatformAddHobCB Add PlatformAddHobCB() callback function for use with PlatformScanE820(). It adds HOBs for high memory and reservations (low memory is handled elsewhere because there are some special cases to consider). This replaces calls to PlatformScanOrAdd64BitE820Ram() with AddHighHobs = TRUE. Write any actions done (adding HOBs, skip unknown types) to the firmware log with INFO loglevel. Also remove PlatformScanOrAdd64BitE820Ram() which is not used any more. Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 186 +++++--------------- 1 file changed, 48 insertions(+), 138 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 57feeb6dab..c24105c329 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -112,143 +112,6 @@ PlatformQemuUc32BaseInitialization ( } } -/** - Iterate over the RAM entries in QEMU's fw_cfg E820 RAM map that start outside - of the 32-bit address range. - - Find the highest exclusive >=4GB RAM address, or produce memory resource - descriptor HOBs for RAM entries that start at or above 4GB. - - @param[out] MaxAddress If MaxAddress is NULL, then PlatformScanOrAdd64BitE820Ram() - produces memory resource descriptor HOBs for RAM - entries that start at or above 4GB. - - Otherwise, MaxAddress holds the highest exclusive - >=4GB RAM address on output. If QEMU's fw_cfg E820 - RAM map contains no RAM entry that starts outside of - the 32-bit address range, then MaxAddress is exactly - 4GB on output. - - @retval EFI_SUCCESS The fw_cfg E820 RAM map was found and processed. - - @retval EFI_PROTOCOL_ERROR The RAM map was found, but its size wasn't a - whole multiple of sizeof(EFI_E820_ENTRY64). No - RAM entry was processed. - - @return Error codes from QemuFwCfgFindFile(). No RAM - entry was processed. -**/ -STATIC -EFI_STATUS -PlatformScanOrAdd64BitE820Ram ( - IN BOOLEAN AddHighHob, - OUT UINT64 *LowMemory OPTIONAL, - OUT UINT64 *MaxAddress OPTIONAL - ) -{ - EFI_STATUS Status; - FIRMWARE_CONFIG_ITEM FwCfgItem; - UINTN FwCfgSize; - EFI_E820_ENTRY64 E820Entry; - UINTN Processed; - - Status = QemuFwCfgFindFile ("etc/e820", &FwCfgItem, &FwCfgSize); - if (EFI_ERROR (Status)) { - return Status; - } - - if (FwCfgSize % sizeof E820Entry != 0) { - return EFI_PROTOCOL_ERROR; - } - - if (LowMemory != NULL) { - *LowMemory = 0; - } - - if (MaxAddress != NULL) { - *MaxAddress = BASE_4GB; - } - - QemuFwCfgSelectItem (FwCfgItem); - for (Processed = 0; Processed < FwCfgSize; Processed += sizeof E820Entry) { - QemuFwCfgReadBytes (sizeof E820Entry, &E820Entry); - DEBUG (( - DEBUG_VERBOSE, - "%a: Base=0x%Lx Length=0x%Lx Type=%u\n", - __FUNCTION__, - E820Entry.BaseAddr, - E820Entry.Length, - E820Entry.Type - )); - if (E820Entry.Type == EfiAcpiAddressRangeMemory) { - if (AddHighHob && (E820Entry.BaseAddr >= BASE_4GB)) { - UINT64 Base; - UINT64 End; - - // - // Round up the start address, and round down the end address. - // - Base = ALIGN_VALUE (E820Entry.BaseAddr, (UINT64)EFI_PAGE_SIZE); - End = (E820Entry.BaseAddr + E820Entry.Length) & - ~(UINT64)EFI_PAGE_MASK; - if (Base < End) { - PlatformAddMemoryRangeHob (Base, End); - DEBUG (( - DEBUG_VERBOSE, - "%a: PlatformAddMemoryRangeHob [0x%Lx, 0x%Lx)\n", - __FUNCTION__, - Base, - End - )); - } - } - - if (MaxAddress || LowMemory) { - UINT64 Candidate; - - Candidate = E820Entry.BaseAddr + E820Entry.Length; - if (MaxAddress && (Candidate > *MaxAddress)) { - *MaxAddress = Candidate; - DEBUG (( - DEBUG_VERBOSE, - "%a: MaxAddress=0x%Lx\n", - __FUNCTION__, - *MaxAddress - )); - } - - if (LowMemory && (Candidate > *LowMemory) && (Candidate < BASE_4GB)) { - *LowMemory = Candidate; - DEBUG (( - DEBUG_VERBOSE, - "%a: LowMemory=0x%Lx\n", - __FUNCTION__, - *LowMemory - )); - } - } - } else if (E820Entry.Type == EfiAcpiAddressRangeReserved) { - if (AddHighHob) { - DEBUG (( - DEBUG_INFO, - "%a: Reserved: Base=0x%Lx Length=0x%Lx\n", - __FUNCTION__, - E820Entry.BaseAddr, - E820Entry.Length - )); - BuildResourceDescriptorHob ( - EFI_RESOURCE_MEMORY_RESERVED, - 0, - E820Entry.BaseAddr, - E820Entry.Length - ); - } - } - } - - return EFI_SUCCESS; -} - typedef VOID (*E820_SCAN_CALLBACK) ( EFI_E820_ENTRY64 *E820Entry, EFI_HOB_PLATFORM_INFO *PlatformInfoHob @@ -306,6 +169,53 @@ PlatformGetLowMemoryCB ( } } +/** + Create HOBs for reservations and RAM (except low memory). +**/ +STATIC +VOID +PlatformAddHobCB ( + IN EFI_E820_ENTRY64 *E820Entry, + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + UINT64 Base, End; + + Base = E820Entry->BaseAddr; + End = E820Entry->BaseAddr + E820Entry->Length; + + switch (E820Entry->Type) { + case EfiAcpiAddressRangeMemory: + if (Base >= BASE_4GB) { + // + // Round up the start address, and round down the end address. + // + Base = ALIGN_VALUE (Base, (UINT64)EFI_PAGE_SIZE); + End = End & ~(UINT64)EFI_PAGE_MASK; + if (Base < End) { + DEBUG ((DEBUG_INFO, "%a: HighMemory [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End)); + PlatformAddMemoryRangeHob (Base, End); + } + } + + break; + case EfiAcpiAddressRangeReserved: + BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_RESERVED, 0, Base, End); + DEBUG ((DEBUG_INFO, "%a: Reserved [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End)); + break; + default: + DEBUG (( + DEBUG_WARN, + "%a: Type %u [0x%Lx, 0x%Lx) (NOT HANDLED)\n", + __FUNCTION__, + E820Entry->Type, + Base, + End + )); + break; + } +} + /** Iterate over the entries in QEMU's fw_cfg E820 RAM map, call the passed callback for each entry. @@ -1051,7 +961,7 @@ PlatformQemuInitializeRam ( // entries. Otherwise, create a single memory HOB with the flat >=4GB // memory size read from the CMOS. // - Status = PlatformScanOrAdd64BitE820Ram (TRUE, NULL, NULL); + Status = PlatformScanE820 (PlatformAddHobCB, PlatformInfoHob); if (EFI_ERROR (Status)) { UpperMemorySize = PlatformGetSystemMemorySizeAbove4gb (); if (UpperMemorySize != 0) { From c2a250adac97d7b32759a4f928b259f7fb81847e Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 17 Jan 2023 13:16:28 +0100 Subject: [PATCH 0498/1529] OvmfPkg/PlatformInitLib: Add PlatformReservationConflictCB Add PlatformReservationConflictCB() callback function for use with PlatformScanE820(). It checks whenever the 64bit PCI MMIO window overlaps with a reservation from qemu. If so move down the MMIO window to resolve the conflict. Write any actions done (moving mmio window) to the firmware log with INFO loglevel. This happens on (virtual) AMD machines with 1TB address space, because the AMD IOMMU uses an address window just below 1TB. Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4251 Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index c24105c329..6c30566db9 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -216,6 +216,51 @@ PlatformAddHobCB ( } } +/** + Check whenever the 64bit PCI MMIO window overlaps with a reservation + from qemu. If so move down the MMIO window to resolve the conflict. + + This happens on (virtual) AMD machines with 1TB address space, + because the AMD IOMMU uses an address window just below 1TB. +**/ +STATIC +VOID +PlatformReservationConflictCB ( + IN EFI_E820_ENTRY64 *E820Entry, + IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob + ) +{ + UINT64 IntersectionBase; + UINT64 IntersectionEnd; + UINT64 NewBase; + + IntersectionBase = MAX ( + E820Entry->BaseAddr, + PlatformInfoHob->PcdPciMmio64Base + ); + IntersectionEnd = MIN ( + E820Entry->BaseAddr + E820Entry->Length, + PlatformInfoHob->PcdPciMmio64Base + + PlatformInfoHob->PcdPciMmio64Size + ); + + if (IntersectionBase >= IntersectionEnd) { + return; // no overlap + } + + NewBase = E820Entry->BaseAddr - PlatformInfoHob->PcdPciMmio64Size; + NewBase = NewBase & ~(PlatformInfoHob->PcdPciMmio64Size - 1); + + DEBUG (( + DEBUG_INFO, + "%a: move mmio: 0x%Lx => %Lx\n", + __FUNCTION__, + PlatformInfoHob->PcdPciMmio64Base, + NewBase + )); + PlatformInfoHob->PcdPciMmio64Base = NewBase; +} + /** Iterate over the entries in QEMU's fw_cfg E820 RAM map, call the passed callback for each entry. @@ -653,6 +698,7 @@ PlatformDynamicMmioWindow ( DEBUG ((DEBUG_INFO, "%a: MMIO Space 0x%Lx (%Ld GB)\n", __func__, MmioSpace, RShiftU64 (MmioSpace, 30))); PlatformInfoHob->PcdPciMmio64Size = MmioSpace; PlatformInfoHob->PcdPciMmio64Base = AddrSpace - MmioSpace; + PlatformScanE820 (PlatformReservationConflictCB, PlatformInfoHob); } else { DEBUG ((DEBUG_INFO, "%a: using classic mmio window\n", __func__)); } From c94b475fd1a14c5f4101fe00f3ae8f73eef314e0 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 17 Jan 2023 13:16:29 +0100 Subject: [PATCH 0499/1529] OvmfPkg/PlatformInitLib: reorder PlatformQemuUc32BaseInitialization First handle the cases which do not need know the value of PlatformInfoHob->LowMemory (microvm and cloudhv). Then call PlatformGetSystemMemorySizeBelow4gb() to get LowMemory. Finally handle the cases (q35 and pc) which need to look at LowMemory, Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 6c30566db9..5aeeeff89f 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -55,8 +55,15 @@ PlatformQemuUc32BaseInitialization ( return; } + if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) { + PlatformInfoHob->Uc32Size = CLOUDHV_MMIO_HOLE_SIZE; + PlatformInfoHob->Uc32Base = CLOUDHV_MMIO_HOLE_ADDRESS; + return; + } + + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { - PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); ASSERT (PcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32); ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= PlatformInfoHob->LowMemory); @@ -78,19 +85,12 @@ PlatformQemuUc32BaseInitialization ( return; } - if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) { - PlatformInfoHob->Uc32Size = CLOUDHV_MMIO_HOLE_SIZE; - PlatformInfoHob->Uc32Base = CLOUDHV_MMIO_HOLE_ADDRESS; - return; - } - ASSERT (PlatformInfoHob->HostBridgeDevId == INTEL_82441_DEVICE_ID); // // On i440fx, start with the [LowerMemorySize, 4GB) range. Make sure one // variable MTRR suffices by truncating the size to a whole power of two, // while keeping the end affixed to 4GB. This will round the base up. // - PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); PlatformInfoHob->Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - PlatformInfoHob->LowMemory)); PlatformInfoHob->Uc32Base = (UINT32)(SIZE_4GB - PlatformInfoHob->Uc32Size); // From b0e8b155e915b8cdda0a078b53bb6a652db6650e Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:28 +0100 Subject: [PATCH 0500/1529] CI: make Python version configurable Add a new parameter "usePythonVersion" to the CI job templates. This makes it possible to specify the version of Python to use. The default value is '', in which case Python will not be downloaded at runtime and the one provided by the VM/container image will be used. Additionally, add a template .azurepipelines/templates/defaults.yml, from which the default Pyhton version string can be obtained. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .azurepipelines/Ubuntu-GCC5.yml | 8 ++++---- .azurepipelines/Windows-VS2019.yml | 4 ++++ .azurepipelines/templates/defaults.yml | 11 +++++++++++ .../templates/platform-build-run-steps.yml | 6 +++++- .azurepipelines/templates/pr-gate-build-job.yml | 2 ++ .azurepipelines/templates/pr-gate-steps.yml | 6 ++++-- 6 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 .azurepipelines/templates/defaults.yml diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml index f83951eeaf..4f9dcf0170 100644 --- a/.azurepipelines/Ubuntu-GCC5.yml +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -13,13 +13,13 @@ pr: - master - stable/* +variables: + - template: templates/defaults.yml + jobs: - template: templates/pr-gate-build-job.yml parameters: tool_chain_tag: 'GCC5' vm_image: 'ubuntu-latest' arch_list: "IA32,X64,ARM,AARCH64,RISCV64,LOONGARCH64" - extra_install_step: - - bash: sudo apt-get install -y lcov - displayName: Install Code Coverage Tools - condition: and(gt(variables.pkg_count, 0), succeeded()) + usePythonVersion: ${{ variables.default_python_version }} diff --git a/.azurepipelines/Windows-VS2019.yml b/.azurepipelines/Windows-VS2019.yml index c07e5bb434..58bb98d42b 100644 --- a/.azurepipelines/Windows-VS2019.yml +++ b/.azurepipelines/Windows-VS2019.yml @@ -12,12 +12,16 @@ pr: - master - stable/* +variables: + - template: templates/defaults.yml + jobs: - template: templates/pr-gate-build-job.yml parameters: tool_chain_tag: 'VS2019' vm_image: 'windows-2019' arch_list: "IA32,X64" + usePythonVersion: ${{ variables.default_python_version }} extra_install_step: - powershell: choco install opencppcoverage; Write-Host "##vso[task.prependpath]C:\Program Files\OpenCppCoverage" displayName: Install Code Coverage Tool diff --git a/.azurepipelines/templates/defaults.yml b/.azurepipelines/templates/defaults.yml new file mode 100644 index 0000000000..b4909448bd --- /dev/null +++ b/.azurepipelines/templates/defaults.yml @@ -0,0 +1,11 @@ +## @file +# File templates/default.yml +# +# template file containing common default values +# +# Copyright (c) Red Hat, Inc. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +variables: + default_python_version: ">=3.10.6" diff --git a/.azurepipelines/templates/platform-build-run-steps.yml b/.azurepipelines/templates/platform-build-run-steps.yml index 40a31a509f..8803d80cf5 100644 --- a/.azurepipelines/templates/platform-build-run-steps.yml +++ b/.azurepipelines/templates/platform-build-run-steps.yml @@ -34,6 +34,9 @@ parameters: - name: extra_install_step type: stepList default: [] +- name: usePythonVersion + type: string + default: '' steps: - checkout: self @@ -42,8 +45,9 @@ steps: - task: UsePythonVersion@0 inputs: - versionSpec: ">=3.10.6" + versionSpec: ${{ parameters.usePythonVersion }} architecture: "x64" + condition: ne('${{ parameters.usePythonVersion }}', '') - script: pip install -r pip-requirements.txt --upgrade displayName: 'Install/Upgrade pip modules' diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index fff61a3193..b8573b90da 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -13,6 +13,7 @@ parameters: vm_image: '' arch_list: '' extra_install_step: [] + usePythonVersion: '' # Build step jobs: @@ -78,6 +79,7 @@ jobs: build_pkgs: $(Build.Pkgs) build_targets: $(Build.Targets) build_archs: ${{ parameters.arch_list }} + usePythonVersion: ${{ parameters.usePythonVersion }} extra_install_step: ${{ parameters.extra_install_step }} - job: Build_${{ parameters.tool_chain_tag }}_TARGET_CODE_COVERAGE diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml index 080f60aea6..ebc1e86c37 100644 --- a/.azurepipelines/templates/pr-gate-steps.yml +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -12,6 +12,7 @@ parameters: build_pkgs: '' build_targets: '' build_archs: '' + usePythonVersion: '' extra_install_step: [] steps: @@ -21,8 +22,9 @@ steps: - task: UsePythonVersion@0 inputs: - versionSpec: '>=3.10.6' - architecture: 'x64' + versionSpec: ${{ parameters.usePythonVersion }} + architecture: "x64" + condition: ne('${{ parameters.usePythonVersion }}', '') - script: pip install -r pip-requirements.txt --upgrade displayName: 'Install/Upgrade pip modules' From 886f0894373ca29271fd29c7a9ea6995f476f99a Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:29 +0100 Subject: [PATCH 0501/1529] ArmVirtPkg: CI: use Python version from defaults template Use the default Python version from the defaults template (.azurepipelines/templates/defaults.yml) in the Windows and Linux CI jobs. Previous changes to the CI job templates make it necessary to specify a version number, if Python shall be pulled at CI runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index b07e3199f1..5a0e589ed4 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -15,6 +15,9 @@ pr: - master - stable/* +variables: + - template: ../../../.azurepipelines/templates/defaults.yml + jobs: - job: Platform_CI variables: @@ -85,6 +88,7 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) + usePythonVersion: ${{ variables.default_python_version }} extra_install_step: - bash: sudo apt-get install qemu displayName: Install qemu From b76379a4c10d83c1a7033db01eb10272970b162f Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:30 +0100 Subject: [PATCH 0502/1529] EmulatorPkg: CI: use Python version from defaults template Use the default Python version from the defaults template (.azurepipelines/templates/defaults.yml) in the Windows and Linux CI jobs. Previous changes to the CI job templates make it necessary to specify a version number, if Python shall be pulled at CI runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 5 +++++ EmulatorPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 416c15e708..a32c57d4aa 100644 --- a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -15,6 +15,10 @@ trigger: pr: - master - stable/* + +variables: + - template: ../../../.azurepipelines/templates/defaults.yml + jobs: - job: Platform_CI variables: @@ -85,3 +89,4 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) + usePythonVersion: ${{ variables.default_python_version }} diff --git a/EmulatorPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml b/EmulatorPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml index e7ead06ae2..09960e7c7a 100644 --- a/EmulatorPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml +++ b/EmulatorPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml @@ -16,6 +16,9 @@ pr: - master - stable/* +variables: + - template: ../../../.azurepipelines/templates/defaults.yml + jobs: - job: Platform_CI variables: @@ -128,3 +131,4 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) + usePythonVersion: ${{ variables.default_python_version }} From 0ac2ae5308bd298d04b4df006c1314951d62e4f3 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:31 +0100 Subject: [PATCH 0503/1529] OvmfPkg: CI: use Python version from defaults template Use the default Python version from the defaults template (.azurepipelines/templates/defaults.yml) in the Windows and Linux CI jobs. Previous changes to the CI job templates make it necessary to specify a version number, if Python shall be pulled at CI runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Jiewen Yao Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 4 ++++ OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 7160d95f7e..6dd90711ac 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -15,6 +15,9 @@ pr: - master - stable/* +variables: + - template: ../../../.azurepipelines/templates/defaults.yml + jobs: - job: Platform_CI variables: @@ -187,6 +190,7 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) + usePythonVersion: ${{ variables.default_python_version }} extra_install_step: - bash: sudo apt-get install qemu displayName: Install qemu diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml b/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml index 7d6344d638..7e63f419b2 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml @@ -14,6 +14,10 @@ trigger: pr: - master - stable/* + +variables: + - template: ../../../.azurepipelines/templates/defaults.yml + jobs: - job: Platform_CI variables: @@ -133,6 +137,7 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) + usePythonVersion: ${{ variables.default_python_version }} extra_install_step: - powershell: choco install qemu --version=2021.5.5; Write-Host "##vso[task.prependpath]c:\Program Files\qemu" displayName: Install QEMU and Set QEMU on path # friendly name displayed in the UI From 866ec7076195eb53641ddd1b3c5b905d2efd5a5b Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:32 +0100 Subject: [PATCH 0504/1529] CI: add ~/.local/bin to PATH (Linux only) Without adding ~/.local/bin to PATH, `pip install` will throw an error when running inside a container. Containers will be introduced to the CI in the following commits. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .azurepipelines/templates/platform-build-run-steps.yml | 6 ++++++ .azurepipelines/templates/pr-gate-steps.yml | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/.azurepipelines/templates/platform-build-run-steps.yml b/.azurepipelines/templates/platform-build-run-steps.yml index 8803d80cf5..087f460d7f 100644 --- a/.azurepipelines/templates/platform-build-run-steps.yml +++ b/.azurepipelines/templates/platform-build-run-steps.yml @@ -39,6 +39,12 @@ parameters: default: '' steps: +- bash: | + echo "##vso[task.prependpath]${HOME}/.local/bin" + echo "new PATH=${PATH}" + displayName: Set PATH + condition: eq('${{ parameters.tool_chain_tag }}', 'GCC5') + - checkout: self clean: true fetchDepth: 1 diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml index ebc1e86c37..78b2b2c8d9 100644 --- a/.azurepipelines/templates/pr-gate-steps.yml +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -16,6 +16,12 @@ parameters: extra_install_step: [] steps: +- bash: | + echo "##vso[task.prependpath]${HOME}/.local/bin" + echo "new PATH=${PATH}" + displayName: Set PATH + condition: eq('${{ parameters.tool_chain_tag }}', 'GCC5') + - checkout: self clean: true fetchDepth: 1 From 5084b1a6e844190a89c2b919a8f829e199b90b33 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:33 +0100 Subject: [PATCH 0505/1529] CI: Allow running in a container. Add a parameter of the pr-gate-build-job template to specify a container image URL. If the value is not '' (default), then the jobs will be run inside a container based on that image. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .azurepipelines/templates/pr-gate-build-job.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index b8573b90da..3999bb1668 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -14,6 +14,7 @@ parameters: arch_list: '' extra_install_step: [] usePythonVersion: '' + container: '' # Build step jobs: @@ -72,6 +73,9 @@ jobs: pool: vmImage: ${{ parameters.vm_image }} + ${{ if not(eq(parameters.container, '')) }}: + container: ${{ parameters.container }} + steps: - template: pr-gate-steps.yml parameters: From 4d52827aa141d775f0cece982cd4497285cff1ab Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 17 Jan 2023 19:09:09 +0100 Subject: [PATCH 0506/1529] CI: Use Fedora 35 container (Linux only) Run all Linux based jobs in a container, using a custom Fedora 35 image (gcc 11). The image URL specified in the defaults.yml template, so that all CI jobs can use it. The image is hosted on ghcr.io and the Dockerfiles are here: https://github.com/tianocore/containers The version numbers of gcc, iasl, and nasm are pinned to avoid unintended upgrades during image rebuild. Do not run apt-get in CI jobs to install qemu and gcc dependencies. Assume the container image provides these. Use Python from the container image, do not download at runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .azurepipelines/Ubuntu-GCC5.yml | 3 ++- .azurepipelines/templates/basetools-build-steps.yml | 9 --------- .azurepipelines/templates/defaults.yml | 1 + 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml index 4f9dcf0170..c3f29625a5 100644 --- a/.azurepipelines/Ubuntu-GCC5.yml +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -21,5 +21,6 @@ jobs: parameters: tool_chain_tag: 'GCC5' vm_image: 'ubuntu-latest' + container: ${{ variables.default_linux_image }} arch_list: "IA32,X64,ARM,AARCH64,RISCV64,LOONGARCH64" - usePythonVersion: ${{ variables.default_python_version }} + usePythonVersion: '' # use Python from the container image diff --git a/.azurepipelines/templates/basetools-build-steps.yml b/.azurepipelines/templates/basetools-build-steps.yml index d8c108c6e2..a72758bc33 100644 --- a/.azurepipelines/templates/basetools-build-steps.yml +++ b/.azurepipelines/templates/basetools-build-steps.yml @@ -10,15 +10,6 @@ parameters: tool_chain_tag: '' steps: -- ${{ if contains(parameters.tool_chain_tag, 'GCC') }}: - - bash: sudo apt-get update - displayName: Update apt - condition: and(gt(variables.pkg_count, 0), succeeded()) - - - bash: sudo apt-get install gcc g++ make uuid-dev - displayName: Install required tools - condition: and(gt(variables.pkg_count, 0), succeeded()) - - task: CmdLine@1 displayName: Build Base Tools from source inputs: diff --git a/.azurepipelines/templates/defaults.yml b/.azurepipelines/templates/defaults.yml index b4909448bd..74d6b41783 100644 --- a/.azurepipelines/templates/defaults.yml +++ b/.azurepipelines/templates/defaults.yml @@ -9,3 +9,4 @@ variables: default_python_version: ">=3.10.6" + default_linux_image: "ghcr.io/tianocore/containers/fedora-35-test:47addc9" From ffd2abb93f46c86c4769190f0d42193780af70f6 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:35 +0100 Subject: [PATCH 0507/1529] ArmVirtPkg: CI: Use Fedora 35 container (Linux only) Run the Linux jobs of the ArmVirtPkg platform CI inside a container, in the same way the general CI does now. Make use of the default image specified in the defaults.yml template. Do not run apt-get in CI jobs to install qemu and gcc dependencies. Assume the container image provides these. Use Python from the container image, do not download at runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 5a0e589ed4..c0a2e0f20d 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -78,6 +78,8 @@ jobs: pool: vmImage: $(vm_image) + container: ${{ variables.default_linux_image }} + steps: - template: ../../../.azurepipelines/templates/platform-build-run-steps.yml parameters: @@ -88,8 +90,4 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) - usePythonVersion: ${{ variables.default_python_version }} - extra_install_step: - - bash: sudo apt-get install qemu - displayName: Install qemu - condition: and(gt(variables.pkg_count, 0), succeeded()) + usePythonVersion: '' # use Python from the container image From bce8d77a065e32829cdd4e2721131f1a43948f1d Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:36 +0100 Subject: [PATCH 0508/1529] EmulatorPkg: CI: Use Fedora 35 container (Linux only) Run the Linux jobs of the EmulatorPkg platform CI inside a container, in the same way the general CI does now. Make use of the default image specified in the defaults.yml template. Use Python from the container image, do not download at runtime. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index a32c57d4aa..3861457ac7 100644 --- a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -79,6 +79,8 @@ jobs: pool: vmImage: $(vm_image) + container: ${{ variables.default_linux_image }} + steps: - template: ../../../.azurepipelines/templates/platform-build-run-steps.yml parameters: @@ -89,4 +91,4 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) - usePythonVersion: ${{ variables.default_python_version }} + usePythonVersion: '' # use Python from the container image From 802014eac8bcc0bdf21944ab335daea26613ce07 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:37 +0100 Subject: [PATCH 0509/1529] OvmfPkg: CI: Use Fedora 35 container (Linux only) Run the Linux jobs of the OvmfPkg platform CI inside a container, in the same way the general CI does now. Make use of the default image specified in the defaults.yml template. Do not run apt-get in CI jobs to install qemu and gcc dependencies. Assume the container image provides these. Use Python from the container image, do not download at runtime. Signed-off-by: Oliver Steffen Acked-by: Jiewen Yao Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 6dd90711ac..85be431ca5 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -180,6 +180,8 @@ jobs: pool: vmImage: $(vm_image) + container: ${{ variables.default_linux_image }} + steps: - template: ../../../.azurepipelines/templates/platform-build-run-steps.yml parameters: @@ -190,8 +192,4 @@ jobs: build_file: $(Build.File) build_flags: $(Build.Flags) run_flags: $(Run.Flags) - usePythonVersion: ${{ variables.default_python_version }} - extra_install_step: - - bash: sudo apt-get install qemu - displayName: Install qemu - condition: and(gt(variables.pkg_count, 0), succeeded()) + usePythonVersion: '' # use Python from the container image From a2096a8e40c72d222e0c645f902be089a5c1e71e Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:38 +0100 Subject: [PATCH 0510/1529] .pytool: CISettings.py: don't add scopes for GCC All ext_dep.yml files for gcc have been removed and gcc is expected to be installed on the system (GCC5_*_PREFIX may indicate the location). No need to adjust the toolchain scopes for Linux builds anymore. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .pytool/CISettings.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 76ac2b09db..d87c8e838e 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -169,15 +169,6 @@ def GetActiveScopes(self): else: logging.warning("Falling back to using in-tree BaseTools") - if is_linux and self.ActualToolChainTag.upper().startswith("GCC"): - if "AARCH64" in self.ActualArchitectures: - scopes += ("gcc_aarch64_linux",) - if "ARM" in self.ActualArchitectures: - scopes += ("gcc_arm_linux",) - if "RISCV64" in self.ActualArchitectures: - scopes += ("gcc_riscv64_unknown",) - if "LOONGARCH64" in self.ActualArchitectures: - scopes += ("gcc_loongarch64_unknown_linux",) self.ActualScopes = scopes return self.ActualScopes From f672ecff22bea7cef9646a75e42638cb77bc6f1c Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:39 +0100 Subject: [PATCH 0511/1529] BaseTools: remove ext_dep files for gcc Remove BaseTools/Bin/gcc_*_ext_dep.yaml to stop downloading gcc from external locations; use the gcc provided by the container image instead. The container image sets the variable GCC5_*_PREFIX accordingly. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml | 21 ------------------ BaseTools/Bin/gcc_arm_linux_ext_dep.yaml | 21 ------------------ ...gcc_loongarch64_unknown_linux_ext_dep.yaml | 22 ------------------- .../Bin/gcc_riscv64_unknown_ext_dep.yaml | 22 ------------------- 4 files changed, 86 deletions(-) delete mode 100644 BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml delete mode 100644 BaseTools/Bin/gcc_arm_linux_ext_dep.yaml delete mode 100644 BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml delete mode 100644 BaseTools/Bin/gcc_riscv64_unknown_ext_dep.yaml diff --git a/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml b/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml deleted file mode 100644 index ff8a9e8681..0000000000 --- a/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml +++ /dev/null @@ -1,21 +0,0 @@ -## @file -# Download GCC AARCH64 compiler from Arm's release site -# Set shell variable GCC5_AARCH64_INSTALL to this folder -# -# This is only downloaded when a build activates scope gcc_aarch64_linux -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "gcc_aarch64_linux", - "type": "web", - "name": "gcc_aarch64_linux", - "source": "https://developer.arm.com/-/media/Files/downloads/gnu/11.2-2022.02/binrel/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu.tar.xz", - "version": "11.2-2022.02", - "sha256": "52dbac3eb71dbe0916f60a8c5ab9b7dc9b66b3ce513047baa09fae56234e53f3", - "compression_type": "tar", - "internal_path": "/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/", - "flags": ["set_shell_var", ], - "var_name": "GCC5_AARCH64_INSTALL" -} diff --git a/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml b/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml deleted file mode 100644 index 151cbfa4b5..0000000000 --- a/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml +++ /dev/null @@ -1,21 +0,0 @@ -## @file -# Download GCC ARM compiler from Arm's release site -# Set shell variable GCC5_ARM_INSTALL to this folder -# -# This is only downloaded when a build activates scope gcc_arm_linux -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "gcc_arm_linux", - "type": "web", - "name": "gcc_arm_linux", - "source": "https://developer.arm.com/-/media/Files/downloads/gnu/11.2-2022.02/binrel/gcc-arm-11.2-2022.02-x86_64-arm-none-linux-gnueabihf.tar.xz", - "version": "11.2-2022.02", - "sha256": "c254f7199261fe76c32ef42187502839bda7efad0a66646cf739d074eff45fad", - "compression_type": "tar", - "internal_path": "/gcc-arm-11.2-2022.02-x86_64-arm-none-linux-gnueabihf/", - "flags": ["set_shell_var", ], - "var_name": "GCC5_ARM_INSTALL" -} diff --git a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml deleted file mode 100644 index 6ebc93a07c..0000000000 --- a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml +++ /dev/null @@ -1,22 +0,0 @@ -## @file -# Download GCC LoongArch64 compiler from LoongArch GitHub release site -# Set shell variable GCC5_LOONGARCH64_INSTALL to this folder -# -# This is only downloaded when a build activates scope gcc_loongarch64_unknown_linux -# -# Copyright (c) Microsoft Corporation. -# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "gcc_loongarch64_unknown_linux", - "type": "web", - "name": "gcc_loongarch64_unknown_linux", - "source":"https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-c-only.tar.xz", - "version": "13.0.0", - "sha256":"744cbb50c6ef07c96551bddf07a8b85cee3250bb18b6040f6ed051e389514951", - "compression_type": "tar", - "internal_path": "/cross-tools/", - "flags": ["set_shell_var", ], - "var_name": "GCC5_LOONGARCH64_INSTALL" -} diff --git a/BaseTools/Bin/gcc_riscv64_unknown_ext_dep.yaml b/BaseTools/Bin/gcc_riscv64_unknown_ext_dep.yaml deleted file mode 100644 index 8abbcd7ba0..0000000000 --- a/BaseTools/Bin/gcc_riscv64_unknown_ext_dep.yaml +++ /dev/null @@ -1,22 +0,0 @@ -## @file -# Download GCC RISCV64 compiler from RISC-V Organization release site -# Set shell variable GCC5_RISCV64_INSTALL to this folder -# -# This is only downloaded when a build activates scope gcc_riscv64_unknown -# -# Copyright (c) Microsoft Corporation. -# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "scope": "gcc_riscv64_unknown", - "type": "web", - "name": "gcc_riscv64_unknown", - "source": "https://raw.githubusercontent.com/riscv/riscv-uefi-edk2-docs/master/gcc-riscv-edk2-ci-toolchain/gcc-riscv-9.2.0-2020.04-x86_64_riscv64-unknown-gnu.tar.xz", - "version": "9.2.0", - "compression_type": "tar", - "sha256": "28373643b69f0ce008273c3dc63f172aa1121952f1b9ae94d7485ac94af7f344", - "internal_path": "/gcc-riscv-9.2.0-2020.04-x86_64_riscv64-unknown-gnu", - "flags": ["set_shell_var", ], - "var_name": "GCC5_RISCV64_INSTALL" -} From 762df4dbe60c823db793066fe3fa8d48e4de3292 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:40 +0100 Subject: [PATCH 0512/1529] ArmVirtPkg: CI: use ubuntu-22.04 vm_image (Linux only) Switch over to ubuntu-22.04 as the vm_image for Linux CI jobs. The previously used ubuntu-18.04 which is not available anymore since Dec 1st 2022. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index c0a2e0f20d..5fa7518d2c 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -22,7 +22,7 @@ jobs: - job: Platform_CI variables: package: 'ArmVirtPkg' - vm_image: 'ubuntu-18.04' + vm_image: 'ubuntu-22.04' should_run: true run_flags: "MAKE_STARTUP_NSH=TRUE QEMU_HEADLESS=TRUE" From 48dd637e9f4668f48a7e4826af04e0a2fa8f5f02 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:41 +0100 Subject: [PATCH 0513/1529] EmulatorPkg: CI: use ubuntu-22.04 vm_image (Linux only) Switch over to ubuntu-22.04 as the vm_image for Linux CI jobs. The previously used ubuntu-18.04 which is not available anymore since Dec 1st 2022. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 3861457ac7..8af4c9c778 100644 --- a/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/EmulatorPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -23,7 +23,7 @@ jobs: - job: Platform_CI variables: package: 'EmulatorPkg' - vm_image: 'ubuntu-18.04' + vm_image: 'ubuntu-22.04' should_run: false run_flags: "MAKE_STARTUP_NSH=TRUE" From 76840dedd08908f063885fc325e777cc540270f5 Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:42 +0100 Subject: [PATCH 0514/1529] OvmfPkg: CI: use ubuntu-22.04 vm_image (Linux only) Switch over to ubuntu-22.04 as the vm_image for Linux CI jobs. The previously used ubuntu-18.04 which is not available anymore since Dec 1st 2022. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Jiewen Yao Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 85be431ca5..1cf9bdf8b9 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -22,7 +22,7 @@ jobs: - job: Platform_CI variables: package: 'OvmfPkg' - vm_image: 'ubuntu-18.04' + vm_image: 'ubuntu-22.04' should_run: true run_flags: "MAKE_STARTUP_NSH=TRUE QEMU_HEADLESS=TRUE" From 42bc182c016effa772d6a81efcadb25670ff706c Mon Sep 17 00:00:00 2001 From: Oliver Steffen Date: Mon, 16 Jan 2023 18:40:43 +0100 Subject: [PATCH 0515/1529] CI: use ubuntu-22.04 image (Linux only) Use the same vm_image as the other Linux CIs in ArmVirtPkg, EmulatorPkg, and OvmfPkg. Switch over to ubuntu-22.04 from ubuntu-latest. Signed-off-by: Oliver Steffen Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Chris Fernald --- .azurepipelines/Ubuntu-GCC5.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml index c3f29625a5..b9a3b851cf 100644 --- a/.azurepipelines/Ubuntu-GCC5.yml +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -20,7 +20,7 @@ jobs: - template: templates/pr-gate-build-job.yml parameters: tool_chain_tag: 'GCC5' - vm_image: 'ubuntu-latest' + vm_image: 'ubuntu-22.04' container: ${{ variables.default_linux_image }} arch_list: "IA32,X64,ARM,AARCH64,RISCV64,LOONGARCH64" usePythonVersion: '' # use Python from the container image From 3b76c556776da481777502969e62f32bf8fe5bf5 Mon Sep 17 00:00:00 2001 From: "Prakash.K" Date: Thu, 24 Nov 2022 10:42:13 +0530 Subject: [PATCH 0516/1529] ShellPkg: Display SMBIOS Type38 fields in smbiosview in formatted view In smbiosview command in shell, below are the fields of SMBIOS Type38 table which can be displayed in formatted manner. 1. Base Address 1. IPMI Specification Version. 2. NV Storage Device Address. Base Address: As per spec, the value in Base Address field of SMBIOS type38 table should be right shifted by 1 if the interface type is SSIF. IPMI Specification Version: If the value in IPMI Specification Version field is 15H, it should be displayed 1.5. NV Storage Device Address: If the value in NV Storage Device Address field is 0xFF, it should be displayed as "No storage device is Present". Cc: Vasudevan Sambandan Cc: Sundaresan Selvaraj Cc: Gayathri Thunuguntla Signed-off-by: Prakash K Reviewed-by: Liming Gao --- .../SmbiosView/PrintInfo.c | 27 ++++++++++++++++--- .../SmbiosView/SmbiosViewStrings.uni | 3 +++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c index e936ee8ea9..2611601230 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c @@ -1177,10 +1177,31 @@ SmbiosPrintStructure ( // case 38: DisplayIPMIDIBMCInterfaceType (Struct->Type38->InterfaceType, Option); - PRINT_STRUCT_VALUE_H (Struct, Type38, IPMISpecificationRevision); + + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_IPMI_SPECIFICATION_REVISION), + gShellDebug1HiiHandle, + RShiftU64 ((UINT64)Struct->Type38->IPMISpecificationRevision, 4), \ + Struct->Type38->IPMISpecificationRevision & 0x0F + ); + PRINT_STRUCT_VALUE_H (Struct, Type38, I2CSlaveAddress); - PRINT_STRUCT_VALUE_H (Struct, Type38, NVStorageDeviceAddress); - PRINT_STRUCT_VALUE_LH (Struct, Type38, BaseAddress); + + if (Struct->Type38->NVStorageDeviceAddress == 0xFF) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_NV_STORAGE_DEVICE_NOT_PRESENT), gShellDebug1HiiHandle); + } else { + PRINT_STRUCT_VALUE_H (Struct, Type38, NVStorageDeviceAddress); + } + + if (Struct->Type38->InterfaceType == IPMIDeviceInfoInterfaceTypeSSIF) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_BASE_ADDRESS), gShellDebug1HiiHandle, RShiftU64 ((UINT64)Struct->Type38->BaseAddress, 1)); + } else { + PRINT_STRUCT_VALUE_LH (Struct, Type38, BaseAddress); + } + break; // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni index 1ab0e3dd60..05f7a61d9d 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni @@ -506,4 +506,7 @@ #string STR_SMBIOSVIEW_PRINTINFO_TPM_DEVICE_CONFIG_PLAT_SW #language en-US "Family configurable via platform software support\r\n" #string STR_SMBIOSVIEW_PRINTINFO_TPM_DEVICE_CONFIG_OEM #language en-US "Family configurable via OEM proprietary mechanism\r\n" #string STR_SMBIOSVIEW_PRINTINFO_BITS_06_63 #language en-US "Bits 6:63 are reserved\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_IPMI_SPECIFICATION_REVISION #language en-US "IPMISpecificationRevision: %d.%d\n" +#string STR_SMBIOSVIEW_PRINTINFO_NV_STORAGE_DEVICE_NOT_PRESENT #language en-US "NVStorageDevice: Not Present\n" +#string STR_SMBIOSVIEW_PRINTINFO_BASE_ADDRESS #language en-US "BaseAddress: 0x%x\n" From 326440e4e8efd70fd1b2b1ffb4094f1618cc0061 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 07:31:55 +0800 Subject: [PATCH 0517/1529] EmbeddedPkg/PrePiLib: Add FFS_CHECK_SECTION_HOOK when finding section BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4152 EmbeddedPkg/PrePiLib provides the service of finding sections based on the input SectionType. But sometimes there maybe multiple sections with the same SectionType. FFS_CHECK_SECTION_HOOK is a hook which can be called to do additional check. Cc: Leif Lindholm Cc: Ard Biesheuvel Cc: Abner Chang Cc: Daniel Schaefer Cc: Gerd Hoffmann Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Acked-by: Ard Biesheuvel Signed-off-by: Min Xu Acked-by: Gerd Hoffmann --- EmbeddedPkg/Include/Library/PrePiLib.h | 23 +++++++++++--- EmbeddedPkg/Library/PrePiLib/FwVol.c | 42 ++++++++++++++++++------- EmbeddedPkg/Library/PrePiLib/PrePiLib.c | 2 +- 3 files changed, 49 insertions(+), 18 deletions(-) diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h index 3741b08c44..f60b667818 100644 --- a/EmbeddedPkg/Include/Library/PrePiLib.h +++ b/EmbeddedPkg/Include/Library/PrePiLib.h @@ -52,11 +52,23 @@ FfsFindNextFile ( IN OUT EFI_PEI_FILE_HANDLE *FileHandle ); +/** + * This is a hook which is used to check if the section is the target one. + * + */ +typedef +EFI_STATUS +(EFIAPI *FFS_CHECK_SECTION_HOOK)( + IN EFI_COMMON_SECTION_HEADER *Section + ); + /** This service enables discovery sections of a given type within a valid FFS file. + Caller also can provide a SectionCheckHook to do additional checking. - @param SearchType The value of the section type to find. - @param FfsFileHeader A pointer to the file header that contains the set of sections to + @param SectionType The value of the section type to find. + @param SectionCheckHook A hook which can check if the section is the target one. + @param FileHeader A pointer to the file header that contains the set of sections to be searched. @param SectionData A pointer to the discovered section, if successful. @@ -67,9 +79,10 @@ FfsFindNextFile ( EFI_STATUS EFIAPI FfsFindSectionData ( - IN EFI_SECTION_TYPE SectionType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN EFI_SECTION_TYPE SectionType, + IN FFS_CHECK_SECTION_HOOK SectionCheckHook, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ); /** diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c index 0a6d6925b7..778d8b13c3 100644 --- a/EmbeddedPkg/Library/PrePiLib/FwVol.c +++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c @@ -264,16 +264,18 @@ FindFileEx ( Go through the file to search SectionType section, when meeting an encapsuled section. - @param SectionType - Filter to find only section of this type. - @param Section - From where to search. - @param SectionSize - The file size to search. - @param OutputBuffer - Pointer to the section to search. + @param SectionType - Filter to find only section of this type. + @param SectionCheckHook - A hook which can check if the section is the target one. + @param Section - From where to search. + @param SectionSize - The file size to search. + @param OutputBuffer - Pointer to the section to search. @retval EFI_SUCCESS **/ EFI_STATUS FfsProcessSection ( IN EFI_SECTION_TYPE SectionType, + IN FFS_CHECK_SECTION_HOOK SectionCheckHook, IN EFI_COMMON_SECTION_HEADER *Section, IN UINTN SectionSize, OUT VOID **OutputBuffer @@ -292,7 +294,9 @@ FfsProcessSection ( UINT32 AuthenticationStatus; CHAR8 *CompressedData; UINT32 CompressedDataLength; + BOOLEAN Found; + Found = FALSE; *OutputBuffer = NULL; ParsedLength = 0; Status = EFI_NOT_FOUND; @@ -302,13 +306,23 @@ FfsProcessSection ( } if (Section->Type == SectionType) { - if (IS_SECTION2 (Section)) { - *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2)); + if (SectionCheckHook != NULL) { + Found = SectionCheckHook (Section) == EFI_SUCCESS; } else { - *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER)); + Found = TRUE; } - return EFI_SUCCESS; + if (Found) { + if (IS_SECTION2 (Section)) { + *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2)); + } else { + *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER)); + } + + return EFI_SUCCESS; + } else { + goto CheckNextSection; + } } else if ((Section->Type == EFI_SECTION_COMPRESSION) || (Section->Type == EFI_SECTION_GUID_DEFINED)) { if (Section->Type == EFI_SECTION_COMPRESSION) { if (IS_SECTION2 (Section)) { @@ -415,6 +429,7 @@ FfsProcessSection ( } else { return FfsProcessSection ( SectionType, + SectionCheckHook, DstBuffer, DstBufferSize, OutputBuffer @@ -422,6 +437,7 @@ FfsProcessSection ( } } +CheckNextSection: if (IS_SECTION2 (Section)) { SectionLength = SECTION2_SIZE (Section); } else { @@ -456,9 +472,10 @@ FfsProcessSection ( EFI_STATUS EFIAPI FfsFindSectionData ( - IN EFI_SECTION_TYPE SectionType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN EFI_SECTION_TYPE SectionType, + IN FFS_CHECK_SECTION_HOOK SectionCheckHook, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ) { EFI_FFS_FILE_HEADER *FfsFileHeader; @@ -478,6 +495,7 @@ FfsFindSectionData ( return FfsProcessSection ( SectionType, + SectionCheckHook, Section, FileSize, SectionData @@ -799,7 +817,7 @@ FfsProcessFvFile ( // // Find FvImage in FvFile // - Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, FvFileHandle, (VOID **)&FvImageHandle); + Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, NULL, FvFileHandle, (VOID **)&FvImageHandle); if (EFI_ERROR (Status)) { return Status; } diff --git a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c index a0c5d02deb..3b6fc4f0eb 100644 --- a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c +++ b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c @@ -131,7 +131,7 @@ LoadDxeCoreFromFfsFile ( VOID *Hob; EFI_FV_FILE_INFO FvFileInfo; - Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage); + Status = FfsFindSectionData (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); if (EFI_ERROR (Status)) { return Status; } From b7a3ce206ef7f8186cc8705d89d691e9ffe6a7f3 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 07:31:56 +0800 Subject: [PATCH 0518/1529] OvmfPkg: Add PCDs/GUID for NCCFV BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4152 NCCFV refers to Non-Confidential-Computing-FV. It includes the DXE phase drivers which are only loaded/started in non-cc guest. Hence the PCDs / GUID for NCCFV are defined in OvmfPkg.dec. Cc: Gerd Hoffmann Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu --- OvmfPkg/OvmfPkg.dec | 3 +++ 1 file changed, 3 insertions(+) diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index e07546f4a7..1b521f2604 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -156,6 +156,7 @@ gUefiOvmfPkgPlatformInfoGuid = {0xdec9b486, 0x1f16, 0x47c7, {0x8f, 0x68, 0xdf, 0x1a, 0x41, 0x88, 0x8b, 0xa5}} gVMMBootOrderGuid = {0x668f4529, 0x63d0, 0x4bb5, {0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a}} gUefiOvmfPkgTdxAcpiHobGuid = {0x6a0c5870, 0xd4ed, 0x44f4, {0xa1, 0x35, 0xdd, 0x23, 0x8b, 0x6f, 0x0c, 0x8d}} + gEfiNonCcFvGuid = {0xae047c6d, 0xbce9, 0x426c, {0xae, 0x03, 0xa6, 0x8e, 0x3b, 0x8a, 0x04, 0x88}} [Ppis] # PPI whose presence in the PPI database signals that the TPM base address @@ -192,6 +193,8 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize|0x0|UINT32|1 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|0x0|UINT32|0x15 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize|0x0|UINT32|0x16 + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeNonCcFvBase|0x0|UINT32|0x6a + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeNonCcFvSize|0x0|UINT32|0x6b ## This flag is used to control the destination port for PlatformDebugLibIoPort gUefiOvmfPkgTokenSpaceGuid.PcdDebugIoPort|0x402|UINT16|4 From 9a361d360230422f5e00e2bb100028e83d44d09c Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 07:31:57 +0800 Subject: [PATCH 0519/1529] OvmfPkg/IntelTdx: Enable separate-fv in IntelTdx/IntelTdxX64.fdf BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4152 In current DXE FV there are 100+ drivers. Some of the drivers are not used in Td guest. (Such as USB support drivers, network related drivers, etc). From the security perspective if a driver is not used, we'd should prevent it from being loaded / started. There are 2 benefits: 1. Reduce the attack surface 2. Improve the boot performance So we separate DXEFV into 2 FVs: DXEFV and NCCFV. All the drivers which are not needed by a Confidential Computing guest are moved from DXEFV to NCCFV. The following patch will find NCCFV for non-cc guest and build FVHob so that NCCFV drivers can be loaded / started in DXE phase. Cc: Gerd Hoffmann Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 11 ++- OvmfPkg/IntelTdx/IntelTdxX64.fdf | 112 ++++++++++++++++++++----------- 2 files changed, 83 insertions(+), 40 deletions(-) diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 81511e3556..0f1e970fbb 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -31,6 +31,11 @@ # DEFINE SECURE_BOOT_ENABLE = FALSE + # + # Shell can be useful for debugging but should not be enabled for production + # + DEFINE BUILD_SHELL = TRUE + # # Device drivers # @@ -204,7 +209,9 @@ VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf +!if $(BUILD_SHELL) == TRUE ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf +!endif ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf @@ -720,12 +727,13 @@ MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf -!if $(TOOL_CHAIN_TAG) != "XCODE5" +!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(BUILD_SHELL) == TRUE OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf { gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE } !endif +!if $(BUILD_SHELL) == TRUE ShellPkg/Application/Shell/Shell.inf { ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf @@ -744,6 +752,7 @@ gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000 } +!endif !if $(SECURE_BOOT_ENABLE) == TRUE SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.fdf b/OvmfPkg/IntelTdx/IntelTdxX64.fdf index a57bbcee89..73dffc1043 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.fdf +++ b/OvmfPkg/IntelTdx/IntelTdxX64.fdf @@ -97,10 +97,14 @@ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCpuidBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCp 0x010000|0x010000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize -0x100000|0xC00000 +0x100000|0x700000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize FV = DXEFV +0x800000|0x500000 +gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeNonCcFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeNonCcFvSize +FV = NCCFV + ########################################################################################## # Set the SEV-ES specific work area PCDs # @@ -183,7 +187,6 @@ INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf -INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf INF UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf INF UefiCpuPkg/CpuDxe/CpuDxe.inf @@ -201,17 +204,6 @@ INF PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf INF OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf INF OvmfPkg/Virtio10Dxe/Virtio10.inf INF OvmfPkg/VirtioBlkDxe/VirtioBlk.inf -INF OvmfPkg/VirtioScsiDxe/VirtioScsi.inf -INF OvmfPkg/VirtioRngDxe/VirtioRng.inf -!if $(PVSCSI_ENABLE) == TRUE -INF OvmfPkg/PvScsiDxe/PvScsiDxe.inf -!endif -!if $(MPT_SCSI_ENABLE) == TRUE -INF OvmfPkg/MptScsiDxe/MptScsiDxe.inf -!endif -!if $(LSI_SCSI_ENABLE) == TRUE -INF OvmfPkg/LsiScsiDxe/LsiScsiDxe.inf -!endif !if $(SECURE_BOOT_ENABLE) == TRUE INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf @@ -222,19 +214,14 @@ INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDx INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf -INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf -INF MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf INF MdeModulePkg/Application/UiApp/UiApp.inf INF OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf -INF MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf -INF MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf -INF MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf INF OvmfPkg/SataControllerDxe/SataControllerDxe.inf INF MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf INF MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf @@ -242,34 +229,94 @@ INF MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf INF MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf INF MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf -INF MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf INF OvmfPkg/SioBusDxe/SioBusDxe.inf INF MdeModulePkg/Bus/Pci/PciSioSerialDxe/PciSioSerialDxe.inf -INF MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf INF MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf INF OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf + +INF FatPkg/EnhancedFatDxe/Fat.inf +INF OvmfPkg/TdxDxe/TdxDxe.inf + +INF OvmfPkg/IoMmuDxe/IoMmuDxe.inf + +# +# Variable driver stack (non-SMM) +# +INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf +INF OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf +INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf +INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf + +# +# EFI_CC_MEASUREMENT_PROTOCOL +# +INF SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf + +################################################################################ + +[FV.NCCFV] +FvForceRebase = FALSE +FvNameGuid = AE047C6D-BCE9-426C-AE03-A68E3B8A0488 +BlockSize = 0x10000 +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE + +# +# DXE Phase modules +# +INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf +INF OvmfPkg/VirtioScsiDxe/VirtioScsi.inf +INF OvmfPkg/VirtioRngDxe/VirtioRng.inf +!if $(PVSCSI_ENABLE) == TRUE +INF OvmfPkg/PvScsiDxe/PvScsiDxe.inf +!endif +!if $(MPT_SCSI_ENABLE) == TRUE +INF OvmfPkg/MptScsiDxe/MptScsiDxe.inf +!endif +!if $(LSI_SCSI_ENABLE) == TRUE +INF OvmfPkg/LsiScsiDxe/LsiScsiDxe.inf +!endif +INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf +INF MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf +INF MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf +INF MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf +INF MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf +INF MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf +INF MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf INF MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf INF MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf - -INF FatPkg/EnhancedFatDxe/Fat.inf INF MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf INF OvmfPkg/VirtioFsDxe/VirtioFsDxe.inf -!if $(TOOL_CHAIN_TAG) != "XCODE5" +!if $(BUILD_SHELL) == TRUE && $(TOOL_CHAIN_TAG) != "XCODE5" INF OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf !endif +!if $(BUILD_SHELL) == TRUE INF ShellPkg/Application/Shell/Shell.inf +!endif INF MdeModulePkg/Logo/LogoDxe.inf -INF OvmfPkg/TdxDxe/TdxDxe.inf - # # Usb Support # @@ -285,20 +332,6 @@ INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf INF OvmfPkg/QemuRamfbDxe/QemuRamfbDxe.inf INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf INF OvmfPkg/PlatformDxe/Platform.inf -INF OvmfPkg/IoMmuDxe/IoMmuDxe.inf - -# -# Variable driver stack (non-SMM) -# -INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf -INF OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf -INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf -INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf - -# -# EFI_CC_MEASUREMENT_PROTOCOL -# -INF SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf ################################################################################ @@ -329,6 +362,7 @@ FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { # compression operation in order to achieve better overall compression. # SECTION FV_IMAGE = DXEFV + SECTION FV_IMAGE = NCCFV } } From 19be41a3fbd897ff91c94f53e17b7246e71c12b7 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 07:31:58 +0800 Subject: [PATCH 0520/1529] OvmfPkg/PeilessStartupLib: Find NCCFV in non-td guest BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4152 As described in BZ#4152, NCCFV includes the DXE phase drivers for non-cc guest. PeilessStartupLib is updated to find NCCFV for non-cc guest. Cc: Gerd Hoffmann Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Signed-off-by: Min Xu Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PeilessStartupLib/DxeLoad.c | 134 +++++++++++++++++- .../PeilessStartupInternal.h | 6 + .../PeilessStartupLib/PeilessStartupLib.inf | 1 + 3 files changed, 140 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c index 6e79c30846..4b1fefd452 100644 --- a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c +++ b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c @@ -22,6 +22,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #define STACK_SIZE 0x20000 +extern EFI_GUID gEfiNonCcFvGuid; /** Transfers control to DxeCore. @@ -136,6 +137,133 @@ FindDxeCore ( return Status; } +/** + * This is a FFS_CHECK_SECTION_HOOK which is defined by caller to check + * if the section is an EFI_SECTION_FIRMWARE_VOLUME_IMAGE and if it is + * a NonCc FV. + * + * @param Section The section in which we're checking for the NonCc FV. + * @return EFI_STATUS The section is the NonCc FV. + */ +EFI_STATUS +EFIAPI +CheckSectionHookForDxeNonCc ( + IN EFI_COMMON_SECTION_HEADER *Section + ) +{ + VOID *Buffer; + EFI_STATUS Status; + EFI_FV_INFO FvImageInfo; + + if (Section->Type != EFI_SECTION_FIRMWARE_VOLUME_IMAGE) { + return EFI_INVALID_PARAMETER; + } + + if (IS_SECTION2 (Section)) { + Buffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2)); + } else { + Buffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER)); + } + + ZeroMem (&FvImageInfo, sizeof (FvImageInfo)); + Status = FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE)(UINTN)Buffer, &FvImageInfo); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_INFO, "Cannot get volume info! %r\n", Status)); + return Status; + } + + return CompareGuid (&FvImageInfo.FvName, &gEfiNonCcFvGuid) ? EFI_SUCCESS : EFI_NOT_FOUND; +} + +/** + * Find the NonCc FV. + * + * @param FvInstance The FvInstance number. + * @return EFI_STATUS Successfuly find the NonCc FV. + */ +EFI_STATUS +EFIAPI +FindDxeNonCc ( + IN INTN FvInstance + ) +{ + EFI_STATUS Status; + EFI_PEI_FV_HANDLE VolumeHandle; + EFI_PEI_FILE_HANDLE FileHandle; + EFI_PEI_FV_HANDLE FvImageHandle; + EFI_FV_INFO FvImageInfo; + UINT32 FvAlignment; + VOID *FvBuffer; + + FileHandle = NULL; + + // + // Caller passed in a specific FV to try, so only try that one + // + Status = FfsFindNextVolume (FvInstance, &VolumeHandle); + ASSERT (Status == EFI_SUCCESS); + + Status = FfsFindNextFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, VolumeHandle, &FileHandle); + ASSERT (FileHandle != NULL); + + // + // Find FvImage in FvFile + // + Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, CheckSectionHookForDxeNonCc, FileHandle, (VOID **)&FvImageHandle); + if (EFI_ERROR (Status)) { + return Status; + } + + // + // Collect FvImage Info. + // + ZeroMem (&FvImageInfo, sizeof (FvImageInfo)); + Status = FfsGetVolumeInfo (FvImageHandle, &FvImageInfo); + ASSERT_EFI_ERROR (Status); + + // + // FvAlignment must be more than 8 bytes required by FvHeader structure. + // + FvAlignment = 1 << ((FvImageInfo.FvAttributes & EFI_FVB2_ALIGNMENT) >> 16); + if (FvAlignment < 8) { + FvAlignment = 8; + } + + // + // Check FvImage + // + if ((UINTN)FvImageInfo.FvStart % FvAlignment != 0) { + FvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32)FvImageInfo.FvSize), FvAlignment); + if (FvBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + CopyMem (FvBuffer, FvImageInfo.FvStart, (UINTN)FvImageInfo.FvSize); + // + // Update FvImageInfo after reload FvImage to new aligned memory + // + FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE)FvBuffer, &FvImageInfo); + } + + // + // Inform HOB consumer phase, i.e. DXE core, the existence of this FV + // + BuildFvHob ((EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart, FvImageInfo.FvSize); + + // + // Makes the encapsulated volume show up in DXE phase to skip processing of + // encapsulated file again. + // + BuildFv2Hob ( + (EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart, + FvImageInfo.FvSize, + &FvImageInfo.FvName, + &(((EFI_FFS_FILE_HEADER *)FileHandle)->Name) + ); + + return Status; +} + /** This function finds DXE Core in the firmware volume and transfer the control to DXE core. @@ -168,10 +296,14 @@ DxeLoadCore ( return Status; } + if (!TdIsEnabled ()) { + FindDxeNonCc (FvInstance); + } + // // Load the DXE Core from a Firmware Volume. // - Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage); + Status = FfsFindSectionData (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); if (EFI_ERROR (Status)) { return Status; } diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h index 09cac3e26c..f56bc3578e 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h @@ -21,6 +21,12 @@ DxeLoadCore ( IN INTN FvInstance ); +EFI_STATUS +EFIAPI +FindDxeNonCc ( + IN INTN FvInstance + ); + VOID EFIAPI TransferHobList ( diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf index def50b4b01..5c6eb1597b 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf @@ -67,6 +67,7 @@ gEfiMemoryTypeInformationGuid gPcdDataBaseHobGuid gCcEventEntryHobGuid + gEfiNonCcFvGuid [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdCfvBase From ab19999a96ba28d589f7b96e40c5e54ebc63b35c Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 15:43:29 +0800 Subject: [PATCH 0521/1529] OvmfPkg/CcExitLib: Move common X86 instruction code to separate file https://bugzilla.tianocore.org/show_bug.cgi?id=4169 Move common X86 instruction codes from CcExitVcHandler.c to separate files (CcInstruction.h / CcInstruction.c) so that these codes can be re-used in TDX. Cc: Gerd Hoffmann Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Reviewed-by: Jiewen Yao Reviewed-by: Tom Lendacky Signed-off-by: Min Xu Acked-by: Gerd Hoffmann --- OvmfPkg/Library/CcExitLib/CcExitLib.inf | 1 + OvmfPkg/Library/CcExitLib/CcExitVcHandler.c | 697 +++----------------- OvmfPkg/Library/CcExitLib/CcInstruction.c | 454 +++++++++++++ OvmfPkg/Library/CcExitLib/CcInstruction.h | 197 ++++++ OvmfPkg/Library/CcExitLib/SecCcExitLib.inf | 1 + 5 files changed, 735 insertions(+), 615 deletions(-) create mode 100644 OvmfPkg/Library/CcExitLib/CcInstruction.c create mode 100644 OvmfPkg/Library/CcExitLib/CcInstruction.h diff --git a/OvmfPkg/Library/CcExitLib/CcExitLib.inf b/OvmfPkg/Library/CcExitLib/CcExitLib.inf index 131fa62675..bc75cd5f5a 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitLib.inf +++ b/OvmfPkg/Library/CcExitLib/CcExitLib.inf @@ -25,6 +25,7 @@ CcExitLib.c CcExitVcHandler.c CcExitVcHandler.h + CcInstruction.c PeiDxeCcExitVcHandler.c CcExitVeHandler.c X64/TdVmcallCpuid.nasm diff --git a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index 985e547977..7fe11c5324 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -17,107 +17,7 @@ #include #include "CcExitVcHandler.h" - -// -// Instruction execution mode definition -// -typedef enum { - LongMode64Bit = 0, - LongModeCompat32Bit, - LongModeCompat16Bit, -} SEV_ES_INSTRUCTION_MODE; - -// -// Instruction size definition (for operand and address) -// -typedef enum { - Size8Bits = 0, - Size16Bits, - Size32Bits, - Size64Bits, -} SEV_ES_INSTRUCTION_SIZE; - -// -// Intruction segment definition -// -typedef enum { - SegmentEs = 0, - SegmentCs, - SegmentSs, - SegmentDs, - SegmentFs, - SegmentGs, -} SEV_ES_INSTRUCTION_SEGMENT; - -// -// Instruction rep function definition -// -typedef enum { - RepNone = 0, - RepZ, - RepNZ, -} SEV_ES_INSTRUCTION_REP; - -typedef struct { - UINT8 Rm; - UINT8 Reg; - UINT8 Mod; -} SEV_ES_INSTRUCTION_MODRM_EXT; - -typedef struct { - UINT8 Base; - UINT8 Index; - UINT8 Scale; -} SEV_ES_INSTRUCTION_SIB_EXT; - -// -// Instruction opcode definition -// -typedef struct { - SEV_ES_INSTRUCTION_MODRM_EXT ModRm; - - SEV_ES_INSTRUCTION_SIB_EXT Sib; - - UINTN RegData; - UINTN RmData; -} SEV_ES_INSTRUCTION_OPCODE_EXT; - -// -// Instruction parsing context definition -// -typedef struct { - GHCB *Ghcb; - - SEV_ES_INSTRUCTION_MODE Mode; - SEV_ES_INSTRUCTION_SIZE DataSize; - SEV_ES_INSTRUCTION_SIZE AddrSize; - BOOLEAN SegmentSpecified; - SEV_ES_INSTRUCTION_SEGMENT Segment; - SEV_ES_INSTRUCTION_REP RepMode; - - UINT8 *Begin; - UINT8 *End; - - UINT8 *Prefixes; - UINT8 *OpCodes; - UINT8 *Displacement; - UINT8 *Immediate; - - INSTRUCTION_REX_PREFIX RexPrefix; - - BOOLEAN ModRmPresent; - INSTRUCTION_MODRM ModRm; - - BOOLEAN SibPresent; - INSTRUCTION_SIB Sib; - - UINTN PrefixSize; - UINTN OpCodeSize; - UINTN DisplacementSize; - UINTN ImmediateSize; - - SEV_ES_INSTRUCTION_OPCODE_EXT Ext; -} SEV_ES_INSTRUCTION_DATA; +#include "CcInstruction.h" // // Non-automatic Exit function prototype @@ -125,9 +25,9 @@ typedef struct { typedef UINT64 (*NAE_EXIT) ( - GHCB *Ghcb, - EFI_SYSTEM_CONTEXT_X64 *Regs, - SEV_ES_INSTRUCTION_DATA *InstructionData + GHCB *Ghcb, + EFI_SYSTEM_CONTEXT_X64 *Regs, + CC_INSTRUCTION_DATA *InstructionData ); // @@ -155,439 +55,6 @@ typedef PACKED struct { SEV_SNP_CPUID_FUNCTION function[0]; } SEV_SNP_CPUID_INFO; -/** - Return a pointer to the contents of the specified register. - - Based upon the input register, return a pointer to the registers contents - in the x86 processor context. - - @param[in] Regs x64 processor context - @param[in] Register Register to obtain pointer for - - @return Pointer to the contents of the requested register - -**/ -STATIC -UINT64 * -GetRegisterPointer ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN UINT8 Register - ) -{ - UINT64 *Reg; - - switch (Register) { - case 0: - Reg = &Regs->Rax; - break; - case 1: - Reg = &Regs->Rcx; - break; - case 2: - Reg = &Regs->Rdx; - break; - case 3: - Reg = &Regs->Rbx; - break; - case 4: - Reg = &Regs->Rsp; - break; - case 5: - Reg = &Regs->Rbp; - break; - case 6: - Reg = &Regs->Rsi; - break; - case 7: - Reg = &Regs->Rdi; - break; - case 8: - Reg = &Regs->R8; - break; - case 9: - Reg = &Regs->R9; - break; - case 10: - Reg = &Regs->R10; - break; - case 11: - Reg = &Regs->R11; - break; - case 12: - Reg = &Regs->R12; - break; - case 13: - Reg = &Regs->R13; - break; - case 14: - Reg = &Regs->R14; - break; - case 15: - Reg = &Regs->R15; - break; - default: - Reg = NULL; - } - - ASSERT (Reg != NULL); - - return Reg; -} - -/** - Update the instruction parsing context for displacement bytes. - - @param[in, out] InstructionData Instruction parsing context - @param[in] Size The instruction displacement size - -**/ -STATIC -VOID -UpdateForDisplacement ( - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData, - IN UINTN Size - ) -{ - InstructionData->DisplacementSize = Size; - InstructionData->Immediate += Size; - InstructionData->End += Size; -} - -/** - Determine if an instruction address if RIP relative. - - Examine the instruction parsing context to determine if the address offset - is relative to the instruction pointer. - - @param[in] InstructionData Instruction parsing context - - @retval TRUE Instruction addressing is RIP relative - @retval FALSE Instruction addressing is not RIP relative - -**/ -STATIC -BOOLEAN -IsRipRelative ( - IN SEV_ES_INSTRUCTION_DATA *InstructionData - ) -{ - SEV_ES_INSTRUCTION_OPCODE_EXT *Ext; - - Ext = &InstructionData->Ext; - - return ((InstructionData->Mode == LongMode64Bit) && - (Ext->ModRm.Mod == 0) && - (Ext->ModRm.Rm == 5) && - (InstructionData->SibPresent == FALSE)); -} - -/** - Return the effective address of a memory operand. - - Examine the instruction parsing context to obtain the effective memory - address of a memory operand. - - @param[in] Regs x64 processor context - @param[in] InstructionData Instruction parsing context - - @return The memory operand effective address - -**/ -STATIC -UINT64 -GetEffectiveMemoryAddress ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData - ) -{ - SEV_ES_INSTRUCTION_OPCODE_EXT *Ext; - UINT64 EffectiveAddress; - - Ext = &InstructionData->Ext; - EffectiveAddress = 0; - - if (IsRipRelative (InstructionData)) { - // - // RIP-relative displacement is a 32-bit signed value - // - INT32 RipRelative; - - RipRelative = *(INT32 *)InstructionData->Displacement; - - UpdateForDisplacement (InstructionData, 4); - - // - // Negative displacement is handled by standard UINT64 wrap-around. - // - return Regs->Rip + (UINT64)RipRelative; - } - - switch (Ext->ModRm.Mod) { - case 1: - UpdateForDisplacement (InstructionData, 1); - EffectiveAddress += (UINT64)(*(INT8 *)(InstructionData->Displacement)); - break; - case 2: - switch (InstructionData->AddrSize) { - case Size16Bits: - UpdateForDisplacement (InstructionData, 2); - EffectiveAddress += (UINT64)(*(INT16 *)(InstructionData->Displacement)); - break; - default: - UpdateForDisplacement (InstructionData, 4); - EffectiveAddress += (UINT64)(*(INT32 *)(InstructionData->Displacement)); - break; - } - - break; - } - - if (InstructionData->SibPresent) { - INT64 Displacement; - - if (Ext->Sib.Index != 4) { - CopyMem ( - &Displacement, - GetRegisterPointer (Regs, Ext->Sib.Index), - sizeof (Displacement) - ); - Displacement *= (INT64)(1 << Ext->Sib.Scale); - - // - // Negative displacement is handled by standard UINT64 wrap-around. - // - EffectiveAddress += (UINT64)Displacement; - } - - if ((Ext->Sib.Base != 5) || Ext->ModRm.Mod) { - EffectiveAddress += *GetRegisterPointer (Regs, Ext->Sib.Base); - } else { - UpdateForDisplacement (InstructionData, 4); - EffectiveAddress += (UINT64)(*(INT32 *)(InstructionData->Displacement)); - } - } else { - EffectiveAddress += *GetRegisterPointer (Regs, Ext->ModRm.Rm); - } - - return EffectiveAddress; -} - -/** - Decode a ModRM byte. - - Examine the instruction parsing context to decode a ModRM byte and the SIB - byte, if present. - - @param[in] Regs x64 processor context - @param[in, out] InstructionData Instruction parsing context - -**/ -STATIC -VOID -DecodeModRm ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData - ) -{ - SEV_ES_INSTRUCTION_OPCODE_EXT *Ext; - INSTRUCTION_REX_PREFIX *RexPrefix; - INSTRUCTION_MODRM *ModRm; - INSTRUCTION_SIB *Sib; - - RexPrefix = &InstructionData->RexPrefix; - Ext = &InstructionData->Ext; - ModRm = &InstructionData->ModRm; - Sib = &InstructionData->Sib; - - InstructionData->ModRmPresent = TRUE; - ModRm->Uint8 = *(InstructionData->End); - - InstructionData->Displacement++; - InstructionData->Immediate++; - InstructionData->End++; - - Ext->ModRm.Mod = ModRm->Bits.Mod; - Ext->ModRm.Reg = (RexPrefix->Bits.BitR << 3) | ModRm->Bits.Reg; - Ext->ModRm.Rm = (RexPrefix->Bits.BitB << 3) | ModRm->Bits.Rm; - - Ext->RegData = *GetRegisterPointer (Regs, Ext->ModRm.Reg); - - if (Ext->ModRm.Mod == 3) { - Ext->RmData = *GetRegisterPointer (Regs, Ext->ModRm.Rm); - } else { - if (ModRm->Bits.Rm == 4) { - InstructionData->SibPresent = TRUE; - Sib->Uint8 = *(InstructionData->End); - - InstructionData->Displacement++; - InstructionData->Immediate++; - InstructionData->End++; - - Ext->Sib.Scale = Sib->Bits.Scale; - Ext->Sib.Index = (RexPrefix->Bits.BitX << 3) | Sib->Bits.Index; - Ext->Sib.Base = (RexPrefix->Bits.BitB << 3) | Sib->Bits.Base; - } - - Ext->RmData = GetEffectiveMemoryAddress (Regs, InstructionData); - } -} - -/** - Decode instruction prefixes. - - Parse the instruction data to track the instruction prefixes that have - been used. - - @param[in] Regs x64 processor context - @param[in, out] InstructionData Instruction parsing context - -**/ -STATIC -VOID -DecodePrefixes ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData - ) -{ - SEV_ES_INSTRUCTION_MODE Mode; - SEV_ES_INSTRUCTION_SIZE ModeDataSize; - SEV_ES_INSTRUCTION_SIZE ModeAddrSize; - UINT8 *Byte; - - // - // Always in 64-bit mode - // - Mode = LongMode64Bit; - ModeDataSize = Size32Bits; - ModeAddrSize = Size64Bits; - - InstructionData->Mode = Mode; - InstructionData->DataSize = ModeDataSize; - InstructionData->AddrSize = ModeAddrSize; - - InstructionData->Prefixes = InstructionData->Begin; - - Byte = InstructionData->Prefixes; - for ( ; ; Byte++, InstructionData->PrefixSize++) { - // - // Check the 0x40 to 0x4F range using an if statement here since some - // compilers don't like the "case 0x40 ... 0x4F:" syntax. This avoids - // 16 case statements below. - // - if ((*Byte >= REX_PREFIX_START) && (*Byte <= REX_PREFIX_STOP)) { - InstructionData->RexPrefix.Uint8 = *Byte; - if ((*Byte & REX_64BIT_OPERAND_SIZE_MASK) != 0) { - InstructionData->DataSize = Size64Bits; - } - - continue; - } - - switch (*Byte) { - case OVERRIDE_SEGMENT_CS: - case OVERRIDE_SEGMENT_DS: - case OVERRIDE_SEGMENT_ES: - case OVERRIDE_SEGMENT_SS: - if (Mode != LongMode64Bit) { - InstructionData->SegmentSpecified = TRUE; - InstructionData->Segment = (*Byte >> 3) & 3; - } - - break; - - case OVERRIDE_SEGMENT_FS: - case OVERRIDE_SEGMENT_GS: - InstructionData->SegmentSpecified = TRUE; - InstructionData->Segment = *Byte & 7; - break; - - case OVERRIDE_OPERAND_SIZE: - if (InstructionData->RexPrefix.Uint8 == 0) { - InstructionData->DataSize = - (Mode == LongMode64Bit) ? Size16Bits : - (Mode == LongModeCompat32Bit) ? Size16Bits : - (Mode == LongModeCompat16Bit) ? Size32Bits : 0; - } - - break; - - case OVERRIDE_ADDRESS_SIZE: - InstructionData->AddrSize = - (Mode == LongMode64Bit) ? Size32Bits : - (Mode == LongModeCompat32Bit) ? Size16Bits : - (Mode == LongModeCompat16Bit) ? Size32Bits : 0; - break; - - case LOCK_PREFIX: - break; - - case REPZ_PREFIX: - InstructionData->RepMode = RepZ; - break; - - case REPNZ_PREFIX: - InstructionData->RepMode = RepNZ; - break; - - default: - InstructionData->OpCodes = Byte; - InstructionData->OpCodeSize = (*Byte == TWO_BYTE_OPCODE_ESCAPE) ? 2 : 1; - - InstructionData->End = Byte + InstructionData->OpCodeSize; - InstructionData->Displacement = InstructionData->End; - InstructionData->Immediate = InstructionData->End; - return; - } - } -} - -/** - Determine instruction length - - Return the total length of the parsed instruction. - - @param[in] InstructionData Instruction parsing context - - @return Length of parsed instruction - -**/ -STATIC -UINT64 -InstructionLength ( - IN SEV_ES_INSTRUCTION_DATA *InstructionData - ) -{ - return (UINT64)(InstructionData->End - InstructionData->Begin); -} - -/** - Initialize the instruction parsing context. - - Initialize the instruction parsing context, which includes decoding the - instruction prefixes. - - @param[in, out] InstructionData Instruction parsing context - @param[in] Ghcb Pointer to the Guest-Hypervisor Communication - Block - @param[in] Regs x64 processor context - -**/ -STATIC -VOID -InitInstructionData ( - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData, - IN GHCB *Ghcb, - IN EFI_SYSTEM_CONTEXT_X64 *Regs - ) -{ - SetMem (InstructionData, sizeof (*InstructionData), 0); - InstructionData->Ghcb = Ghcb; - InstructionData->Begin = (UINT8 *)Regs->Rip; - InstructionData->End = (UINT8 *)Regs->Rip; - - DecodePrefixes (Regs, InstructionData); -} - /** Report an unsupported event to the hypervisor @@ -604,9 +71,9 @@ InitInstructionData ( STATIC UINT64 UnsupportedExit ( - IN GHCB *Ghcb, - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN GHCB *Ghcb, + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 Status; @@ -703,9 +170,9 @@ ValidateMmioMemory ( STATIC UINT64 MmioExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData ) { UINT64 ExitInfo1, ExitInfo2, Status; @@ -731,7 +198,7 @@ MmioExit ( // fall through // case 0x89: - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Bytes = ((Bytes != 0) ? Bytes : (InstructionData->DataSize == Size16Bits) ? 2 : (InstructionData->DataSize == Size32Bits) ? 4 : @@ -824,7 +291,7 @@ MmioExit ( // fall through // case 0xC7: - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Bytes = ((Bytes != 0) ? Bytes : (InstructionData->DataSize == Size16Bits) ? 2 : (InstructionData->DataSize == Size32Bits) ? 4 : @@ -860,7 +327,7 @@ MmioExit ( // fall through // case 0x8B: - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Bytes = ((Bytes != 0) ? Bytes : (InstructionData->DataSize == Size16Bits) ? 2 : (InstructionData->DataSize == Size32Bits) ? 4 : @@ -888,7 +355,7 @@ MmioExit ( return Status; } - Register = GetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); if (Bytes == 4) { // // Zero-extend for 32-bit operation @@ -967,7 +434,7 @@ MmioExit ( // fall through // case 0xB7: - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Bytes = (Bytes != 0) ? Bytes : 2; Status = ValidateMmioMemory (Ghcb, InstructionData->Ext.RmData, Bytes); @@ -985,7 +452,7 @@ MmioExit ( return Status; } - Register = GetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); SetMem (Register, (UINTN)(1 << InstructionData->DataSize), 0); CopyMem (Register, Ghcb->SharedBuffer, Bytes); break; @@ -999,7 +466,7 @@ MmioExit ( // fall through // case 0xBF: - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Bytes = (Bytes != 0) ? Bytes : 2; Status = ValidateMmioMemory (Ghcb, InstructionData->Ext.RmData, Bytes); @@ -1029,7 +496,7 @@ MmioExit ( SignByte = ((*Data & BIT15) != 0) ? 0xFF : 0x00; } - Register = GetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); SetMem (Register, (UINTN)(1 << InstructionData->DataSize), SignByte); CopyMem (Register, Ghcb->SharedBuffer, Bytes); break; @@ -1060,12 +527,12 @@ MmioExit ( STATIC UINT64 MwaitExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; CcExitVmgSetOffsetValid (Ghcb, GhcbRax); @@ -1092,12 +559,12 @@ MwaitExit ( STATIC UINT64 MonitorExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; // Identity mapped, so VA = PA CcExitVmgSetOffsetValid (Ghcb, GhcbRax); @@ -1126,9 +593,9 @@ MonitorExit ( STATIC UINT64 WbinvdExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { return CcExitVmgExit (Ghcb, SVM_EXIT_WBINVD, 0, 0); @@ -1151,14 +618,14 @@ WbinvdExit ( STATIC UINT64 RdtscpExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 Status; - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Status = CcExitVmgExit (Ghcb, SVM_EXIT_RDTSCP, 0, 0); if (Status != 0) { @@ -1196,14 +663,14 @@ RdtscpExit ( STATIC UINT64 VmmCallExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 Status; - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); Ghcb->SaveArea.Rax = Regs->Rax; CcExitVmgSetOffsetValid (Ghcb, GhcbRax); @@ -1241,9 +708,9 @@ VmmCallExit ( STATIC UINT64 MsrExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 ExitInfo1, Status; @@ -1302,8 +769,8 @@ MsrExit ( STATIC UINT64 IoioExitInfo ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN OUT SEV_ES_INSTRUCTION_DATA *InstructionData + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData ) { UINT64 ExitInfo; @@ -1437,9 +904,9 @@ IoioExitInfo ( STATIC UINT64 IoioExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 ExitInfo1, ExitInfo2, Status; @@ -1531,9 +998,9 @@ IoioExit ( STATIC UINT64 InvdExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { return CcExitVmgExit (Ghcb, SVM_EXIT_INVD, 0, 0); @@ -1949,9 +1416,9 @@ GetCpuidFw ( STATIC UINT64 CpuidExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { BOOLEAN Unsupported; @@ -2041,9 +1508,9 @@ CpuidExit ( STATIC UINT64 RdpmcExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 Status; @@ -2085,9 +1552,9 @@ RdpmcExit ( STATIC UINT64 RdtscExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { UINT64 Status; @@ -2126,25 +1593,25 @@ RdtscExit ( STATIC UINT64 Dr7WriteExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { - SEV_ES_INSTRUCTION_OPCODE_EXT *Ext; - SEV_ES_PER_CPU_DATA *SevEsData; - UINT64 *Register; - UINT64 Status; + CC_INSTRUCTION_OPCODE_EXT *Ext; + SEV_ES_PER_CPU_DATA *SevEsData; + UINT64 *Register; + UINT64 Status; Ext = &InstructionData->Ext; SevEsData = (SEV_ES_PER_CPU_DATA *)(Ghcb + 1); - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); // // MOV DRn always treats MOD == 3 no matter how encoded // - Register = GetRegisterPointer (Regs, Ext->ModRm.Rm); + Register = CcGetRegisterPointer (Regs, Ext->ModRm.Rm); // // Using a value of 0 for ExitInfo1 means RAX holds the value @@ -2179,24 +1646,24 @@ Dr7WriteExit ( STATIC UINT64 Dr7ReadExit ( - IN OUT GHCB *Ghcb, - IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, - IN SEV_ES_INSTRUCTION_DATA *InstructionData + IN OUT GHCB *Ghcb, + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData ) { - SEV_ES_INSTRUCTION_OPCODE_EXT *Ext; - SEV_ES_PER_CPU_DATA *SevEsData; - UINT64 *Register; + CC_INSTRUCTION_OPCODE_EXT *Ext; + SEV_ES_PER_CPU_DATA *SevEsData; + UINT64 *Register; Ext = &InstructionData->Ext; SevEsData = (SEV_ES_PER_CPU_DATA *)(Ghcb + 1); - DecodeModRm (Regs, InstructionData); + CcDecodeModRm (Regs, InstructionData); // // MOV DRn always treats MOD == 3 no matter how encoded // - Register = GetRegisterPointer (Regs, Ext->ModRm.Rm); + Register = CcGetRegisterPointer (Regs, Ext->ModRm.Rm); // // If there is a cached valued for DR7, return that. Otherwise return the @@ -2232,12 +1699,12 @@ InternalVmgExitHandleVc ( IN OUT EFI_SYSTEM_CONTEXT SystemContext ) { - EFI_SYSTEM_CONTEXT_X64 *Regs; - NAE_EXIT NaeExit; - SEV_ES_INSTRUCTION_DATA InstructionData; - UINT64 ExitCode, Status; - EFI_STATUS VcRet; - BOOLEAN InterruptState; + EFI_SYSTEM_CONTEXT_X64 *Regs; + NAE_EXIT NaeExit; + CC_INSTRUCTION_DATA InstructionData; + UINT64 ExitCode, Status; + EFI_STATUS VcRet; + BOOLEAN InterruptState; VcRet = EFI_SUCCESS; @@ -2307,11 +1774,11 @@ InternalVmgExitHandleVc ( NaeExit = UnsupportedExit; } - InitInstructionData (&InstructionData, Ghcb, Regs); + CcInitInstructionData (&InstructionData, Ghcb, Regs); Status = NaeExit (Ghcb, Regs, &InstructionData); if (Status == 0) { - Regs->Rip += InstructionLength (&InstructionData); + Regs->Rip += CcInstructionLength (&InstructionData); } else { GHCB_EVENT_INJECTION Event; diff --git a/OvmfPkg/Library/CcExitLib/CcInstruction.c b/OvmfPkg/Library/CcExitLib/CcInstruction.c new file mode 100644 index 0000000000..0fb54b3ed5 --- /dev/null +++ b/OvmfPkg/Library/CcExitLib/CcInstruction.c @@ -0,0 +1,454 @@ +/** @file + X64 Instruction function. + + Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include "CcInstruction.h" + +#define MAX_INSTRUCTION_LENGTH 15 + +/** + Return a pointer to the contents of the specified register. + + Based upon the input register, return a pointer to the registers contents + in the x86 processor context. + + @param[in] Regs x64 processor context + @param[in] Register Register to obtain pointer for + + @return Pointer to the contents of the requested register + +**/ +UINT64 * +CcGetRegisterPointer ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN UINT8 Register + ) +{ + UINT64 *Reg; + + switch (Register) { + case 0: + Reg = &Regs->Rax; + break; + case 1: + Reg = &Regs->Rcx; + break; + case 2: + Reg = &Regs->Rdx; + break; + case 3: + Reg = &Regs->Rbx; + break; + case 4: + Reg = &Regs->Rsp; + break; + case 5: + Reg = &Regs->Rbp; + break; + case 6: + Reg = &Regs->Rsi; + break; + case 7: + Reg = &Regs->Rdi; + break; + case 8: + Reg = &Regs->R8; + break; + case 9: + Reg = &Regs->R9; + break; + case 10: + Reg = &Regs->R10; + break; + case 11: + Reg = &Regs->R11; + break; + case 12: + Reg = &Regs->R12; + break; + case 13: + Reg = &Regs->R13; + break; + case 14: + Reg = &Regs->R14; + break; + case 15: + Reg = &Regs->R15; + break; + default: + Reg = NULL; + } + + ASSERT (Reg != NULL); + + return Reg; +} + +/** + Update the instruction parsing context for displacement bytes. + + @param[in, out] InstructionData Instruction parsing context + @param[in] Size The instruction displacement size + +**/ +STATIC +VOID +UpdateForDisplacement ( + IN OUT CC_INSTRUCTION_DATA *InstructionData, + IN UINTN Size + ) +{ + InstructionData->DisplacementSize = Size; + InstructionData->Immediate += Size; + InstructionData->End += Size; +} + +/** + Determine if an instruction address if RIP relative. + + Examine the instruction parsing context to determine if the address offset + is relative to the instruction pointer. + + @param[in] InstructionData Instruction parsing context + + @retval TRUE Instruction addressing is RIP relative + @retval FALSE Instruction addressing is not RIP relative + +**/ +STATIC +BOOLEAN +IsRipRelative ( + IN CC_INSTRUCTION_DATA *InstructionData + ) +{ + CC_INSTRUCTION_OPCODE_EXT *Ext; + + Ext = &InstructionData->Ext; + + return ((InstructionData->Mode == LongMode64Bit) && + (Ext->ModRm.Mod == 0) && + (Ext->ModRm.Rm == 5) && + (InstructionData->SibPresent == FALSE)); +} + +/** + Return the effective address of a memory operand. + + Examine the instruction parsing context to obtain the effective memory + address of a memory operand. + + @param[in] Regs x64 processor context + @param[in] InstructionData Instruction parsing context + + @return The memory operand effective address + +**/ +STATIC +UINT64 +GetEffectiveMemoryAddress ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN CC_INSTRUCTION_DATA *InstructionData + ) +{ + CC_INSTRUCTION_OPCODE_EXT *Ext; + UINT64 EffectiveAddress; + + Ext = &InstructionData->Ext; + EffectiveAddress = 0; + + if (IsRipRelative (InstructionData)) { + // + // RIP-relative displacement is a 32-bit signed value + // + INT32 RipRelative; + + RipRelative = *(INT32 *)InstructionData->Displacement; + + UpdateForDisplacement (InstructionData, 4); + + // + // Negative displacement is handled by standard UINT64 wrap-around. + // + return Regs->Rip + (UINT64)RipRelative; + } + + switch (Ext->ModRm.Mod) { + case 1: + UpdateForDisplacement (InstructionData, 1); + EffectiveAddress += (UINT64)(*(INT8 *)(InstructionData->Displacement)); + break; + case 2: + switch (InstructionData->AddrSize) { + case Size16Bits: + UpdateForDisplacement (InstructionData, 2); + EffectiveAddress += (UINT64)(*(INT16 *)(InstructionData->Displacement)); + break; + default: + UpdateForDisplacement (InstructionData, 4); + EffectiveAddress += (UINT64)(*(INT32 *)(InstructionData->Displacement)); + break; + } + + break; + } + + if (InstructionData->SibPresent) { + INT64 Displacement; + + if (Ext->Sib.Index != 4) { + CopyMem ( + &Displacement, + CcGetRegisterPointer (Regs, Ext->Sib.Index), + sizeof (Displacement) + ); + Displacement *= (INT64)(1 << Ext->Sib.Scale); + + // + // Negative displacement is handled by standard UINT64 wrap-around. + // + EffectiveAddress += (UINT64)Displacement; + } + + if ((Ext->Sib.Base != 5) || Ext->ModRm.Mod) { + EffectiveAddress += *CcGetRegisterPointer (Regs, Ext->Sib.Base); + } else { + UpdateForDisplacement (InstructionData, 4); + EffectiveAddress += (UINT64)(*(INT32 *)(InstructionData->Displacement)); + } + } else { + EffectiveAddress += *CcGetRegisterPointer (Regs, Ext->ModRm.Rm); + } + + return EffectiveAddress; +} + +/** + Decode a ModRM byte. + + Examine the instruction parsing context to decode a ModRM byte and the SIB + byte, if present. + + @param[in] Regs x64 processor context + @param[in, out] InstructionData Instruction parsing context + +**/ +VOID +CcDecodeModRm ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData + ) +{ + CC_INSTRUCTION_OPCODE_EXT *Ext; + INSTRUCTION_REX_PREFIX *RexPrefix; + INSTRUCTION_MODRM *ModRm; + INSTRUCTION_SIB *Sib; + + RexPrefix = &InstructionData->RexPrefix; + Ext = &InstructionData->Ext; + ModRm = &InstructionData->ModRm; + Sib = &InstructionData->Sib; + + InstructionData->ModRmPresent = TRUE; + ModRm->Uint8 = *(InstructionData->End); + + InstructionData->Displacement++; + InstructionData->Immediate++; + InstructionData->End++; + + Ext->ModRm.Mod = ModRm->Bits.Mod; + Ext->ModRm.Reg = (RexPrefix->Bits.BitR << 3) | ModRm->Bits.Reg; + Ext->ModRm.Rm = (RexPrefix->Bits.BitB << 3) | ModRm->Bits.Rm; + + Ext->RegData = *CcGetRegisterPointer (Regs, Ext->ModRm.Reg); + + if (Ext->ModRm.Mod == 3) { + Ext->RmData = *CcGetRegisterPointer (Regs, Ext->ModRm.Rm); + } else { + if (ModRm->Bits.Rm == 4) { + InstructionData->SibPresent = TRUE; + Sib->Uint8 = *(InstructionData->End); + + InstructionData->Displacement++; + InstructionData->Immediate++; + InstructionData->End++; + + Ext->Sib.Scale = Sib->Bits.Scale; + Ext->Sib.Index = (RexPrefix->Bits.BitX << 3) | Sib->Bits.Index; + Ext->Sib.Base = (RexPrefix->Bits.BitB << 3) | Sib->Bits.Base; + } + + Ext->RmData = GetEffectiveMemoryAddress (Regs, InstructionData); + } +} + +/** + Decode instruction prefixes. + + Parse the instruction data to track the instruction prefixes that have + been used. + + @param[in] Regs x64 processor context + @param[in, out] InstructionData Instruction parsing context + + @retval EFI_SUCCESS Successfully decode Prefixes + @retval Others Other error as indicated +**/ +STATIC +EFI_STATUS +DecodePrefixes ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData + ) +{ + CC_INSTRUCTION_MODE Mode; + CC_INSTRUCTION_SIZE ModeDataSize; + CC_INSTRUCTION_SIZE ModeAddrSize; + UINT8 *Byte; + UINT8 ParsedLength; + + ParsedLength = 0; + + // + // Always in 64-bit mode + // + Mode = LongMode64Bit; + ModeDataSize = Size32Bits; + ModeAddrSize = Size64Bits; + + InstructionData->Mode = Mode; + InstructionData->DataSize = ModeDataSize; + InstructionData->AddrSize = ModeAddrSize; + + InstructionData->Prefixes = InstructionData->Begin; + + Byte = InstructionData->Prefixes; + for ( ; ParsedLength <= MAX_INSTRUCTION_LENGTH; Byte++, InstructionData->PrefixSize++, ParsedLength++) { + // + // Check the 0x40 to 0x4F range using an if statement here since some + // compilers don't like the "case 0x40 ... 0x4F:" syntax. This avoids + // 16 case statements below. + // + if ((*Byte >= REX_PREFIX_START) && (*Byte <= REX_PREFIX_STOP)) { + InstructionData->RexPrefix.Uint8 = *Byte; + if ((*Byte & REX_64BIT_OPERAND_SIZE_MASK) != 0) { + InstructionData->DataSize = Size64Bits; + } + + continue; + } + + switch (*Byte) { + case OVERRIDE_SEGMENT_CS: + case OVERRIDE_SEGMENT_DS: + case OVERRIDE_SEGMENT_ES: + case OVERRIDE_SEGMENT_SS: + if (Mode != LongMode64Bit) { + InstructionData->SegmentSpecified = TRUE; + InstructionData->Segment = (*Byte >> 3) & 3; + } + + break; + + case OVERRIDE_SEGMENT_FS: + case OVERRIDE_SEGMENT_GS: + InstructionData->SegmentSpecified = TRUE; + InstructionData->Segment = *Byte & 7; + break; + + case OVERRIDE_OPERAND_SIZE: + if (InstructionData->RexPrefix.Uint8 == 0) { + InstructionData->DataSize = + (Mode == LongMode64Bit) ? Size16Bits : + (Mode == LongModeCompat32Bit) ? Size16Bits : + (Mode == LongModeCompat16Bit) ? Size32Bits : 0; + } + + break; + + case OVERRIDE_ADDRESS_SIZE: + InstructionData->AddrSize = + (Mode == LongMode64Bit) ? Size32Bits : + (Mode == LongModeCompat32Bit) ? Size16Bits : + (Mode == LongModeCompat16Bit) ? Size32Bits : 0; + break; + + case LOCK_PREFIX: + break; + + case REPZ_PREFIX: + InstructionData->RepMode = RepZ; + break; + + case REPNZ_PREFIX: + InstructionData->RepMode = RepNZ; + break; + + default: + InstructionData->OpCodes = Byte; + InstructionData->OpCodeSize = (*Byte == TWO_BYTE_OPCODE_ESCAPE) ? 2 : 1; + + InstructionData->End = Byte + InstructionData->OpCodeSize; + InstructionData->Displacement = InstructionData->End; + InstructionData->Immediate = InstructionData->End; + return EFI_SUCCESS; + } + } + + return EFI_ABORTED; +} + +/** + Determine instruction length + + Return the total length of the parsed instruction. + + @param[in] InstructionData Instruction parsing context + + @return Length of parsed instruction + +**/ +UINT64 +CcInstructionLength ( + IN CC_INSTRUCTION_DATA *InstructionData + ) +{ + return (UINT64)(InstructionData->End - InstructionData->Begin); +} + +/** + Initialize the instruction parsing context. + + Initialize the instruction parsing context, which includes decoding the + instruction prefixes. + + @param[in, out] InstructionData Instruction parsing context + @param[in] Ghcb Pointer to the Guest-Hypervisor Communication + Block + @param[in] Regs x64 processor context + + @retval EFI_SUCCESS Successfully initialize InstructionData + @retval Others Other error as indicated +**/ +EFI_STATUS +CcInitInstructionData ( + IN OUT CC_INSTRUCTION_DATA *InstructionData, + IN GHCB *Ghcb, + IN EFI_SYSTEM_CONTEXT_X64 *Regs + ) +{ + SetMem (InstructionData, sizeof (*InstructionData), 0); + InstructionData->Ghcb = Ghcb; + InstructionData->Begin = (UINT8 *)Regs->Rip; + InstructionData->End = (UINT8 *)Regs->Rip; + + return DecodePrefixes (Regs, InstructionData); +} diff --git a/OvmfPkg/Library/CcExitLib/CcInstruction.h b/OvmfPkg/Library/CcExitLib/CcInstruction.h new file mode 100644 index 0000000000..a8223a6a7d --- /dev/null +++ b/OvmfPkg/Library/CcExitLib/CcInstruction.h @@ -0,0 +1,197 @@ +/** @file + Confidential Computing X64 Instruction + + Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef CC_INSTRUCTION_H_ +#define CC_INSTRUCTION_H_ + +#include +#include +#include +#include +#include + +// +// Instruction execution mode definition +// +typedef enum { + LongMode64Bit = 0, + LongModeCompat32Bit, + LongModeCompat16Bit, +} CC_INSTRUCTION_MODE; + +// +// Instruction size definition (for operand and address) +// +typedef enum { + Size8Bits = 0, + Size16Bits, + Size32Bits, + Size64Bits, +} CC_INSTRUCTION_SIZE; + +// +// Intruction segment definition +// +typedef enum { + SegmentEs = 0, + SegmentCs, + SegmentSs, + SegmentDs, + SegmentFs, + SegmentGs, +} CC_INSTRUCTION_SEGMENT; + +// +// Instruction rep function definition +// +typedef enum { + RepNone = 0, + RepZ, + RepNZ, +} CC_INSTRUCTION_REP; + +typedef struct { + UINT8 Rm; + UINT8 Reg; + UINT8 Mod; +} CC_INSTRUCTION_MODRM_EXT; + +typedef struct { + UINT8 Base; + UINT8 Index; + UINT8 Scale; +} CC_INSTRUCTION_SIB_EXT; + +// +// Instruction opcode definition +// +typedef struct { + CC_INSTRUCTION_MODRM_EXT ModRm; + + CC_INSTRUCTION_SIB_EXT Sib; + + UINTN RegData; + UINTN RmData; +} CC_INSTRUCTION_OPCODE_EXT; + +// +// Instruction parsing context definition +// +typedef struct { + GHCB *Ghcb; + + CC_INSTRUCTION_MODE Mode; + CC_INSTRUCTION_SIZE DataSize; + CC_INSTRUCTION_SIZE AddrSize; + BOOLEAN SegmentSpecified; + CC_INSTRUCTION_SEGMENT Segment; + CC_INSTRUCTION_REP RepMode; + + UINT8 *Begin; + UINT8 *End; + + UINT8 *Prefixes; + UINT8 *OpCodes; + UINT8 *Displacement; + UINT8 *Immediate; + + INSTRUCTION_REX_PREFIX RexPrefix; + + BOOLEAN ModRmPresent; + INSTRUCTION_MODRM ModRm; + + BOOLEAN SibPresent; + INSTRUCTION_SIB Sib; + + UINTN PrefixSize; + UINTN OpCodeSize; + UINTN DisplacementSize; + UINTN ImmediateSize; + + CC_INSTRUCTION_OPCODE_EXT Ext; +} CC_INSTRUCTION_DATA; + +EFI_STATUS +CcInitInstructionData ( + IN OUT CC_INSTRUCTION_DATA *InstructionData, + IN GHCB *Ghcb, + IN EFI_SYSTEM_CONTEXT_X64 *Regs + ); + +/** + Return a pointer to the contents of the specified register. + + Based upon the input register, return a pointer to the registers contents + in the x86 processor context. + + @param[in] Regs x64 processor context + @param[in] Register Register to obtain pointer for + + @return Pointer to the contents of the requested register + +**/ +UINT64 * +CcGetRegisterPointer ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN UINT8 Register + ); + +/** + Decode a ModRM byte. + + Examine the instruction parsing context to decode a ModRM byte and the SIB + byte, if present. + + @param[in] Regs x64 processor context + @param[in, out] InstructionData Instruction parsing context + +**/ +VOID +CcDecodeModRm ( + IN EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData + ); + +/** + Determine instruction length + + Return the total length of the parsed instruction. + + @param[in] InstructionData Instruction parsing context + + @return Length of parsed instruction + +**/ +UINT64 +CcInstructionLength ( + IN CC_INSTRUCTION_DATA *InstructionData + ); + +/** + Initialize the instruction parsing context. + + Initialize the instruction parsing context, which includes decoding the + instruction prefixes. + + @param[in, out] InstructionData Instruction parsing context + @param[in] Ghcb Pointer to the Guest-Hypervisor Communication + Block + @param[in] Regs x64 processor context + + @retval EFI_SUCCESS Successfully initialize InstructionData + @retval Others Other error as indicated +**/ +EFI_STATUS +CcInitInstructionData ( + IN OUT CC_INSTRUCTION_DATA *InstructionData, + IN GHCB *Ghcb, + IN EFI_SYSTEM_CONTEXT_X64 *Regs + ); + +#endif diff --git a/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf b/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf index 1ee22ce0ae..811269dd2c 100644 --- a/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf +++ b/OvmfPkg/Library/CcExitLib/SecCcExitLib.inf @@ -24,6 +24,7 @@ CcExitLib.c CcExitVcHandler.c CcExitVcHandler.h + CcInstruction.c SecCcExitVcHandler.c CcExitVeHandler.c X64/TdVmcallCpuid.nasm From 0286563a678a95f33f54ed76f4048e54ea060db0 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Tue, 17 Jan 2023 15:43:30 +0800 Subject: [PATCH 0522/1529] OvmfPkg/CcExitLib: Refactor TDX MmioExit BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4169 The previous TDX MmioExit doesn't handle the Mmio instructions correctly in some scenarios. This patch refactors the implementation to fix the issues. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Ryan Afranji Reported-by: Ryan Afranji Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann --- OvmfPkg/Library/CcExitLib/CcExitVeHandler.c | 544 ++++++++++++++------ 1 file changed, 381 insertions(+), 163 deletions(-) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index 30d547d5fe..b8979ec2c0 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -13,6 +13,10 @@ #include #include #include +#include "CcInstruction.h" + +#define TDX_MMIO_READ 0 +#define TDX_MMIO_WRITE 1 typedef union { struct { @@ -216,14 +220,15 @@ STATIC VOID EFIAPI TdxDecodeInstruction ( - IN UINT8 *Rip + IN UINT8 *Rip, + IN UINT32 Length ) { UINTN i; DEBUG ((DEBUG_INFO, "TDX: #TD[EPT] instruction (%p):", Rip)); - for (i = 0; i < 15; i++) { - DEBUG ((DEBUG_INFO, "%02x:", Rip[i])); + for (i = 0; i < MIN (15, Length); i++) { + DEBUG ((DEBUG_INFO, "%02x ", Rip[i])); } DEBUG ((DEBUG_INFO, "\n")); @@ -233,52 +238,339 @@ TdxDecodeInstruction ( if ((x)) { \ TdxDecodeInstruction(Rip); \ TdVmCall(TDVMCALL_HALT, 0, 0, 0, 0, 0); \ + CpuDeadLoop (); \ } +/** + * Tdx MMIO access via TdVmcall. + * + * @param MmioSize Size of the MMIO access + * @param ReadOrWrite Read or write operation + * @param GuestPA Guest physical address + * @param Val Pointer to the value which is read or written + + * @retval EFI_SUCCESS Successfully access the mmio + * @retval Others Other errors as indicated + */ STATIC -UINT64 * -EFIAPI -GetRegFromContext ( - IN EFI_SYSTEM_CONTEXT_X64 *Regs, - IN UINTN RegIndex +EFI_STATUS +TdxMmioReadWrite ( + IN UINT32 MmioSize, + IN UINT32 ReadOrWrite, + IN UINT64 GuestPA, + IN UINT64 *Val ) { - switch (RegIndex) { - case 0: return &Regs->Rax; - break; - case 1: return &Regs->Rcx; - break; - case 2: return &Regs->Rdx; - break; - case 3: return &Regs->Rbx; - break; - case 4: return &Regs->Rsp; - break; - case 5: return &Regs->Rbp; - break; - case 6: return &Regs->Rsi; - break; - case 7: return &Regs->Rdi; - break; - case 8: return &Regs->R8; - break; - case 9: return &Regs->R9; + UINT64 TdStatus; + + if ((MmioSize != 1) && (MmioSize != 2) && (MmioSize != 4) && (MmioSize != 8)) { + DEBUG ((DEBUG_ERROR, "%a: Invalid MmioSize - %d\n", __FUNCTION__, MmioSize)); + return EFI_INVALID_PARAMETER; + } + + if (Val == NULL) { + return EFI_INVALID_PARAMETER; + } + + TdStatus = 0; + if (ReadOrWrite == TDX_MMIO_READ) { + TdStatus = TdVmCall (TDVMCALL_MMIO, MmioSize, TDX_MMIO_READ, GuestPA, 0, Val); + } else if (ReadOrWrite == TDX_MMIO_WRITE) { + TdStatus = TdVmCall (TDVMCALL_MMIO, MmioSize, TDX_MMIO_WRITE, GuestPA, *Val, 0); + } else { + return EFI_INVALID_PARAMETER; + } + + if (TdStatus != 0) { + DEBUG ((DEBUG_ERROR, "%a: TdVmcall failed with %llx\n", __FUNCTION__, TdStatus)); + return EFI_ABORTED; + } + + return EFI_SUCCESS; +} + +typedef struct { + UINT8 OpCode; + UINT32 Bytes; + EFI_PHYSICAL_ADDRESS Address; + UINT64 Val; + UINT64 *Register; + UINT32 ReadOrWrite; +} MMIO_EXIT_PARSED_INSTRUCTION; + +/** + * Parse the MMIO instructions. + * + * @param Regs Pointer to the EFI_SYSTEM_CONTEXT_X64 which includes the instructions + * @param InstructionData Pointer to the CC_INSTRUCTION_DATA + * @param ParsedInstruction Pointer to the parsed instruction data + * + * @retval EFI_SUCCESS Successfully parsed the instructions + * @retval Others Other error as indicated + */ +STATIC +EFI_STATUS +ParseMmioExitInstructions ( + IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, + IN OUT CC_INSTRUCTION_DATA *InstructionData, + OUT MMIO_EXIT_PARSED_INSTRUCTION *ParsedInstruction + ) +{ + EFI_STATUS Status; + UINT8 OpCode; + UINT8 SignByte; + UINT32 Bytes; + EFI_PHYSICAL_ADDRESS Address; + UINT64 Val; + UINT64 *Register; + UINT32 ReadOrWrite; + + Address = 0; + Bytes = 0; + Register = NULL; + Status = EFI_SUCCESS; + Val = 0; + + Status = CcInitInstructionData (InstructionData, NULL, Regs); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Initialize InstructionData failed! (%r)\n", __FUNCTION__, Status)); + return Status; + } + + OpCode = *(InstructionData->OpCodes); + if (OpCode == TWO_BYTE_OPCODE_ESCAPE) { + OpCode = *(InstructionData->OpCodes + 1); + } + + switch (OpCode) { + // + // MMIO write (MOV reg/memX, regX) + // + case 0x88: + Bytes = 1; + // + // fall through + // + case 0x89: + CcDecodeModRm (Regs, InstructionData); + Bytes = ((Bytes != 0) ? Bytes : + (InstructionData->DataSize == Size16Bits) ? 2 : + (InstructionData->DataSize == Size32Bits) ? 4 : + (InstructionData->DataSize == Size64Bits) ? 8 : + 0); + + if (InstructionData->Ext.ModRm.Mod == 3) { + DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __FUNCTION__, OpCode)); + return EFI_UNSUPPORTED; + } + + Address = InstructionData->Ext.RmData; + Val = InstructionData->Ext.RegData; + ReadOrWrite = TDX_MMIO_WRITE; + break; - case 10: return &Regs->R10; + + // + // MMIO write (MOV moffsetX, aX) + // + case 0xA2: + Bytes = 1; + // + // fall through + // + case 0xA3: + Bytes = ((Bytes != 0) ? Bytes : + (InstructionData->DataSize == Size16Bits) ? 2 : + (InstructionData->DataSize == Size32Bits) ? 4 : + (InstructionData->DataSize == Size64Bits) ? 8 : + 0); + + InstructionData->ImmediateSize = (UINTN)(1 << InstructionData->AddrSize); + InstructionData->End += InstructionData->ImmediateSize; + CopyMem (&Address, InstructionData->Immediate, InstructionData->ImmediateSize); + + Val = Regs->Rax; + ReadOrWrite = TDX_MMIO_WRITE; break; - case 11: return &Regs->R11; + + // + // MMIO write (MOV reg/memX, immX) + // + case 0xC6: + Bytes = 1; + // + // fall through + // + case 0xC7: + CcDecodeModRm (Regs, InstructionData); + Bytes = ((Bytes != 0) ? Bytes : + (InstructionData->DataSize == Size16Bits) ? 2 : + (InstructionData->DataSize == Size32Bits) ? 4 : + (InstructionData->DataSize == Size64Bits) ? 8 : + 0); + + InstructionData->ImmediateSize = Bytes; + InstructionData->End += Bytes; + + Val = 0; + CopyMem (&Val, InstructionData->Immediate, InstructionData->ImmediateSize); + + Address = InstructionData->Ext.RmData; + ReadOrWrite = TDX_MMIO_WRITE; + break; - case 12: return &Regs->R12; + + // + // MMIO read (MOV regX, reg/memX) + // + case 0x8A: + Bytes = 1; + // + // fall through + // + case 0x8B: + CcDecodeModRm (Regs, InstructionData); + Bytes = ((Bytes != 0) ? Bytes : + (InstructionData->DataSize == Size16Bits) ? 2 : + (InstructionData->DataSize == Size32Bits) ? 4 : + (InstructionData->DataSize == Size64Bits) ? 8 : + 0); + if (InstructionData->Ext.ModRm.Mod == 3) { + // + // NPF on two register operands??? + // + DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __FUNCTION__, OpCode)); + return EFI_UNSUPPORTED; + } + + Address = InstructionData->Ext.RmData; + ReadOrWrite = TDX_MMIO_READ; + + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + if (Register == NULL) { + return EFI_ABORTED; + } + + if (Bytes == 4) { + // + // Zero-extend for 32-bit operation + // + *Register = 0; + } + break; - case 13: return &Regs->R13; + + // + // MMIO read (MOV aX, moffsetX) + // + case 0xA0: + Bytes = 1; + // + // fall through + // + case 0xA1: + Bytes = ((Bytes != 0) ? Bytes : + (InstructionData->DataSize == Size16Bits) ? 2 : + (InstructionData->DataSize == Size32Bits) ? 4 : + (InstructionData->DataSize == Size64Bits) ? 8 : + 0); + + InstructionData->ImmediateSize = (UINTN)(1 << InstructionData->AddrSize); + InstructionData->End += InstructionData->ImmediateSize; + + Address = 0; + CopyMem ( + &Address, + InstructionData->Immediate, + InstructionData->ImmediateSize + ); + + if (Bytes == 4) { + // + // Zero-extend for 32-bit operation + // + Regs->Rax = 0; + } + + Register = &Regs->Rax; + ReadOrWrite = TDX_MMIO_READ; + break; - case 14: return &Regs->R14; + + // + // MMIO read w/ zero-extension ((MOVZX regX, reg/memX) + // + case 0xB6: + Bytes = 1; + // + // fall through + // + case 0xB7: + CcDecodeModRm (Regs, InstructionData); + Bytes = (Bytes != 0) ? Bytes : 2; + Address = InstructionData->Ext.RmData; + + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + if (Register == NULL) { + return EFI_ABORTED; + } + + SetMem (Register, (UINTN)(1 << InstructionData->DataSize), 0); + + ReadOrWrite = TDX_MMIO_READ; + break; - case 15: return &Regs->R15; + + // + // MMIO read w/ sign-extension (MOVSX regX, reg/memX) + // + case 0xBE: + Bytes = 1; + // + // fall through + // + case 0xBF: + CcDecodeModRm (Regs, InstructionData); + Bytes = (Bytes != 0) ? Bytes : 2; + + Address = InstructionData->Ext.RmData; + + if (Bytes == 1) { + UINT8 *Data; + Data = (UINT8 *)&Val; + SignByte = ((*Data & BIT7) != 0) ? 0xFF : 0x00; + } else { + UINT16 *Data; + Data = (UINT16 *)&Val; + SignByte = ((*Data & BIT15) != 0) ? 0xFF : 0x00; + } + + Register = CcGetRegisterPointer (Regs, InstructionData->Ext.ModRm.Reg); + if (Register == NULL) { + return EFI_ABORTED; + } + + SetMem (Register, (UINTN)(1 << InstructionData->DataSize), SignByte); + + ReadOrWrite = TDX_MMIO_READ; + break; + + default: + DEBUG ((DEBUG_ERROR, "%a: Invalid MMIO opcode (%x)\n", __FUNCTION__, OpCode)); + Status = EFI_UNSUPPORTED; } - return NULL; + if (!EFI_ERROR (Status)) { + ParsedInstruction->OpCode = OpCode; + ParsedInstruction->Address = Address; + ParsedInstruction->Bytes = Bytes; + ParsedInstruction->Register = Register; + ParsedInstruction->Val = Val; + ParsedInstruction->ReadOrWrite = ReadOrWrite; + } + + return Status; } /** @@ -290,160 +582,84 @@ GetRegFromContext ( @param[in] Veinfo VE Info @retval 0 Event handled successfully - @return New exception value to propagate **/ STATIC -INTN +UINT64 EFIAPI MmioExit ( IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs, IN TDCALL_VEINFO_RETURN_DATA *Veinfo ) { - UINT64 Status; - UINT32 MmioSize; - UINT32 RegSize; - UINT8 OpCode; - BOOLEAN SeenRex; - UINT64 *Reg; - UINT8 *Rip; - UINT64 Val; - UINT32 OpSize; - MODRM ModRm; - REX Rex; - TD_RETURN_DATA TdReturnData; - UINT8 Gpaw; - UINT64 TdSharedPageMask; - - Rip = (UINT8 *)Regs->Rip; - Val = 0; - Rex.Val = 0; - SeenRex = FALSE; - - Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); - if (Status == TDX_EXIT_REASON_SUCCESS) { + UINT64 TdStatus; + EFI_STATUS Status; + TD_RETURN_DATA TdReturnData; + UINT8 Gpaw; + UINT64 Val; + UINT64 TdSharedPageMask; + CC_INSTRUCTION_DATA InstructionData; + MMIO_EXIT_PARSED_INSTRUCTION ParsedInstruction; + + TdStatus = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (TdStatus == TDX_EXIT_REASON_SUCCESS) { Gpaw = (UINT8)(TdReturnData.TdInfo.Gpaw & 0x3f); TdSharedPageMask = 1ULL << (Gpaw - 1); } else { - DEBUG ((DEBUG_ERROR, "TDCALL failed with status=%llx\n", Status)); - return Status; + DEBUG ((DEBUG_ERROR, "%a: TDCALL failed with status=%llx\n", __FUNCTION__, TdStatus)); + goto FatalError; } if ((Veinfo->GuestPA & TdSharedPageMask) == 0) { - DEBUG ((DEBUG_ERROR, "EPT-violation #VE on private memory is not allowed!")); - TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0); - CpuDeadLoop (); + DEBUG ((DEBUG_ERROR, "%a: EPT-violation #VE on private memory is not allowed!", __FUNCTION__)); + goto FatalError; } - // - // Default to 32bit transfer - // - OpSize = 4; - - do { - OpCode = *Rip++; - if (OpCode == 0x66) { - OpSize = 2; - } else if ((OpCode == 0x64) || (OpCode == 0x65) || (OpCode == 0x67)) { - continue; - } else if ((OpCode >= 0x40) && (OpCode <= 0x4f)) { - SeenRex = TRUE; - Rex.Val = OpCode; - } else { - break; - } - } while (TRUE); - - // - // We need to have at least 2 more bytes for this instruction - // - TDX_DECODER_BUG_ON (((UINT64)Rip - Regs->Rip) > 13); - - OpCode = *Rip++; - // - // Two-byte opecode, get next byte - // - if (OpCode == 0x0F) { - OpCode = *Rip++; - } - - switch (OpCode) { - case 0x88: - case 0x8A: - case 0xB6: - MmioSize = 1; - break; - case 0xB7: - MmioSize = 2; - break; - default: - MmioSize = Rex.Bits.W ? 8 : OpSize; - break; + Status = ParseMmioExitInstructions (Regs, &InstructionData, &ParsedInstruction); + if (EFI_ERROR (Status)) { + goto FatalError; } - /* Punt on AH/BH/CH/DH unless it shows up. */ - ModRm.Val = *Rip++; - TDX_DECODER_BUG_ON (MmioSize == 1 && ModRm.Bits.Reg > 4 && !SeenRex && OpCode != 0xB6); - Reg = GetRegFromContext (Regs, ModRm.Bits.Reg | ((int)Rex.Bits.R << 3)); - TDX_DECODER_BUG_ON (!Reg); - - if (ModRm.Bits.Rm == 4) { - ++Rip; /* SIB byte */ + if (Veinfo->GuestPA != (ParsedInstruction.Address | TdSharedPageMask)) { + DEBUG (( + DEBUG_ERROR, + "%a: Address is not correct! (%d: 0x%llx != 0x%llx)\n", + __FUNCTION__, + ParsedInstruction.OpCode, + Veinfo->GuestPA, + ParsedInstruction.Address + )); + goto FatalError; } - if ((ModRm.Bits.Mod == 2) || ((ModRm.Bits.Mod == 0) && (ModRm.Bits.Rm == 5))) { - Rip += 4; /* DISP32 */ - } else if (ModRm.Bits.Mod == 1) { - ++Rip; /* DISP8 */ + if (ParsedInstruction.ReadOrWrite == TDX_MMIO_WRITE ) { + Status = TdxMmioReadWrite (ParsedInstruction.Bytes, TDX_MMIO_WRITE, Veinfo->GuestPA, &ParsedInstruction.Val); + } else if (ParsedInstruction.ReadOrWrite == TDX_MMIO_READ) { + Val = 0; + Status = TdxMmioReadWrite (ParsedInstruction.Bytes, TDX_MMIO_READ, Veinfo->GuestPA, &Val); + if (!EFI_ERROR (Status)) { + CopyMem (ParsedInstruction.Register, &Val, ParsedInstruction.Bytes); + } + } else { + goto FatalError; } - switch (OpCode) { - case 0x88: - case 0x89: - CopyMem ((void *)&Val, Reg, MmioSize); - Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 1, Veinfo->GuestPA, Val, 0); - break; - case 0xC7: - CopyMem ((void *)&Val, Rip, OpSize); - Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 1, Veinfo->GuestPA, Val, 0); - Rip += OpSize; - default: - // - // 32-bit write registers are zero extended to the full register - // Hence 'MOVZX r[32/64], r/m16' is - // hardcoded to reg size 8, and the straight MOV case has a reg - // size of 8 in the 32-bit read case. - // - switch (OpCode) { - case 0xB6: - RegSize = Rex.Bits.W ? 8 : OpSize; - break; - case 0xB7: - RegSize = 8; - break; - default: - RegSize = MmioSize == 4 ? 8 : MmioSize; - break; - } - - Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 0, Veinfo->GuestPA, 0, &Val); - if (Status == 0) { - ZeroMem (Reg, RegSize); - CopyMem (Reg, (void *)&Val, MmioSize); - } + if (EFI_ERROR (Status)) { + goto FatalError; } - if (Status == 0) { - TDX_DECODER_BUG_ON (((UINT64)Rip - Regs->Rip) > 15); + // + // We change instruction length to reflect true size so handler can + // bump rip + // + Veinfo->ExitInstructionLength = (UINT32)(CcInstructionLength (&InstructionData)); + TdxDecodeInstruction ((UINT8 *)Regs->Rip, Veinfo->ExitInstructionLength); - // - // We change instruction length to reflect true size so handler can - // bump rip - // - Veinfo->ExitInstructionLength = (UINT32)((UINT64)Rip - Regs->Rip); - } + return 0; - return Status; +FatalError: + TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0); + CpuDeadLoop (); + return 0; } /** @@ -479,6 +695,7 @@ CcExitHandleVe ( if (Status != 0) { DEBUG ((DEBUG_ERROR, "#VE happened. TDGETVEINFO failed with Status = 0x%llx\n", Status)); TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0); + CpuDeadLoop (); } switch (ReturnData.VeInfo.ExitReason) { @@ -571,6 +788,7 @@ CcExitHandleVe ( )); TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0); + CpuDeadLoop (); } SystemContext.SystemContextX64->Rip += ReturnData.VeInfo.ExitInstructionLength; From 59211ce6d5270c5a28dd7bf1ea191ab3a7c4ae0a Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 18 Jan 2023 07:53:26 +0800 Subject: [PATCH 0523/1529] SecurityPkg/TdTcg2Dxe: Extend EFI boot variable to PCR[1] According to TCG PC Client PFP spec 0021 Section 2.4.4.2 EFI boot variable should be measured and extended to PCR[1], not PCR[5]. This patch is proposed to fix this error. Cc: Jiewen Yao Cc: Jian J Wang Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c index d19923b0c6..59341a8c02 100644 --- a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c +++ b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c @@ -1873,12 +1873,8 @@ ReadAndMeasureBootVariable ( OUT VOID **VarData ) { - // - // Boot variables are measured into (PCR[5]) RTMR[1], - // details in section 8.1 of TDVF design guide. - // return ReadAndMeasureVariable ( - MapPcrToMrIndex (5), + MapPcrToMrIndex (1), EV_EFI_VARIABLE_BOOT, VarName, VendorGuid, From ea437af536f3aadebe7b558c4c9efef6b0806680 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 18 Jan 2023 07:52:32 +0800 Subject: [PATCH 0524/1529] OvmfPkg/BaseMemEncryptTdxLib: Refactor error handle of SetOrClearSharedBit The previous implementation of SetOrClearSharedBit doesn't handle the error correctly. In this patch SetOrClearSharedBit is changed to return error code so that the caller can handle it. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- .../BaseMemEncryptTdxLib/MemoryEncryption.c | 48 +++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c index 503f626d75..5b13042512 100644 --- a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c +++ b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c @@ -510,8 +510,11 @@ Split1GPageTo2M ( @param[in] PagetablePoint Page table entry pointer (PTE). @param[in] Mode Set or Clear shared bit + @retval EFI_SUCCESS Successfully set or clear the memory shared bit + @retval Others Other error as indicated **/ -STATIC VOID +STATIC +EFI_STATUS SetOrClearSharedBit ( IN OUT UINT64 *PageTablePointer, IN TDX_PAGETABLE_MODE Mode, @@ -520,7 +523,8 @@ SetOrClearSharedBit ( ) { UINT64 AddressEncMask; - UINT64 Status; + UINT64 TdStatus; + EFI_STATUS Status; EDKII_MEMORY_ACCEPT_PROTOCOL *MemoryAcceptProtocol; AddressEncMask = GetMemEncryptionAddressMask (); @@ -536,16 +540,30 @@ SetOrClearSharedBit ( PhysicalAddress &= ~AddressEncMask; } - Status = TdVmCall (TDVMCALL_MAPGPA, PhysicalAddress, Length, 0, 0, NULL); + TdStatus = TdVmCall (TDVMCALL_MAPGPA, PhysicalAddress, Length, 0, 0, NULL); + if (TdStatus != 0) { + DEBUG ((DEBUG_ERROR, "%a: TdVmcall(MAPGPA) failed with %llx\n", __FUNCTION__, TdStatus)); + ASSERT (FALSE); + return EFI_DEVICE_ERROR; + } // // If changing shared to private, must accept-page again // if (Mode == ClearSharedBit) { Status = gBS->LocateProtocol (&gEdkiiMemoryAcceptProtocolGuid, NULL, (VOID **)&MemoryAcceptProtocol); - ASSERT (!EFI_ERROR (Status)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Failed to locate MemoryAcceptProtocol with %r\n", __FUNCTION__, Status)); + ASSERT (FALSE); + return Status; + } + Status = MemoryAcceptProtocol->AcceptMemory (MemoryAcceptProtocol, PhysicalAddress, Length); - ASSERT (!EFI_ERROR (Status)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Failed to AcceptMemory with %r\n", __FUNCTION__, Status)); + ASSERT (FALSE); + return Status; + } } DEBUG (( @@ -558,6 +576,8 @@ SetOrClearSharedBit ( Mode, Status )); + + return EFI_SUCCESS; } /** @@ -747,7 +767,11 @@ SetMemorySharedOrPrivate ( // If we have at least 1GB to go, we can just update this entry // if (!(PhysicalAddress & (BIT30 - 1)) && (Length >= BIT30)) { - SetOrClearSharedBit (&PageDirectory1GEntry->Uint64, Mode, PhysicalAddress, BIT30); + Status = SetOrClearSharedBit (&PageDirectory1GEntry->Uint64, Mode, PhysicalAddress, BIT30); + if (EFI_ERROR (Status)) { + goto Done; + } + DEBUG (( DEBUG_VERBOSE, "%a:%a: updated 1GB entry for Physical=0x%Lx\n", @@ -809,7 +833,11 @@ SetMemorySharedOrPrivate ( // If we have at least 2MB left to go, we can just update this entry // if (!(PhysicalAddress & (BIT21-1)) && (Length >= BIT21)) { - SetOrClearSharedBit (&PageDirectory2MEntry->Uint64, Mode, PhysicalAddress, BIT21); + Status = SetOrClearSharedBit (&PageDirectory2MEntry->Uint64, Mode, PhysicalAddress, BIT21); + if (EFI_ERROR (Status)) { + goto Done; + } + PhysicalAddress += BIT21; Length -= BIT21; } else { @@ -856,7 +884,11 @@ SetMemorySharedOrPrivate ( goto Done; } - SetOrClearSharedBit (&PageTableEntry->Uint64, Mode, PhysicalAddress, EFI_PAGE_SIZE); + Status = SetOrClearSharedBit (&PageTableEntry->Uint64, Mode, PhysicalAddress, EFI_PAGE_SIZE); + if (EFI_ERROR (Status)) { + goto Done; + } + PhysicalAddress += EFI_PAGE_SIZE; Length -= EFI_PAGE_SIZE; } From 6ed51be56698b120655dfbd49439ca89cebcb7c1 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 18 Jan 2023 07:53:01 +0800 Subject: [PATCH 0525/1529] OvmfPkg/CcExitLib: Initialize Status in IoExit Status should be initialized otherwise it may return unexpected value. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Library/CcExitLib/CcExitVeHandler.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index b8979ec2c0..2c1de0039d 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -109,10 +109,11 @@ IoExit ( UINT64 RepCnt; UINT64 Status; - Val = 0; - Write = Veinfo->ExitQualification.Io.Direction ? FALSE : TRUE; - Size = Veinfo->ExitQualification.Io.Size + 1; - Port = Veinfo->ExitQualification.Io.Port; + Val = 0; + Status = 0; + Write = Veinfo->ExitQualification.Io.Direction ? FALSE : TRUE; + Size = Veinfo->ExitQualification.Io.Size + 1; + Port = Veinfo->ExitQualification.Io.Port; if (Veinfo->ExitQualification.Io.String) { // From faef1f014f42f6096ad9f664076353565857e566 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 23 Dec 2022 14:20:06 +0800 Subject: [PATCH 0526/1529] MdePkg/IndustryStandard: Update IPMI definitions This change updates IPMI header files to support build up SMBIOS 42 Redfish Host Interface record using the information retrieved via IPMI App/Net Function. In IpmiNetFnApp.h, we also remove the duplicate definition of IPMI_APP_GET_CHANNEL_INFO. Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Nate DeSimone Reviewed-by: Isaac Oram Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/Ipmi.h | 17 +++++++++ .../Include/IndustryStandard/IpmiNetFnApp.h | 37 +++++++++++++++++-- .../IndustryStandard/IpmiNetFnTransport.h | 32 ++++++++++++++++ 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/Ipmi.h b/MdePkg/Include/IndustryStandard/Ipmi.h index 9d1d412b53..d6e7436b5a 100644 --- a/MdePkg/Include/IndustryStandard/Ipmi.h +++ b/MdePkg/Include/IndustryStandard/Ipmi.h @@ -6,6 +6,7 @@ and Appendix H, Sub-function Assignments. Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -52,4 +53,20 @@ #define IPMI_COMP_CODE_SUBFUNCTION_DISABLED 0xD6 #define IPMI_COMP_CODE_UNSPECIFIED 0xFF +#define IPMI_CHANNEL_NUMBER_PRIMARY_IPMB 0x00 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_1 0x01 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_2 0x02 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_3 0x03 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_4 0x04 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_5 0x05 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_6 0x06 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_7 0x07 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_8 0x08 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_9 0x09 +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_10 0x0A +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_11 0x0B +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_RESERVED_12 0x0C +#define IPMI_CHANNEL_NUMBER_IMPLEMENTATION_RESERVED_13 0x0D +#define IPMI_CHANNEL_NUMBER_PRIMARY_PRESENT_IF 0x0E +#define IPMI_CHANNEL_NUMBER_PRIMARY_SYSTEM_INTERFACE 0x0F #endif diff --git a/MdePkg/Include/IndustryStandard/IpmiNetFnApp.h b/MdePkg/Include/IndustryStandard/IpmiNetFnApp.h index 0721bc6b27..a5835ba08c 100644 --- a/MdePkg/Include/IndustryStandard/IpmiNetFnApp.h +++ b/MdePkg/Include/IndustryStandard/IpmiNetFnApp.h @@ -12,6 +12,7 @@ and Appendix H, Sub-function Assignments. Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -486,6 +487,11 @@ typedef struct { // #define IPMI_APP_GET_SYSTEM_GUID 0x37 +typedef struct { + UINT8 CompletionCode; + EFI_GUID SystemUuid; +} IPMI_GET_SYSTEM_UUID_RESPONSE; + // // Constants and Structure definitions for "Get System GUID" command to follow here // @@ -671,6 +677,30 @@ typedef struct { #define IPMI_CHANNEL_MEDIA_TYPE_OEM_START 0x60 #define IPMI_CHANNEL_MEDIA_TYPE_OEM_END 0x7F +// +// Definitions for channel protocol type +// +// Not available +#define IPMI_CHANNEL_PROTOCOL_TYPE_NA 0x00 +// IPMB-1.0 +#define IPMI_CHANNEL_PROTOCOL_TYPE_IPMB_1_0 0x01 +// ICMB-1.0 +#define IPMI_CHANNEL_PROTOCOL_TYPE_ICMB_1_0 0x02 +// Reserved +#define IPMI_CHANNEL_PROTOCOL_TYPE_RESERVED 0x03 +// IPMI SMBUS +#define IPMI_CHANNEL_PROTOCOL_TYPE_IPMI_SMBUS 0x04 +// KCS +#define IPMI_CHANNEL_PROTOCOL_TYPE_KCS 0x05 +// SMIC +#define IPMI_CHANNEL_PROTOCOL_TYPE_SMIC 0x06 +// BT-10 +#define IPMI_CHANNEL_PROTOCOL_TYPE_BT_10 0x07 +// BT-15 +#define IPMI_CHANNEL_PROTOCOL_TYPE_BT_15 0x08 +// TMode +#define IPMI_CHANNEL_PROTOCOL_TYPE_TMODE 0x09 + typedef union { struct { UINT8 ChannelNo : 4; @@ -713,10 +743,9 @@ typedef struct { UINT16 AuxChannelInfo; } IPMI_GET_CHANNEL_INFO_RESPONSE; -// -// Definitions for Get Channel Info command -// -#define IPMI_APP_GET_CHANNEL_INFO 0x42 +typedef struct { + IPMI_CHANNEL_INFO_CHANNEL_NUMBER ChannelNumber; +} IPMI_GET_CHANNEL_INFO_REQUEST; // // Constants and Structure definitions for "Get Channel Info" command to follow here diff --git a/MdePkg/Include/IndustryStandard/IpmiNetFnTransport.h b/MdePkg/Include/IndustryStandard/IpmiNetFnTransport.h index 19db84e512..2024c35f7f 100644 --- a/MdePkg/Include/IndustryStandard/IpmiNetFnTransport.h +++ b/MdePkg/Include/IndustryStandard/IpmiNetFnTransport.h @@ -11,6 +11,7 @@ and Appendix H, Sub-function Assignments. Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -60,6 +61,7 @@ typedef enum { IpmiLanReserved3, IpmiLanDestinationType, IpmiLanDestinationAddress, + IpmiLanVlanId = 0x14, IpmiIpv4OrIpv6Support = 0x32, IpmiIpv4OrIpv6AddressEnable, IpmiIpv6HdrStatTrafficClass, @@ -103,6 +105,14 @@ typedef enum { IpmiOem2 } IPMI_LAN_DEST_TYPE_DEST_TYPE; +// +// Destination address format +// +typedef enum { + IpmiDestinationAddressVersion4, + IpmiDestinationAddressVersion6 +} IPMI_LAN_DEST_ADDRESS_VERSION; + typedef union { struct { UINT8 NoAuth : 1; @@ -177,6 +187,10 @@ typedef struct { UINT8 ArpInterval; } IPMI_LAN_ARP_INTERVAL; +typedef struct { + UINT8 IpAddress[4]; +} IPMI_LAN_DEFAULT_GATEWAY; + typedef struct { UINT8 Data[18]; } IPMI_LAN_COMMUNITY_STRING; @@ -227,6 +241,24 @@ typedef struct { IPMI_LAN_MAC_ADDRESS AlertingMacAddress; } IPMI_LAN_DEST_ADDRESS; +typedef struct { + UINT8 VanIdLowByte; +} IPMI_LAN_VLAN_ID_DATA1; + +typedef union { + struct { + UINT8 VanIdHighByte : 4; + UINT8 Reserved : 3; + UINT8 Enabled : 1; + } Bits; + UINT8 Uint8; +} IPMI_LAN_VLAN_ID_DATA2; + +typedef struct { + IPMI_LAN_VLAN_ID_DATA1 Data1; + IPMI_LAN_VLAN_ID_DATA2 Data2; +} IPMI_LAN_VLAN_ID; + typedef union { IPMI_LAN_AUTH_TYPE IpmiLanAuthType; IPMI_LAN_IP_ADDRESS IpmiLanIpAddress; From 80ad92dc4ecaa62303638f416c4b7100572db446 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 23 Dec 2022 14:33:48 +0800 Subject: [PATCH 0527/1529] RedfishPkg/Include: Add Redfish IPMI definitions Add the definitions of Redfish Host Interface credential bootstrapping IPMI commands. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Reviewed-by: Igor Kulchytskyy Reviewed-by: Isaac Oram --- .../RedfishHostInterfaceIpmi.h | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 RedfishPkg/Include/IndustryStandard/RedfishHostInterfaceIpmi.h diff --git a/RedfishPkg/Include/IndustryStandard/RedfishHostInterfaceIpmi.h b/RedfishPkg/Include/IndustryStandard/RedfishHostInterfaceIpmi.h new file mode 100644 index 0000000000..9b4a5eb8e3 --- /dev/null +++ b/RedfishPkg/Include/IndustryStandard/RedfishHostInterfaceIpmi.h @@ -0,0 +1,51 @@ +/** @file + Redfish Host Interface IPMI command + + Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef REDFISH_HOST_INTERFACE_IPMI_H_ +#define REDFISH_HOST_INTERFACE_IPMI_H_ + +#include +#include + +#define REDFISH_IPMI_GROUP_EXTENSION 0x52 +#define REDFISH_IPMI_GET_BOOTSTRAP_CREDENTIALS_CMD 0x02 +#define REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_ENABLE 0xA5 +#define REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_DISABLE 0x00 +#define REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED 0x80 + +/// +/// Per Redfish Host Interface Specification 1.3, The maximum length of +/// username and password is 16 characters long. +// +#define USERNAME_MAX_LENGTH 16 +#define PASSWORD_MAX_LENGTH 16 +#define USERNAME_MAX_SIZE (USERNAME_MAX_LENGTH + 1) // NULL terminator +#define PASSWORD_MAX_SIZE (PASSWORD_MAX_LENGTH + 1) // NULL terminator + +#pragma pack(1) + +/// +/// The definition of IPMI command to get bootstrap account credentials +/// +typedef struct { + UINT8 GroupExtensionId; + UINT8 DisableBootstrapControl; +} IPMI_BOOTSTRAP_CREDENTIALS_COMMAND_DATA; + +/// +/// The response data of getting bootstrap credential +/// +typedef struct { + UINT8 CompletionCode; + UINT8 GroupExtensionId; + CHAR8 Username[USERNAME_MAX_LENGTH]; + CHAR8 Password[PASSWORD_MAX_LENGTH]; +} IPMI_BOOTSTRAP_CREDENTIALS_RESULT_RESPONSE; + +#pragma pack() + +#endif From 119314a86ed89679fa969baa9f6a0a1d873c12b0 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 23 Dec 2022 14:40:15 +0800 Subject: [PATCH 0528/1529] RedfishPkg/Include: Redfish USB Interface V2 update Support USB_INTERFACE_DEVICE_DESCRIPTOR_V2 which is updated in Redfish Host Interface spec v1.3. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Igor Kulchytskyy Reviewed-by: Nickle Wang --- .../IndustryStandard/RedfishHostInterface.h | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/RedfishPkg/Include/IndustryStandard/RedfishHostInterface.h b/RedfishPkg/Include/IndustryStandard/RedfishHostInterface.h index 49b3ceee39..d125347cc0 100644 --- a/RedfishPkg/Include/IndustryStandard/RedfishHostInterface.h +++ b/RedfishPkg/Include/IndustryStandard/RedfishHostInterface.h @@ -3,6 +3,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -29,6 +30,18 @@ #define REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4 0x01 #define REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP6 0x02 +/// +/// Definitions for IP assignment tyeps. +/// +typedef enum { + RedfishHostIpAssignmentUnknown, + RedfishHostIpAssignmentStatic, + RedfishHostIpAssignmentDhcp, + RedfishHostIpAssignmentAutoConfigure, + RedfishHostIpAssignmentHostSelected, + RedfishHostIpAssignmentReserved +} REDFISH_HOST_IP_ASSIGNMENT; + #pragma pack(1) /// /// Structure definitions of Host Interface device type 04h (USB Network Interface V2) @@ -40,12 +53,18 @@ typedef struct { ///< idVendor field of the USB descriptor. UINT16 IdProduct; ///< The Product ID of the device, as read from the ///< idProduct field of the USB descriptor. - UINT8 SecialNumberStr; ///< The string number for the Serial Number of the + UINT8 SerialNumberStr; ///< The string number for the Serial Number of the ///< device. The string data is read from the ///< iSerialNumber.bDescriptorType field of the USB ///< descriptor, and is converted from Unicode to ASCII ///< and is NULL terminated. UINT8 MacAddress[6]; ///< The MAC address of the PCI/PCIe network device. + + /// + /// Below is defined in Redfish Host Interface spec v1.3 + /// + UINT16 Characteristics; ///< Additional device characteristics. + UINT16 CredentialBootstrappingHandle; ///< Credential bootstrapping handle. } USB_INTERFACE_DEVICE_DESCRIPTOR_V2; // @@ -74,6 +93,10 @@ typedef struct { /// /// Define union for the Host Interface Device Descriptor /// +#define USB_INTERFACE_DEVICE_DESCRIPTOR_V2_SIZE_1_3 0x11 ///< Length USB interface device v2 defined in + ///< Redfish host interface spec v1.3 +#define USB_INTERFACE_DEVICE_DESCRIPTOR_V2_SIZE_1_2 0x0d ///< Length USB interface device v2 defined in + ///< Redfish host interface spec v1.2 typedef union { USB_INTERFACE_DEVICE_DESCRIPTOR_V2 UsbDeviceV2; ///< Device type USB V2 device discriptor. PCI_OR_PCIE_INTERFACE_DEVICE_DESCRIPTOR_V2 PciPcieDeviceV2; ///< Device type PCI/PCIe V2 device discriptor. From d06dfa2352a33f3d7b7fd1a7edd835e8aef25380 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 26 Dec 2022 15:06:22 +0800 Subject: [PATCH 0529/1529] MdeModulePkg/Include: Add IpmiCommandLib header file Add IpmiCommandLib to MdeModulePkg. This header file is copied from edk2-platforms/Features/Intel/OutOfBandManagement/ IpmiFeaturePkg\Include\Library. Having this header file in edk2 to avoid the dependence of edk2 module with edk2-platfrom. The NULL instance of IpmiCommandLib under MdeModulePkg has to be implemented for the same reason. IpmiCommandLib.h in edk2-platforms should be removed once this patch set is merged. Expect no impacts on edk2-platforms because MdeModulePkg is referred in INF file by all edk2 modules under edk2-platforms that use IpmiCommandLib. Signed-off-by: Abner Chang Cc: Jian J Wang Cc: Liming Gao Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Nate DeSimone Reviewed-by: Isaac Oram Reviewed-by: Igor Kulchytskyy Reviewed-by: Liming Gao --- MdeModulePkg/Include/Library/IpmiCommandLib.h | 683 ++++++++++++++++++ 1 file changed, 683 insertions(+) create mode 100644 MdeModulePkg/Include/Library/IpmiCommandLib.h diff --git a/MdeModulePkg/Include/Library/IpmiCommandLib.h b/MdeModulePkg/Include/Library/IpmiCommandLib.h new file mode 100644 index 0000000000..7edaf36cbe --- /dev/null +++ b/MdeModulePkg/Include/Library/IpmiCommandLib.h @@ -0,0 +1,683 @@ +/** @file + This library abstract how to send/receive IPMI command. + +Copyright (c) 2018-2021, Intel Corporation. All rights reserved.
+Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef IPMI_COMMAND_LIB_H_ +#define IPMI_COMMAND_LIB_H_ + +#include +#include + +// +// IPMI NetFnApp +// + +/** + This function gets the IPMI Device ID. + + @param[out] DeviceId Get device ID response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetDeviceId ( + OUT IPMI_GET_DEVICE_ID_RESPONSE *DeviceId + ); + +/** + This function gets the self-test result. + + @param[out] SelfTestResult Self test command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelfTestResult ( + OUT IPMI_SELF_TEST_RESULT_RESPONSE *SelfTestResult + ); + +/** + This function resets watchdog timer. + + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiResetWatchdogTimer ( + OUT UINT8 *CompletionCode + ); + +/** + This function sets watchdog timer. + + @param[in] SetWatchdogTimer Set watchdog timer request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + + +**/ +EFI_STATUS +EFIAPI +IpmiSetWatchdogTimer ( + IN IPMI_SET_WATCHDOG_TIMER_REQUEST *SetWatchdogTimer, + OUT UINT8 *CompletionCode + ); + +/** + This function gets watchdog timer. + + @param[out] GetWatchdogTimer Get watchdog timer response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetWatchdogTimer ( + OUT IPMI_GET_WATCHDOG_TIMER_RESPONSE *GetWatchdogTimer + ); + +/** + This function sets BMC global enables. + + @param[in] SetBmcGlobalEnables Set BMC global enables command request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSetBmcGlobalEnables ( + IN IPMI_SET_BMC_GLOBAL_ENABLES_REQUEST *SetBmcGlobalEnables, + OUT UINT8 *CompletionCode + ); + +/** + This function gets BMC global enables. + + @param[out] GetBmcGlobalEnables Get BMC global enables command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetBmcGlobalEnables ( + OUT IPMI_GET_BMC_GLOBAL_ENABLES_RESPONSE *GetBmcGlobalEnables + ); + +/** + This function clears message flag. + + @param[in] ClearMessageFlagsRequest Clear message flags command request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiClearMessageFlags ( + IN IPMI_CLEAR_MESSAGE_FLAGS_REQUEST *ClearMessageFlagsRequest, + OUT UINT8 *CompletionCode + ); + +/** + This function gets message flag. + + @param[out] GetMessageFlagsResponse Get message flags response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetMessageFlags ( + OUT IPMI_GET_MESSAGE_FLAGS_RESPONSE *GetMessageFlagsResponse + ); + +/** + This function gets message. + + @param[out] GetMessageResponse Get message command response. + @param[in,out] GetMessageResponseSize The size of get message response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetMessage ( + OUT IPMI_GET_MESSAGE_RESPONSE *GetMessageResponse, + IN OUT UINT32 *GetMessageResponseSize + ); + +/** + This function sends message. + + @param[in] SendMessageRequest The send message command request. + @param[in] SendMessageRequestSize The size of the send message command request. + @param[out] SendMessageResponse The send message command response. + @param[in,out] SendMessageResponseSize The size of the send message command response. + When input, the expected size of response. + When output, the actual size of response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSendMessage ( + IN IPMI_SEND_MESSAGE_REQUEST *SendMessageRequest, + IN UINT32 SendMessageRequestSize, + OUT IPMI_SEND_MESSAGE_RESPONSE *SendMessageResponse, + IN OUT UINT32 *SendMessageResponseSize + ); + +/** + This function gets the system UUID. + + @param[out] SystemGuid The pointer to retrieve system UUID. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Others Other errors. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSystemUuid ( + OUT EFI_GUID *SystemGuid + ); + +/** + This function gets the channel information. + + @param[in] GetChannelInfoRequest The get channel information request. + @param[in] GetChannelInfoResponse The get channel information response. + @param[in,out] GetChannelInfoResponseSize When input, the expected size of response. + When output, the exact size of the returned + response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChannelInfo ( + IN IPMI_GET_CHANNEL_INFO_REQUEST *GetChannelInfoRequest, + OUT IPMI_GET_CHANNEL_INFO_RESPONSE *GetChannelInfoResponse, + OUT UINT32 *GetChannelInfoResponseSize + ); + +// +// IPMI NetFnTransport +// + +/** + This function activates SOL + + @param[in] SolActivatingRequest SOL activating request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSolActivating ( + IN IPMI_SOL_ACTIVATING_REQUEST *SolActivatingRequest, + OUT UINT8 *CompletionCode + ); + +/** + This function sets SOL configuration parameters. + + @param[in] SetConfigurationParametersRequest Set SOL configuration parameters + command request. + @param[in] SetConfigurationParametersRequestSize Size of the set SOL configuration + parameters command request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSolConfigurationParameters ( + IN IPMI_SET_SOL_CONFIGURATION_PARAMETERS_REQUEST *SetConfigurationParametersRequest, + IN UINT32 SetConfigurationParametersRequestSize, + OUT UINT8 *CompletionCode + ); + +/** + This function gets SOL configuration parameters. + + @param[in] GetConfigurationParametersRequest Get SOL configuration parameters + command request. + @param[out] GetConfigurationParametersResponse Get SOL configuration parameters + response. + @param[in,out] GetConfigurationParametersResponseSize When input, the size of the expected + response. + When output, the exact size of + expect response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSolConfigurationParameters ( + IN IPMI_GET_SOL_CONFIGURATION_PARAMETERS_REQUEST *GetConfigurationParametersRequest, + OUT IPMI_GET_SOL_CONFIGURATION_PARAMETERS_RESPONSE *GetConfigurationParametersResponse, + IN OUT UINT32 *GetConfigurationParametersResponseSize + ); + +/** + This function gets the LAN configuration parameter. + + @param[in] GetLanConfigurationParametersRequest Get LAN configuration parameters command request. + @param[in] GetLanConfigurationParametersResponse The response of the get LAN configuration parameters. + @param[in,out] GetLanConfigurationParametersSize When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ + +EFI_STATUS +EFIAPI +IpmiGetLanConfigurationParameters ( + IN IPMI_GET_LAN_CONFIGURATION_PARAMETERS_REQUEST *GetLanConfigurationParametersRequest, + OUT IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *GetLanConfigurationParametersResponse, + IN OUT UINT32 *GetLanConfigurationParametersSize + ); + +// +// IPMI NetFnChassis +// + +/** + This function gets chassis capability. + + @param[out] GetChassisCapabilitiesResponse Gets chassis capability command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChassisCapabilities ( + OUT IPMI_GET_CHASSIS_CAPABILITIES_RESPONSE *GetChassisCapabilitiesResponse + ); + +/** + This function gets chassis status. + + @param[out] GetChassisCapabilitiesResponse The get chassis status command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChassisStatus ( + OUT IPMI_GET_CHASSIS_STATUS_RESPONSE *GetChassisStatusResponse + ); + +/** + This function sends chassis control request. + + @param[in] ChassisControlRequest The chassis control request. + @param[out] CompletionCode The command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiChassisControl ( + IN IPMI_CHASSIS_CONTROL_REQUEST *ChassisControlRequest, + OUT UINT8 *CompletionCode + ); + +/** + This function sets power restore policy. + + @param[in] SetPowerRestireRequest The set power restore policy control + command request. + @param[out] SetPowerRestireResponse The response of power restore policy. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSetPowerRestorePolicy ( + IN IPMI_SET_POWER_RESTORE_POLICY_REQUEST *SetPowerRestireRequest, + OUT IPMI_SET_POWER_RESTORE_POLICY_RESPONSE *SetPowerRestireResponse + ); + +// +// IPMI NetFnStorage +// + +/** + This function sets system boot option. + + @param[in] BootOptionsRequest Set system boot option request. + @param[out] BootOptionsResponse The response of set system boot + option request. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSystemBootOptions ( + IN IPMI_SET_BOOT_OPTIONS_REQUEST *BootOptionsRequest, + OUT IPMI_SET_BOOT_OPTIONS_RESPONSE *BootOptionsResponse + ); + +/** + This function gets system boot option. + + @param[in] BootOptionsRequest Get system boot option request. + @param[out] BootOptionsResponse The response of get system boot + option request. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSystemBootOptions ( + IN IPMI_GET_BOOT_OPTIONS_REQUEST *BootOptionsRequest, + OUT IPMI_GET_BOOT_OPTIONS_RESPONSE *BootOptionsResponse + ); + +/** + This function gets FRU inventory area info. + + @param[in] GetFruInventoryAreaInfoRequest Get FRU inventory area command request. + @param[out] GetFruInventoryAreaInfoResponse get FRU inventory area command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetFruInventoryAreaInfo ( + IN IPMI_GET_FRU_INVENTORY_AREA_INFO_REQUEST *GetFruInventoryAreaInfoRequest, + OUT IPMI_GET_FRU_INVENTORY_AREA_INFO_RESPONSE *GetFruInventoryAreaInfoResponse + ); + +/** + This function reads FRU data. + + @param[in] ReadFruDataRequest Read FRU data command request. + @param[out] ReadFruDataResponse Read FRU data command response. + @param[in,out] ReadFruDataResponseSize Size of the read FRU data response. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiReadFruData ( + IN IPMI_READ_FRU_DATA_REQUEST *ReadFruDataRequest, + OUT IPMI_READ_FRU_DATA_RESPONSE *ReadFruDataResponse, + IN OUT UINT32 *ReadFruDataResponseSize + ); + +/** + This function gets chassis capability. + + @param[in] WriteFruDataRequest Write FRU data command request. + @param[in] WriteFruDataRequestSize Size of the write FRU data command request. + @param[out] WriteFruDataResponse Write FRU data response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiWriteFruData ( + IN IPMI_WRITE_FRU_DATA_REQUEST *WriteFruDataRequest, + IN UINT32 WriteFruDataRequestSize, + OUT IPMI_WRITE_FRU_DATA_RESPONSE *WriteFruDataResponse + ); + +/** + This function gets SEL information. + + @param[out] GetSelInfoResponse Get SEL information command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelInfo ( + OUT IPMI_GET_SEL_INFO_RESPONSE *GetSelInfoResponse + ); + +/** + This function gets SEL entry. + + @param[in] GetSelEntryRequest Get SEL entry command request. + @param[out] GetSelEntryResponse Get SEL entry command response. + @param[in,out] GetSelEntryResponseSize Size of Get SEL entry request. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelEntry ( + IN IPMI_GET_SEL_ENTRY_REQUEST *GetSelEntryRequest, + OUT IPMI_GET_SEL_ENTRY_RESPONSE *GetSelEntryResponse, + IN OUT UINT32 *GetSelEntryResponseSize + ); + +/** + This function adds SEL entry. + + @param[in] AddSelEntryRequest Add SEL entry command request. + @param[out] AddSelEntryResponse Add SEL entry command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiAddSelEntry ( + IN IPMI_ADD_SEL_ENTRY_REQUEST *AddSelEntryRequest, + OUT IPMI_ADD_SEL_ENTRY_RESPONSE *AddSelEntryResponse + ); + +/** + This function partially adds SEL entry. + + @param[in] PartialAddSelEntryRequest Partial add SEL entry command request. + @param[in] PartialAddSelEntryRequestSize Size of partial add SEL entry command request. + @param[out] PartialAddSelEntryResponse Partial add SEL entry command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiPartialAddSelEntry ( + IN IPMI_PARTIAL_ADD_SEL_ENTRY_REQUEST *PartialAddSelEntryRequest, + IN UINT32 PartialAddSelEntryRequestSize, + OUT IPMI_PARTIAL_ADD_SEL_ENTRY_RESPONSE *PartialAddSelEntryResponse + ); + +/** + This function clears SEL entry. + + @param[in] ClearSelRequest Clear SEL command request. + @param[out] ClearSelResponse Clear SEL command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiClearSel ( + IN IPMI_CLEAR_SEL_REQUEST *ClearSelRequest, + OUT IPMI_CLEAR_SEL_RESPONSE *ClearSelResponse + ); + +/** + This function gets SEL time. + + @param[out] GetSelTimeResponse Get SEL time command response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelTime ( + OUT IPMI_GET_SEL_TIME_RESPONSE *GetSelTimeResponse + ); + +/** + This function sets SEL time. + + @param[in] SetSelTimeRequest Set SEL time command request. + @param[out] CompletionCode Command completion code. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSelTime ( + IN IPMI_SET_SEL_TIME_REQUEST *SetSelTimeRequest, + OUT UINT8 *CompletionCode + ); + +/** + This function gets SDR repository information. + + @param[out] GetSdrRepositoryInfoResp Get SDR repository response. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. +**/ +EFI_STATUS +EFIAPI +IpmiGetSdrRepositoryInfo ( + OUT IPMI_GET_SDR_REPOSITORY_INFO_RESPONSE *GetSdrRepositoryInfoResp + ); + +/** + This function gets SDR + + @param[in] GetSdrRequest Get SDR resquest. + @param[out] GetSdrResponse Get SDR response. + @param[in,out] GetSdrResponseSize The size of get SDR response. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_SUCCESS Command is sent successfully. + @retval EFI_NOT_AVAILABLE_YET Transport interface is not ready yet. + @retval Other Failure. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSdr ( + IN IPMI_GET_SDR_REQUEST *GetSdrRequest, + OUT IPMI_GET_SDR_RESPONSE *GetSdrResponse, + IN OUT UINT32 *GetSdrResponseSize + ); + +#endif From b1e7c0d3f610b76e0a58da5f1bb4cc98fb8b4deb Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 26 Dec 2022 15:06:55 +0800 Subject: [PATCH 0530/1529] MdeModulePkg/IpmiCommandLib: Add NULL instance library The NULL instance of IpmiCommandLib library under MdeModulePkg as the default IpmiCommandLib instance used by the modules under edk2. Signed-off-by: Abner Chang Cc: Jian J Wang Cc: Liming Gao Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Nate DeSimone Reviewed-by: Isaac Oram Reviewed-by: Igor Kulchytskyy Reviewed-by: Liming Gao --- .../BaseIpmiCommandLibNull.inf | 34 +++ .../IpmiCommandLibNetFnApp.c | 252 ++++++++++++++++++ .../IpmiCommandLibNetFnChassis.c | 123 +++++++++ .../IpmiCommandLibNetFnStorage.c | 248 +++++++++++++++++ .../IpmiCommandLibNetFnTransport.c | 100 +++++++ 5 files changed, 757 insertions(+) create mode 100644 MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf create mode 100644 MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnApp.c create mode 100644 MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnChassis.c create mode 100644 MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnStorage.c create mode 100644 MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnTransport.c diff --git a/MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf b/MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf new file mode 100644 index 0000000000..175e1ae433 --- /dev/null +++ b/MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf @@ -0,0 +1,34 @@ +## @file +# NULL instance of IpmiCommandLib +# +# Component description file for IPMI Command Library. +# +# Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
+# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseIpmiCommandLibNull + FILE_GUID = 63F06EF8-B78A-4E7E-823E-D11A21059669 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = IpmiCommandLib + +[sources] + IpmiCommandLibNetFnApp.c + IpmiCommandLibNetFnTransport.c + IpmiCommandLibNetFnChassis.c + IpmiCommandLibNetFnStorage.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseMemoryLib + DebugLib + diff --git a/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnApp.c b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnApp.c new file mode 100644 index 0000000000..2312e08258 --- /dev/null +++ b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnApp.c @@ -0,0 +1,252 @@ +/** @file + IPMI Command - NetFnApp NULL instance library. + + Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include + +/** + This function gets the IPMI Device ID. + + @param[out] DeviceId Get device ID response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetDeviceId ( + OUT IPMI_GET_DEVICE_ID_RESPONSE *DeviceId + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets the self-test result. + + @param[out] SelfTestResult Self test command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelfTestResult ( + OUT IPMI_SELF_TEST_RESULT_RESPONSE *SelfTestResult + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function resets watchdog timer. + + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiResetWatchdogTimer ( + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets watchdog timer. + + @param[in] SetWatchdogTimer Set watchdog timer request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetWatchdogTimer ( + IN IPMI_SET_WATCHDOG_TIMER_REQUEST *SetWatchdogTimer, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets watchdog timer. + + @param[out] GetWatchdogTimer Get watchdog timer response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetWatchdogTimer ( + OUT IPMI_GET_WATCHDOG_TIMER_RESPONSE *GetWatchdogTimer + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets BMC global enables. + + @param[in] SetBmcGlobalEnables Set BMC global enables command request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetBmcGlobalEnables ( + IN IPMI_SET_BMC_GLOBAL_ENABLES_REQUEST *SetBmcGlobalEnables, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets BMC global enables. + + @param[out] GetBmcGlobalEnables Get BMC global enables command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetBmcGlobalEnables ( + OUT IPMI_GET_BMC_GLOBAL_ENABLES_RESPONSE *GetBmcGlobalEnables + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function clears message flag. + + @param[in] ClearMessageFlagsRequest Clear message flags command Request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiClearMessageFlags ( + IN IPMI_CLEAR_MESSAGE_FLAGS_REQUEST *ClearMessageFlagsRequest, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets message flags. + + @param[out] GetMessageFlagsResponse Get message flags response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetMessageFlags ( + OUT IPMI_GET_MESSAGE_FLAGS_RESPONSE *GetMessageFlagsResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets message. + + @param[out] GetMessageResponse Get message command response. + @param[in,out] GetMessageResponseSize The size of get message response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetMessage ( + OUT IPMI_GET_MESSAGE_RESPONSE *GetMessageResponse, + IN OUT UINT32 *GetMessageResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sends message. + + @param[in] SendMessageRequest The send message command request. + @param[in] SendMessageRequestSize The size of the send message command request. + @param[out] SendMessageResponse The send message command response. + @param[in,out] SendMessageResponseSize The size of the send message command response. + When input, the expected size of response. + When output, the actual size of response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSendMessage ( + IN IPMI_SEND_MESSAGE_REQUEST *SendMessageRequest, + IN UINT32 SendMessageRequestSize, + OUT IPMI_SEND_MESSAGE_RESPONSE *SendMessageResponse, + IN OUT UINT32 *SendMessageResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets the system UUID. + + @param[out] SystemGuid The pointer to retrieve system UUID. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. +**/ +EFI_STATUS +EFIAPI +IpmiGetSystemUuid ( + OUT EFI_GUID *SystemGuid + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets the channel information. + + @param[in] GetChannelInfoRequest The get channel information request. + @param[out] GetChannelInfoResponse The get channel information response. + @param[out] GetChannelInfoResponseSize When input, the expected size of response. + When output, the exact size of the returned + response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChannelInfo ( + IN IPMI_GET_CHANNEL_INFO_REQUEST *GetChannelInfoRequest, + OUT IPMI_GET_CHANNEL_INFO_RESPONSE *GetChannelInfoResponse, + OUT UINT32 *GetChannelInfoResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} diff --git a/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnChassis.c b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnChassis.c new file mode 100644 index 0000000000..300a9b045f --- /dev/null +++ b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnChassis.c @@ -0,0 +1,123 @@ +/** @file + IPMI Command - NetFnChassis NULL instance library. + + Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include + +/** + This function gets chassis capability. + + @param[out] GetChassisCapabilitiesResponse Gets chassis capability command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChassisCapabilities ( + OUT IPMI_GET_CHASSIS_CAPABILITIES_RESPONSE *GetChassisCapabilitiesResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets chassis status. + + @param[out] GetChassisStatusResponse The get chassis status command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetChassisStatus ( + OUT IPMI_GET_CHASSIS_STATUS_RESPONSE *GetChassisStatusResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sends chassis control request. + + @param[in] ChassisControlRequest The chassis control request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiChassisControl ( + IN IPMI_CHASSIS_CONTROL_REQUEST *ChassisControlRequest, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets power restore policy. + + @param[in] ChassisControlRequest The set power restore policy control + command request. + @param[out] ChassisControlResponse The response of power restore policy. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetPowerRestorePolicy ( + IN IPMI_SET_POWER_RESTORE_POLICY_REQUEST *ChassisControlRequest, + OUT IPMI_SET_POWER_RESTORE_POLICY_RESPONSE *ChassisControlResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets system boot option. + + @param[in] BootOptionsRequest Set system boot option request. + @param[out] BootOptionsResponse The response of set system boot + option request. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSystemBootOptions ( + IN IPMI_SET_BOOT_OPTIONS_REQUEST *BootOptionsRequest, + OUT IPMI_SET_BOOT_OPTIONS_RESPONSE *BootOptionsResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets system boot option. + + @param[in] BootOptionsRequest Get system boot option request. + @param[out] BootOptionsResponse The response of get system boot + option request. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSystemBootOptions ( + IN IPMI_GET_BOOT_OPTIONS_REQUEST *BootOptionsRequest, + OUT IPMI_GET_BOOT_OPTIONS_RESPONSE *BootOptionsResponse + ) +{ + return RETURN_UNSUPPORTED; +} diff --git a/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnStorage.c b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnStorage.c new file mode 100644 index 0000000000..9e5ac959e4 --- /dev/null +++ b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnStorage.c @@ -0,0 +1,248 @@ +/** @file + IPMI Command - NetFnStorage NULL instance library. + + Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include + +/** + This function gets FRU inventory area info. + + @param[in] GetFruInventoryAreaInfoRequest Get FRU inventory area command request. + @param[out] GetFruInventoryAreaInfoResponse get FRU inventory area command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetFruInventoryAreaInfo ( + IN IPMI_GET_FRU_INVENTORY_AREA_INFO_REQUEST *GetFruInventoryAreaInfoRequest, + OUT IPMI_GET_FRU_INVENTORY_AREA_INFO_RESPONSE *GetFruInventoryAreaInfoResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function reads FRU data. + + @param[in] ReadFruDataRequest Read FRU data command request. + @param[out] ReadFruDataResponse Read FRU data command response. + @param[in,out] ReadFruDataResponseSize Size of the read FRU data response. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiReadFruData ( + IN IPMI_READ_FRU_DATA_REQUEST *ReadFruDataRequest, + OUT IPMI_READ_FRU_DATA_RESPONSE *ReadFruDataResponse, + IN OUT UINT32 *ReadFruDataResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets chassis capability. + + @param[in] WriteFruDataRequest Write FRU data command request. + @param[in] WriteFruDataRequestSize Size of the write FRU data command request. + @param[out] WriteFruDataResponse Write FRU data response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiWriteFruData ( + IN IPMI_WRITE_FRU_DATA_REQUEST *WriteFruDataRequest, + IN UINT32 WriteFruDataRequestSize, + OUT IPMI_WRITE_FRU_DATA_RESPONSE *WriteFruDataResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SEL information. + + @param[out] GetSelInfoResponse Get SEL information command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelInfo ( + OUT IPMI_GET_SEL_INFO_RESPONSE *GetSelInfoResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SEL entry. + + @param[in] GetSelEntryRequest Get SEL entry command request. + @param[out] GetSelEntryResponse Get SEL entry command response. + @param[in,out] GetSelEntryResponseSize Size of Get SEL entry request. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelEntry ( + IN IPMI_GET_SEL_ENTRY_REQUEST *GetSelEntryRequest, + OUT IPMI_GET_SEL_ENTRY_RESPONSE *GetSelEntryResponse, + IN OUT UINT32 *GetSelEntryResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function adds SEL entry. + + @param[in] AddSelEntryRequest Add SEL entry command request. + @param[out] AddSelEntryResponse Add SEL entry command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiAddSelEntry ( + IN IPMI_ADD_SEL_ENTRY_REQUEST *AddSelEntryRequest, + OUT IPMI_ADD_SEL_ENTRY_RESPONSE *AddSelEntryResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function partially adds SEL entry. + + @param[in] PartialAddSelEntryRequest Partial add SEL entry command request. + @param[in] PartialAddSelEntryRequestSize Size of partial add SEL entry command request. + @param[out] PartialAddSelEntryResponse Partial add SEL entry command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiPartialAddSelEntry ( + IN IPMI_PARTIAL_ADD_SEL_ENTRY_REQUEST *PartialAddSelEntryRequest, + IN UINT32 PartialAddSelEntryRequestSize, + OUT IPMI_PARTIAL_ADD_SEL_ENTRY_RESPONSE *PartialAddSelEntryResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function clears SEL entry. + + @param[in] ClearSelRequest Clear SEL command request. + @param[out] ClearSelResponse Clear SEL command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiClearSel ( + IN IPMI_CLEAR_SEL_REQUEST *ClearSelRequest, + OUT IPMI_CLEAR_SEL_RESPONSE *ClearSelResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SEL time. + + @param[out] GetSelTimeResponse Get SEL time command response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSelTime ( + OUT IPMI_GET_SEL_TIME_RESPONSE *GetSelTimeResponse + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets SEL time. + + @param[in] SetSelTimeRequest Set SEL time command request. + @param[out] CompletionCode Command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSelTime ( + IN IPMI_SET_SEL_TIME_REQUEST *SetSelTimeRequest, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SDR repository information. + + @param[out] GetSdrRepositoryInfoResp Get SDR repository response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSdrRepositoryInfo ( + OUT IPMI_GET_SDR_REPOSITORY_INFO_RESPONSE *GetSdrRepositoryInfoResp + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SDR + + @param[in] GetSdrRequest Get SDR resquest. + @param[out] GetSdrResponse Get SDR response. + @param[in,out] GetSdrResponseSize The size of get SDR response. + When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSdr ( + IN IPMI_GET_SDR_REQUEST *GetSdrRequest, + OUT IPMI_GET_SDR_RESPONSE *GetSdrResponse, + IN OUT UINT32 *GetSdrResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} diff --git a/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnTransport.c b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnTransport.c new file mode 100644 index 0000000000..b45329f240 --- /dev/null +++ b/MdeModulePkg/Library/BaseIpmiCommandLibNull/IpmiCommandLibNetFnTransport.c @@ -0,0 +1,100 @@ +/** @file + IPMI Command - NetFnTransport NULL instance library. + + Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.
+ Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include + +/** + This function activates SOL + + @param[in] SolActivatingRequest SOL activating request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSolActivating ( + IN IPMI_SOL_ACTIVATING_REQUEST *SolActivatingRequest, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function sets SOL configuration parameters. + + @param[in] SetConfigurationParametersRequest Set SOL configuration parameters + command request. + @param[in] SetConfigurationParametersRequestSize Size of set SOL configuration + parameters command request. + @param[out] CompletionCode The command completion code. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiSetSolConfigurationParameters ( + IN IPMI_SET_SOL_CONFIGURATION_PARAMETERS_REQUEST *SetConfigurationParametersRequest, + IN UINT32 SetConfigurationParametersRequestSize, + OUT UINT8 *CompletionCode + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets SOL configuration parameters. + + @param[in] GetConfigurationParametersRequest Get SOL configuration parameters + command request. + @param[out] GetConfigurationParametersResponse Get SOL configuration parameters + response. + @param[in,out] GetConfigurationParametersResponseSize When input, the size of expect response. + When output, the exact size of + expect response. + + @retval EFI_UNSUPPORTED Unsupported in the NULL lib. + +**/ +EFI_STATUS +EFIAPI +IpmiGetSolConfigurationParameters ( + IN IPMI_GET_SOL_CONFIGURATION_PARAMETERS_REQUEST *GetConfigurationParametersRequest, + OUT IPMI_GET_SOL_CONFIGURATION_PARAMETERS_RESPONSE *GetConfigurationParametersResponse, + IN OUT UINT32 *GetConfigurationParametersResponseSize + ) +{ + return RETURN_UNSUPPORTED; +} + +/** + This function gets the LAN configuration parameter. + + @param[in] GetLanConfigurationParametersRequest Request data + @param[out] GetLanConfigurationParametersResponse Response data + @param[in,out] GetLanConfigurationParametersSize When input, the expected size of response data. + When out, the exact size of response data. + + @retval EFI_SUCCESS Lan configuration parameter is returned in the response. + @retval Others Other errors. + +**/ +EFI_STATUS +EFIAPI +IpmiGetLanConfigurationParameters ( + IN IPMI_GET_LAN_CONFIGURATION_PARAMETERS_REQUEST *GetLanConfigurationParametersRequest, + OUT IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *GetLanConfigurationParametersResponse, + IN OUT UINT32 *GetLanConfigurationParametersSize + ) +{ + return RETURN_UNSUPPORTED; +} From 030d2f1f01251a115dbb6752587eff69aa6f7a62 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Mon, 26 Dec 2022 15:07:17 +0800 Subject: [PATCH 0531/1529] MdeModulePkg: Add IpmiCommandLib Add IpmiCommandLib to MdeModulePkg DEC/DSC files. Signed-off-by: Abner Chang Cc: Jian J Wang Cc: Liming Gao Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Nate DeSimone Reviewed-by: Isaac Oram Reviewed-by: Igor Kulchytskyy Reviewed-by: Liming Gao --- MdeModulePkg/MdeModulePkg.dec | 5 +++++ MdeModulePkg/MdeModulePkg.dsc | 3 +++ 2 files changed, 8 insertions(+) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index be5e829ca9..9605c617b7 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -9,6 +9,7 @@ # (C) Copyright 2016 - 2019 Hewlett Packard Enterprise Development LP
# Copyright (c) 2017, AMD Incorporated. All rights reserved.
# Copyright (c) Microsoft Corporation.
+# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -117,6 +118,10 @@ # IpmiLib|Include/Library/IpmiLib.h + ## @libraryclass Provides interfaces to send/receive IPMI command. + # + IpmiCommandLib|Include/Library/IpmiCommandLib.h + ## @libraryclass Provides interfaces for platform to return root bridge information to PciHostBridgeDxe driver. # PciHostBridgeLib|Include/Library/PciHostBridgeLib.h diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc index 659482ab73..1014598f31 100644 --- a/MdeModulePkg/MdeModulePkg.dsc +++ b/MdeModulePkg/MdeModulePkg.dsc @@ -4,6 +4,7 @@ # (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation. +# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -104,6 +105,7 @@ VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf MmUnblockMemoryLib|MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf + IpmiCommandLib|MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf [LibraryClasses.EBC.PEIM] IoLib|MdePkg/Library/PeiIoLibCpuIo/PeiIoLibCpuIo.inf @@ -333,6 +335,7 @@ MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.inf MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.inf MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.inf + MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.inf MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf From 564d6a2cf37c630dd7bed47370012eb0479859d5 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 19 Jan 2023 09:51:07 +0800 Subject: [PATCH 0532/1529] EmbeddedPkg: Rename FfsFindSectionData as FfsFindSectionDataWithHook Commit c673216f53 introduces FFS_CHECK_SECTION_HOOK and add it as the second input parameter in FfsFindSectionData. This change breaks the build of ArmVirtPkg. To fix this issue, the new version of FfsFindSectionData is renamed as FfsFindSectionDataWithHook in this patch. In the following patch the original FfsFindSectionData will be added back. FfsFindSectionData is renamed as FfsFindSectionDataWithHook. Accordingly PeilessStartupLib in OvmfPkg should be updated as well. To prevent the build from being broken, the changes in OvmfPkg are in this patch. Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann --- EmbeddedPkg/Include/Library/PrePiLib.h | 2 +- EmbeddedPkg/Library/PrePiLib/FwVol.c | 10 ++++++---- EmbeddedPkg/Library/PrePiLib/PrePiLib.c | 2 +- OvmfPkg/Library/PeilessStartupLib/DxeLoad.c | 4 ++-- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h index f60b667818..0c259864d6 100644 --- a/EmbeddedPkg/Include/Library/PrePiLib.h +++ b/EmbeddedPkg/Include/Library/PrePiLib.h @@ -78,7 +78,7 @@ EFI_STATUS **/ EFI_STATUS EFIAPI -FfsFindSectionData ( +FfsFindSectionDataWithHook ( IN EFI_SECTION_TYPE SectionType, IN FFS_CHECK_SECTION_HOOK SectionCheckHook, IN EFI_PEI_FILE_HANDLE FileHandle, diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c index 778d8b13c3..85dbf5b0ad 100644 --- a/EmbeddedPkg/Library/PrePiLib/FwVol.c +++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c @@ -459,9 +459,11 @@ FfsProcessSection ( /** This service enables discovery sections of a given type within a valid FFS file. + Caller also can provide a SectionCheckHook to do additional checking. - @param SearchType The value of the section type to find. - @param FfsFileHeader A pointer to the file header that contains the set of sections to + @param SectionType The value of the section type to find. + @param SectionCheckHook A hook which can check if the section is the target one. + @param FileHandle A pointer to the file header that contains the set of sections to be searched. @param SectionData A pointer to the discovered section, if successful. @@ -471,7 +473,7 @@ FfsProcessSection ( **/ EFI_STATUS EFIAPI -FfsFindSectionData ( +FfsFindSectionDataWithHook ( IN EFI_SECTION_TYPE SectionType, IN FFS_CHECK_SECTION_HOOK SectionCheckHook, IN EFI_PEI_FILE_HANDLE FileHandle, @@ -817,7 +819,7 @@ FfsProcessFvFile ( // // Find FvImage in FvFile // - Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, NULL, FvFileHandle, (VOID **)&FvImageHandle); + Status = FfsFindSectionDataWithHook (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, NULL, FvFileHandle, (VOID **)&FvImageHandle); if (EFI_ERROR (Status)) { return Status; } diff --git a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c index 3b6fc4f0eb..3cf866dab2 100644 --- a/EmbeddedPkg/Library/PrePiLib/PrePiLib.c +++ b/EmbeddedPkg/Library/PrePiLib/PrePiLib.c @@ -131,7 +131,7 @@ LoadDxeCoreFromFfsFile ( VOID *Hob; EFI_FV_FILE_INFO FvFileInfo; - Status = FfsFindSectionData (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); + Status = FfsFindSectionDataWithHook (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); if (EFI_ERROR (Status)) { return Status; } diff --git a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c index 4b1fefd452..d34690eb8a 100644 --- a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c +++ b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c @@ -209,7 +209,7 @@ FindDxeNonCc ( // // Find FvImage in FvFile // - Status = FfsFindSectionData (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, CheckSectionHookForDxeNonCc, FileHandle, (VOID **)&FvImageHandle); + Status = FfsFindSectionDataWithHook (EFI_SECTION_FIRMWARE_VOLUME_IMAGE, CheckSectionHookForDxeNonCc, FileHandle, (VOID **)&FvImageHandle); if (EFI_ERROR (Status)) { return Status; } @@ -303,7 +303,7 @@ DxeLoadCore ( // // Load the DXE Core from a Firmware Volume. // - Status = FfsFindSectionData (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); + Status = FfsFindSectionDataWithHook (EFI_SECTION_PE32, NULL, FileHandle, &PeCoffImage); if (EFI_ERROR (Status)) { return Status; } From 7ccaa03b75fb40c8b1465cd78fb325ce04cde434 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 19 Jan 2023 09:51:08 +0800 Subject: [PATCH 0533/1529] EmbeddedPkg: Add back FfsFindSectionData In commit c673216f53 a new input parameter is added in FfsFindSectionData. That change breaks the build of ArmVirtPkg. In this patch FfsFindSectionData is added back. It calls FfsFindSectionDataWithHook with a NULL hook. Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann --- EmbeddedPkg/Include/Library/PrePiLib.h | 20 ++++++++++++++++++++ EmbeddedPkg/Library/PrePiLib/FwVol.c | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h index 0c259864d6..93a9115eac 100644 --- a/EmbeddedPkg/Include/Library/PrePiLib.h +++ b/EmbeddedPkg/Include/Library/PrePiLib.h @@ -85,6 +85,26 @@ FfsFindSectionDataWithHook ( OUT VOID **SectionData ); +/** + This service enables discovery sections of a given type within a valid FFS file. + + @param SectionType The value of the section type to find. + @param FileHandle A pointer to the file header that contains the set of sections to + be searched. + @param SectionData A pointer to the discovered section, if successful. + + @retval EFI_SUCCESS The section was found. + @retval EFI_NOT_FOUND The section was not found. + +**/ +EFI_STATUS +EFIAPI +FfsFindSectionData ( + IN EFI_SECTION_TYPE SectionType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData + ); + /** Find a file in the volume by name diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c index 85dbf5b0ad..7739a5c8aa 100644 --- a/EmbeddedPkg/Library/PrePiLib/FwVol.c +++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c @@ -504,6 +504,29 @@ FfsFindSectionDataWithHook ( ); } +/** + This service enables discovery sections of a given type within a valid FFS file. + + @param SectionType The value of the section type to find. + @param FileHandle A pointer to the file header that contains the set of sections to + be searched. + @param SectionData A pointer to the discovered section, if successful. + + @retval EFI_SUCCESS The section was found. + @retval EFI_NOT_FOUND The section was not found. + +**/ +EFI_STATUS +EFIAPI +FfsFindSectionData ( + IN EFI_SECTION_TYPE SectionType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData + ) +{ + return FfsFindSectionDataWithHook (SectionType, NULL, FileHandle, SectionData); +} + /** This service enables discovery of additional firmware files. From 878c5fb74cf5bb5fe2877a5e68eaf7e902a39ccc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 19 Jan 2023 14:43:02 +0100 Subject: [PATCH 0534/1529] OvmfPkg/PlatformCI VS2019: Enable temporary workaround for cpuhp bugfix QEMU for x86 has a nasty CPU hotplug bug of which the ramifications are difficult to oversee, even though KVM acceleration seems to be unaffected. This has been addressed in QEMU mainline, and will percolate through the ecosystem at its usual pace. In the mean time, due to the potential impact on production workloads, we will be updating OVMF to abort the boot when it detects a QEMU build that is affected. Tiancore's platform CI uses QEMU in TCG mode, and is therefore impacted by this mitigation, unless its QEMU builds are updated. This has been done for Ubuntu-GCC5, but Windows-VS2019 still uses a QEMU build that is affected. Aborting the boot upon detecting the QEMU issue will render all boot tests carried out on Windows-VS2019 broken unless we implement the 'escape hatch' that enables proceed-at-your-own-risk mode, and permits the boot to proceed even if the QEMU issue is detected. So let's enable this for Windows-VS2019, and remove it again once it is no longer needed. Cc: Laszlo Ersek Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Michael Brown Cc: Oliver Steffen Cc: Michael Kubacki Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4250 Signed-off-by: Ard Biesheuvel Message-Id: <20230119134302.1524569-1-ardb@kernel.org> Acked-by: Gerd Hoffmann Reviewed-by: Michael Kubacki Acked-by: Jiewen Yao Reviewed-by: Laszlo Ersek --- .../PlatformCI/.azurepipelines/Windows-VS2019.yml | 2 +- OvmfPkg/PlatformCI/PlatformBuildLib.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml b/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml index 7e63f419b2..b3b91aa84e 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Windows-VS2019.yml @@ -24,7 +24,7 @@ jobs: package: 'OvmfPkg' vm_image: 'windows-2019' should_run: true - run_flags: "MAKE_STARTUP_NSH=TRUE QEMU_HEADLESS=TRUE" + run_flags: "MAKE_STARTUP_NSH=TRUE QEMU_HEADLESS=TRUE QEMU_CPUHP_QUIRK=TRUE" #Use matrix to speed up the build process strategy: diff --git a/OvmfPkg/PlatformCI/PlatformBuildLib.py b/OvmfPkg/PlatformCI/PlatformBuildLib.py index bfef9849c7..58dc1189a2 100644 --- a/OvmfPkg/PlatformCI/PlatformBuildLib.py +++ b/OvmfPkg/PlatformCI/PlatformBuildLib.py @@ -170,6 +170,7 @@ def SetPlatformEnv(self): self.env.SetValue("PRODUCT_NAME", "OVMF", "Platform Hardcoded") self.env.SetValue("MAKE_STARTUP_NSH", "FALSE", "Default to false") self.env.SetValue("QEMU_HEADLESS", "FALSE", "Default to false") + self.env.SetValue("QEMU_CPUHP_QUIRK", "FALSE", "Default to false") return 0 def PlatformPreBuild(self): @@ -211,6 +212,17 @@ def FlashRomImage(self): args += " -pflash " + os.path.join(OutputPath_FV, "OVMF.fd") # path to firmware + ### + ### NOTE This is a temporary workaround to allow platform CI to cope with + ### a QEMU bug in the CPU hotplug code. Once the CI environment has + ### been updated to carry a fixed version of QEMU, this can be + ### removed again + ### + ### Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4250 + ### + if (self.env.GetValue("QEMU_CPUHP_QUIRK").upper() == "TRUE"): + args += " -fw_cfg name=opt/org.tianocore/X-Cpuhp-Bugcheck-Override,string=yes" + if (self.env.GetValue("MAKE_STARTUP_NSH").upper() == "TRUE"): f = open(os.path.join(VirtualDrive, "startup.nsh"), "w") f.write("BOOT SUCCESS !!! \n") From 9330a9314b78f359a52e710ced31b44dd79fd3e1 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 19 Jan 2023 12:01:30 +0100 Subject: [PATCH 0535/1529] OvmfPkg/PlatformInitLib: factor out PlatformCpuCountBugCheck() Move the QEMU v2.7 reset bug check/workaround to a separate function, as we'll need to detect further issues. Cc: Ard Biesheuvel Cc: Brijesh Singh Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Jordan Justen Cc: Michael Brown Cc: Min Xu Cc: Oliver Steffen Cc: Sebastien Boeuf Cc: Tom Lendacky Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4250 Signed-off-by: Laszlo Ersek Message-Id: <20230119110131.91923-2-lersek@redhat.com> Reviewed-by: Ard Biesheuvel Hugely-appreciated-by: Michael Brown Acked-by: Gerd Hoffmann --- OvmfPkg/Library/PlatformInitLib/Platform.c | 81 ++++++++++++++++------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 9ab0342fd8..d1be5c2d79 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -404,6 +404,61 @@ PlatformMiscInitialization ( } } +/** + Check for various QEMU bugs concerning CPU numbers. + + Compensate for those bugs if various conditions are satisfied, by updating a + suitable subset of the input-output parameters. The function may not return + (it may hang deliberately), even in RELEASE builds, if the QEMU bug is + impossible to cover up. + + @param[in,out] BootCpuCount On input, the boot CPU count reported by QEMU via + fw_cfg (QemuFwCfgItemSmpCpuCount). The caller is + responsible for ensuring (BootCpuCount > 0); that + is, if QEMU does not provide the boot CPU count + via fw_cfg *at all*, then this function must not + be called. + + @param[in,out] Present On input, the number of present-at-boot CPUs, as + reported by QEMU through the modern CPU hotplug + register block. + + @param[in,out] Possible On input, the number of possible CPUs, as + reported by QEMU through the modern CPU hotplug + register block. +**/ +STATIC +VOID +PlatformCpuCountBugCheck ( + IN OUT UINT16 *BootCpuCount, + IN OUT UINT32 *Present, + IN OUT UINT32 *Possible + ) +{ + ASSERT (*BootCpuCount > 0); + + // + // Sanity check: fw_cfg and the modern CPU hotplug interface should expose the + // same boot CPU count. + // + if (*BootCpuCount != *Present) { + DEBUG (( + DEBUG_WARN, + "%a: QEMU v2.7 reset bug: BootCpuCount=%d Present=%u\n", + __FUNCTION__, + *BootCpuCount, + *Present + )); + // + // The handling of QemuFwCfgItemSmpCpuCount, across CPU hotplug plus + // platform reset (including S3), was corrected in QEMU commit e3cadac073a9 + // ("pc: fix FW_CFG_NB_CPUS to account for -device added CPUs", 2016-11-16), + // part of release v2.8.0. + // + *BootCpuCount = (UINT16)*Present; + } +} + /** Fetch the boot CPU count and the possible CPU count from QEMU, and expose them to UefiCpuPkg modules. @@ -518,8 +573,8 @@ PlatformMaxCpuCountInitialization ( UINT8 CpuStatus; // - // Read the status of the currently selected CPU. This will help with a - // sanity check against "BootCpuCount". + // Read the status of the currently selected CPU. This will help with + // various CPU count sanity checks. // CpuStatus = IoRead8 (CpuHpBase + QEMU_CPUHP_R_CPU_STAT); if ((CpuStatus & QEMU_CPUHP_STAT_ENABLED) != 0) { @@ -540,27 +595,7 @@ PlatformMaxCpuCountInitialization ( ASSERT (Selected == Possible || Selected == 0); } while (Selected > 0); - // - // Sanity check: fw_cfg and the modern CPU hotplug interface should - // return the same boot CPU count. - // - if (BootCpuCount != Present) { - DEBUG (( - DEBUG_WARN, - "%a: QEMU v2.7 reset bug: BootCpuCount=%d " - "Present=%u\n", - __FUNCTION__, - BootCpuCount, - Present - )); - // - // The handling of QemuFwCfgItemSmpCpuCount, across CPU hotplug plus - // platform reset (including S3), was corrected in QEMU commit - // e3cadac073a9 ("pc: fix FW_CFG_NB_CPUS to account for -device added - // CPUs", 2016-11-16), part of release v2.8.0. - // - BootCpuCount = (UINT16)Present; - } + PlatformCpuCountBugCheck (&BootCpuCount, &Present, &Possible); MaxCpuCount = Possible; } From 0c28a60452db716cc41fdd47924af9a719c700af Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 19 Jan 2023 12:01:31 +0100 Subject: [PATCH 0536/1529] OvmfPkg/PlatformInitLib: catch QEMU's CPU hotplug reg block regression In QEMU v5.1.0, the CPU hotplug register block misbehaves: the negotiation protocol is (effectively) broken such that it suggests that switching from the legacy interface to the modern interface works, but in reality the switch never happens. The symptom has been witnessed when using TCG acceleration; KVM seems to mask the issue. The issue persists with the following (latest) stable QEMU releases: v5.2.0, v6.2.0, v7.2.0. Currently there is no stable release that addresses the problem. The QEMU bug confuses the Present and Possible counting in function PlatformMaxCpuCountInitialization(), in "OvmfPkg/Library/PlatformInitLib/Platform.c". OVMF ends up with Present=0 Possible=1. This in turn further confuses MpInitLib in UefiCpuPkg (hence firmware-time multiprocessing will be broken). Worse, CPU hot(un)plug with SMI will be summarily broken in OvmfPkg/CpuHotplugSmm, which (considering the privilege level of SMM) is not that great. Detect the issue in PlatformCpuCountBugCheck(), and print an error message and *hang* if the issue is present. Users willing to take risks can override the hang with the experimental QEMU command line option -fw_cfg name=opt/org.tianocore/X-Cpuhp-Bugcheck-Override,string=yes (The "-fw_cfg" QEMU option itself is not experimental; its above argument, as far it concerns the firmware, is experimental.) The problem was originally reported by Ard [0]. We analyzed it at [1] and [2]. A QEMU patch was sent at [3]; now merged as commit dab30fbef389 ("acpi: cpuhp: fix guest-visible maximum access size to the legacy reg block", 2023-01-08), to be included in QEMU v8.0.0. [0] https://bugzilla.tianocore.org/show_bug.cgi?id=4234#c2 [1] https://bugzilla.tianocore.org/show_bug.cgi?id=4234#c3 [2] IO port write width clamping differs between TCG and KVM http://mid.mail-archive.com/aaedee84-d3ed-a4f9-21e7-d221a28d1683@redhat.com https://lists.gnu.org/archive/html/qemu-devel/2023-01/msg00199.html [3] acpi: cpuhp: fix guest-visible maximum access size to the legacy reg block http://mid.mail-archive.com/20230104090138.214862-1-lersek@redhat.com https://lists.gnu.org/archive/html/qemu-devel/2023-01/msg00278.html NOTE: PlatformInitLib is used in the following platform DSCs: OvmfPkg/AmdSev/AmdSevX64.dsc OvmfPkg/CloudHv/CloudHvX64.dsc OvmfPkg/IntelTdx/IntelTdxX64.dsc OvmfPkg/Microvm/MicrovmX64.dsc OvmfPkg/OvmfPkgIa32.dsc OvmfPkg/OvmfPkgIa32X64.dsc OvmfPkg/OvmfPkgX64.dsc but I can only test this change with the last three platforms, running on QEMU. Test results: TCG QEMU OVMF override result patched patched --- ------- ------- -------- -------------------------------------- 0 0 0 0 CPU counts OK (KVM masks the QEMU bug) 0 0 1 0 CPU counts OK (KVM masks the QEMU bug) 0 1 0 0 CPU counts OK (QEMU fix, but KVM masks the QEMU bug anyway) 0 1 1 0 CPU counts OK (QEMU fix, but KVM masks the QEMU bug anyway) 1 0 0 0 boot with broken CPU counts (original QEMU bug) 1 0 1 0 broken CPU count caught (boot hangs) 1 0 1 1 broken CPU count caught, bug check overridden, boot continues 1 1 0 0 CPU counts OK (QEMU fix) 1 1 1 0 CPU counts OK (QEMU fix) Cc: Ard Biesheuvel Cc: Brijesh Singh Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Jordan Justen Cc: Michael Brown Cc: Min Xu Cc: Oliver Steffen Cc: Sebastien Boeuf Cc: Tom Lendacky Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4250 Signed-off-by: Laszlo Ersek Message-Id: <20230119110131.91923-3-lersek@redhat.com> Reviewed-by: Ard Biesheuvel Hugely-appreciated-by: Michael Brown Acked-by: Gerd Hoffmann --- OvmfPkg/Library/PlatformInitLib/Platform.c | 87 ++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index d1be5c2d79..9fee6e4810 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -36,6 +36,9 @@ #include +#define CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE \ + "opt/org.tianocore/X-Cpuhp-Bugcheck-Override" + VOID EFIAPI PlatformAddIoMemoryBaseSizeHob ( @@ -437,6 +440,87 @@ PlatformCpuCountBugCheck ( { ASSERT (*BootCpuCount > 0); + // + // Sanity check: we need at least 1 present CPU (CPU#0 is always present). + // + // The legacy-to-modern switching of the CPU hotplug register block got broken + // (for TCG) in QEMU v5.1.0. Refer to "IO port write width clamping differs + // between TCG and KVM" at + // + // or at + // . + // + // QEMU received the fix in commit dab30fbef389 ("acpi: cpuhp: fix + // guest-visible maximum access size to the legacy reg block", 2023-01-08), to + // be included in QEMU v8.0.0. + // + // If we're affected by this QEMU bug, then we must not continue: it confuses + // the multiprocessing in UefiCpuPkg/Library/MpInitLib, and breaks CPU + // hot(un)plug with SMI in OvmfPkg/CpuHotplugSmm. + // + if (*Present == 0) { + UINTN Idx; + STATIC CONST CHAR8 *CONST Message[] = { + "Broken CPU hotplug register block found. Update QEMU to version 8+, or", + "to a stable release with commit dab30fbef389 backported. Refer to", + ".", + "Consequences of the QEMU bug may include, but are not limited to:", + "- all firmware logic, dependent on the CPU hotplug register block,", + " being confused, for example, multiprocessing-related logic;", + "- guest OS data loss, including filesystem corruption, due to crash or", + " hang during ACPI S3 resume;", + "- SMM privilege escalation, by a malicious guest OS or 3rd partty UEFI", + " agent, against the platform firmware.", + "These symptoms need not necessarily be limited to the QEMU user", + "attempting to hot(un)plug a CPU.", + "The firmware will now stop (hang) deliberately, in order to prevent the", + "above symptoms.", + "You can forcibly override the hang, *at your own risk*, with the", + "following *experimental* QEMU command line option:", + " -fw_cfg name=" CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE ",string=yes", + "Please only report such bugs that you can reproduce *without* the", + "override.", + }; + RETURN_STATUS ParseStatus; + BOOLEAN Override; + + DEBUG (( + DEBUG_ERROR, + "%a: Present=%u Possible=%u\n", + __FUNCTION__, + *Present, + *Possible + )); + for (Idx = 0; Idx < ARRAY_SIZE (Message); ++Idx) { + DEBUG ((DEBUG_ERROR, "%a: %a\n", __FUNCTION__, Message[Idx])); + } + + ParseStatus = QemuFwCfgParseBool ( + CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE, + &Override + ); + if (!RETURN_ERROR (ParseStatus) && Override) { + DEBUG (( + DEBUG_WARN, + "%a: \"%a\" active. You've been warned.\n", + __FUNCTION__, + CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE + )); + // + // The bug is in QEMU v5.1.0+, where we're not affected by the QEMU v2.7 + // reset bug, so BootCpuCount from fw_cfg is reliable. Assume a fully + // populated topology, like when the modern CPU hotplug interface is + // unavailable. + // + *Present = *BootCpuCount; + *Possible = *BootCpuCount; + return; + } + + ASSERT (FALSE); + CpuDeadLoop (); + } + // // Sanity check: fw_cfg and the modern CPU hotplug interface should expose the // same boot CPU count. @@ -596,6 +680,9 @@ PlatformMaxCpuCountInitialization ( } while (Selected > 0); PlatformCpuCountBugCheck (&BootCpuCount, &Present, &Possible); + ASSERT (Present > 0); + ASSERT (Present <= Possible); + ASSERT (BootCpuCount == Present); MaxCpuCount = Possible; } From 40c9c5cbc76edca458eeed45583aa58be450f466 Mon Sep 17 00:00:00 2001 From: Tomas Pilar Date: Tue, 3 Jan 2023 09:02:29 -0800 Subject: [PATCH 0537/1529] ShellPkg: Export default shell delay as PCD Create PcdShellDefaultDelay to configure the default delay the shell provides for the user at the start time if the user wishes to cancel the execution of a potential startup script. The shell application already allows the user to override the delay default value by specifying the -delay cmdline argument. This however cannot be used when loading the shell application using direct boot or when integrating the shell into the platform firmware build. Thus, a PCD can be easily configured by the developer either at build time, or even at runtime. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Tomas Pilar Reviewed-by: Michael D Kinney --- ShellPkg/Application/Shell/Shell.c | 2 +- ShellPkg/Application/Shell/Shell.inf | 1 + ShellPkg/ShellPkg.dec | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/ShellPkg/Application/Shell/Shell.c b/ShellPkg/Application/Shell/Shell.c index df00adfdfa..0ae6e14a34 100644 --- a/ShellPkg/Application/Shell/Shell.c +++ b/ShellPkg/Application/Shell/Shell.c @@ -990,7 +990,7 @@ ProcessCommandLine ( ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = FALSE; ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = FALSE; ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest = FALSE; - ShellInfoObject.ShellInitSettings.Delay = 5; + ShellInfoObject.ShellInitSettings.Delay = PcdGet32 (PcdShellDefaultDelay); // // Start LoopVar at 0 to parse only optional arguments at Argv[0] diff --git a/ShellPkg/Application/Shell/Shell.inf b/ShellPkg/Application/Shell/Shell.inf index 4c32960a96..f1e41de133 100644 --- a/ShellPkg/Application/Shell/Shell.inf +++ b/ShellPkg/Application/Shell/Shell.inf @@ -103,3 +103,4 @@ gEfiShellPkgTokenSpaceGuid.PcdShellForceConsole ## CONSUMES gEfiShellPkgTokenSpaceGuid.PcdShellSupplier ## CONSUMES gEfiShellPkgTokenSpaceGuid.PcdShellMaxHistoryCommandCount ## CONSUMES + gEfiShellPkgTokenSpaceGuid.PcdShellDefaultDelay ## CONSUMES diff --git a/ShellPkg/ShellPkg.dec b/ShellPkg/ShellPkg.dec index 7b2d1230bd..2ebea0a261 100644 --- a/ShellPkg/ShellPkg.dec +++ b/ShellPkg/ShellPkg.dec @@ -136,3 +136,7 @@ # Up to this many bytes of vendor specific data will be used. Default is 0 # (disabled). gEfiShellPkgTokenSpaceGuid.PcdShellVendorExtendedDecode|0|UINT32|0x00000013 + + ## Controls the default delay the shell will offer to the user at the + # start to check if the user wishes to cancel the script autostart + gEfiShellPkgTokenSpaceGuid.PcdShellDefaultDelay|5|UINT32|0x00000015 From 119cceb44708f9578ad907d2885b0d93d7963eb8 Mon Sep 17 00:00:00 2001 From: "devel@edk2.groups.io" Date: Sat, 7 Jan 2023 07:16:10 -0800 Subject: [PATCH 0538/1529] MdeModulePkg: remove garbage pixels in LaffStd glyphs Signed-off-by: Jan Engelhardt Reviewed-by: Michael D Kinney --- .../Universal/Console/GraphicsConsoleDxe/LaffStd.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/LaffStd.c b/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/LaffStd.c index 1f7fe4cda8..99d909592c 100644 --- a/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/LaffStd.c +++ b/MdeModulePkg/Universal/Console/GraphicsConsoleDxe/LaffStd.c @@ -213,13 +213,13 @@ EFI_NARROW_GLYPH gUsStdNarrowGlyphData[] = { }, { 0x00a3, 0x00, { 0x00, 0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00 } }, - { 0x00a4, 0x00, { 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00 } + { 0x00a4, 0x00, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { 0x00a5, 0x00, { 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00 } }, { 0x00a6, 0x00, { 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00 } }, - { 0x00a7, 0x00, { 0x00, 0x00, 0x18, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00 } + { 0x00a7, 0x00, { 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00 } }, { 0x00a8, 0x00, { 0x00, 0x00, 0x00, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, @@ -315,7 +315,7 @@ EFI_NARROW_GLYPH gUsStdNarrowGlyphData[] = { }, { 0x00d6, 0x00, { 0xCC, 0xCC, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00 } }, - { 0x00d7, 0x00, { 0x10, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00 } + { 0x00d7, 0x00, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { 0x00d8, 0x00, { 0x00, 0x00, 0x00, 0x7C, 0xCE, 0xCE, 0xDE, 0xD6, 0xD6, 0xD6, 0xD6, 0xF6, 0xE6, 0xE6, 0x7C, 0x40, 0x00, 0x00, 0x00 } }, @@ -329,11 +329,11 @@ EFI_NARROW_GLYPH gUsStdNarrowGlyphData[] = { }, { 0x00dd, 0x00, { 0x18, 0x30, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00 } }, - { 0x00de, 0x00, { 0x00, 0x00, 0x10, 0x00, 0xF0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00 } + { 0x00de, 0x00, { 0x00, 0x00, 0x00, 0x00, 0xF0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00 } }, { 0x00df, 0x00, { 0x00, 0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xD8, 0xCC, 0xC6, 0xC6, 0xC6, 0xC6, 0xCC, 0x00, 0x00, 0x00, 0x00 } }, - { 0x00e0, 0x00, { 0x00, 0x30, 0x30, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00 } + { 0x00e0, 0x00, { 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00 } }, { 0x00e1, 0x00, { 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00 } }, From 350cfa87af485b694915a858ff5d02970a9cdf20 Mon Sep 17 00:00:00 2001 From: Jan Bobek Date: Mon, 23 Jan 2023 05:53:48 +0800 Subject: [PATCH 0539/1529] SecurityPkg/AuthVariableLib: Check SHA-256 OID with ContentInfo present REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4305 Based on whether the DER-encoded ContentInfo structure is present in authenticated SetVariable payload or not, the SHA-256 OID can be located at different places. UEFI specification explicitly states the driver shall support both cases, but the old code assumed ContentInfo was not present and incorrectly rejected authenticated variable updates when it were present. Cc: Jiewen Yao Cc: Jian J Wang Cc: Min Xu Signed-off-by: Jan Bobek Reviewed-by: Jiewen Yao --- .../Library/AuthVariableLib/AuthService.c | 50 ++++++++++++++++--- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/SecurityPkg/Library/AuthVariableLib/AuthService.c b/SecurityPkg/Library/AuthVariableLib/AuthService.c index 054ee4d1d9..9beeca09ae 100644 --- a/SecurityPkg/Library/AuthVariableLib/AuthService.c +++ b/SecurityPkg/Library/AuthVariableLib/AuthService.c @@ -1925,7 +1925,7 @@ VerifyTimeBasedPayload ( // SignedData.digestAlgorithms shall contain the digest algorithm used when preparing the // signature. Only a digest algorithm of SHA-256 is accepted. // - // According to PKCS#7 Definition: + // According to PKCS#7 Definition (https://www.rfc-editor.org/rfc/rfc2315): // SignedData ::= SEQUENCE { // version Version, // digestAlgorithms DigestAlgorithmIdentifiers, @@ -1933,15 +1933,49 @@ VerifyTimeBasedPayload ( // .... } // The DigestAlgorithmIdentifiers can be used to determine the hash algorithm // in VARIABLE_AUTHENTICATION_2 descriptor. - // This field has the fixed offset (+13) and be calculated based on two bytes of length encoding. + // This field has the fixed offset (+13) or (+32) based on whether the DER-encoded + // ContentInfo structure is present or not, and can be calculated based on two + // bytes of length encoding. + // + // Both condition can be handled in WrapPkcs7Data() in CryptPkcs7VerifyCommon.c. + // + // See below examples: + // + // 1. Without ContentInfo + // 30 82 0c da // SEQUENCE (5 element) (3294 BYTES) -- SignedData + // 02 01 01 // INTEGER 1 -- Version + // 31 0f // SET (1 element) (15 BYTES) -- DigestAlgorithmIdentifiers + // 30 0d // SEQUENCE (2 element) (13 BYTES) -- AlgorithmIdentifier + // 06 09 // OBJECT-IDENTIFIER (9 BYTES) -- algorithm + // 60 86 48 01 65 03 04 02 01 // sha256 [2.16.840.1.101.3.4.2.1] + // 05 00 // NULL (0 BYTES) -- parameters + // + // Example from: https://uefi.org/revocationlistfile + // + // 2. With ContentInfo + // 30 82 05 90 // SEQUENCE (1424 BYTES) -- ContentInfo + // 06 09 // OBJECT-IDENTIFIER (9 BYTES) -- ContentType + // 2a 86 48 86 f7 0d 01 07 02 // signedData [1.2.840.113549.1.7.2] + // a0 82 05 81 // CONTEXT-SPECIFIC CONSTRUCTED TAG 0 (1409 BYTES) -- content + // 30 82 05 7d // SEQUENCE (1405 BYTES) -- SignedData + // 02 01 01 // INTEGER 1 -- Version + // 31 0f // SET (1 element) (15 BYTES) -- DigestAlgorithmIdentifiers + // 30 0d // SEQUENCE (13 BYTES) -- AlgorithmIdentifier + // 06 09 // OBJECT-IDENTIFIER (9 BYTES) -- algorithm + // 60 86 48 01 65 03 04 02 01 // sha256 [2.16.840.1.101.3.4.2.1] + // 05 00 // NULL (0 BYTES) -- parameters + // + // Example generated with: https://wiki.archlinux.org/title/Unified_Extensible_Firmware_Interface/Secure_Boot#Manual_process // if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) { - if (SigDataSize >= (13 + sizeof (mSha256OidValue))) { - if (((*(SigData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) || - (CompareMem (SigData + 13, &mSha256OidValue, sizeof (mSha256OidValue)) != 0)) - { - return EFI_SECURITY_VIOLATION; - } + if ( ( (SigDataSize >= (13 + sizeof (mSha256OidValue))) + && ( ((*(SigData + 1) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) + || (CompareMem (SigData + 13, &mSha256OidValue, sizeof (mSha256OidValue)) != 0))) + && ( (SigDataSize >= (32 + sizeof (mSha256OidValue))) + && ( ((*(SigData + 20) & TWO_BYTE_ENCODE) != TWO_BYTE_ENCODE) + || (CompareMem (SigData + 32, &mSha256OidValue, sizeof (mSha256OidValue)) != 0)))) + { + return EFI_SECURITY_VIOLATION; } } From 2eb81e9f47e60a070d18ae73ee973eafff656b29 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 25 Jan 2023 18:10:49 +0100 Subject: [PATCH 0540/1529] OvmfPkg: fix BuildResourceDescriptorHob call in PlatformAddHobCB() BuildResourceDescriptorHob() expects the third parameter be the Length, not the End address. Fixes: 328076cfdf45 ("OvmfPkg/PlatformInitLib: Add PlatformAddHobCB") Reported-by: Tom Lendacky Signed-off-by: Gerd Hoffmann Tested-by: Tom Lendacky Reviewed-by: Jiewen Yao --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 5aeeeff89f..38cece9173 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -200,7 +200,7 @@ PlatformAddHobCB ( break; case EfiAcpiAddressRangeReserved: - BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_RESERVED, 0, Base, End); + BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_RESERVED, 0, Base, End - Base); DEBUG ((DEBUG_INFO, "%a: Reserved [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End)); break; default: From ef81268b5a85e796e6ea5047a4892ac6359f3014 Mon Sep 17 00:00:00 2001 From: Jake Garver Date: Thu, 26 Jan 2023 09:05:22 +0100 Subject: [PATCH 0541/1529] CryptoPkg/Library: Reinstate ARM/AARCH64 sections in SmmCryptLib.inf These sections were removed mistakenly. SmmCryptLib.inf supports these architectures. Signed-off-by: Jake Garver Reviewed-by: Michael D Kinney Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index 55df99f843..ab19930871 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -75,6 +75,12 @@ [Sources.X64] Rand/CryptRandTsc.c +[Sources.ARM] + Rand/CryptRand.c + +[Sources.AARCH64] + Rand/CryptRand.c + [Packages] MdePkg/MdePkg.dec CryptoPkg/CryptoPkg.dec From 86094f8f99bc54a94cb25838de83680a50a64ce3 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 19 Jan 2023 00:15:08 +0100 Subject: [PATCH 0542/1529] ArmVirtPkg/PrePi: Ensure timely execution of library constructors PrePi has a bare metal entry point, and so it is in charge of calling the library constructors once the C runtime has been initialized sufficiently. However, we are now relying on a HOB to have been constructed by the time the MMU code runs, and so the constructors should be run before that. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann --- ArmVirtPkg/PrePi/PrePi.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ArmVirtPkg/PrePi/PrePi.c b/ArmVirtPkg/PrePi/PrePi.c index c15dc305fc..3d943b2138 100755 --- a/ArmVirtPkg/PrePi/PrePi.c +++ b/ArmVirtPkg/PrePi/PrePi.c @@ -60,6 +60,9 @@ PrePiMain ( // InvalidateDataCacheRange ((VOID *)(UINTN)PcdGet64 (PcdFdBaseAddress), PcdGet32 (PcdFdSize)); + // SEC phase needs to run library constructors by hand. + ProcessLibraryConstructorList (); + // Initialize MMU and Memory HOBs (Resource Descriptor HOBs) Status = MemoryPeim (UefiMemoryBase, FixedPcdGet32 (PcdSystemMemoryUefiRegionSize)); ASSERT_EFI_ERROR (Status); @@ -93,9 +96,6 @@ PrePiMain ( // Now, the HOB List has been initialized, we can register performance information PERF_START (NULL, "PEI", NULL, StartTimeStamp); - // SEC phase needs to run library constructors by hand. - ProcessLibraryConstructorList (); - // Assume the FV that contains the SEC (our code) also contains a compressed FV. Status = DecompressFirstFv (); ASSERT_EFI_ERROR (Status); From 2ffda9a74bc410b25af8ed1cf2378f2ee1bd76d9 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Jan 2023 13:49:51 +0100 Subject: [PATCH 0543/1529] ArmVirtPkg/ArmVirtQemu: enlarge initial flash mapping The initial ID map used by ArmVirtQemu only covers 2 MiB of NOR flash, while the NOOPT build can be up to 3 MiB in size, resulting in a crash if the unmapped 1 MiB is accessed before the real page tables are up. So increate the initial flash mapping to 4 MiB. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann --- ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S index 4a4b7b77ed..584ffcb3eb 100644 --- a/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S @@ -15,6 +15,7 @@ .set TT_MT_MEM, (0x3 << 2) | (0x3 << 8) // MAIR #3 .set PAGE_XIP, TT_TYPE_PAGE | TT_MT_MEM | TT_AF | TT_RO | TT_NG + .set BLOCK_XIP, TT_TYPE_BLOCK | TT_MT_MEM | TT_AF | TT_RO | TT_NG .set BLOCK_DEV, TT_TYPE_BLOCK | TT_MT_DEV | TT_AF | TT_XN | TT_NG .set BLOCK_MEM, TT_TYPE_BLOCK | TT_MT_MEM | TT_AF | TT_XN | TT_NG @@ -33,7 +34,8 @@ idmap: /* level 0 */ 20: /* level 2 */ .quad 3f + TT_TYPE_TABLE // up to 2 MB of flash - .fill 63, 8, 0x0 // 126 MB of unused flash + .quad BLOCK_XIP | (0x1 << 21) // another 2 MB of flash + .fill 62, 8, 0x0 // 124 MB of unused flash .set idx, 64 .rept 448 .quad BLOCK_DEV | (idx << 21) // 896 MB of RW- device mappings From ac7dc6cecc0b705ae0f987bacbb34655e9a90af0 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Jan 2023 15:34:24 +0000 Subject: [PATCH 0544/1529] ArmVirtPkg/PlatformCI: factor out reusable PlatformBuildLib.py In order to reduce the amount of code duplication, refactor the PlatformBuild.py script that builds ArmVirtQemu.dsc into a reusable PlatformBuildLib.py containing most of the bits and pieces, and a small QemuBuild.py which is specific to the DSC in question. Suggested-by: Gerd Hoffmann Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Michael Kubacki --- .../.azurepipelines/Ubuntu-GCC5.yml | 12 +++---- .../{PlatformBuild.py => PlatformBuildLib.py} | 19 ++---------- ArmVirtPkg/PlatformCI/QemuBuild.py | 31 +++++++++++++++++++ 3 files changed, 39 insertions(+), 23 deletions(-) rename ArmVirtPkg/PlatformCI/{PlatformBuild.py => PlatformBuildLib.py} (90%) create mode 100644 ArmVirtPkg/PlatformCI/QemuBuild.py diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 5fa7518d2c..b1526ae8e5 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -30,42 +30,42 @@ jobs: strategy: matrix: QEMU_AARCH64_DEBUG: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" Build.Flags: "" Build.Target: "DEBUG" Run.Flags: $(run_flags) Run: $(should_run) QEMU_AARCH64_RELEASE: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" Build.Flags: "" Build.Target: "RELEASE" Run.Flags: $(run_flags) Run: $(should_run) QEMU_AARCH64_NOOPT: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" Build.Flags: "" Build.Target: "NOOPT" Run.Flags: $(run_flags) Run: $(should_run) QEMU_ARM_DEBUG: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "ARM" Build.Flags: "" Build.Target: "DEBUG" Run.Flags: $(run_flags) Run: $(should_run) QEMU_ARM_RELEASE: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "ARM" Build.Flags: "" Build.Target: "RELEASE" Run.Flags: $(run_flags) Run: $(should_run) QEMU_ARM_NOOPT: - Build.File: "$(package)/PlatformCI/PlatformBuild.py" + Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "ARM" Build.Flags: "" Build.Target: "NOOPT" diff --git a/ArmVirtPkg/PlatformCI/PlatformBuild.py b/ArmVirtPkg/PlatformCI/PlatformBuildLib.py similarity index 90% rename from ArmVirtPkg/PlatformCI/PlatformBuild.py rename to ArmVirtPkg/PlatformCI/PlatformBuildLib.py index dff653e919..91aa9b31d3 100644 --- a/ArmVirtPkg/PlatformCI/PlatformBuild.py +++ b/ArmVirtPkg/PlatformCI/PlatformBuildLib.py @@ -17,21 +17,6 @@ from edk2toollib.utility_functions import RunCmd from edk2toollib.utility_functions import GetHostInfo -# ####################################################################################### # -# Common Configuration # -# ####################################################################################### # - - -class CommonPlatform(): - ''' Common settings for this platform. Define static data here and use - for the different parts of stuart - ''' - PackagesSupported = ("ArmVirtPkg",) - ArchSupported = ("AARCH64", "ARM") - TargetsSupported = ("DEBUG", "RELEASE", "NOOPT") - Scopes = ('armvirt', 'edk2-build') - WorkspaceRoot = os.path.realpath(os.path.join( - os.path.dirname(os.path.abspath(__file__)), "..", "..")) # ####################################################################################### # # Configuration for Update & Setup # @@ -139,7 +124,7 @@ def GetPlatformDscAndConfig(self) -> tuple: The tuple should be (, ) ''' - return (os.path.join("ArmVirtPkg", "ArmVirtQemu.dsc"), {}) + return (CommonPlatform.DscName, {}) # ####################################################################################### # @@ -163,7 +148,7 @@ def RetrieveCommandLineOptions(self, args): "TARGET_ARCH", args.build_arch.upper(), "From CmdLine") shell_environment.GetBuildVars().SetValue( - "ACTIVE_PLATFORM", "ArmVirtPkg/ArmVirtQemu.dsc", "From CmdLine") + "ACTIVE_PLATFORM", CommonPlatform.DscName, "From CmdLine") def GetWorkspaceRoot(self): ''' get WorkspacePath ''' diff --git a/ArmVirtPkg/PlatformCI/QemuBuild.py b/ArmVirtPkg/PlatformCI/QemuBuild.py new file mode 100644 index 0000000000..f4dcc1d1d2 --- /dev/null +++ b/ArmVirtPkg/PlatformCI/QemuBuild.py @@ -0,0 +1,31 @@ +# @file +# Script to Build OVMF UEFI firmware +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from PlatformBuildLib import SettingsManager +from PlatformBuildLib import PlatformBuilder + + # ####################################################################################### # + # Common Configuration # + # ####################################################################################### # +class CommonPlatform(): + ''' Common settings for this platform. Define static data here and use + for the different parts of stuart + ''' + PackagesSupported = ("ArmVirtPkg",) + ArchSupported = ("AARCH64", "ARM") + TargetsSupported = ("DEBUG", "RELEASE", "NOOPT") + Scopes = ('armvirt', 'edk2-build') + WorkspaceRoot = os.path.realpath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..")) + + DscName = os.path.join("ArmVirtPkg", "ArmVirtQemu.dsc") + +import PlatformBuildLib +PlatformBuildLib.CommonPlatform = CommonPlatform From 0336d1e11a6891cf52f5fe69e754747aacaf99ae Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Jan 2023 13:22:03 +0100 Subject: [PATCH 0545/1529] ArmVirtPkg/PlatformCI: Enable optional features on Qemu AARCH64 builds To increase the CI coverage, enable secure boot, TPM2 support and HTTPS boot on ArmVirtQemu builds used in CI. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Michael Kubacki --- ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index b1526ae8e5..44a1d3da67 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -32,21 +32,21 @@ jobs: QEMU_AARCH64_DEBUG: Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" - Build.Flags: "" + Build.Flags: "BLD_*_SECURE_BOOT_ENABLE=1 BLD_*_TPM2_ENABLE=1 BLD_*_NETWORK_TLS_ENABLE=1 BLD_*_NETWORK_IP6_ENABLE=1 BLD_*_NETWORK_HTTP_BOOT_ENABLE=1" Build.Target: "DEBUG" Run.Flags: $(run_flags) Run: $(should_run) QEMU_AARCH64_RELEASE: Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" - Build.Flags: "" + Build.Flags: "BLD_*_SECURE_BOOT_ENABLE=1 BLD_*_TPM2_ENABLE=1 BLD_*_NETWORK_TLS_ENABLE=1 BLD_*_NETWORK_IP6_ENABLE=1 BLD_*_NETWORK_HTTP_BOOT_ENABLE=1" Build.Target: "RELEASE" Run.Flags: $(run_flags) Run: $(should_run) QEMU_AARCH64_NOOPT: Build.File: "$(package)/PlatformCI/QemuBuild.py" Build.Arch: "AARCH64" - Build.Flags: "" + Build.Flags: "BLD_*_SECURE_BOOT_ENABLE=1 BLD_*_TPM2_ENABLE=1 BLD_*_NETWORK_TLS_ENABLE=1 BLD_*_NETWORK_IP6_ENABLE=1 BLD_*_NETWORK_HTTP_BOOT_ENABLE=1" Build.Target: "NOOPT" Run.Flags: $(run_flags) Run: $(should_run) From 1a6ca91cf3c09476a41f9efe3ea41a8d3e7e03fe Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 24 Jan 2023 15:45:02 +0000 Subject: [PATCH 0546/1529] ArmVirtPkg/PlatformCI: Add CI coverage for ArmVirtQemuKernel ArmVirtQemuKernel.dsc describes a firmware build that is loadable at arbitrary address and can be invoked using the Linux/arm64 kernel boot protocol. The early code deviates significantly from ArmVirtQemu, and so it makes sense to cover this platform in CI even if it is not widely used. This ensures that the relocatable PrePi and other components in EmbeddedPkg don't regress on ARM as they are being updated for use on TDVF. Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Michael Kubacki --- .../.azurepipelines/Ubuntu-GCC5.yml | 43 +++++++++++++++++++ ArmVirtPkg/PlatformCI/PlatformBuildLib.py | 4 +- ArmVirtPkg/PlatformCI/QemuBuild.py | 3 ++ ArmVirtPkg/PlatformCI/QemuKernelBuild.py | 35 +++++++++++++++ 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 ArmVirtPkg/PlatformCI/QemuKernelBuild.py diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 44a1d3da67..2b6cc11916 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -72,6 +72,49 @@ jobs: Run.Flags: $(run_flags) Run: $(should_run) + QEMU_KERNEL_AARCH64_DEBUG: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "AARCH64" + Build.Flags: "" + Build.Target: "DEBUG" + Run.Flags: $(run_flags) + Run: $(should_run) + QEMU_KERNEL_AARCH64_RELEASE: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "AARCH64" + Build.Flags: "" + Build.Target: "RELEASE" + Run.Flags: $(run_flags) + Run: $(should_run) + QEMU_KERNEL_AARCH64_NOOPT: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "AARCH64" + Build.Flags: "" + Build.Target: "NOOPT" + Run.Flags: $(run_flags) + Run: $(should_run) + QEMU_KERNEL_ARM_DEBUG: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "ARM" + Build.Flags: "" + Build.Target: "DEBUG" + Run.Flags: $(run_flags) + Run: $(should_run) + QEMU_KERNEL_ARM_RELEASE: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "ARM" + Build.Flags: "" + Build.Target: "RELEASE" + Run.Flags: $(run_flags) + Run: $(should_run) + QEMU_KERNEL_ARM_NOOPT: + Build.File: "$(package)/PlatformCI/QemuKernelBuild.py" + Build.Arch: "ARM" + Build.Flags: "" + Build.Target: "NOOPT" + Run.Flags: $(run_flags) + Run: $(should_run) + workspace: clean: all diff --git a/ArmVirtPkg/PlatformCI/PlatformBuildLib.py b/ArmVirtPkg/PlatformCI/PlatformBuildLib.py index 91aa9b31d3..405817cae7 100644 --- a/ArmVirtPkg/PlatformCI/PlatformBuildLib.py +++ b/ArmVirtPkg/PlatformCI/PlatformBuildLib.py @@ -226,13 +226,13 @@ def FlashRomImage(self): args += " -cpu cortex-a57" # emulate cpu elif(self.env.GetValue("TARGET_ARCH").upper() == "ARM"): cmd = "qemu-system-arm" - args = "-M virt" + args = "-M virt,highmem=off" args += " -cpu cortex-a15" # emulate cpu else: raise NotImplementedError() # Common Args - args += " -pflash " + Built_FV # path to fw + args += CommonPlatform.FvQemuArg + Built_FV # path to fw args += " -m 1024" # 1gb memory # turn off network args += " -net none" diff --git a/ArmVirtPkg/PlatformCI/QemuBuild.py b/ArmVirtPkg/PlatformCI/QemuBuild.py index f4dcc1d1d2..c651a9501f 100644 --- a/ArmVirtPkg/PlatformCI/QemuBuild.py +++ b/ArmVirtPkg/PlatformCI/QemuBuild.py @@ -27,5 +27,8 @@ class CommonPlatform(): DscName = os.path.join("ArmVirtPkg", "ArmVirtQemu.dsc") + # this platform produces a bootable NOR flash image + FvQemuArg = " -pflash " + import PlatformBuildLib PlatformBuildLib.CommonPlatform = CommonPlatform diff --git a/ArmVirtPkg/PlatformCI/QemuKernelBuild.py b/ArmVirtPkg/PlatformCI/QemuKernelBuild.py new file mode 100644 index 0000000000..f340dfac88 --- /dev/null +++ b/ArmVirtPkg/PlatformCI/QemuKernelBuild.py @@ -0,0 +1,35 @@ +# @file +# Script to Build OVMF UEFI firmware +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from PlatformBuildLib import SettingsManager +from PlatformBuildLib import PlatformBuilder + + # ####################################################################################### # + # Common Configuration # + # ####################################################################################### # +class CommonPlatform(): + ''' Common settings for this platform. Define static data here and use + for the different parts of stuart + ''' + PackagesSupported = ("ArmVirtPkg",) + ArchSupported = ("AARCH64", "ARM") + TargetsSupported = ("DEBUG", "RELEASE", "NOOPT") + Scopes = ('armvirt', 'edk2-build') + WorkspaceRoot = os.path.realpath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..")) + + DscName = os.path.join("ArmVirtPkg", "ArmVirtQemuKernel.dsc") + + # this platform produces an executable image that is invoked using + # the Linux/arm64 kernel boot protocol + FvQemuArg = " -kernel " + +import PlatformBuildLib +PlatformBuildLib.CommonPlatform = CommonPlatform From 7ead2f7e396bf0bdface0d6836bcc7bd05e658c9 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 18 Jan 2023 18:18:09 +0100 Subject: [PATCH 0547/1529] ArmVirtPkg/PlatformCI: Perform build test of ArmVirtKvmTool Signed-off-by: Ard Biesheuvel Acked-by: Gerd Hoffmann Reviewed-by: Michael Kubacki --- .../.azurepipelines/Ubuntu-GCC5.yml | 25 +++++++++++++++ ArmVirtPkg/PlatformCI/KvmToolBuild.py | 32 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 ArmVirtPkg/PlatformCI/KvmToolBuild.py diff --git a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 2b6cc11916..d1772a65fc 100644 --- a/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/ArmVirtPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -115,6 +115,31 @@ jobs: Run.Flags: $(run_flags) Run: $(should_run) + KVMTOOL_AARCH64_DEBUG: + Build.File: "$(package)/PlatformCI/KvmToolBuild.py" + Build.Arch: "AARCH64" + Build.Flags: "" + Build.Target: "DEBUG" + Run: false + KVMTOOL_AARCH64_RELEASE: + Build.File: "$(package)/PlatformCI/KvmToolBuild.py" + Build.Arch: "AARCH64" + Build.Flags: "" + Build.Target: "RELEASE" + Run: false + KVMTOOL_ARM_DEBUG: + Build.File: "$(package)/PlatformCI/KvmToolBuild.py" + Build.Arch: "ARM" + Build.Flags: "" + Build.Target: "DEBUG" + Run: false + KVMTOOL_ARM_RELEASE: + Build.File: "$(package)/PlatformCI/KvmToolBuild.py" + Build.Arch: "ARM" + Build.Flags: "" + Build.Target: "RELEASE" + Run: false + workspace: clean: all diff --git a/ArmVirtPkg/PlatformCI/KvmToolBuild.py b/ArmVirtPkg/PlatformCI/KvmToolBuild.py new file mode 100644 index 0000000000..4d02dba124 --- /dev/null +++ b/ArmVirtPkg/PlatformCI/KvmToolBuild.py @@ -0,0 +1,32 @@ +# @file +# Script to Build ArmVirtPkg UEFI firmware +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from PlatformBuildLib import SettingsManager +from PlatformBuildLib import PlatformBuilder + + # ####################################################################################### # + # Common Configuration # + # ####################################################################################### # +class CommonPlatform(): + ''' Common settings for this platform. Define static data here and use + for the different parts of stuart + ''' + PackagesSupported = ("ArmVirtPkg",) + ArchSupported = ("AARCH64", "ARM") + TargetsSupported = ("DEBUG", "RELEASE") + Scopes = ('armvirt', 'edk2-build') + WorkspaceRoot = os.path.realpath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..")) + + DscName = os.path.join("ArmVirtPkg", "ArmVirtKvmTool.dsc") + FvQemuArg = "" # ignored + +import PlatformBuildLib +PlatformBuildLib.CommonPlatform = CommonPlatform From 02b31c82c2f1691b3b50ebccf69e21754a7e6c58 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Thu, 26 Jan 2023 21:17:37 +0000 Subject: [PATCH 0548/1529] OvmfPkg: Add memory acceptance event in AmdSevDxe The added behavior is to accept all unaccepted memory at ExitBootServices if the behavior is not disabled. This allows safe upgrades for OS loaders to affirm their support for the unaccepted memory type. Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Ard Biesheuvel Cc: "Min M. Xu" Cc: Andrew Fish Cc: "Michael D. Kinney" Signed-off-by: Dionna Glaze Reviewed-by: Ard Biesheuvel --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 97 +++++++++++++++++++++++++++++++++ OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 1 + 2 files changed, 98 insertions(+) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index f7600c3c81..37d1a3ff55 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -20,6 +20,7 @@ #include #include #include +#include #include STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { @@ -34,6 +35,10 @@ STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { STATIC EFI_HANDLE mAmdSevDxeHandle = NULL; +STATIC BOOLEAN mAcceptAllMemoryAtEBS = TRUE; + +STATIC EFI_EVENT mAcceptAllMemoryEvent = NULL; + #define IS_ALIGNED(x, y) ((((x) & ((y) - 1)) == 0)) STATIC @@ -62,6 +67,82 @@ AmdSevMemoryAccept ( return EFI_SUCCESS; } +STATIC +EFI_STATUS +AcceptAllMemory ( + VOID + ) +{ + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap; + UINTN NumEntries; + UINTN Index; + EFI_STATUS Status; + + DEBUG ((DEBUG_INFO, "Accepting all memory\n")); + + /* + * Get a copy of the memory space map to iterate over while + * changing the map. + */ + Status = gDS->GetMemorySpaceMap (&NumEntries, &AllDescMap); + if (EFI_ERROR (Status)) { + return Status; + } + + for (Index = 0; Index < NumEntries; Index++) { + CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Desc; + + Desc = &AllDescMap[Index]; + if (Desc->GcdMemoryType != EFI_GCD_MEMORY_TYPE_UNACCEPTED) { + continue; + } + + Status = AmdSevMemoryAccept ( + NULL, + Desc->BaseAddress, + Desc->Length + ); + if (EFI_ERROR (Status)) { + break; + } + + Status = gDS->RemoveMemorySpace (Desc->BaseAddress, Desc->Length); + if (EFI_ERROR (Status)) { + break; + } + + Status = gDS->AddMemorySpace ( + EfiGcdMemoryTypeSystemMemory, + Desc->BaseAddress, + Desc->Length, + EFI_MEMORY_CPU_CRYPTO | EFI_MEMORY_XP | EFI_MEMORY_RO | EFI_MEMORY_RP + ); + if (EFI_ERROR (Status)) { + break; + } + } + + gBS->FreePool (AllDescMap); + return Status; +} + +VOID +EFIAPI +ResolveUnacceptedMemory ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + EFI_STATUS Status; + + if (!mAcceptAllMemoryAtEBS) { + return; + } + + Status = AcceptAllMemory (); + ASSERT_EFI_ERROR (Status); +} + STATIC EDKII_MEMORY_ACCEPT_PROTOCOL mMemoryAcceptProtocol = { AmdSevMemoryAccept }; @@ -195,6 +276,22 @@ AmdSevDxeEntryPoint ( ); ASSERT_EFI_ERROR (Status); + // SEV-SNP support does not automatically imply unaccepted memory support, + // so make ExitBootServices accept all unaccepted memory if support is + // not communicated. + Status = gBS->CreateEventEx ( + EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + ResolveUnacceptedMemory, + NULL, + &gEfiEventBeforeExitBootServicesGuid, + &mAcceptAllMemoryEvent + ); + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "AllowUnacceptedMemory event creation for EventBeforeExitBootServices failed.\n")); + } + // // If its SEV-SNP active guest then install the CONFIDENTIAL_COMPUTING_SEV_SNP_BLOB. // It contains the location for both the Secrets and CPUID page. diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf index cd1b686c53..5b443d45bc 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf @@ -52,6 +52,7 @@ [Guids] gConfidentialComputingSevSnpBlobGuid + gEfiEventBeforeExitBootServicesGuid [Pcd] gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId From c9ba5b26c7350c723d6c2f67d90946e5c42c82a1 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Thu, 26 Jan 2023 21:17:38 +0000 Subject: [PATCH 0549/1529] OvmfPkg: Introduce the OvmfSevMemoryAcceptance protocol The default behavior for unaccepted memory in SEV-SNP is to accept all memory when ExitBootServices is called. An OS loader can use this protocol to disable this behavior to assume responsibility for memory acceptance and to affirm that the OS can handle the unaccepted memory type. Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Ard Biesheuvel Cc: "Min M. Xu" Cc: Andrew Fish Cc: "Michael D. Kinney" Signed-off-by: Dionna Glaze Reviewed-by: Ard Biesheuvel --- .../Include/Protocol/SevMemoryAcceptance.h | 43 +++++++++++++++++++ OvmfPkg/OvmfPkg.dec | 1 + 2 files changed, 44 insertions(+) create mode 100644 OvmfPkg/Include/Protocol/SevMemoryAcceptance.h diff --git a/OvmfPkg/Include/Protocol/SevMemoryAcceptance.h b/OvmfPkg/Include/Protocol/SevMemoryAcceptance.h new file mode 100644 index 0000000000..c5ea3f383a --- /dev/null +++ b/OvmfPkg/Include/Protocol/SevMemoryAcceptance.h @@ -0,0 +1,43 @@ +/** @file + The file provides the protocol that disables the behavior that all memory + gets accepted at ExitBootServices(). This protocol is only meant to be called + by the OS loader, and not EDK2 itself. The SEV naming is due to the + coincidence that only SEV-SNP needs this protocol, since SEV-SNP Linux + support was released before it had support for unaccepted memory. The + technology enablement thus does not strictly imply support for the unaccepted + memory type. + + Copyright (c) 2023, Google LLC. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef SEV_MEMORY_ACCEPTANCE_H_ +#define SEV_MEMORY_ACCEPTANCE_H_ + +#define OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID \ + {0xc5a010fe, \ + 0x38a7, \ + 0x4531, \ + {0x8a, 0x4a, 0x05, 0x00, 0xd2, 0xfd, 0x16, 0x49}} + +typedef struct _OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL + OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL; + +/** + @param This A pointer to a OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL. +**/ +typedef + EFI_STATUS +(EFIAPI *OVMF_SEV_ALLOW_UNACCEPTED_MEMORY)( + IN OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL *This + ); + +/// +/// The OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL allows the OS loader to +/// indicate to EDK2 that ExitBootServices should not accept all memory. +/// +struct _OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL { + OVMF_SEV_ALLOW_UNACCEPTED_MEMORY AllowUnacceptedMemory; +}; + +#endif diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index 1b521f2604..a22eb246c6 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -184,6 +184,7 @@ gEfiLegacyInterruptProtocolGuid = {0x31ce593d, 0x108a, 0x485d, {0xad, 0xb2, 0x78, 0xf2, 0x1f, 0x29, 0x66, 0xbe}} gEfiVgaMiniPortProtocolGuid = {0xc7735a2f, 0x88f5, 0x4882, {0xae, 0x63, 0xfa, 0xac, 0x8c, 0x8b, 0x86, 0xb3}} gOvmfLoadedX86LinuxKernelProtocolGuid = {0xa3edc05d, 0xb618, 0x4ff6, {0x95, 0x52, 0x76, 0xd7, 0x88, 0x63, 0x43, 0xc8}} + gOvmfSevMemoryAcceptanceProtocolGuid = {0xc5a010fe, 0x38a7, 0x4531, {0x8a, 0x4a, 0x05, 0x00, 0xd2, 0xfd, 0x16, 0x49}} gQemuAcpiTableNotifyProtocolGuid = {0x928939b2, 0x4235, 0x462f, {0x95, 0x80, 0xf6, 0xa2, 0xb2, 0xc2, 0x1a, 0x4f}} gEfiMpInitLibMpDepProtocolGuid = {0xbb00a5ca, 0x8ce, 0x462f, {0xa5, 0x37, 0x43, 0xc7, 0x4a, 0x82, 0x5c, 0xa4}} gEfiMpInitLibUpDepProtocolGuid = {0xa9e7cef1, 0x5682, 0x42cc, {0xb1, 0x23, 0x99, 0x30, 0x97, 0x3f, 0x4a, 0x9f}} From 7732eda9f8c3e6d3f387e739b116cd4e38205fae Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Thu, 26 Jan 2023 21:17:39 +0000 Subject: [PATCH 0550/1529] OvmfPkg: Implement AcceptAllUnacceptedMemory in AmdSevDxe This protocol implementation disables the accept-all-memory behavior of the BeforeExitBootServices event this driver adds. Cc: Gerd Hoffmann Cc: James Bottomley Cc: Jiewen Yao Cc: Tom Lendacky Cc: Ard Biesheuvel Cc: "Min M. Xu" Cc: Andrew Fish Cc: "Michael D. Kinney" Signed-off-by: Dionna Glaze Reviewed-by: Ard Biesheuvel --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 24 +++++++++++++++++++++--- OvmfPkg/AmdSevDxe/AmdSevDxe.inf | 1 + 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 37d1a3ff55..6391d1f775 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -21,6 +21,7 @@ #include #include #include +#include #include STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { @@ -143,6 +144,21 @@ ResolveUnacceptedMemory ( ASSERT_EFI_ERROR (Status); } +STATIC +EFI_STATUS +EFIAPI +AllowUnacceptedMemory ( + IN OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL *This + ) +{ + mAcceptAllMemoryAtEBS = FALSE; + return EFI_SUCCESS; +} + +STATIC +OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL + mMemoryAcceptanceProtocol = { AllowUnacceptedMemory }; + STATIC EDKII_MEMORY_ACCEPT_PROTOCOL mMemoryAcceptProtocol = { AmdSevMemoryAccept }; @@ -268,11 +284,13 @@ AmdSevDxeEntryPoint ( // Memory acceptance began being required in SEV-SNP, so install the // memory accept protocol implementation for a SEV-SNP active guest. // - Status = gBS->InstallProtocolInterface ( + Status = gBS->InstallMultipleProtocolInterfaces ( &mAmdSevDxeHandle, &gEdkiiMemoryAcceptProtocolGuid, - EFI_NATIVE_INTERFACE, - &mMemoryAcceptProtocol + &mMemoryAcceptProtocol, + &gOvmfSevMemoryAcceptanceProtocolGuid, + &mMemoryAcceptanceProtocol, + NULL ); ASSERT_EFI_ERROR (Status); diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf index 5b443d45bc..e7c7d526c9 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.inf +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.inf @@ -49,6 +49,7 @@ [Protocols] gEdkiiMemoryAcceptProtocolGuid + gOvmfSevMemoryAcceptanceProtocolGuid [Guids] gConfidentialComputingSevSnpBlobGuid From 1dd25a806503bbce4a2442ae2a3b8b0a44e3d2c9 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Thu, 26 Jan 2023 21:17:40 +0000 Subject: [PATCH 0551/1529] OvmfPkg/PlatformPei: SEV-SNP make >=4GB unaccepted Instead of eagerly accepting all memory in PEI, only accept memory under the 4GB address. This allows a loaded image to use the MEMORY_ACCEPTANCE_PROTOCOL to disable the accept behavior and indicate that it can interpret the memory type accordingly. This classification is safe since ExitBootServices will accept and reclassify the memory as conventional if the disable protocol is not used. Cc: Ard Biescheuvel Cc: "Min M. Xu" Cc: Gerd Hoffmann Cc: James Bottomley Cc: Tom Lendacky Cc: Jiewen Yao Cc: Erdem Aktas Signed-off-by: Dionna Glaze Reviewed-by: Ard Biesheuvel --- OvmfPkg/PlatformPei/AmdSev.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index e4e7b72e67..e6b602d79a 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +66,11 @@ AmdSevSnpInitialize ( ResourceHob = Hob.ResourceDescriptor; if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) { + if (ResourceHob->PhysicalStart >= SIZE_4GB) { + ResourceHob->ResourceType = BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED; + continue; + } + MemEncryptSevSnpPreValidateSystemRam ( ResourceHob->PhysicalStart, EFI_SIZE_TO_PAGES ((UINTN)ResourceHob->ResourceLength) From 086965bb242dbcf06a4414647af080ddef635f45 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Mon, 16 Jan 2023 21:57:30 -0700 Subject: [PATCH 0552/1529] ArmPkg: Add GET_MPIDR_AFFINITY_BITS and MPIDR_MT_BIT to ArmLib.h Signed-off-by: Rebecca Cran Reviewed-by: Ard Biesheuvel --- ArmPkg/Include/Library/ArmLib.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/ArmPkg/Include/Library/ArmLib.h b/ArmPkg/Include/Library/ArmLib.h index 6566deebdd..fa605f128b 100644 --- a/ArmPkg/Include/Library/ArmLib.h +++ b/ArmPkg/Include/Library/ArmLib.h @@ -108,14 +108,16 @@ typedef enum { #define ARM_CORE_MASK ARM_CORE_AFF0 #define ARM_CLUSTER_MASK ARM_CORE_AFF1 -#define GET_CORE_ID(MpId) ((MpId) & ARM_CORE_MASK) -#define GET_CLUSTER_ID(MpId) (((MpId) & ARM_CLUSTER_MASK) >> 8) -#define GET_MPID(ClusterId, CoreId) (((ClusterId) << 8) | (CoreId)) -#define GET_MPIDR_AFF0(MpId) ((MpId) & ARM_CORE_AFF0) -#define GET_MPIDR_AFF1(MpId) (((MpId) & ARM_CORE_AFF1) >> 8) -#define GET_MPIDR_AFF2(MpId) (((MpId) & ARM_CORE_AFF2) >> 16) -#define GET_MPIDR_AFF3(MpId) (((MpId) & ARM_CORE_AFF3) >> 32) +#define GET_CORE_ID(MpId) ((MpId) & ARM_CORE_MASK) +#define GET_CLUSTER_ID(MpId) (((MpId) & ARM_CLUSTER_MASK) >> 8) +#define GET_MPID(ClusterId, CoreId) (((ClusterId) << 8) | (CoreId)) +#define GET_MPIDR_AFF0(MpId) ((MpId) & ARM_CORE_AFF0) +#define GET_MPIDR_AFF1(MpId) (((MpId) & ARM_CORE_AFF1) >> 8) +#define GET_MPIDR_AFF2(MpId) (((MpId) & ARM_CORE_AFF2) >> 16) +#define GET_MPIDR_AFF3(MpId) (((MpId) & ARM_CORE_AFF3) >> 32) +#define GET_MPIDR_AFFINITY_BITS(MpId) ((MpId) & 0xFF00FFFFFF) #define PRIMARY_CORE_ID (PcdGet32(PcdArmPrimaryCore) & ARM_CORE_MASK) +#define MPIDR_MT_BIT BIT24 /** Reads the CCSIDR register for the specified cache. From 13022030470866b33b225b68cb248b37f1a3180a Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Mon, 16 Jan 2023 21:57:31 -0700 Subject: [PATCH 0553/1529] ArmPkg: implement EFI_MP_SERVICES_PROTOCOL based on PSCI calls Add support for EFI_MP_SERVICES_PROTOCOL during the DXE phase under AArch64. PSCI_CPU_ON is called to power on the core, the supplied procedure is executed and PSCI_CPU_OFF is called to power off the core. Fixes contributed by Ard Biesheuvel. Signed-off-by: Rebecca Cran Reviewed-by: Ard Biesheuvel Tested-by: Kun Qin --- ArmPkg/ArmPkg.dsc | 1 + .../ArmPsciMpServicesDxe.c | 1859 +++++++++++++++++ .../ArmPsciMpServicesDxe.inf | 56 + ArmPkg/Drivers/ArmPsciMpServicesDxe/MpFuncs.S | 74 + .../ArmPsciMpServicesDxe/MpServicesInternal.h | 345 +++ 5 files changed, 2335 insertions(+) create mode 100644 ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.c create mode 100644 ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf create mode 100644 ArmPkg/Drivers/ArmPsciMpServicesDxe/MpFuncs.S create mode 100644 ArmPkg/Drivers/ArmPsciMpServicesDxe/MpServicesInternal.h diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index ac24ebce48..1e873b90c5 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -164,6 +164,7 @@ ArmPkg/Universal/Smbios/OemMiscLibNull/OemMiscLibNull.inf [Components.AARCH64] + ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf diff --git a/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.c b/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.c new file mode 100644 index 0000000000..f822a9877c --- /dev/null +++ b/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.c @@ -0,0 +1,1859 @@ +/** @file + Construct MP Services Protocol. + + The MP Services Protocol provides a generalized way of performing following tasks: + - Retrieving information of multi-processor environment and MP-related status of + specific processors. + - Dispatching user-provided function to APs. + - Maintain MP-related processor status. + + The MP Services Protocol must be produced on any system with more than one logical + processor. + + The Protocol is available only during boot time. + + MP Services Protocol is hardware-independent. Most of the logic of this protocol + is architecturally neutral. It abstracts the multi-processor environment and + status of processors, and provides interfaces to retrieve information, maintain, + and dispatch. + + MP Services Protocol may be consumed by ACPI module. The ACPI module may use this + protocol to retrieve data that are needed for an MP platform and report them to OS. + MP Services Protocol may also be used to program and configure processors, such + as MTRR synchronization for memory space attributes setting in DXE Services. + MP Services Protocol may be used by non-CPU DXE drivers to speed up platform boot + by taking advantage of the processing capabilities of the APs, for example, using + APs to help test system memory in parallel with other device initialization. + Diagnostics applications may also use this protocol for multi-processor. + + Copyright (c) 2022, Qualcomm Innovation Center, Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MpServicesInternal.h" + +#define POLL_INTERVAL_US 50000 + +STATIC CPU_MP_DATA mCpuMpData; +STATIC BOOLEAN mNonBlockingModeAllowed; +UINT64 *gApStacksBase; +UINT64 *gProcessorIDs; +CONST UINT64 gApStackSize = AP_STACK_SIZE; +VOID *gTtbr0; +UINTN gTcr; +UINTN gMair; + +STATIC +BOOLEAN +IsCurrentProcessorBSP ( + VOID + ); + +/** Turns on the specified core using PSCI and executes the user-supplied + function that's been configured via a previous call to SetApProcedure. + + @param ProcessorIndex The index of the core to turn on. + + @retval EFI_SUCCESS Success. + @retval EFI_DEVICE_ERROR The processor could not be turned on. + +**/ +STATIC +EFI_STATUS +EFIAPI +DispatchCpu ( + IN UINTN ProcessorIndex + ) +{ + ARM_SMC_ARGS Args; + EFI_STATUS Status; + + Status = EFI_SUCCESS; + + mCpuMpData.CpuData[ProcessorIndex].State = CpuStateBusy; + + /* Turn the AP on */ + if (sizeof (Args.Arg0) == sizeof (UINT32)) { + Args.Arg0 = ARM_SMC_ID_PSCI_CPU_ON_AARCH32; + } else { + Args.Arg0 = ARM_SMC_ID_PSCI_CPU_ON_AARCH64; + } + + Args.Arg1 = gProcessorIDs[ProcessorIndex]; + Args.Arg2 = (UINTN)ApEntryPoint; + + ArmCallSmc (&Args); + + if (Args.Arg0 != ARM_SMC_PSCI_RET_SUCCESS) { + DEBUG ((DEBUG_ERROR, "PSCI_CPU_ON call failed: %d\n", Args.Arg0)); + Status = EFI_DEVICE_ERROR; + } + + return Status; +} + +/** Returns whether the specified processor is the BSP. + + @param[in] ProcessorIndex The index the processor to check. + + @return TRUE if the processor is the BSP, FALSE otherwise. +**/ +STATIC +BOOLEAN +IsProcessorBSP ( + UINTN ProcessorIndex + ) +{ + EFI_PROCESSOR_INFORMATION *CpuInfo; + + CpuInfo = &mCpuMpData.CpuData[ProcessorIndex].Info; + + return (CpuInfo->StatusFlag & PROCESSOR_AS_BSP_BIT) != 0; +} + +/** Get the Application Processors state. + + @param[in] CpuData The pointer to CPU_AP_DATA of specified AP. + + @return The AP status. +**/ +CPU_STATE +GetApState ( + IN CPU_AP_DATA *CpuData + ) +{ + return CpuData->State; +} + +/** Configures the processor context with the user-supplied procedure and + argument. + + @param CpuData The processor context. + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + +**/ +STATIC +VOID +SetApProcedure ( + IN CPU_AP_DATA *CpuData, + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument + ) +{ + ASSERT (CpuData != NULL); + ASSERT (Procedure != NULL); + + CpuData->Parameter = ProcedureArgument; + CpuData->Procedure = Procedure; +} + +/** Returns the index of the next processor that is blocked. + + @param[out] NextNumber The index of the next blocked processor. + + @retval EFI_SUCCESS Successfully found the next blocked processor. + @retval EFI_NOT_FOUND There are no blocked processors. + +**/ +STATIC +EFI_STATUS +GetNextBlockedNumber ( + OUT UINTN *NextNumber + ) +{ + UINTN Index; + CPU_STATE State; + CPU_AP_DATA *CpuData; + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + CpuData = &mCpuMpData.CpuData[Index]; + if (IsProcessorBSP (Index)) { + // Skip BSP + continue; + } + + State = CpuData->State; + + if (State == CpuStateBlocked) { + *NextNumber = Index; + return EFI_SUCCESS; + } + } + + return EFI_NOT_FOUND; +} + +/** Stalls the BSP for the minimum of POLL_INTERVAL_US and Timeout. + + @param[in] Timeout The time limit in microseconds remaining for + APs to return from Procedure. + + @retval StallTime Time of execution stall. +**/ +STATIC +UINTN +CalculateAndStallInterval ( + IN UINTN Timeout + ) +{ + UINTN StallTime; + + if ((Timeout < POLL_INTERVAL_US) && (Timeout != 0)) { + StallTime = Timeout; + } else { + StallTime = POLL_INTERVAL_US; + } + + gBS->Stall (StallTime); + + return StallTime; +} + +/** + This service retrieves the number of logical processor in the platform + and the number of those logical processors that are enabled on this boot. + This service may only be called from the BSP. + + This function is used to retrieve the following information: + - The number of logical processors that are present in the system. + - The number of enabled logical processors in the system at the instant + this call is made. + + Because MP Service Protocol provides services to enable and disable processors + dynamically, the number of enabled logical processors may vary during the + course of a boot session. + + If this service is called from an AP, then EFI_DEVICE_ERROR is returned. + If NumberOfProcessors or NumberOfEnabledProcessors is NULL, then + EFI_INVALID_PARAMETER is returned. Otherwise, the total number of processors + is returned in NumberOfProcessors, the number of currently enabled processor + is returned in NumberOfEnabledProcessors, and EFI_SUCCESS is returned. + + @param[in] This A pointer to the + EFI_MP_SERVICES_PROTOCOL instance. + @param[out] NumberOfProcessors Pointer to the total number of logical + processors in the system, including + the BSP and disabled APs. + @param[out] NumberOfEnabledProcessors Pointer to the number of enabled + logical processors that exist in the + system, including the BSP. + + @retval EFI_SUCCESS The number of logical processors and enabled + logical processors was retrieved. + @retval EFI_DEVICE_ERROR The calling processor is an AP. + @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL. + @retval EFI_INVALID_PARAMETER NumberOfEnabledProcessors is NULL. + +**/ +STATIC +EFI_STATUS +EFIAPI +GetNumberOfProcessors ( + IN EFI_MP_SERVICES_PROTOCOL *This, + OUT UINTN *NumberOfProcessors, + OUT UINTN *NumberOfEnabledProcessors + ) +{ + if ((NumberOfProcessors == NULL) || (NumberOfEnabledProcessors == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if (!IsCurrentProcessorBSP ()) { + return EFI_DEVICE_ERROR; + } + + *NumberOfProcessors = mCpuMpData.NumberOfProcessors; + *NumberOfEnabledProcessors = mCpuMpData.NumberOfEnabledProcessors; + return EFI_SUCCESS; +} + +/** + Gets detailed MP-related information on the requested processor at the + instant this call is made. This service may only be called from the BSP. + + This service retrieves detailed MP-related information about any processor + on the platform. Note the following: + - The processor information may change during the course of a boot session. + - The information presented here is entirely MP related. + + Information regarding the number of caches and their sizes, frequency of + operation, slot numbers is all considered platform-related information and is + not provided by this service. + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL + instance. + @param[in] ProcessorIndex The index of the processor. + @param[out] ProcessorInfoBuffer A pointer to the buffer where information + for the requested processor is deposited. + + @retval EFI_SUCCESS Processor information was returned. + @retval EFI_DEVICE_ERROR The calling processor is an AP. + @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL. + @retval EFI_NOT_FOUND The processor with the handle specified by + ProcessorNumber does not exist in the platform. + +**/ +STATIC +EFI_STATUS +EFIAPI +GetProcessorInfo ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorIndex, + OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer + ) +{ + if (ProcessorInfoBuffer == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (!IsCurrentProcessorBSP ()) { + return EFI_DEVICE_ERROR; + } + + ProcessorIndex &= ~CPU_V2_EXTENDED_TOPOLOGY; + + if (ProcessorIndex >= mCpuMpData.NumberOfProcessors) { + return EFI_NOT_FOUND; + } + + CopyMem ( + ProcessorInfoBuffer, + &mCpuMpData.CpuData[ProcessorIndex], + sizeof (EFI_PROCESSOR_INFORMATION) + ); + return EFI_SUCCESS; +} + +/** + This service executes a caller provided function on all enabled APs. APs can + run either simultaneously or one at a time in sequence. This service supports + both blocking and non-blocking requests. The non-blocking requests use EFI + events so the BSP can detect when the APs have finished. This service may only + be called from the BSP. + + This function is used to dispatch all the enabled APs to the function + specified by Procedure. If any enabled AP is busy, then EFI_NOT_READY is + returned immediately and Procedure is not started on any AP. + + If SingleThread is TRUE, all the enabled APs execute the function specified by + Procedure one by one, in ascending order of processor handle number. + Otherwise, all the enabled APs execute the function specified by Procedure + simultaneously. + + If WaitEvent is NULL, execution is in blocking mode. The BSP waits until all + APs finish or TimeoutInMicroseconds expires. Otherwise, execution is in + non-blocking mode, and the BSP returns from this service without waiting for + APs. If a non-blocking mode is requested after the UEFI Event + EFI_EVENT_GROUP_READY_TO_BOOT is signaled, then EFI_UNSUPPORTED must be + returned. + + If the timeout specified by TimeoutInMicroseconds expires before all APs + return from Procedure, then Procedure on the failed APs is terminated. + All enabled APs are always available for further calls to + EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() and + EFI_MP_SERVICES_PROTOCOL.StartupThisAP(). If FailedCpuList is not NULL, its + content points to the list of processor handle numbers in which Procedure was + terminated. + + Note: It is the responsibility of the consumer of the + EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() to make sure that the nature of the + code that is executed on the BSP and the dispatched APs is well controlled. + The MP Services Protocol does not guarantee that the Procedure function is + MP-safe. Hence, the tasks that can be run in parallel are limited to certain + independent tasks and well-controlled exclusive code. EFI services and + protocols may not be called by APs unless otherwise specified. + + In blocking execution mode, BSP waits until all APs finish or + TimeoutInMicroseconds expires. + + In non-blocking execution mode, BSP is freed to return to the caller and then + proceed to the next task without having to wait for APs. The following + sequence needs to occur in a non-blocking execution mode: + + -# The caller that intends to use this MP Services Protocol in non-blocking + mode creates WaitEvent by calling the EFI CreateEvent() service. The + caller invokes EFI_MP_SERVICES_PROTOCOL.StartupAllAPs(). If the parameter + WaitEvent is not NULL, then StartupAllAPs() executes in non-blocking + mode. It requests the function specified by Procedure to be started on + all the enabled APs, and releases the BSP to continue with other tasks. + -# The caller can use the CheckEvent() and WaitForEvent() services to check + the state of the WaitEvent created in step 1. + -# When the APs complete their task or TimeoutInMicroSecondss expires, the + MP Service signals WaitEvent by calling the EFI SignalEvent() function. + If FailedCpuList is not NULL, its content is available when WaitEvent is + signaled. If all APs returned from Procedure prior to the timeout, then + FailedCpuList is set to NULL. If not all APs return from Procedure before + the timeout, then FailedCpuList is filled in with the list of the failed + APs. The buffer is allocated by MP Service Protocol using AllocatePool(). + It is the caller's responsibility to free the buffer with FreePool() + service. + -# This invocation of SignalEvent() function informs the caller that invoked + EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() that either all the APs + completed the specified task or a timeout occurred. The contents of + FailedCpuList can be examined to determine which APs did not complete the + specified task prior to the timeout. + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL + instance. + @param[in] Procedure A pointer to the function to be run on + enabled APs of the system. See type + EFI_AP_PROCEDURE. + @param[in] SingleThread If TRUE, then all the enabled APs execute + the function specified by Procedure one by + one, in ascending order of processor + handle number. If FALSE, then all the + enabled APs execute the function specified + by Procedure simultaneously. + @param[in] WaitEvent The event created by the caller with + CreateEvent() service. If it is NULL, + then execute in blocking mode. BSP waits + until all APs finish or + TimeoutInMicroseconds expires. If it's + not NULL, then execute in non-blocking + mode. BSP requests the function specified + by Procedure to be started on all the + enabled APs, and go on executing + immediately. If all return from Procedure, + or TimeoutInMicroseconds expires, this + event is signaled. The BSP can use the + CheckEvent() or WaitForEvent() + services to check the state of event. Type + EFI_EVENT is defined in CreateEvent() in + the Unified Extensible Firmware Interface + Specification. + @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds + for APs to return from Procedure, either + for blocking or non-blocking mode. Zero + means infinity. If the timeout expires + before all APs return from Procedure, then + Procedure on the failed APs is terminated. + All enabled APs are available for next + function assigned by + EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() + or EFI_MP_SERVICES_PROTOCOL.StartupThisAP(). + If the timeout expires in blocking mode, + BSP returns EFI_TIMEOUT. If the timeout + expires in non-blocking mode, WaitEvent + is signaled with SignalEvent(). + @param[in] ProcedureArgument The parameter passed into Procedure for + all APs. + @param[out] FailedCpuList If NULL, this parameter is ignored. + Otherwise, if all APs finish successfully, + then its content is set to NULL. If not + all APs finish before timeout expires, + then its content is set to address of the + buffer holding handle numbers of the + failed APs. + The buffer is allocated by MP Service + Protocol, and it's the caller's + responsibility to free the buffer with + FreePool() service. + In blocking mode, it is ready for + consumption when the call returns. In + non-blocking mode, it is ready when + WaitEvent is signaled. The list of failed + CPU is terminated by END_OF_CPU_LIST. + + @retval EFI_SUCCESS In blocking mode, all APs have finished before + the timeout expired. + @retval EFI_SUCCESS In non-blocking mode, function has been + dispatched to all enabled APs. + @retval EFI_UNSUPPORTED A non-blocking mode request was made after the + UEFI event EFI_EVENT_GROUP_READY_TO_BOOT was + signaled. + @retval EFI_DEVICE_ERROR Caller processor is AP. + @retval EFI_NOT_STARTED No enabled APs exist in the system. + @retval EFI_NOT_READY Any enabled APs are busy. + @retval EFI_TIMEOUT In blocking mode, the timeout expired before + all enabled APs have finished. + @retval EFI_INVALID_PARAMETER Procedure is NULL. + +**/ +STATIC +EFI_STATUS +EFIAPI +StartupAllAPs ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN EFI_AP_PROCEDURE Procedure, + IN BOOLEAN SingleThread, + IN EFI_EVENT WaitEvent OPTIONAL, + IN UINTN TimeoutInMicroseconds, + IN VOID *ProcedureArgument OPTIONAL, + OUT UINTN **FailedCpuList OPTIONAL + ) +{ + EFI_STATUS Status; + + if (!IsCurrentProcessorBSP ()) { + return EFI_DEVICE_ERROR; + } + + if ((mCpuMpData.NumberOfProcessors == 1) || (mCpuMpData.NumberOfEnabledProcessors == 1)) { + return EFI_NOT_STARTED; + } + + if (Procedure == NULL) { + return EFI_INVALID_PARAMETER; + } + + if ((WaitEvent != NULL) && !mNonBlockingModeAllowed) { + return EFI_UNSUPPORTED; + } + + if (FailedCpuList != NULL) { + mCpuMpData.FailedList = AllocateZeroPool ( + (mCpuMpData.NumberOfProcessors + 1) * + sizeof (UINTN) + ); + if (mCpuMpData.FailedList == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + SetMemN ( + mCpuMpData.FailedList, + (mCpuMpData.NumberOfProcessors + 1) * + sizeof (UINTN), + END_OF_CPU_LIST + ); + mCpuMpData.FailedListIndex = 0; + *FailedCpuList = mCpuMpData.FailedList; + } + + StartupAllAPsPrepareState (SingleThread); + + // If any enabled APs are busy (ignoring the BSP), return EFI_NOT_READY + if (mCpuMpData.StartCount != (mCpuMpData.NumberOfEnabledProcessors - 1)) { + return EFI_NOT_READY; + } + + if (WaitEvent != NULL) { + Status = StartupAllAPsWithWaitEvent ( + Procedure, + ProcedureArgument, + WaitEvent, + TimeoutInMicroseconds, + SingleThread, + FailedCpuList + ); + + if (EFI_ERROR (Status) && (FailedCpuList != NULL)) { + if (mCpuMpData.FailedListIndex == 0) { + FreePool (*FailedCpuList); + *FailedCpuList = NULL; + } + } + } else { + Status = StartupAllAPsNoWaitEvent ( + Procedure, + ProcedureArgument, + TimeoutInMicroseconds, + SingleThread, + FailedCpuList + ); + + if (FailedCpuList != NULL) { + if (mCpuMpData.FailedListIndex == 0) { + FreePool (*FailedCpuList); + *FailedCpuList = NULL; + } + } + } + + return Status; +} + +/** + This service lets the caller get one enabled AP to execute a caller-provided + function. The caller can request the BSP to either wait for the completion + of the AP or just proceed with the next task by using the EFI event mechanism. + See EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() for more details on non-blocking + execution support. This service may only be called from the BSP. + + This function is used to dispatch one enabled AP to the function specified by + Procedure passing in the argument specified by ProcedureArgument. If WaitEvent + is NULL, execution is in blocking mode. The BSP waits until the AP finishes or + TimeoutInMicroSecondss expires. Otherwise, execution is in non-blocking mode. + BSP proceeds to the next task without waiting for the AP. If a non-blocking mode + is requested after the UEFI Event EFI_EVENT_GROUP_READY_TO_BOOT is signaled, + then EFI_UNSUPPORTED must be returned. + + If the timeout specified by TimeoutInMicroseconds expires before the AP returns + from Procedure, then execution of Procedure by the AP is terminated. The AP is + available for subsequent calls to EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() and + EFI_MP_SERVICES_PROTOCOL.StartupThisAP(). + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL + instance. + @param[in] Procedure A pointer to the function to be run on + enabled APs of the system. See type + EFI_AP_PROCEDURE. + @param[in] ProcessorNumber The handle number of the AP. The range is + from 0 to the total number of logical + processors minus 1. The total number of + logical processors can be retrieved by + EFI_MP_SERVICES_PROTOCOL.GetNumberOfProcessors(). + @param[in] WaitEvent The event created by the caller with CreateEvent() + service. If it is NULL, then execute in + blocking mode. BSP waits until all APs finish + or TimeoutInMicroseconds expires. If it's + not NULL, then execute in non-blocking mode. + BSP requests the function specified by + Procedure to be started on all the enabled + APs, and go on executing immediately. If + all return from Procedure or TimeoutInMicroseconds + expires, this event is signaled. The BSP + can use the CheckEvent() or WaitForEvent() + services to check the state of event. Type + EFI_EVENT is defined in CreateEvent() in + the Unified Extensible Firmware Interface + Specification. + @param[in] TimeoutInMicroseconds Indicates the time limit in microseconds for + APs to return from Procedure, either for + blocking or non-blocking mode. Zero means + infinity. If the timeout expires before + all APs return from Procedure, then Procedure + on the failed APs is terminated. All enabled + APs are available for next function assigned + by EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() + or EFI_MP_SERVICES_PROTOCOL.StartupThisAP(). + If the timeout expires in blocking mode, + BSP returns EFI_TIMEOUT. If the timeout + expires in non-blocking mode, WaitEvent + is signaled with SignalEvent(). + @param[in] ProcedureArgument The parameter passed into Procedure for + all APs. + @param[out] Finished If NULL, this parameter is ignored. In + blocking mode, this parameter is ignored. + In non-blocking mode, if AP returns from + Procedure before the timeout expires, its + content is set to TRUE. Otherwise, the + value is set to FALSE. The caller can + determine if the AP returned from Procedure + by evaluating this value. + + @retval EFI_SUCCESS In blocking mode, specified AP finished before + the timeout expires. + @retval EFI_SUCCESS In non-blocking mode, the function has been + dispatched to specified AP. + @retval EFI_UNSUPPORTED A non-blocking mode request was made after the + UEFI event EFI_EVENT_GROUP_READY_TO_BOOT was + signaled. + @retval EFI_DEVICE_ERROR The calling processor is an AP. + @retval EFI_TIMEOUT In blocking mode, the timeout expired before + the specified AP has finished. + @retval EFI_NOT_READY The specified AP is busy. + @retval EFI_NOT_FOUND The processor with the handle specified by + ProcessorNumber does not exist. + @retval EFI_INVALID_PARAMETER ProcessorNumber specifies the BSP or disabled AP. + @retval EFI_INVALID_PARAMETER Procedure is NULL. + +**/ +STATIC +EFI_STATUS +EFIAPI +StartupThisAP ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN EFI_AP_PROCEDURE Procedure, + IN UINTN ProcessorNumber, + IN EFI_EVENT WaitEvent OPTIONAL, + IN UINTN TimeoutInMicroseconds, + IN VOID *ProcedureArgument OPTIONAL, + OUT BOOLEAN *Finished OPTIONAL + ) +{ + EFI_STATUS Status; + UINTN Timeout; + CPU_AP_DATA *CpuData; + + if (!IsCurrentProcessorBSP ()) { + return EFI_DEVICE_ERROR; + } + + if (Procedure == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (ProcessorNumber >= mCpuMpData.NumberOfProcessors) { + return EFI_NOT_FOUND; + } + + CpuData = &mCpuMpData.CpuData[ProcessorNumber]; + + if (IsProcessorBSP (ProcessorNumber)) { + return EFI_INVALID_PARAMETER; + } + + if (!IsProcessorEnabled (ProcessorNumber)) { + return EFI_INVALID_PARAMETER; + } + + if ((GetApState (CpuData) != CpuStateIdle) && + (GetApState (CpuData) != CpuStateFinished)) + { + return EFI_NOT_READY; + } + + if ((WaitEvent != NULL) && !mNonBlockingModeAllowed) { + return EFI_UNSUPPORTED; + } + + Timeout = TimeoutInMicroseconds; + + CpuData->Timeout = TimeoutInMicroseconds; + CpuData->TimeTaken = 0; + CpuData->TimeoutActive = (BOOLEAN)(TimeoutInMicroseconds != 0); + + SetApProcedure ( + CpuData, + Procedure, + ProcedureArgument + ); + + Status = DispatchCpu (ProcessorNumber); + if (EFI_ERROR (Status)) { + CpuData->State = CpuStateIdle; + return EFI_NOT_READY; + } + + if (WaitEvent != NULL) { + // Non Blocking + if (Finished != NULL) { + CpuData->SingleApFinished = Finished; + *Finished = FALSE; + } + + CpuData->WaitEvent = WaitEvent; + Status = gBS->SetTimer ( + CpuData->CheckThisAPEvent, + TimerPeriodic, + POLL_INTERVAL_US + ); + + return EFI_SUCCESS; + } + + // Blocking + while (TRUE) { + if (GetApState (CpuData) == CpuStateFinished) { + CpuData->State = CpuStateIdle; + break; + } + + if ((TimeoutInMicroseconds != 0) && (Timeout == 0)) { + return EFI_TIMEOUT; + } + + Timeout -= CalculateAndStallInterval (Timeout); + } + + return EFI_SUCCESS; +} + +/** + This service switches the requested AP to be the BSP from that point onward. + This service changes the BSP for all purposes. This call can only be + performed by the current BSP. + + This service switches the requested AP to be the BSP from that point onward. + This service changes the BSP for all purposes. The new BSP can take over the + execution of the old BSP and continue seamlessly from where the old one left + off. This service may not be supported after the UEFI Event EFI_EVENT_GROUP_READY_TO_BOOT + is signaled. + + If the BSP cannot be switched prior to the return from this service, then + EFI_UNSUPPORTED must be returned. + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL instance. + @param[in] ProcessorNumber The handle number of AP that is to become the new + BSP. The range is from 0 to the total number of + logical processors minus 1. The total number of + logical processors can be retrieved by + EFI_MP_SERVICES_PROTOCOL.GetNumberOfProcessors(). + @param[in] EnableOldBSP If TRUE, then the old BSP will be listed as an + enabled AP. Otherwise, it will be disabled. + + @retval EFI_SUCCESS BSP successfully switched. + @retval EFI_UNSUPPORTED Switching the BSP cannot be completed prior to + this service returning. + @retval EFI_UNSUPPORTED Switching the BSP is not supported. + @retval EFI_SUCCESS The calling processor is an AP. + @retval EFI_NOT_FOUND The processor with the handle specified by + ProcessorNumber does not exist. + @retval EFI_INVALID_PARAMETER ProcessorNumber specifies the current BSP or + a disabled AP. + @retval EFI_NOT_READY The specified AP is busy. + +**/ +STATIC +EFI_STATUS +EFIAPI +SwitchBSP ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableOldBSP + ) +{ + return EFI_UNSUPPORTED; +} + +/** + This service lets the caller enable or disable an AP from this point onward. + This service may only be called from the BSP. + + This service allows the caller enable or disable an AP from this point onward. + The caller can optionally specify the health status of the AP by Health. If + an AP is being disabled, then the state of the disabled AP is implementation + dependent. If an AP is enabled, then the implementation must guarantee that a + complete initialization sequence is performed on the AP, so the AP is in a state + that is compatible with an MP operating system. This service may not be supported + after the UEFI Event EFI_EVENT_GROUP_READY_TO_BOOT is signaled. + + If the enable or disable AP operation cannot be completed prior to the return + from this service, then EFI_UNSUPPORTED must be returned. + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL instance. + @param[in] ProcessorNumber The handle number of AP that is to become the new + BSP. The range is from 0 to the total number of + logical processors minus 1. The total number of + logical processors can be retrieved by + EFI_MP_SERVICES_PROTOCOL.GetNumberOfProcessors(). + @param[in] EnableAP Specifies the new state for the processor for + enabled, FALSE for disabled. + @param[in] HealthFlag If not NULL, a pointer to a value that specifies + the new health status of the AP. This flag + corresponds to StatusFlag defined in + EFI_MP_SERVICES_PROTOCOL.GetProcessorInfo(). Only + the PROCESSOR_HEALTH_STATUS_BIT is used. All other + bits are ignored. If it is NULL, this parameter + is ignored. + + @retval EFI_SUCCESS The specified AP was enabled or disabled successfully. + @retval EFI_UNSUPPORTED Enabling or disabling an AP cannot be completed + prior to this service returning. + @retval EFI_UNSUPPORTED Enabling or disabling an AP is not supported. + @retval EFI_DEVICE_ERROR The calling processor is an AP. + @retval EFI_NOT_FOUND Processor with the handle specified by ProcessorNumber + does not exist. + @retval EFI_INVALID_PARAMETER ProcessorNumber specifies the BSP. + +**/ +STATIC +EFI_STATUS +EFIAPI +EnableDisableAP ( + IN EFI_MP_SERVICES_PROTOCOL *This, + IN UINTN ProcessorNumber, + IN BOOLEAN EnableAP, + IN UINT32 *HealthFlag OPTIONAL + ) +{ + UINTN StatusFlag; + CPU_AP_DATA *CpuData; + + StatusFlag = mCpuMpData.CpuData[ProcessorNumber].Info.StatusFlag; + CpuData = &mCpuMpData.CpuData[ProcessorNumber]; + + if (!IsCurrentProcessorBSP ()) { + return EFI_DEVICE_ERROR; + } + + if (ProcessorNumber >= mCpuMpData.NumberOfProcessors) { + return EFI_NOT_FOUND; + } + + if (IsProcessorBSP (ProcessorNumber)) { + return EFI_INVALID_PARAMETER; + } + + if (GetApState (CpuData) != CpuStateIdle) { + return EFI_UNSUPPORTED; + } + + if (EnableAP) { + if (!IsProcessorEnabled (ProcessorNumber)) { + mCpuMpData.NumberOfEnabledProcessors++; + } + + StatusFlag |= PROCESSOR_ENABLED_BIT; + } else { + if (IsProcessorEnabled (ProcessorNumber) && !IsProcessorBSP (ProcessorNumber)) { + mCpuMpData.NumberOfEnabledProcessors--; + } + + StatusFlag &= ~PROCESSOR_ENABLED_BIT; + } + + if ((HealthFlag != NULL) && !IsProcessorBSP (ProcessorNumber)) { + StatusFlag &= ~PROCESSOR_HEALTH_STATUS_BIT; + StatusFlag |= (*HealthFlag & PROCESSOR_HEALTH_STATUS_BIT); + } + + mCpuMpData.CpuData[ProcessorNumber].Info.StatusFlag = StatusFlag; + return EFI_SUCCESS; +} + +/** + This return the handle number for the calling processor. This service may be + called from the BSP and APs. + + This service returns the processor handle number for the calling processor. + The returned value is in the range from 0 to the total number of logical + processors minus 1. The total number of logical processors can be retrieved + with EFI_MP_SERVICES_PROTOCOL.GetNumberOfProcessors(). This service may be + called from the BSP and APs. If ProcessorNumber is NULL, then EFI_INVALID_PARAMETER + is returned. Otherwise, the current processors handle number is returned in + ProcessorNumber, and EFI_SUCCESS is returned. + + @param[in] This A pointer to the EFI_MP_SERVICES_PROTOCOL instance. + @param[out] ProcessorNumber The handle number of AP that is to become the new + BSP. The range is from 0 to the total number of + logical processors minus 1. The total number of + logical processors can be retrieved by + EFI_MP_SERVICES_PROTOCOL.GetNumberOfProcessors(). + + @retval EFI_SUCCESS The current processor handle number was returned + in ProcessorNumber. + @retval EFI_INVALID_PARAMETER ProcessorNumber is NULL. + +**/ +STATIC +EFI_STATUS +EFIAPI +WhoAmI ( + IN EFI_MP_SERVICES_PROTOCOL *This, + OUT UINTN *ProcessorNumber + ) +{ + UINTN Index; + UINT64 ProcessorId; + + if (ProcessorNumber == NULL) { + return EFI_INVALID_PARAMETER; + } + + ProcessorId = GET_MPIDR_AFFINITY_BITS (ArmReadMpidr ()); + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + if (ProcessorId == gProcessorIDs[Index]) { + *ProcessorNumber = Index; + break; + } + } + + return EFI_SUCCESS; +} + +STATIC EFI_MP_SERVICES_PROTOCOL mMpServicesProtocol = { + GetNumberOfProcessors, + GetProcessorInfo, + StartupAllAPs, + StartupThisAP, + SwitchBSP, + EnableDisableAP, + WhoAmI +}; + +/** Adds the specified processor the list of failed processors. + + @param ProcessorIndex The processor index to add. + @param ApState Processor state. + +**/ +STATIC +VOID +AddProcessorToFailedList ( + UINTN ProcessorIndex, + CPU_STATE ApState + ) +{ + UINTN Index; + BOOLEAN Found; + + Found = FALSE; + + if ((mCpuMpData.FailedList == NULL) || + (ApState == CpuStateIdle) || + (ApState == CpuStateFinished) || + IsProcessorBSP (ProcessorIndex)) + { + return; + } + + // If we are retrying make sure we don't double count + for (Index = 0; Index < mCpuMpData.FailedListIndex; Index++) { + if (mCpuMpData.FailedList[Index] == ProcessorIndex) { + Found = TRUE; + break; + } + } + + /* If the CPU isn't already in the FailedList, add it */ + if (!Found) { + mCpuMpData.FailedList[mCpuMpData.FailedListIndex++] = ProcessorIndex; + } +} + +/** Handles the StartupAllAPs case where the timeout has occurred. + +**/ +STATIC +VOID +ProcessStartupAllAPsTimeout ( + VOID + ) +{ + CPU_AP_DATA *CpuData; + UINTN Index; + + if (mCpuMpData.FailedList == NULL) { + return; + } + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + CpuData = &mCpuMpData.CpuData[Index]; + if (IsProcessorBSP (Index)) { + // Skip BSP + continue; + } + + if (!IsProcessorEnabled (Index)) { + // Skip Disabled processors + continue; + } + + CpuData = &mCpuMpData.CpuData[Index]; + AddProcessorToFailedList (Index, GetApState (CpuData)); + } +} + +/** Updates the status of the APs. + + @param[in] ProcessorIndex The index of the AP to update. +**/ +STATIC +VOID +UpdateApStatus ( + IN UINTN ProcessorIndex + ) +{ + EFI_STATUS Status; + CPU_AP_DATA *CpuData; + CPU_AP_DATA *NextCpuData; + CPU_STATE State; + UINTN NextNumber; + + CpuData = &mCpuMpData.CpuData[ProcessorIndex]; + + if (IsProcessorBSP (ProcessorIndex)) { + // Skip BSP + return; + } + + if (!IsProcessorEnabled (ProcessorIndex)) { + // Skip Disabled processors + return; + } + + State = GetApState (CpuData); + + switch (State) { + case CpuStateFinished: + if (mCpuMpData.SingleThread) { + Status = GetNextBlockedNumber (&NextNumber); + if (!EFI_ERROR (Status)) { + NextCpuData = &mCpuMpData.CpuData[NextNumber]; + + NextCpuData->State = CpuStateReady; + + SetApProcedure ( + NextCpuData, + mCpuMpData.Procedure, + mCpuMpData.ProcedureArgument + ); + + Status = DispatchCpu (NextNumber); + if (!EFI_ERROR (Status)) { + mCpuMpData.StartCount++; + } else { + AddProcessorToFailedList (NextNumber, NextCpuData->State); + } + } + } + + CpuData->State = CpuStateIdle; + mCpuMpData.FinishCount++; + break; + + default: + break; + } +} + +/** + If a timeout is specified in StartupAllAps(), a timer is set, which invokes + this procedure periodically to check whether all APs have finished. + + @param[in] Event The WaitEvent the user supplied. + @param[in] Context The event context. +**/ +STATIC +VOID +EFIAPI +CheckAllAPsStatus ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + EFI_STATUS Status; + UINTN Index; + + mCpuMpData.AllTimeTaken += POLL_INTERVAL_US; + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + UpdateApStatus (Index); + } + + if (mCpuMpData.AllTimeoutActive && (mCpuMpData.AllTimeTaken > mCpuMpData.AllTimeout)) { + ProcessStartupAllAPsTimeout (); + + // Force terminal exit + mCpuMpData.FinishCount = mCpuMpData.StartCount; + } + + if (mCpuMpData.FinishCount != mCpuMpData.StartCount) { + return; + } + + gBS->SetTimer ( + mCpuMpData.CheckAllAPsEvent, + TimerCancel, + 0 + ); + + if (mCpuMpData.FailedListIndex == 0) { + if (mCpuMpData.FailedList != NULL) { + // Since we don't have the original `FailedCpuList` + // pointer here to set to NULL, don't free the + // memory. + } + } + + Status = gBS->SignalEvent (mCpuMpData.AllWaitEvent); + ASSERT_EFI_ERROR (Status); + mCpuMpData.AllWaitEvent = NULL; +} + +/** Invoked periodically via a timer to check the state of the processor. + + @param Event The event supplied by the timer expiration. + @param Context The processor context. + +**/ +STATIC +VOID +EFIAPI +CheckThisAPStatus ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + EFI_STATUS Status; + CPU_AP_DATA *CpuData; + CPU_STATE State; + + CpuData = Context; + + CpuData->TimeTaken += POLL_INTERVAL_US; + + State = GetApState (CpuData); + + if (State == CpuStateFinished) { + Status = gBS->SetTimer (CpuData->CheckThisAPEvent, TimerCancel, 0); + ASSERT_EFI_ERROR (Status); + + if (CpuData->SingleApFinished != NULL) { + *(CpuData->SingleApFinished) = TRUE; + } + + if (CpuData->WaitEvent != NULL) { + Status = gBS->SignalEvent (CpuData->WaitEvent); + ASSERT_EFI_ERROR (Status); + } + + CpuData->State = CpuStateIdle; + } + + if (CpuData->TimeoutActive && (CpuData->TimeTaken > CpuData->Timeout)) { + Status = gBS->SetTimer (CpuData->CheckThisAPEvent, TimerCancel, 0); + if (CpuData->WaitEvent != NULL) { + Status = gBS->SignalEvent (CpuData->WaitEvent); + ASSERT_EFI_ERROR (Status); + CpuData->WaitEvent = NULL; + } + } +} + +/** + This function is called by all processors (both BSP and AP) once and collects + MP related data. + + @param BSP TRUE if the processor is the BSP. + @param Mpidr The MPIDR for the specified processor. This should be + the full MPIDR and not only the affinity bits. + @param ProcessorIndex The index of the processor. + + @return EFI_SUCCESS if the data for the processor collected and filled in. + +**/ +STATIC +EFI_STATUS +FillInProcessorInformation ( + IN BOOLEAN BSP, + IN UINTN Mpidr, + IN UINTN ProcessorIndex + ) +{ + EFI_PROCESSOR_INFORMATION *CpuInfo; + + CpuInfo = &mCpuMpData.CpuData[ProcessorIndex].Info; + + CpuInfo->ProcessorId = GET_MPIDR_AFFINITY_BITS (Mpidr); + CpuInfo->StatusFlag = PROCESSOR_ENABLED_BIT | PROCESSOR_HEALTH_STATUS_BIT; + + if (BSP) { + CpuInfo->StatusFlag |= PROCESSOR_AS_BSP_BIT; + } + + if ((Mpidr & MPIDR_MT_BIT) > 0) { + CpuInfo->Location.Package = GET_MPIDR_AFF2 (Mpidr); + CpuInfo->Location.Core = GET_MPIDR_AFF1 (Mpidr); + CpuInfo->Location.Thread = GET_MPIDR_AFF0 (Mpidr); + + CpuInfo->ExtendedInformation.Location2.Package = GET_MPIDR_AFF3 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Die = GET_MPIDR_AFF2 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Core = GET_MPIDR_AFF1 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Thread = GET_MPIDR_AFF0 (Mpidr); + } else { + CpuInfo->Location.Package = GET_MPIDR_AFF1 (Mpidr); + CpuInfo->Location.Core = GET_MPIDR_AFF0 (Mpidr); + CpuInfo->Location.Thread = 0; + + CpuInfo->ExtendedInformation.Location2.Package = GET_MPIDR_AFF2 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Die = GET_MPIDR_AFF1 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Core = GET_MPIDR_AFF0 (Mpidr); + CpuInfo->ExtendedInformation.Location2.Thread = 0; + } + + mCpuMpData.CpuData[ProcessorIndex].State = BSP ? CpuStateBusy : CpuStateIdle; + + mCpuMpData.CpuData[ProcessorIndex].Procedure = NULL; + mCpuMpData.CpuData[ProcessorIndex].Parameter = NULL; + + return EFI_SUCCESS; +} + +/** Initializes the MP Services system data + + @param NumberOfProcessors The number of processors, both BSP and AP. + @param CoreInfo CPU information gathered earlier during boot. + +**/ +STATIC +EFI_STATUS +MpServicesInitialize ( + IN UINTN NumberOfProcessors, + IN CONST ARM_CORE_INFO *CoreInfo + ) +{ + EFI_STATUS Status; + UINTN Index; + EFI_EVENT ReadyToBootEvent; + BOOLEAN IsBsp; + + // + // Clear the data structure area first. + // + ZeroMem (&mCpuMpData, sizeof (CPU_MP_DATA)); + // + // First BSP fills and inits all known values, including its own records. + // + mCpuMpData.NumberOfProcessors = NumberOfProcessors; + mCpuMpData.NumberOfEnabledProcessors = NumberOfProcessors; + + mCpuMpData.CpuData = AllocateZeroPool ( + mCpuMpData.NumberOfProcessors * sizeof (CPU_AP_DATA) + ); + + if (mCpuMpData.CpuData == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + /* Allocate one extra for the sentinel entry at the end */ + gProcessorIDs = AllocateZeroPool ((mCpuMpData.NumberOfProcessors + 1) * sizeof (UINT64)); + ASSERT (gProcessorIDs != NULL); + + Status = gBS->CreateEvent ( + EVT_TIMER | EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + CheckAllAPsStatus, + NULL, + &mCpuMpData.CheckAllAPsEvent + ); + ASSERT_EFI_ERROR (Status); + + gApStacksBase = AllocatePages ( + EFI_SIZE_TO_PAGES ( + mCpuMpData.NumberOfProcessors * + gApStackSize + ) + ); + ASSERT (gApStacksBase != NULL); + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + if (GET_MPIDR_AFFINITY_BITS (ArmReadMpidr ()) == CoreInfo[Index].Mpidr) { + IsBsp = TRUE; + } else { + IsBsp = FALSE; + } + + FillInProcessorInformation (IsBsp, CoreInfo[Index].Mpidr, Index); + + gProcessorIDs[Index] = mCpuMpData.CpuData[Index].Info.ProcessorId; + + Status = gBS->CreateEvent ( + EVT_TIMER | EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + CheckThisAPStatus, + (VOID *)&mCpuMpData.CpuData[Index], + &mCpuMpData.CpuData[Index].CheckThisAPEvent + ); + ASSERT_EFI_ERROR (Status); + } + + gProcessorIDs[Index] = MAX_UINT64; + + gTcr = ArmGetTCR (); + gMair = ArmGetMAIR (); + gTtbr0 = ArmGetTTBR0BaseAddress (); + + // + // The global pointer variables as well as the gProcessorIDs array contents + // are accessed by the other cores so we must clean them to the PoC + // + WriteBackDataCacheRange (&gProcessorIDs, sizeof (UINT64 *)); + WriteBackDataCacheRange (&gApStacksBase, sizeof (UINT64 *)); + + WriteBackDataCacheRange ( + gProcessorIDs, + (mCpuMpData.NumberOfProcessors + 1) * sizeof (UINT64) + ); + + mNonBlockingModeAllowed = TRUE; + + Status = EfiCreateEventReadyToBootEx ( + TPL_CALLBACK, + ReadyToBootSignaled, + NULL, + &ReadyToBootEvent + ); + ASSERT_EFI_ERROR (Status); + + return EFI_SUCCESS; +} + +/** + Event notification function called when the EFI_EVENT_GROUP_READY_TO_BOOT is + signaled. After this point, non-blocking mode is no longer allowed. + + @param Event Event whose notification function is being invoked. + @param Context The pointer to the notification function's context, + which is implementation-dependent. + +**/ +STATIC +VOID +EFIAPI +ReadyToBootSignaled ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + mNonBlockingModeAllowed = FALSE; +} + +/** Initialize multi-processor support. + + @param ImageHandle Image handle. + @param SystemTable System table. + + @return EFI_SUCCESS on success, or an error code. + +**/ +EFI_STATUS +EFIAPI +ArmPsciMpServicesDxeInitialize ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + EFI_HANDLE Handle; + UINTN MaxCpus; + EFI_LOADED_IMAGE_PROTOCOL *Image; + EFI_HOB_GENERIC_HEADER *Hob; + VOID *HobData; + UINTN HobDataSize; + CONST ARM_CORE_INFO *CoreInfo; + + MaxCpus = 1; + + Status = gBS->HandleProtocol ( + ImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&Image + ); + ASSERT_EFI_ERROR (Status); + + // + // Parts of the code in this driver may be executed by other cores running + // with the MMU off so we need to ensure that everything is clean to the + // point of coherency (PoC) + // + WriteBackDataCacheRange (Image->ImageBase, Image->ImageSize); + + Hob = GetFirstGuidHob (&gArmMpCoreInfoGuid); + if (Hob != NULL) { + HobData = GET_GUID_HOB_DATA (Hob); + HobDataSize = GET_GUID_HOB_DATA_SIZE (Hob); + CoreInfo = (ARM_CORE_INFO *)HobData; + MaxCpus = HobDataSize / sizeof (ARM_CORE_INFO); + } + + if (MaxCpus == 1) { + DEBUG ((DEBUG_WARN, "Trying to use EFI_MP_SERVICES_PROTOCOL on a UP system")); + // We are not MP so nothing to do + return EFI_NOT_FOUND; + } + + Status = MpServicesInitialize (MaxCpus, CoreInfo); + if (Status != EFI_SUCCESS) { + ASSERT_EFI_ERROR (Status); + return Status; + } + + // + // Now install the MP services protocol. + // + Handle = NULL; + Status = gBS->InstallMultipleProtocolInterfaces ( + &Handle, + &gEfiMpServiceProtocolGuid, + &mMpServicesProtocol, + NULL + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} + +/** AP exception handler. + + @param InterruptType The AArch64 CPU exception type. + @param SystemContext System context. + +**/ +STATIC +VOID +EFIAPI +ApExceptionHandler ( + IN CONST EFI_EXCEPTION_TYPE InterruptType, + IN CONST EFI_SYSTEM_CONTEXT SystemContext + ) +{ + ARM_SMC_ARGS Args; + UINT64 Mpidr; + UINTN Index; + UINTN ProcessorIndex; + + Mpidr = GET_MPIDR_AFFINITY_BITS (ArmReadMpidr ()); + + Index = 0; + ProcessorIndex = MAX_UINT64; + + do { + if (gProcessorIDs[Index] == Mpidr) { + ProcessorIndex = Index; + break; + } + + Index++; + } while (gProcessorIDs[Index] != MAX_UINT64); + + if (ProcessorIndex != MAX_UINT64) { + mCpuMpData.CpuData[ProcessorIndex].State = CpuStateFinished; + ArmDataMemoryBarrier (); + } + + Args.Arg0 = ARM_SMC_ID_PSCI_CPU_OFF; + ArmCallSmc (&Args); + + /* Should never be reached */ + ASSERT (FALSE); + CpuDeadLoop (); +} + +/** C entry-point for the AP. + This function gets called from the assembly function ApEntryPoint. + +**/ +VOID +ApProcedure ( + VOID + ) +{ + ARM_SMC_ARGS Args; + EFI_AP_PROCEDURE UserApProcedure; + VOID *UserApParameter; + UINTN ProcessorIndex; + + ProcessorIndex = 0; + + WhoAmI (&mMpServicesProtocol, &ProcessorIndex); + + /* Fetch the user-supplied procedure and parameter to execute */ + UserApProcedure = mCpuMpData.CpuData[ProcessorIndex].Procedure; + UserApParameter = mCpuMpData.CpuData[ProcessorIndex].Parameter; + + InitializeCpuExceptionHandlers (NULL); + RegisterCpuInterruptHandler (EXCEPT_AARCH64_SYNCHRONOUS_EXCEPTIONS, ApExceptionHandler); + RegisterCpuInterruptHandler (EXCEPT_AARCH64_IRQ, ApExceptionHandler); + RegisterCpuInterruptHandler (EXCEPT_AARCH64_FIQ, ApExceptionHandler); + RegisterCpuInterruptHandler (EXCEPT_AARCH64_SERROR, ApExceptionHandler); + + UserApProcedure (UserApParameter); + + mCpuMpData.CpuData[ProcessorIndex].State = CpuStateFinished; + + ArmDataMemoryBarrier (); + + /* Since we're finished with this AP, turn it off */ + Args.Arg0 = ARM_SMC_ID_PSCI_CPU_OFF; + ArmCallSmc (&Args); + + /* Should never be reached */ + ASSERT (FALSE); + CpuDeadLoop (); +} + +/** Returns whether the processor executing this function is the BSP. + + @return Whether the current processor is the BSP. +**/ +STATIC +BOOLEAN +IsCurrentProcessorBSP ( + VOID + ) +{ + EFI_STATUS Status; + UINTN ProcessorIndex; + + Status = WhoAmI (&mMpServicesProtocol, &ProcessorIndex); + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return FALSE; + } + + return IsProcessorBSP (ProcessorIndex); +} + +/** Returns whether the specified processor is enabled. + + @param[in] ProcessorIndex The index of the processor to check. + + @return TRUE if the processor is enabled, FALSE otherwise. +**/ +STATIC +BOOLEAN +IsProcessorEnabled ( + UINTN ProcessorIndex + ) +{ + EFI_PROCESSOR_INFORMATION *CpuInfo; + + CpuInfo = &mCpuMpData.CpuData[ProcessorIndex].Info; + + return (CpuInfo->StatusFlag & PROCESSOR_ENABLED_BIT) != 0; +} + +/** Sets up the state for the StartupAllAPs function. + + @param SingleThread Whether the APs will execute sequentially. + +**/ +STATIC +VOID +StartupAllAPsPrepareState ( + IN BOOLEAN SingleThread + ) +{ + UINTN Index; + CPU_STATE APInitialState; + CPU_AP_DATA *CpuData; + + mCpuMpData.FinishCount = 0; + mCpuMpData.StartCount = 0; + mCpuMpData.SingleThread = SingleThread; + + APInitialState = CpuStateReady; + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + CpuData = &mCpuMpData.CpuData[Index]; + + // + // Get APs prepared, and put failing APs into FailedCpuList. + // If "SingleThread", only 1 AP will put into ready state, other AP will be + // put into ready state 1 by 1, until the previous 1 finished its task. + // If not "SingleThread", all APs are put into ready state from the + // beginning + // + + if (IsProcessorBSP (Index)) { + // Skip BSP + continue; + } + + if (!IsProcessorEnabled (Index)) { + // Skip Disabled processors + if (mCpuMpData.FailedList != NULL) { + mCpuMpData.FailedList[mCpuMpData.FailedListIndex++] = Index; + } + + continue; + } + + // If any APs finished after timing out, reset state to Idle + if (GetApState (CpuData) == CpuStateFinished) { + CpuData->State = CpuStateIdle; + } + + if (GetApState (CpuData) != CpuStateIdle) { + // Skip busy processors + if (mCpuMpData.FailedList != NULL) { + mCpuMpData.FailedList[mCpuMpData.FailedListIndex++] = Index; + } + } + + CpuData->State = APInitialState; + + mCpuMpData.StartCount++; + if (SingleThread) { + APInitialState = CpuStateBlocked; + } + } +} + +/** Handles execution of StartupAllAPs when a WaitEvent has been specified. + + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + @param WaitEvent The wait event to be signaled when the work is + complete or a timeout has occurred. + @param TimeoutInMicroseconds The timeout for the work to be completed. Zero + indicates an infinite timeout. + @param SingleThread Whether the APs will execute sequentially. + @param FailedCpuList User-supplied pointer for list of failed CPUs. + + @return EFI_SUCCESS on success. +**/ +STATIC +EFI_STATUS +StartupAllAPsWithWaitEvent ( + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument, + IN EFI_EVENT WaitEvent, + IN UINTN TimeoutInMicroseconds, + IN BOOLEAN SingleThread, + IN UINTN **FailedCpuList + ) +{ + EFI_STATUS Status; + UINTN Index; + CPU_AP_DATA *CpuData; + + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + CpuData = &mCpuMpData.CpuData[Index]; + if (IsProcessorBSP (Index)) { + // Skip BSP + continue; + } + + if (!IsProcessorEnabled (Index)) { + // Skip Disabled processors + continue; + } + + if (GetApState (CpuData) == CpuStateReady) { + SetApProcedure (CpuData, Procedure, ProcedureArgument); + if ((mCpuMpData.StartCount == 0) || !SingleThread) { + Status = DispatchCpu (Index); + if (EFI_ERROR (Status)) { + AddProcessorToFailedList (Index, CpuData->State); + break; + } + } + } + } + + if (EFI_ERROR (Status)) { + return EFI_NOT_READY; + } + + // + // Save data into private data structure, and create timer to poll AP state + // before exiting + // + mCpuMpData.Procedure = Procedure; + mCpuMpData.ProcedureArgument = ProcedureArgument; + mCpuMpData.AllWaitEvent = WaitEvent; + mCpuMpData.AllTimeout = TimeoutInMicroseconds; + mCpuMpData.AllTimeTaken = 0; + mCpuMpData.AllTimeoutActive = (BOOLEAN)(TimeoutInMicroseconds != 0); + Status = gBS->SetTimer ( + mCpuMpData.CheckAllAPsEvent, + TimerPeriodic, + POLL_INTERVAL_US + ); + + return Status; +} + +/** Handles execution of StartupAllAPs when no wait event has been specified. + + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + @param TimeoutInMicroseconds The timeout for the work to be completed. Zero + indicates an infinite timeout. + @param SingleThread Whether the APs will execute sequentially. + @param FailedCpuList User-supplied pointer for list of failed CPUs. + + @return EFI_SUCCESS on success. +**/ +STATIC +EFI_STATUS +StartupAllAPsNoWaitEvent ( + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument, + IN UINTN TimeoutInMicroseconds, + IN BOOLEAN SingleThread, + IN UINTN **FailedCpuList + ) +{ + EFI_STATUS Status; + UINTN Index; + UINTN NextIndex; + UINTN Timeout; + CPU_AP_DATA *CpuData; + BOOLEAN DispatchError; + + Timeout = TimeoutInMicroseconds; + DispatchError = FALSE; + + while (TRUE) { + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + CpuData = &mCpuMpData.CpuData[Index]; + if (IsProcessorBSP (Index)) { + // Skip BSP + continue; + } + + if (!IsProcessorEnabled (Index)) { + // Skip Disabled processors + continue; + } + + switch (GetApState (CpuData)) { + case CpuStateReady: + SetApProcedure (CpuData, Procedure, ProcedureArgument); + Status = DispatchCpu (Index); + if (EFI_ERROR (Status)) { + AddProcessorToFailedList (Index, CpuData->State); + CpuData->State = CpuStateIdle; + mCpuMpData.StartCount--; + DispatchError = TRUE; + + if (SingleThread) { + // Dispatch the next available AP + Status = GetNextBlockedNumber (&NextIndex); + if (!EFI_ERROR (Status)) { + mCpuMpData.CpuData[NextIndex].State = CpuStateReady; + } + } + } + + break; + + case CpuStateFinished: + mCpuMpData.FinishCount++; + if (SingleThread) { + Status = GetNextBlockedNumber (&NextIndex); + if (!EFI_ERROR (Status)) { + mCpuMpData.CpuData[NextIndex].State = CpuStateReady; + } + } + + CpuData->State = CpuStateIdle; + break; + + default: + break; + } + } + + if (mCpuMpData.FinishCount == mCpuMpData.StartCount) { + Status = EFI_SUCCESS; + break; + } + + if ((TimeoutInMicroseconds != 0) && (Timeout == 0)) { + Status = EFI_TIMEOUT; + break; + } + + Timeout -= CalculateAndStallInterval (Timeout); + } + + if (Status == EFI_TIMEOUT) { + // Add any remaining CPUs to the FailedCpuList + if (FailedCpuList != NULL) { + for (Index = 0; Index < mCpuMpData.NumberOfProcessors; Index++) { + AddProcessorToFailedList (Index, mCpuMpData.CpuData[Index].State); + } + } + } + + if (DispatchError) { + Status = EFI_NOT_READY; + } + + return Status; +} diff --git a/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf b/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf new file mode 100644 index 0000000000..2c9ab99038 --- /dev/null +++ b/ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf @@ -0,0 +1,56 @@ +## @file +# ARM MP services protocol driver +# +# Copyright (c) 2022, Qualcomm Innovation Center, Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = ArmPsciMpServicesDxe + FILE_GUID = 007ab472-dc4a-4df8-a5c2-abb4a327278c + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + + ENTRY_POINT = ArmPsciMpServicesDxeInitialize + +[Sources.Common] + ArmPsciMpServicesDxe.c + MpFuncs.S + MpServicesInternal.h + +[Packages] + ArmPkg/ArmPkg.dec + ArmPlatformPkg/ArmPlatformPkg.dec + EmbeddedPkg/EmbeddedPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + ArmLib + ArmMmuLib + ArmSmcLib + BaseMemoryLib + CacheMaintenanceLib + CpuExceptionHandlerLib + DebugLib + HobLib + MemoryAllocationLib + UefiBootServicesTableLib + UefiDriverEntryPoint + UefiLib + +[Protocols] + gEfiMpServiceProtocolGuid ## PRODUCES + gEfiLoadedImageProtocolGuid ## CONSUMES + +[Guids] + gArmMpCoreInfoGuid + +[Depex] + TRUE + +[BuildOptions] + GCC:*_*_*_CC_FLAGS = -mstrict-align diff --git a/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpFuncs.S b/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpFuncs.S new file mode 100644 index 0000000000..f73edc1792 --- /dev/null +++ b/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpFuncs.S @@ -0,0 +1,74 @@ +#=============================================================================== +# Copyright (c) 2022 Qualcomm Innovation Center, Inc. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +#=============================================================================== + +.text +.align 3 + +#include +#include +#include + +#include "MpServicesInternal.h" + +GCC_ASM_IMPORT (gApStacksBase) +GCC_ASM_IMPORT (gProcessorIDs) +GCC_ASM_IMPORT (ApProcedure) +GCC_ASM_IMPORT (gApStackSize) +GCC_ASM_IMPORT (gTcr) +GCC_ASM_IMPORT (gTtbr0) +GCC_ASM_IMPORT (gMair) + +GCC_ASM_EXPORT (ApEntryPoint) + +// Entry-point for the AP +// VOID +// ApEntryPoint ( +// VOID +// ); +ASM_PFX(ApEntryPoint): + // Configure the MMU and caches + ldr x0, gTcr + bl ArmSetTCR + ldr x0, gTtbr0 + bl ArmSetTTBR0 + ldr x0, gMair + bl ArmSetMAIR + bl ArmDisableAlignmentCheck + bl ArmEnableStackAlignmentCheck + bl ArmEnableInstructionCache + bl ArmEnableDataCache + bl ArmEnableMmu + + mrs x0, mpidr_el1 + // Mask the non-affinity bits + bic x0, x0, 0x00ff000000 + and x0, x0, 0xffffffffff + ldr x1, gProcessorIDs + mov x2, 0 // x2 = processor index + +// Find index in gProcessorIDs for current processor +1: + ldr x3, [x1, x2, lsl #3] // x4 = gProcessorIDs + x2 * 8 + cmp x3, #-1 // check if we've reached the end of gProcessorIDs + beq ProcessorNotFound + add x2, x2, 1 // x2++ + cmp x0, x3 // if mpidr_el1 != gProcessorIDs[x] then loop + bne 1b + +// Calculate stack address + // x2 contains the index for the current processor plus 1 + ldr x0, gApStacksBase + ldr x1, gApStackSize + mul x3, x2, x1 // x3 = (ProcessorIndex + 1) * gApStackSize + add sp, x0, x3 // sp = gApStacksBase + x3 + mov x29, xzr + bl ApProcedure // doesn't return + +ProcessorNotFound: +// Turn off the processor + MOV32 (w0, ARM_SMC_ID_PSCI_CPU_OFF) + smc #0 + b . diff --git a/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpServicesInternal.h b/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpServicesInternal.h new file mode 100644 index 0000000000..a0c203f0a2 --- /dev/null +++ b/ArmPkg/Drivers/ArmPsciMpServicesDxe/MpServicesInternal.h @@ -0,0 +1,345 @@ +/** @file + +Copyright (c) 2022, Qualcomm Innovation Center, Inc. All rights reserved.
+Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.
+Portions copyright (c) 2011, Apple Inc. All rights reserved. + +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef MP_SERVICES_INTERNAL_H_ +#define MP_SERVICES_INTERNAL_H_ + +#include +#include + +#include +#include + +#define AP_STACK_SIZE 0x1000 + +// +// Internal Data Structures +// + +// +// AP state +// +// The state transitions for an AP when it processes a procedure are: +// Idle ----> Ready ----> Busy ----> Finished ----> Idle +// [BSP] [BSP] [AP] [BSP] +// +typedef enum { + CpuStateIdle, + CpuStateReady, + CpuStateBlocked, + CpuStateBusy, + CpuStateFinished, + CpuStateDisabled +} CPU_STATE; + +// +// Define Individual Processor Data block. +// +typedef struct { + EFI_PROCESSOR_INFORMATION Info; + EFI_AP_PROCEDURE Procedure; + VOID *Parameter; + CPU_STATE State; + EFI_EVENT CheckThisAPEvent; + EFI_EVENT WaitEvent; + UINTN Timeout; + UINTN TimeTaken; + BOOLEAN TimeoutActive; + BOOLEAN *SingleApFinished; +} CPU_AP_DATA; + +// +// Define MP data block which consumes individual processor block. +// +typedef struct { + UINTN NumberOfProcessors; + UINTN NumberOfEnabledProcessors; + EFI_EVENT CheckAllAPsEvent; + EFI_EVENT AllWaitEvent; + UINTN FinishCount; + UINTN StartCount; + EFI_AP_PROCEDURE Procedure; + VOID *ProcedureArgument; + BOOLEAN SingleThread; + UINTN StartedNumber; + CPU_AP_DATA *CpuData; + UINTN *FailedList; + UINTN FailedListIndex; + UINTN AllTimeout; + UINTN AllTimeTaken; + BOOLEAN AllTimeoutActive; +} CPU_MP_DATA; + +/** Secondary core entry point. + +**/ +VOID +ApEntryPoint ( + VOID + ); + +/** C entry-point for the AP. + This function gets called from the assembly function ApEntryPoint. +**/ +VOID +ApProcedure ( + VOID + ); + +/** Turns on the specified core using PSCI and executes the user-supplied + function that's been configured via a previous call to SetApProcedure. + + @param ProcessorIndex The index of the core to turn on. + + @retval EFI_SUCCESS The processor was successfully turned on. + @retval EFI_DEVICE_ERROR An error occurred turning the processor on. + +**/ +STATIC +EFI_STATUS +EFIAPI +DispatchCpu ( + IN UINTN ProcessorIndex + ); + +/** Returns whether the specified processor is the BSP. + + @param[in] ProcessorIndex The index the processor to check. + + @return TRUE if the processor is the BSP, FALSE otherwise. +**/ +STATIC +BOOLEAN +IsProcessorBSP ( + UINTN ProcessorIndex + ); + +/** Returns whether the processor executing this function is the BSP. + + @return Whether the current processor is the BSP. +**/ +STATIC +BOOLEAN +IsCurrentProcessorBSP ( + VOID + ); + +/** Returns whether the specified processor is enabled. + + @param[in] ProcessorIndex The index of the processor to check. + + @return TRUE if the processor is enabled, FALSE otherwise. +**/ +STATIC +BOOLEAN +IsProcessorEnabled ( + UINTN ProcessorIndex + ); + +/** Configures the processor context with the user-supplied procedure and + argument. + + @param CpuData The processor context. + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + +**/ +STATIC +VOID +SetApProcedure ( + IN CPU_AP_DATA *CpuData, + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument + ); + +/** + Get the Application Processors state. + + @param[in] CpuData The pointer to CPU_AP_DATA of specified AP + + @return The AP status +**/ +CPU_STATE +GetApState ( + IN CPU_AP_DATA *CpuData + ); + +/** Returns the index of the next processor that is blocked. + + @param[out] NextNumber The index of the next blocked processor. + + @retval EFI_SUCCESS Successfully found the next blocked processor. + @retval EFI_NOT_FOUND There are no blocked processors. + +**/ +STATIC +EFI_STATUS +GetNextBlockedNumber ( + OUT UINTN *NextNumber + ); + +/** Stalls the BSP for the minimum of gPollInterval and Timeout. + + @param[in] Timeout The time limit in microseconds remaining for + APs to return from Procedure. + + @retval StallTime Time of execution stall. +**/ +STATIC +UINTN +CalculateAndStallInterval ( + IN UINTN Timeout + ); + +/** Sets up the state for the StartupAllAPs function. + + @param SingleThread Whether the APs will execute sequentially. + +**/ +STATIC +VOID +StartupAllAPsPrepareState ( + IN BOOLEAN SingleThread + ); + +/** Handles execution of StartupAllAPs when a WaitEvent has been specified. + + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + @param WaitEvent The wait event to be signaled when the work is + complete or a timeout has occurred. + @param TimeoutInMicroseconds The timeout for the work to be completed. Zero + indicates an infinite timeout. + @param SingleThread Whether the APs will execute sequentially. + @param FailedCpuList User-supplied pointer for list of failed CPUs. + + @return EFI_SUCCESS on success. +**/ +STATIC +EFI_STATUS +StartupAllAPsWithWaitEvent ( + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument, + IN EFI_EVENT WaitEvent, + IN UINTN TimeoutInMicroseconds, + IN BOOLEAN SingleThread, + IN UINTN **FailedCpuList + ); + +/** Handles execution of StartupAllAPs when no wait event has been specified. + + @param Procedure The user-supplied procedure. + @param ProcedureArgument The user-supplied procedure argument. + @param TimeoutInMicroseconds The timeout for the work to be completed. Zero + indicates an infinite timeout. + @param SingleThread Whether the APs will execute sequentially. + @param FailedCpuList User-supplied pointer for list of failed CPUs. + + @return EFI_SUCCESS on success. +**/ +STATIC +EFI_STATUS +StartupAllAPsNoWaitEvent ( + IN EFI_AP_PROCEDURE Procedure, + IN VOID *ProcedureArgument, + IN UINTN TimeoutInMicroseconds, + IN BOOLEAN SingleThread, + IN UINTN **FailedCpuList + ); + +/** Adds the specified processor the list of failed processors. + + @param ProcessorIndex The processor index to add. + @param ApState Processor state. + +**/ +STATIC +VOID +AddProcessorToFailedList ( + UINTN ProcessorIndex, + CPU_STATE ApState + ); + +/** Handles the StartupAllAPs case where the timeout has occurred. + +**/ +STATIC +VOID +ProcessStartupAllAPsTimeout ( + VOID + ); + +/** + If a timeout is specified in StartupAllAps(), a timer is set, which invokes + this procedure periodically to check whether all APs have finished. + + @param[in] Event The WaitEvent the user supplied. + @param[in] Context The event context. +**/ +STATIC +VOID +EFIAPI +CheckAllAPsStatus ( + IN EFI_EVENT Event, + IN VOID *Context + ); + +/** Invoked periodically via a timer to check the state of the processor. + + @param Event The event supplied by the timer expiration. + @param Context The processor context. + +**/ +STATIC +VOID +EFIAPI +CheckThisAPStatus ( + IN EFI_EVENT Event, + IN VOID *Context + ); + +/** + This function is called by all processors (both BSP and AP) once and collects + MP related data. + + @param BSP TRUE if the processor is the BSP. + @param Mpidr The MPIDR for the specified processor. This should be + the full MPIDR and not only the affinity bits. + @param ProcessorIndex The index of the processor. + + @return EFI_SUCCESS if the data for the processor collected and filled in. + +**/ +STATIC +EFI_STATUS +FillInProcessorInformation ( + IN BOOLEAN BSP, + IN UINTN Mpidr, + IN UINTN ProcessorIndex + ); + +/** + Event notification function called when the EFI_EVENT_GROUP_READY_TO_BOOT is + signaled. After this point, non-blocking mode is no longer allowed. + + @param Event Event whose notification function is being invoked. + @param Context The pointer to the notification function's context, + which is implementation-dependent. + +**/ +STATIC +VOID +EFIAPI +ReadyToBootSignaled ( + IN EFI_EVENT Event, + IN VOID *Context + ); + +#endif /* MP_SERVICES_INTERNAL_H_ */ From 62600514f010cbf793c1eb4efa04a056f942afbc Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Wed, 25 Jan 2023 17:20:59 +0800 Subject: [PATCH 0554/1529] tools_def: Remove duplicated -Os BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2928 commit 17bd834eb5fd ("BaseTools: Factorize GCC flags") makes GCC48_ALL_CC_FLAGS inherit from GCC_ALL_CC_FLAGS. GCC_ALL_CC_FLAGS contains the '-Os' flag. The latest flag in a command line overrides the previous optimization option. This allows more specific build configuration to override the inherited '-Os' flag. If a build configuration includes GCC48_ALL_CC_FLAGS, hard-coded '-Os' options are not necessary anymore. Remove them. Reported-by: Laszlo Ersek Signed-off-by: Pierre Gondois Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Conf/tools_def.template | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 380d458733..f77e936c04 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2024,8 +2024,8 @@ DEFINE GCC5_LOONGARCH64_PP_FLAGS = -mabi=lp64d -march=loongarch64 DEF( *_GCC48_IA32_OBJCOPY_FLAGS = *_GCC48_IA32_NASM_FLAGS = -f elf32 - DEBUG_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) -Os -RELEASE_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) -Os -Wno-unused-but-set-variable + DEBUG_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) +RELEASE_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) -Wno-unused-but-set-variable NOOPT_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) -O0 ################## @@ -2052,8 +2052,8 @@ RELEASE_GCC48_IA32_CC_FLAGS = DEF(GCC48_IA32_CC_FLAGS) -Os -Wno-unused-but *_GCC48_X64_OBJCOPY_FLAGS = *_GCC48_X64_NASM_FLAGS = -f elf64 - DEBUG_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -Os -RELEASE_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -Os -Wno-unused-but-set-variable + DEBUG_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) +RELEASE_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -Wno-unused-but-set-variable NOOPT_GCC48_X64_CC_FLAGS = DEF(GCC48_X64_CC_FLAGS) -O0 ################## @@ -2161,8 +2161,8 @@ RELEASE_GCC48_AARCH64_CC_FLAGS = DEF(GCC48_AARCH64_CC_FLAGS) -Wno-unused-but-s *_GCC49_IA32_OBJCOPY_FLAGS = *_GCC49_IA32_NASM_FLAGS = -f elf32 - DEBUG_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) -Os -RELEASE_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) -Os -Wno-unused-but-set-variable -Wno-unused-const-variable + DEBUG_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) +RELEASE_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) -Wno-unused-but-set-variable -Wno-unused-const-variable NOOPT_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) -O0 ################## @@ -2189,8 +2189,8 @@ RELEASE_GCC49_IA32_CC_FLAGS = DEF(GCC49_IA32_CC_FLAGS) -Os -Wno-unused-but *_GCC49_X64_OBJCOPY_FLAGS = *_GCC49_X64_NASM_FLAGS = -f elf64 - DEBUG_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -Os -RELEASE_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -Os -Wno-unused-but-set-variable -Wno-unused-const-variable + DEBUG_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) +RELEASE_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -Wno-unused-but-set-variable -Wno-unused-const-variable NOOPT_GCC49_X64_CC_FLAGS = DEF(GCC49_X64_CC_FLAGS) -O0 ################## @@ -2304,10 +2304,10 @@ RELEASE_GCC49_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_GCC5_IA32_OBJCOPY_FLAGS = *_GCC5_IA32_NASM_FLAGS = -f elf32 - DEBUG_GCC5_IA32_CC_FLAGS = DEF(GCC5_IA32_CC_FLAGS) -flto -Os + DEBUG_GCC5_IA32_CC_FLAGS = DEF(GCC5_IA32_CC_FLAGS) -flto DEBUG_GCC5_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -flto -Os -Wl,-m,elf_i386,--oformat=elf32-i386 -RELEASE_GCC5_IA32_CC_FLAGS = DEF(GCC5_IA32_CC_FLAGS) -flto -Os -Wno-unused-but-set-variable -Wno-unused-const-variable +RELEASE_GCC5_IA32_CC_FLAGS = DEF(GCC5_IA32_CC_FLAGS) -flto -Wno-unused-but-set-variable -Wno-unused-const-variable RELEASE_GCC5_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -flto -Os -Wl,-m,elf_i386,--oformat=elf32-i386 NOOPT_GCC5_IA32_CC_FLAGS = DEF(GCC5_IA32_CC_FLAGS) -O0 @@ -2336,10 +2336,10 @@ RELEASE_GCC5_IA32_DLINK_FLAGS = DEF(GCC5_IA32_X64_DLINK_FLAGS) -flto -Os -Wl, *_GCC5_X64_OBJCOPY_FLAGS = *_GCC5_X64_NASM_FLAGS = -f elf64 - DEBUG_GCC5_X64_CC_FLAGS = DEF(GCC5_X64_CC_FLAGS) -flto -DUSING_LTO -Os + DEBUG_GCC5_X64_CC_FLAGS = DEF(GCC5_X64_CC_FLAGS) -flto -DUSING_LTO DEBUG_GCC5_X64_DLINK_FLAGS = DEF(GCC5_X64_DLINK_FLAGS) -flto -Os -RELEASE_GCC5_X64_CC_FLAGS = DEF(GCC5_X64_CC_FLAGS) -flto -DUSING_LTO -Os -Wno-unused-but-set-variable -Wno-unused-const-variable +RELEASE_GCC5_X64_CC_FLAGS = DEF(GCC5_X64_CC_FLAGS) -flto -DUSING_LTO -Wno-unused-but-set-variable -Wno-unused-const-variable RELEASE_GCC5_X64_DLINK_FLAGS = DEF(GCC5_X64_DLINK_FLAGS) -flto -Os NOOPT_GCC5_X64_CC_FLAGS = DEF(GCC5_X64_CC_FLAGS) -O0 From 26f089c665879d2336c5716c4e4a53a74e6cc571 Mon Sep 17 00:00:00 2001 From: "Dionna Glaze via groups.io" Date: Fri, 27 Jan 2023 19:21:16 +0000 Subject: [PATCH 0555/1529] MdeModulePkg: Correct memory type in PrePiDxeCis.h The enumeration in MdePkg/Include/Pi/PiDxeCis.h has a duplicated entry, so the 8th position in the list doesn't count as index 7. The value EfiGcdMemoryTypeUnaccepted will have when added before EfiGcdMemoryTypeMaximum will be 6. Cc: Min M Xu Cc: Jiewen Yao Signed-off-by: Dionna Glaze Reviewed-by: Min Xu Reviewed-by: Liming Gao --- MdeModulePkg/Include/Pi/PrePiDxeCis.h | 2 +- MdePkg/Include/Pi/PiDxeCis.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Include/Pi/PrePiDxeCis.h b/MdeModulePkg/Include/Pi/PrePiDxeCis.h index 113ac37924..9be71d2618 100644 --- a/MdeModulePkg/Include/Pi/PrePiDxeCis.h +++ b/MdeModulePkg/Include/Pi/PrePiDxeCis.h @@ -20,6 +20,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// After this memory region is defined in PI spec, it should be a value in /// EFI_GCD_MEMORY_TYPE in PiDxeCis.h. /// -#define EFI_GCD_MEMORY_TYPE_UNACCEPTED 7 +#define EFI_GCD_MEMORY_TYPE_UNACCEPTED 6 #endif diff --git a/MdePkg/Include/Pi/PiDxeCis.h b/MdePkg/Include/Pi/PiDxeCis.h index 27b219aa3f..bb7fb2c38a 100644 --- a/MdePkg/Include/Pi/PiDxeCis.h +++ b/MdePkg/Include/Pi/PiDxeCis.h @@ -64,7 +64,7 @@ typedef enum { // /// EfiGcdMemoryTypeUnaccepted is defined in PrePiDxeCis.h because it has not been // /// defined in PI spec. // EfiGcdMemoryTypeUnaccepted, - EfiGcdMemoryTypeMaximum = 8 + EfiGcdMemoryTypeMaximum = 7 } EFI_GCD_MEMORY_TYPE; /// From 96fd36a9b4ddf2b8eec83f6e3acf6ce2ff017033 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Fri, 27 Jan 2023 09:42:48 -0700 Subject: [PATCH 0556/1529] BaseTools: Delete Bin/{CYGWIN_NT-5.1-i686,Darwin-i386} directories The Bin/CYGWIN_NT-5.1-i686 and Bin/Darwin-i386 directories contained files needed for RVCT support. Since EDK2 no longer supports RVCT, delete those directories. Signed-off-by: Rebecca Cran Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao Acked-by: Bob Feng --- .../Bin/CYGWIN_NT-5.1-i686/BootSectImage | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/BuildEnv | 5 - BaseTools/Bin/CYGWIN_NT-5.1-i686/Ecc | 14 --- BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiLdrImage | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiRom | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenCrc32 | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenDepex | 14 --- BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFds | 14 --- BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFfs | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFv | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFw | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenPage | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenSec | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/GenVtf | 29 ------ .../Bin/CYGWIN_NT-5.1-i686/GnuGenBootSector | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaCompress | 29 ------ .../Bin/CYGWIN_NT-5.1-i686/LzmaF86Compress | 17 ---- .../CYGWIN_NT-5.1-i686/RunBinToolFromBuildDir | 29 ------ .../Bin/CYGWIN_NT-5.1-i686/RunToolFromSource | 5 - BaseTools/Bin/CYGWIN_NT-5.1-i686/Split | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/TargetTool | 14 --- .../Bin/CYGWIN_NT-5.1-i686/TianoCompress | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/Trim | 14 --- BaseTools/Bin/CYGWIN_NT-5.1-i686/VfrCompile | 29 ------ BaseTools/Bin/CYGWIN_NT-5.1-i686/VolInfo | 29 ------ .../Bin/CYGWIN_NT-5.1-i686/armcc_wrapper.py | 87 ------------------ BaseTools/Bin/CYGWIN_NT-5.1-i686/build | 14 --- .../DEBUG_XCODE31/CompilerIntrinsicsLib.lib | Bin 36072 -> 0 bytes .../DEBUG_XCODE32/CompilerIntrinsicsLib.lib | Bin 36072 -> 0 bytes .../RELEASE_XCODE31/CompilerIntrinsicsLib.lib | Bin 11504 -> 0 bytes .../RELEASE_XCODE32/CompilerIntrinsicsLib.lib | Bin 11504 -> 0 bytes 31 files changed, 691 deletions(-) delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/BootSectImage delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/BuildEnv delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/Ecc delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiLdrImage delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiRom delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenCrc32 delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenDepex delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFds delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFfs delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFv delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFw delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenPage delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenSec delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GenVtf delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/GnuGenBootSector delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaCompress delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaF86Compress delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/RunBinToolFromBuildDir delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/RunToolFromSource delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/Split delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/TargetTool delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/TianoCompress delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/Trim delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/VfrCompile delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/VolInfo delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/armcc_wrapper.py delete mode 100755 BaseTools/Bin/CYGWIN_NT-5.1-i686/build delete mode 100644 BaseTools/Bin/Darwin-i386/Arm/DEBUG_XCODE31/CompilerIntrinsicsLib.lib delete mode 100644 BaseTools/Bin/Darwin-i386/Arm/DEBUG_XCODE32/CompilerIntrinsicsLib.lib delete mode 100644 BaseTools/Bin/Darwin-i386/Arm/RELEASE_XCODE31/CompilerIntrinsicsLib.lib delete mode 100644 BaseTools/Bin/Darwin-i386/Arm/RELEASE_XCODE32/CompilerIntrinsicsLib.lib diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/BootSectImage b/BaseTools/Bin/CYGWIN_NT-5.1-i686/BootSectImage deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/BootSectImage +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/BuildEnv b/BaseTools/Bin/CYGWIN_NT-5.1-i686/BuildEnv deleted file mode 100755 index 2cb8b86a99..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/BuildEnv +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* -PYTHONPATH="`dirname $0`/../../Source/Python" \ - python "`dirname $0`/../../Source/Python"/`basename $0`/`basename $0`.py $* - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Ecc b/BaseTools/Bin/CYGWIN_NT-5.1-i686/Ecc deleted file mode 100755 index 1ba451cf5e..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Ecc +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$cmd/$cmd.py" "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiLdrImage b/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiLdrImage deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiLdrImage +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiRom b/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiRom deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/EfiRom +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenCrc32 b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenCrc32 deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenCrc32 +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenDepex b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenDepex deleted file mode 100755 index 1ba451cf5e..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenDepex +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$cmd/$cmd.py" "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFds b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFds deleted file mode 100755 index 1ba451cf5e..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFds +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$cmd/$cmd.py" "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFfs b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFfs deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFfs +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFv b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFv deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFv +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFw b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFw deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenFw +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenPage b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenPage deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenPage +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenSec b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenSec deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenSec +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenVtf b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenVtf deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GenVtf +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GnuGenBootSector b/BaseTools/Bin/CYGWIN_NT-5.1-i686/GnuGenBootSector deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/GnuGenBootSector +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaCompress b/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaCompress deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaCompress +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaF86Compress b/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaF86Compress deleted file mode 100755 index c712b131be..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/LzmaF86Compress +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash -# -# This script will exec LzmaCompress tool with --f86 option that enables converter for x86 code. -# -# Copyright (c) 2012, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# - -for arg; do - case $arg in - -e|-d) - set -- "$@" --f86 - break - ;; -esac - -exec LzmaCompress "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunBinToolFromBuildDir b/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunBinToolFromBuildDir deleted file mode 100755 index 4821d24fa7..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunBinToolFromBuildDir +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* -#exec `dirname $0`/../../../../C/bin/`basename $0` $* - -TOOL_BASENAME=`basename $0` - -if [ -n "$WORKSPACE" -a -e $WORKSPACE/Conf/BaseToolsCBinaries ] -then - exec $WORKSPACE/Conf/BaseToolsCBinaries/$TOOL_BASENAME -elif [ -n "$WORKSPACE" -a -e $EDK_TOOLS_PATH/Source/C ] -then - if [ ! -e $EDK_TOOLS_PATH/Source/C/bin/$TOOL_BASENAME ] - then - echo BaseTools C Tool binary was not found \($TOOL_BASENAME\) - echo You may need to run: - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec $EDK_TOOLS_PATH/Source/C/bin/$TOOL_BASENAME $* - fi -elif [ -e `dirname $0`/../../Source/C/bin/$TOOL_BASENAME ] -then - exec `dirname $0`/../../Source/C/bin/$TOOL_BASENAME $* -else - echo Unable to find the real \'$TOOL_BASENAME\' to run - echo This message was printed by - echo " $0" - exit -1 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunToolFromSource b/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunToolFromSource deleted file mode 100755 index 2cb8b86a99..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/RunToolFromSource +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* -PYTHONPATH="`dirname $0`/../../Source/Python" \ - python "`dirname $0`/../../Source/Python"/`basename $0`/`basename $0`.py $* - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Split b/BaseTools/Bin/CYGWIN_NT-5.1-i686/Split deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Split +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/TargetTool b/BaseTools/Bin/CYGWIN_NT-5.1-i686/TargetTool deleted file mode 100755 index 1ba451cf5e..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/TargetTool +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$cmd/$cmd.py" "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/TianoCompress b/BaseTools/Bin/CYGWIN_NT-5.1-i686/TianoCompress deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/TianoCompress +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Trim b/BaseTools/Bin/CYGWIN_NT-5.1-i686/Trim deleted file mode 100755 index b53b79bba4..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/Trim +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -exe=$(basename "$full_cmd") - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$exe/$exe.py" "$@" diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/VfrCompile b/BaseTools/Bin/CYGWIN_NT-5.1-i686/VfrCompile deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/VfrCompile +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/VolInfo b/BaseTools/Bin/CYGWIN_NT-5.1-i686/VolInfo deleted file mode 100755 index 0945d86d92..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/VolInfo +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -if [ -n "$WORKSPACE" ] && [ -e "$WORKSPACE/Conf/BaseToolsCBinaries" ] -then - exec "$WORKSPACE/Conf/BaseToolsCBinaries/$cmd" -elif [ -n "$WORKSPACE" ] && [ -e "$EDK_TOOLS_PATH/Source/C" ] -then - if [ ! -e "$EDK_TOOLS_PATH/Source/C/bin/$cmd" ] - then - echo "BaseTools C Tool binary was not found ($cmd)" - echo "You may need to run:" - echo " make -C $EDK_TOOLS_PATH/Source/C" - else - exec "$EDK_TOOLS_PATH/Source/C/bin/$cmd" "$@" - fi -elif [ -e "$dir/../../Source/C/bin/$cmd" ] -then - exec "$dir/../../Source/C/bin/$cmd" "$@" -else - echo "Unable to find the real '$cmd' to run" - echo "This message was printed by" - echo " $0" - exit 127 -fi - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/armcc_wrapper.py b/BaseTools/Bin/CYGWIN_NT-5.1-i686/armcc_wrapper.py deleted file mode 100755 index 3035732d5c..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/armcc_wrapper.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# - -# -# ARMCC tools do not support cygwin paths. Ths script converts cygwin paths to DOS paths -# in any arguments. -# -# armcc_wrapper.py ToolToExec [command line to convert] -# -# anything with the / will be converted via cygpath cygwin call or manually. -# -I/cygpath/c/example is a special case as you can not pass -I to cygpath -# -# ExceptionList if a tool takes an argument with a / add it to the exception list -# -from __future__ import print_function -import sys -import os -import subprocess -import pipes - -# -# Convert using cygpath command line tool -# Currently not used, but just in case we need it in the future -# -def ConvertCygPathToDosViacygpath(CygPath): - p = subprocess.Popen("cygpath -m " + pipes.quote(CygPath), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) - return p.stdout.read().strip() - -# -# -# -def ConvertCygPathToDos(CygPath): - if CygPath.find("/cygdrive/") == 0: - # convert /cygdrive/c/Xyz to c:/Xyz - DosPath = CygPath[10] + ':' + CygPath[11:] - else: - DosPath = CygPath - - # pipes.quote will add the extra \\ for us. - return DosPath.replace('/', '\\') - - -# we receive our options as a list, but we will be passing them to the shell as a line -# this means we have to requote things as they will get one round of unquoting. -# we can't set "shell=False" because we are running commands from the PATH and -# if you don't use the shell you don't get a PATH search. -def main(argv): - - # use 1st argument as name of tool to call - Command = pipes.quote(sys.argv[1]); - - ExceptionList = ["/interwork"] - - for arg in argv: - if arg.find('/') == -1: - # if we don't need to convert just add to the command line - Command = Command + ' ' + pipes.quote(arg) - elif arg in ExceptionList: - # if it is in the list, then don't do a cygpath - # assembler stuff after --apcs has the /. - Command = Command + ' ' + pipes.quote(arg) - else: - if ((arg[0] == '-') and (arg[1] == 'I' or arg[1] == 'i')): - CygPath = arg[0] + arg[1] + ConvertCygPathToDos(arg[2:]) - else: - CygPath = ConvertCygPathToDos(arg) - - Command = Command + ' ' + pipes.quote(CygPath) - - # call the real tool with the converted paths - return subprocess.call(Command, shell=True) - - -if __name__ == "__main__": - try: - ret = main(sys.argv[2:]) - - except: - print("exiting: exception from " + sys.argv[0]) - ret = 2 - - sys.exit(ret) - diff --git a/BaseTools/Bin/CYGWIN_NT-5.1-i686/build b/BaseTools/Bin/CYGWIN_NT-5.1-i686/build deleted file mode 100755 index 1ba451cf5e..0000000000 --- a/BaseTools/Bin/CYGWIN_NT-5.1-i686/build +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -#python `dirname $0`/RunToolFromSource.py `basename $0` $* - -# If a ${PYTHON_COMMAND} command is available, use it in preference to python -if command -v ${PYTHON_COMMAND} >/dev/null 2>&1; then - python_exe=${PYTHON_COMMAND} -fi - -full_cmd=${BASH_SOURCE:-$0} # see http://mywiki.wooledge.org/BashFAQ/028 for a discussion of why $0 is not a good choice here -dir=$(dirname "$full_cmd") -cmd=${full_cmd##*/} - -export PYTHONPATH="$dir/../../Source/Python" -exec "${python_exe:-python}" "$dir/../../Source/Python/$cmd/$cmd.py" "$@" diff --git a/BaseTools/Bin/Darwin-i386/Arm/DEBUG_XCODE31/CompilerIntrinsicsLib.lib b/BaseTools/Bin/Darwin-i386/Arm/DEBUG_XCODE31/CompilerIntrinsicsLib.lib deleted file mode 100644 index 79964fe1b65afe472af19fdb87c2733f5297d0a4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 36072 zcmeHw4SZZxnfJLflXjX++i6p2NF$x3DU{kalQguU6qu$1v``?lsTKv(Gzlb{CN&>? zXkBM*`4C&Iw6cJF3@&QdFRBa5Drlghfan%swYaR#q>Wn(YE|6V<#p}*|3A;U$t06$ zCn0Fw_xGM(&OHBn?m5pr_uTV5_kW*zb8qqT`i_R?^K$2umsNyA1F5{CvTAX8xT?G| z6gn$hffc&CJRDw9iLy%mNZOcNSGQ>0m6t{@xG=Qt^0l=WL=DnDeY77Pea0*mB(f>eSV(Zq3b2n;W*=XzCz4o4VL?b9`uYu zO9sjpV}F@49ry5(;g5U8S!ZJn)5csoP>b3(y-$_l_eXF1`Y$}>6ObKbFY*EYgmk%? zc$l;`$C%f!j&dT_GrLo#uCA-;hOU7|b#=8DY^WVrCR&2b_S|Mlin+M1uCZxT_qBD` zbkuKdLSbE9^j#~~Ug)kiRX}0nQlCs!(>$qP7iO*|S4T_RHSH`Js-qcY=c0BkbTDm! z4vqs-nvVKSn>w1VOV{yP)O-vLK4}|DYyC;r(NW)aZBu7jKd#0&gwSR+2N5ZLf_>Rs z-ypj)bYDJfk5h})p_=43tsku|Z5-0Heo#j)4v4E`FZz+IiqdtoH^`cy{kR2V`FX7A z^lQVE-!vUtx;M4q=ynd(u?TZ2gocIK{*W}Bj;RhW3MV zn~8I4NJ{I6J+x_KnvD)BD?t7ewnKaHVbEzy^v5;Gsfp{EN0Y*j&Yqw5a$eE%GtZyz zyj)V`NraZ=uP7`E78MueCd_>Q0bfyQ&g7z(BA+h2FA^%6w{qHw@DtjX<4BHiwoVC5 zHbp5Lrycva15*Oqy*GJoXW!1ovJQ~Xx#+U>p_QS^Md3x|p?NE|Y-w!@t!`^r6x!6? z(%Kk0tMcsdnZ_ww-`UjBS$0iJXLH&0?H%tgTU&o!Q`_ZRn%dU2cXu>2m96O5T=V{G z%ht4P>ZtFyv211g<}EF)O&zP-x;k3gI$Ih#v8HUr+Dpq^7pIexon!L&C$_e?T^o|0 zZZx>It*J58($;0Xt1qivQfWL@v|*1wXP}y_U60l9yq>dv%GJJ!gW7t0IjrRIOzdoK z@8}8*Ug^ovQmNwj`&TwJ*LN6?GeM-!H!-KX+xVS@8!>PbK46?hU&NLsbOV(M>TESm zSXOoem2c(vPTYcDX8(NrIOv%6o12=r14YdJ>vY%qx6ewGoPo2Zv)bW?m^fUX4;#mi zgO^)xoK^0M+|K5fYr0VIENam6=G9~M#S5{SdMpL#`%YtVr*ST0$3BJy^z%RQlMiK+ z&6K*jl^3pTZ|m%;Z|hpeqjv4e*80xQwN2MFbu_g#G#PHxaWKWEIdlE_d0ziCXSx%F zW>2Zf%R3JRI60kSy#8f*=j5%<$E?$GV{&FXUVmO5%N>+Yn4D5+qT{U2XQ{u~tj;gX zGiK5v=lpDar;#n`VYT)8^`{6J-3 zIgOP@VJAJ1CU^dEX#yI0%vXRM=fD1#%Y8-37|wljQY*T&v58g$`)loPgi)=%6vs~~ z(V_-=m70$BhNjNW_Kxb7w#G%xx<5IxS67)F55Y`GJ={4So*UkV9QHozlRL){o zK_-RlKkGTB)~y1F0!af0lpNtf49|eku)=&~c1bw|O+|ePZN&Nw8VJmriT)i+zCYrJ z@^@A~X5}MR(sH=|CM$J^jn8Y>|8HCV2PZ@om$nNzd}?D9V%#YJbX+!YBw!G2`ombAg4+_D5aql5Fe;FjXv8qh60 zLs5=@ZuyRlIOyb-3wV+eZn;npx#c2RNp4v-rrc5@C(f#VZpmXwZprf=x#dOd0h7xu zFM1XWtB{3TuI8!p16(g8^3PZbn8_z4k#bfY-z2ga`!qQV?#Kai(_a9_CwH_4fx~kG z?)V;XKlMS%9mxslk0{BqC_`5AoXcf$M{-6P2IY*TLN28{1vr&MQcY>fdNyZv>jO$+ zH|TP}7Najg$ zs=3Ra2LWTql3XsADc)FvTFa5Y3mrV(CyLQ!iZ|{+yJy(}d*0{y80wgG3IVwN$ixTN zqvn@U@7XuO2R#_$5OiE;x!f}YXwAR} zFTnubj(zz~c3f`Qc;m~^F&jEA#rB7!w0Oi6LioQv}U0r6CWg}WV$sA9hvxG zb~-w5+`Os1wXUNJU1@O*+7Gw>*rVQu zZ`tR$!@K*rnZ7%6?#M6l-E(E6CgQs%=hNQ%V}*CG@Z9tI%*91>i#A0XBGYGmafLbE z+-Z)r9c2xcP25)#xiZ3<$A*cA&P(YF{fu(f8QXJi^4;vc1u;=62u$P@eHuHVef+EQ zSL==&q_^xRQx^2~8&YjZX!I=#h9WR&Z>l-f&KIPI#;~u>yPQv8=q7+Vu5imIY_bcy zAvkeUOIK%IOIuwdBFK$(o6C)}k}dq5b!Zc18_)I4lRE3r=mIX)Bb(fV_{rnX1E`w~ z#oU8>ql{CYAo4h2aO82~K;#j7FtEUo+oY65oCI=DM_?2C;08Ja#n_o_2&Ov&P~FVM zPI=_KGOmJ?{WBKbI|09351z==p#zBl68<DF-CkG)J=PQ6Lwacg5W!f&+&$r9f zkc??YA@d>E*ku_l<)Pe!OAB>#bXgk9-0ep|ljM|s&8-9|iFQxlIl-*m?OV6oM@+pQ z^Wpxp7yGe5>eTM`t>5ii1RO!mGrGLnk3uXP?uWl1U-MAZ3*WA>)rHSXUI^Nc|H}FSuzkLw@#X|#Q!+&GgWAazZ(ePi+f0zHh zjzQGXF)ZeU@Wj!gWw z7&Y%l+fTg-{`(#12tmhU%Uw&+4?7-d{m8_Be_?B`dlUSZIwoPmu8sxhM=tt>l-7?- z{Pzfm6MfWGG>pM1O-H8t?UgtPyX$V>tdxj!gdh7-Sf7wETAm+V>xH=yB7& zN1vYg{LJP^eIzn#(k#!z=Gda6XBO2*Rz)I(`-b7OrEWt=`VHl?!R@}Al+D8b8nW5H zEtjQhRW8duGG*qnX?OOA(pNqQz#IL`4pPt9+}Kwx%g4sRWq%+&wD%iRxU5?)T$T&q zasym;SSrg}q%UB$=Z)9PI7*B(FL}(Y=$9R~jvYo^%)_pFFpbtkTdXLy~OGf-JD>DM?Q0a9LkQL&+&! zr!#Q%OwBx{I0nyEYT`!N&@t<62?(iMRO=RHpq8A?OzeTW8lKQO1=WDKuAf`d2Qsny zqv4k0kUMh!PsSZ(j55Yemk$4&X4P4IW|wJWu6;~(5OEytInBc|y2@R)T0B%NX8{fo zrOO+!C@Gt`soQ?gdBta9R)tIgPKM=B%IlseD*g#F54i@J>1{T1yR0*sG~28_glT%u z`H-Pd^&RCU@lTpie4EF_lO`BHblUNlb$ETG~k53DGwoPL>&*hDFr|$)h z*$#X=1s_PkycQ{Sbn+enj^a59F8xYyuAz6Bj!o+8Hb z8^Ke>@_s8gXhM+31W%Kj7rzsnZ{|VrIw|VRkZZv|2!5MzgVzP0B5|@m3Z5yv{J#Vj z$Z`H(z}#ORJMQ*WyYIZXaUX#`>BBPjv=}^=wydlC+>Y{d7FLv3F2%#_ODe0*>4!_tF??WdSy#om z9Tn$<&nd4!$#v~5jmx?gpDT}kTV=~GR0oCK?oYW$Beln+?qk!iM}1m+kU0)}ALFpy zB8Pix|JDbCFc(pQay0hnwm+FY^17W=Vg@R5j-}coVZZ+_5lV|&_B2oiq` zgv2PASWdn;4=aL@M<9ptMPBwWv+YzXAx4z;;r!(1xv3_ebRzL2Z06NH#w2pg#>76H zkGO5!6ha4k7I*1%2K%%X<=OyKFdS0S0pgoZrDv#6i((k2Q&r8bV z^t_}zE+Au}JWl_wLV4U26GA(e#}Ug|@CS+Katj%_P5Iw7M6P-DF)r*zC*>H}jk|+` zEN7&A4*wcy{{d3$W$0tdqvmt1JRmq2l%ug1w>|Bm6?){j4r4D}STP563P7}iz^Qz$ z80E|;mIvu6N1A9aPhK8Rip>NT{%Zfj@nrD8rM*7bPwu{W(q}>mU$8il8!AcUhUX;w zJv)1SrY4aSd=h1A6M5nN3DdK)?={%jLG#1@`fi=zfs1-g;E5x&y;bO332g6FNZ0oE z0>_YYQda0_O>yZ5n}jlPv0lOf&Fg!NoFPrvP*OIR_#7&%eX?m-PQ_9Vb49hCEh2 z2D%3M7z{~T8nNFgUupw8@H_JV#A9=w-oc*Xpiz#-@3`&hcly&XerE@^aV9F<0Kda| zm+E)sp`4j>hjm7ij=}E)c%GiT@K;^?9_S0LiYN18CXv_UN!;t7lGqanB>eD0i}vn7 zS#BaPF(pyb41W~a*%w%Kd*ZGMfyDd`@nmWLdS8O&yK%0c|IAGZU(J1ecQ~QMolnnA z_~P+o&c0Y8FGznDPZrQ8O@89YG5Dn8FktSR>yPdMj@cc0JO%$K1(O%J{z$Jm)gS3K zr}`u1$Lf!cpnlX*f290a{gGaCsy}*F>Zm_@O|beSjU}l+(pZxEBjq6KkCcO`KXPM9 zmC&IaME#NaP4!3WH`O1xu_XEW|cK zsy|Y{ss2d)rurjJq^MJ3wqU#JH|LlxVD+1&<_2K(n{y?;qJHyqIZo;~&oJ9jNB!nJ zb1N|YCXXrSJLl=ZH3n#f{(t|t@MP*5#>SJ0u9JE)3yJX5mZz1qCxhp=Cq3bY z#B8(f5Ux3H0}t{$HQRb;hZ`6_I~1G~Pllh4C#T?A#gA+L&rFRccl5-PQ$pL4PPjGU zgje?NpXwz3@wf40pl4&kiEQu9F}2B$hU3XUARaKqY)g_`852K58NfcezU*G$7&24# zF>m!{>ZjC~sh?6`rhZC&nffX9W$LHYm#LppU#5OaeVO_x^=0a()R(EBQeUQiN`0C7 zDdkq`r_`6JpHg3@eoB3r`YGjB>Zg=jsh=toZl!)|mT)WeQ$@n9)K9%#xRv^;(}Y{8 zpPDV)O8rzwxRv^;V&PWmr%HrRsh=tpU#5O)uJ|(bQ>TkBQ$KZv_%h{p^W-=wznd?< zO!?hA#4gD1cuYChAqM#}_YEcE!I`;!VNAT4RhFeY%k0mphQIH2c1k?bzS`xa{*2dY zOcXq}!=*3^>1!xmeg>B#DI0$lLQS@(KePV}GANFM_r;v>8E&?x57=vU^g!ZoM9*+9 zKz$$bBUZ;VR!6FDX8#J14`Ll-pAVs+065jJGM2-PVu|Mr^3flgx zGbooPpZ5~!|?jKlRB)LC<>os1J$^AdXd~lENRfB6O z-shVEWw5WS!F&4c>kGg!WTxklV+2S)M~)F7fw=VBm!8+vzVy7V_NC`_wJ$xdEC0~* zy7CV_ud99Od0p*G&+BSmwB_OKi~h2IOzeZe<1_H#&djl~9-ZccttaDkK_W=hq{+1###9+QWvrBT z!&qsm?Lhyyw;eYwN={5W;uv#G+-vJJJA!*2r*@=08=DBCeFxy1v!lxLf%mD<%B6#q z1C(^M=bw2bpEyXAqp>5mJ?&_o&l0L(>}VC%y@)ysK=@w5_EPQW0Lqy;S6)D-u92qx zcp>gl%z!Ng%+4d>jra9=Lw6(%;(HG6RXoOL9(%6nMHg@yTF1x9A>VljyPoSo?C;k+ zU*VZCuete%3EtP2i&)@vd8F%|hfto6@`BHE8S8jGzXa`lA>y@%Ft{FX*RA&)>g7gIuLjru=+AGCA3y4Zt9!j>dUBH8 zmWjltd20eetS>O(O}*Z*Cy|eM0%Hfuz47E>w3&_=Ly?U!oQ8d_MvP&0sG-+MZ0ns? zftW#fXJ7ew*p9icZ~1%U$)f6Qh%@Z$y9j;rg}HC*4u!EjC%gjNp2qQz{WM{3&>M0^&O1=F!@ewgE0`d zf3qVEy}?pEGZaiDpDgnviqS`ZXlI`j+Sa@OeB5_(yoqJ#b5Z5CJ`(in`FXqQs;MD@XCb+-%$ud4Gb>9(B7~Ajh;F%6@!h}2t zPoy^Ct$8}(#BamAeK(J3p`07cu7neOFv0!@;xU=uoCmO>qnKZZIKMc58PlF&@3AqS zO*{KB&Lw*xVQW|KvCB~_=R(qVGr?X=i~#9p$T0$>*N|fbNaSSh^^e9Xl%M&b!@cjV zu?pp9dM`@(ncj<1ex}z>%Fp!LN%@&xJ1IZYYbT8l>9v!_hxFP><3oDwr12rWcGCC| zubtd`Z*LQ<@u5=$YkX*?V2uxPAft}PhfWo&v2Ol9n|tqVmSBw!6$#e((Ax!Te2D*i z7j;5rBgSdA;9`jng#?#Ke5hFP9ElH=2%anPp*ez2m-rAlO4K<+;zM%<&y)Dj>4MLc z<8g*yjSrFUM;(n1ohf*M#JcATUTAiqKkpE{$Z!sj=R}<{a~JSJ!C}Mr;3C20CJtOC zc(Hj1I4ro*a2}NlUShrkTp_qh-W$AF@Y&`OlvfH~CUfd6!OP{nze@z4YkE*;so?X> zcY&(}pKqQ4K3i}^t`U|AULog;a|BnLmr#e#8AqL!@=V6Lf}?Ve_&mWEzzG<0zTgYZ zVc>}1RdRi?Lhx#t*VTeAmS?zD3cf_H_oIT>$UWi<1Yc@+9dV)H%jD#Bk>DDM{j3sv zh1?rkEqJZOl`j^&PVUuTBDmIYZmto$UScGd3VxU2oVrZ#2D!GoT=12`S8D{nTb`G> zLhyU!7_Jq3l^maSg0GgbuNC}W8Q1lK>txK{DR`rd$GZgAV;u3n_kuSW?#Gpa8>El# z7TjpK{r3oNGSq#Q;A^Gb)q5L$R@#C%vQ*21b@K9Ag>kNX|_XBZ`A3MSXqnUZh8IX`vhNSc0s;h z@bzX7WUJsC%w3S11>b1yg=`c2K@*2;7yKdf5abrYTP2S60l^9`GjxKVTLB-yt||!oa%) zKWHj}d5ojZXG|6FrvyJ_mIL1@__HPg{11XZC;zL!c@TB>npG&jTkt=bHNf`>{(`9i z{U`VW1^i{f-!bh<}u($1%KZ>4*Ye&&zK(IZwP+Yd>8mJ!Oxjzfd57C56ttx z-xU13IRN}E!9O%F0Y5JIN9G{#6N3NMyaN1f!3RtN_&b7MFo%I@Z&Bw(a|HNF!7rKD zfS(flZ{`^Ae!)L6uLIL2qs~vwpMakhe9-(E_J813xSH z6%zn{PVmo75cmgze_>_-)3&2dQl8`bq2OLqgz_H=K4e0`|0?*fDFvqeN1Z;oZhHZ^ z5t-Lw5dGKNAnLLVA+c?)lVoF9dJUNxCAKTZ%d>(h7rJ8>(bAnBd@=5h%m2l4q;a{5 zCGJ0#ZOqkg5e&o7`p@*4qAEs>L*{!I@_p`#ZQd7)baNi}6 z>3sxjkLy*#cZX3&GcK0xyzf`(>d5py0`gw^pIf1WiSPfnFil6M_Yu^h=51&jnII}s zf6{eict7jUQ8R>=&siP2POvYT-be5kyS1ZP^dr;zS*ha+jEAd(?@7b;G*jBXWO^UL zlC6Q;yd8ZXQ%+8;?4?k#w? z-0+~CwW~zxANC~4Ho|=-tWF9U{W!9nw!OI0^Fm? z-MbV$9*3_9=%0P)-Uwb3FdhH)k0FuQ1_UAb8h}$E`OZ}Ol4+3SgLWdxGzt0CDQQ4i674P*(HWmNTb1MEV|>jt<8=Y^uR6f<-!1^b3lig^OB z;MSQDQRar20c#;P2waC>Ndf#$LB_lJxu+!xDM|&d*yWU&cq!X+Lh(Krr_Dxi2dhhG5z1U0nRqGZ1ScEc*TqC`Yhjv> zOuRILnzy0t0-EIDl&&KKFMSR*LumVTtK-%a>`NwIdem<1Ct36(6ECHXa*T(ogZ!BH z{=cZzsZmp#HwgGC1;-VS|m~6DY?Y|<3eZ7$H7JO!9{~<-xuKixQVu^ zJk-CPU#|LFa!_@F%0byLrg6_f^^1ln9F#pD0SDcK>irz_b?);2gB;X7n%upG@Id2{ zgSxX1-OG}Ll8}*elCO{>7TM*Hl_ijTr4<<->xCg%uL6?XwbHJ4IcK%4_io5itd~(! zj!8F^!ZGQ7*s5%b`;V=1Gu#IBb2G~nQY;s^j{6@`h+j!;%He^2 z3icr7vsAP z4d3L!elvWt6zw@{gV??Y@(9cWR?NgjNhjl*wW#Hwb_6<@_|8fT({yCwoBS@p(`dUQ z3!Yb>fo~RK97E7CfrE$?1i#6&FPZq}GU#AB-RjUK`AyrGOnj3%0@$#tqX7M|v@u;r zdxIz+`t8sQF@PJfrouLqO8S$gBNN~J9CU=x=8o)i49hpa2OabxU&}&ACceqJ&GgGG zbY$Y2+34WF(2Z`e$Gs8qt>ByCM`sk>UG0An`Cv)Wu4?a#$Oj!fg@xfxctR)p=4lD~ zI5d9wKbS9iVE^jzOV^$0L}cffJd8u|)22%wz>+uf7f^?O^i&$kM^6v3;m~lVz8lp$ z>_<<%sUJP{4*lqgU+sIc7q0%eBqMd$BJ1aINNDvl+Gg z^{uVOd(kIR3t#VK-EMiwf2Z-Tp_W{{Y1RFvwzJYV7qKvKvF4QjDFPnneuNolvMQPdRx^574;! zPQZW#;9v|xVAr%>w;7*?=&EaN*@VxUq7vR3E7tl>NCJL3fL@ND44{`Ib*1Z}B*UZ( zL6XACfG9O3|8w8+?{ZCdnJkk{++{#X+#EOIegz-|OqK33pd=Dj)kq8w+_o0a`EP@eoX)PTpcIMz6@@-NGegN|Z74rx%WtwWXl0IF&;OrcJ^ueKCI8Qt zvd_x@u=3xm{GpYoGbmo@+UZF7+tP4Y=^Ng6)p>nOS3`5vN%`AhY@3OF*eWRfhvUHt zlrDc`eWq;qo7-NGgth~DidiH_h;<5}bTTAk496f-Vi-eb=6&~|i9g(R%Xppl zuj7!vHS>O5(i{Hy(m?pzG?yA(OpZWgK*~9-| z{?f(v_E5jSFJF@C@JBoELpUaMLX@NN_iV@ZC-e6q)Zsmfmmr7Ed$I;*ta9&T0F5kt zwdcJ_`umuzUnNy>ZYnsIhs7@b|? zXkBM*`4C&Iw6cJF3@&QdFRBa5Drlghfan%swYaR#q>Wn(YE|6V<#p}*|3A;U$t06$ zCn0Fw_xGM(&OHBn?m5pr_uTV5_kW*zb8qqT`i_R?^K$2umsNyA1F5{CvTAX8xT?G| z6gn$hffc&CJRDw9iLy%mNZOcNSGQ>0m6t{@xG=Qt^0l=WL=DnDeY77Pea0*mB(f>eSV(Zq3b2n;W*=XzCz4o4VL?b9`uYu zO9sjpV}F@49ry5(;g5U8S!ZJn)5csoP>b3(y-$_l_eXF1`Y$}>6ObKbFY*EYgmk%? zc$l;`$C%f!j&dT_GrLo#uCA-;hOU7|b#=8DY^WVrCR&2b_S|Mlin+M1uCZxT_qBD` zbkuKdLSbE9^j#~~Ug)kiRX}0nQlCs!(>$qP7iO*|S4T_RHSH`Js-qcY=c0BkbTDm! z4vqs-nvVKSn>w1VOV{yP)O-vLK4}|DYyC;r(NW)aZBu7jKd#0&gwSR+2N5ZLf_>Rs z-ypj)bYDJfk5h})p_=43tsku|Z5-0Heo#j)4v4E`FZz+IiqdtoH^`cy{kR2V`FX7A z^lQVE-!vUtx;M4q=ynd(u?TZ2gocIK{*W}Bj;RhW3MV zn~8I4NJ{I6J+x_KnvD)BD?t7ewnKaHVbEzy^v5;Gsfp{EN0Y*j&Yqw5a$eE%GtZyz zyj)V`NraZ=uP7`E78MueCd_>Q0bfyQ&g7z(BA+h2FA^%6w{qHw@DtjX<4BHiwoVC5 zHbp5Lrycva15*Oqy*GJoXW!1ovJQ~Xx#+U>p_QS^Md3x|p?NE|Y-w!@t!`^r6x!6? z(%Kk0tMcsdnZ_ww-`UjBS$0iJXLH&0?H%tgTU&o!Q`_ZRn%dU2cXu>2m96O5T=V{G z%ht4P>ZtFyv211g<}EF)O&zP-x;k3gI$Ih#v8HUr+Dpq^7pIexon!L&C$_e?T^o|0 zZZx>It*J58($;0Xt1qivQfWL@v|*1wXP}y_U60l9yq>dv%GJJ!gW7t0IjrRIOzdoK z@8}8*Ug^ovQmNwj`&TwJ*LN6?GeM-!H!-KX+xVS@8!>PbK46?hU&NLsbOV(M>TESm zSXOoem2c(vPTYcDX8(NrIOv%6o12=r14YdJ>vY%qx6ewGoPo2Zv)bW?m^fUX4;#mi zgO^)xoK^0M+|K5fYr0VIENam6=G9~M#S5{SdMpL#`%YtVr*ST0$3BJy^z%RQlMiK+ z&6K*jl^3pTZ|m%;Z|hpeqjv4e*80xQwN2MFbu_g#G#PHxaWKWEIdlE_d0ziCXSx%F zW>2Zf%R3JRI60kSy#8f*=j5%<$E?$GV{&FXUVmO5%N>+Yn4D5+qT{U2XQ{u~tj;gX zGiK5v=lpDar;#n`VYT)8^`{6J-3 zIgOP@VJAJ1CU^dEX#yI0%vXRM=fD1#%Y8-37|wljQY*T&v58g$`)loPgi)=%6vs~~ z(V_-=m70$BhNjNW_Kxb7w#G%xx<5IxS67)F55Y`GJ={4So*UkV9QHozlRL){o zK_-RlKkGTB)~y1F0!af0lpNtf49|eku)=&~c1bw|O+|ePZN&Nw8VJmriT)i+zCYrJ z@^@A~X5}MR(sH=|CM$J^jn8Y>|8HCV2PZ@om$nNzd}?D9V%#YJbX+!YBw!G2`ombAg4+_D5aql5Fe;FjXv8qh60 zLs5=@ZuyRlIOyb-3wV+eZn;npx#c2RNp4v-rrc5@C(f#VZpmXwZprf=x#dOd0h7xu zFM1XWtB{3TuI8!p16(g8^3PZbn8_z4k#bfY-z2ga`!qQV?#Kai(_a9_CwH_4fx~kG z?)V;XKlMS%9mxslk0{BqC_`5AoXcf$M{-6P2IY*TLN28{1vr&MQcY>fdNyZv>jO$+ zH|TP}7Najg$ zs=3Ra2LWTql3XsADc)FvTFa5Y3mrV(CyLQ!iZ|{+yJy(}d*0{y80wgG3IVwN$ixTN zqvn@U@7XuO2R#_$5OiE;x!f}YXwAR} zFTnubj(zz~c3f`Qc;m~^F&jEA#rB7!w0Oi6LioQv}U0r6CWg}WV$sA9hvxG zb~-w5+`Os1wXUNJU1@O*+7Gw>*rVQu zZ`tR$!@K*rnZ7%6?#M6l-E(E6CgQs%=hNQ%V}*CG@Z9tI%*91>i#A0XBGYGmafLbE z+-Z)r9c2xcP25)#xiZ3<$A*cA&P(YF{fu(f8QXJi^4;vc1u;=62u$P@eHuHVef+EQ zSL==&q_^xRQx^2~8&YjZX!I=#h9WR&Z>l-f&KIPI#;~u>yPQv8=q7+Vu5imIY_bcy zAvkeUOIK%IOIuwdBFK$(o6C)}k}dq5b!Zc18_)I4lRE3r=mIX)Bb(fV_{rnX1E`w~ z#oU8>ql{CYAo4h2aO82~K;#j7FtEUo+oY65oCI=DM_?2C;08Ja#n_o_2&Ov&P~FVM zPI=_KGOmJ?{WBKbI|09351z==p#zBl68<DF-CkG)J=PQ6Lwacg5W!f&+&$r9f zkc??YA@d>E*ku_l<)Pe!OAB>#bXgk9-0ep|ljM|s&8-9|iFQxlIl-*m?OV6oM@+pQ z^Wpxp7yGe5>eTM`t>5ii1RO!mGrGLnk3uXP?uWl1U-MAZ3*WA>)rHSXUI^Nc|H}FSuzkLw@#X|#Q!+&GgWAazZ(ePi+f0zHh zjzQGXF)ZeU@Wj!gWw z7&Y%l+fTg-{`(#12tmhU%Uw&+4?7-d{m8_Be_?B`dlUSZIwoPmu8sxhM=tt>l-7?- z{Pzfm6MfWGG>pM1O-H8t?UgtPyX$V>tdxj!gdh7-Sf7wETAm+V>xH=yB7& zN1vYg{LJP^eIzn#(k#!z=Gda6XBO2*Rz)I(`-b7OrEWt=`VHl?!R@}Al+D8b8nW5H zEtjQhRW8duGG*qnX?OOA(pNqQz#IL`4pPt9+}Kwx%g4sRWq%+&wD%iRxU5?)T$T&q zasym;SSrg}q%UB$=Z)9PI7*B(FL}(Y=$9R~jvYo^%)_pFFpbtkTdXLy~OGf-JD>DM?Q0a9LkQL&+&! zr!#Q%OwBx{I0nyEYT`!N&@t<62?(iMRO=RHpq8A?OzeTW8lKQO1=WDKuAf`d2Qsny zqv4k0kUMh!PsSZ(j55Yemk$4&X4P4IW|wJWu6;~(5OEytInBc|y2@R)T0B%NX8{fo zrOO+!C@Gt`soQ?gdBta9R)tIgPKM=B%IlseD*g#F54i@J>1{T1yR0*sG~28_glT%u z`H-Pd^&RCU@lTpie4EF_lO`BHblUNlb$ETG~k53DGwoPL>&*hDFr|$)h z*$#X=1s_PkycQ{Sbn+enj^a59F8xYyuAz6Bj!o+8Hb z8^Ke>@_s8gXhM+31W%Kj7rzsnZ{|VrIw|VRkZZv|2!5MzgVzP0B5|@m3Z5yv{J#Vj z$Z`H(z}#ORJMQ*WyYIZXaUX#`>BBPjv=}^=wydlC+>Y{d7FLv3F2%#_ODe0*>4!_tF??WdSy#om z9Tn$<&nd4!$#v~5jmx?gpDT}kTV=~GR0oCK?oYW$Beln+?qk!iM}1m+kU0)}ALFpy zB8Pix|JDbCFc(pQay0hnwm+FY^17W=Vg@R5j-}coVZZ+_5lV|&_B2oiq` zgv2PASWdn;4=aL@M<9ptMPBwWv+YzXAx4z;;r!(1xv3_ebRzL2Z06NH#w2pg#>76H zkGO5!6ha4k7I*1%2K%%X<=OyKFdS0S0pgoZrDv#6i((k2Q&r8bV z^t_}zE+Au}JWl_wLV4U26GA(e#}Ug|@CS+Katj%_P5Iw7M6P-DF)r*zC*>H}jk|+` zEN7&A4*wcy{{d3$W$0tdqvmt1JRmq2l%ug1w>|Bm6?){j4r4D}STP563P7}iz^Qz$ z80E|;mIvu6N1A9aPhK8Rip>NT{%Zfj@nrD8rM*7bPwu{W(q}>mU$8il8!AcUhUX;w zJv)1SrY4aSd=h1A6M5nN3DdK)?={%jLG#1@`fi=zfs1-g;E5x&y;bO332g6FNZ0oE z0>_YYQda0_O>yZ5n}jlPv0lOf&Fg!NoFPrvP*OIR_#7&%eX?m-PQ_9Vb49hCEh2 z2D%3M7z{~T8nNFgUupw8@H_JV#A9=w-oc*Xpiz#-@3`&hcly&XerE@^aV9F<0Kda| zm+E)sp`4j>hjm7ij=}E)c%GiT@K;^?9_S0LiYN18CXv_UN!;t7lGqanB>eD0i}vn7 zS#BaPF(pyb41W~a*%w%Kd*ZGMfyDd`@nmWLdS8O&yK%0c|IAGZU(J1ecQ~QMolnnA z_~P+o&c0Y8FGznDPZrQ8O@89YG5Dn8FktSR>yPdMj@cc0JO%$K1(O%J{z$Jm)gS3K zr}`u1$Lf!cpnlX*f290a{gGaCsy}*F>Zm_@O|beSjU}l+(pZxEBjq6KkCcO`KXPM9 zmC&IaME#NaP4!3WH`O1xu_XEW|cK zsy|Y{ss2d)rurjJq^MJ3wqU#JH|LlxVD+1&<_2K(n{y?;qJHyqIZo;~&oJ9jNB!nJ zb1N|YCXXrSJLl=ZH3n#f{(t|t@MP*5#>SJ0u9JE)3yJX5mZz1qCxhp=Cq3bY z#B8(f5Ux3H0}t{$HQRb;hZ`6_I~1G~Pllh4C#T?A#gA+L&rFRccl5-PQ$pL4PPjGU zgje?NpXwz3@wf40pl4&kiEQu9F}2B$hU3XUARaKqY)g_`852K58NfcezU*G$7&24# zF>m!{>ZjC~sh?6`rhZC&nffX9W$LHYm#LppU#5OaeVO_x^=0a()R(EBQeUQiN`0C7 zDdkq`r_`6JpHg3@eoB3r`YGjB>Zg=jsh=toZl!)|mT)WeQ$@n9)K9%#xRv^;(}Y{8 zpPDV)O8rzwxRv^;V&PWmr%HrRsh=tpU#5O)uJ|(bQ>TkBQ$KZv_%h{p^W-=wznd?< zO!?hA#4gD1cuYChAqM#}_YEcE!I`;!VNAT4RhFeY%k0mphQIH2c1k?bzS`xa{*2dY zOcXq}!=*3^>1!xmeg>B#DI0$lLQS@(KePV}GANFM_r;v>8E&?x57=vU^g!ZoM9*+9 zKz$$bBUZ;VR!6FDX8#J14`Ll-pAVs+065jJGM2-PVu|Mr^3flgx zGbooPpZ5~!|?jKlRB)LC<>os1J$^AdXd~lENRfB6O z-shVEWw5WS!F&4c>kGg!WTxklV+2S)M~)F7fw=VBm!8+vzVy7V_NC`_wJ$xdEC0~* zy7CV_ud99Od0p*G&+BSmwB_OKi~h2IOzeZe<1_H#&djl~9-ZccttaDkK_W=hq{+1###9+QWvrBT z!&qsm?Lhyyw;eYwN={5W;uv#G+-vJJJA!*2r*@=08=DBCeFxy1v!lxLf%mD<%B6#q z1C(^M=bw2bpEyXAqp>5mJ?&_o&l0L(>}VC%y@)ysK=@w5_EPQW0Lqy;S6)D-u92qx zcp>gl%z!Ng%+4d>jra9=Lw6(%;(HG6RXoOL9(%6nMHg@yTF1x9A>VljyPoSo?C;k+ zU*VZCuete%3EtP2i&)@vd8F%|hfto6@`BHE8S8jGzXa`lA>y@%Ft{FX*RA&)>g7gIuLjru=+AGCA3y4Zt9!j>dUBH8 zmWjltd20eetS>O(O}*Z*Cy|eM0%Hfuz47E>w3&_=Ly?U!oQ8d_MvP&0sG-+MZ0ns? zftW#fXJ7ew*p9icZ~1%U$)f6Qh%@Z$y9j;rg}HC*4u!EjC%gjNp2qQz{WM{3&>M0^&O1=F!@ewgE0`d zf3qVEy}?pEGZaiDpDgnviqS`ZXlI`j+Sa@OeB5_(yoqJ#b5Z5CJ`(in`FXqQs;MD@XCb+-%$ud4Gb>9(B7~Ajh;F%6@!h}2t zPoy^Ct$8}(#BamAeK(J3p`07cu7neOFv0!@;xU=uoCmO>qnKZZIKMc58PlF&@3AqS zO*{KB&Lw*xVQW|KvCB~_=R(qVGr?X=i~#9p$T0$>*N|fbNaSSh^^e9Xl%M&b!@cjV zu?pp9dM`@(ncj<1ex}z>%Fp!LN%@&xJ1IZYYbT8l>9v!_hxFP><3oDwr12rWcGCC| zubtd`Z*LQ<@u5=$YkX*?V2uxPAft}PhfWo&v2Ol9n|tqVmSBw!6$#e((Ax!Te2D*i z7j;5rBgSdA;9`jng#?#Ke5hFP9ElH=2%anPp*ez2m-rAlO4K<+;zM%<&y)Dj>4MLc z<8g*yjSrFUM;(n1ohf*M#JcATUTAiqKkpE{$Z!sj=R}<{a~JSJ!C}Mr;3C20CJtOC zc(Hj1I4ro*a2}NlUShrkTp_qh-W$AF@Y&`OlvfH~CUfd6!OP{nze@z4YkE*;so?X> zcY&(}pKqQ4K3i}^t`U|AULog;a|BnLmr#e#8AqL!@=V6Lf}?Ve_&mWEzzG<0zTgYZ zVc>}1RdRi?Lhx#t*VTeAmS?zD3cf_H_oIT>$UWi<1Yc@+9dV)H%jD#Bk>DDM{j3sv zh1?rkEqJZOl`j^&PVUuTBDmIYZmto$UScGd3VxU2oVrZ#2D!GoT=12`S8D{nTb`G> zLhyU!7_Jq3l^maSg0GgbuNC}W8Q1lK>txK{DR`rd$GZgAV;u3n_kuSW?#Gpa8>El# z7TjpK{r3oNGSq#Q;A^Gb)q5L$R@#C%vQ*21b@K9Ag>kNX|_XBZ`A3MSXqnUZh8IX`vhNSc0s;h z@bzX7WUJsC%w3S11>b1yg=`c2K@*2;7yKdf5abrYTP2S60l^9`GjxKVTLB-yt||!oa%) zKWHj}d5ojZXG|6FrvyJ_mIL1@__HPg{11XZC;zL!c@TB>npG&jTkt=bHNf`>{(`9i z{U`VW1^i{f-!bh<}u($1%KZ>4*Ye&&zK(IZwP+Yd>8mJ!Oxjzfd57C56ttx z-xU13IRN}E!9O%F0Y5JIN9G{#6N3NMyaN1f!3RtN_&b7MFo%I@Z&Bw(a|HNF!7rKD zfS(flZ{`^Ae!)L6uLIL2qs~vwpMakhe9-(E_J813xSH z6%zn{PVmo75cmgze_>_-)3&2dQl8`bq2OLqgz_H=K4e0`|0?*fDFvqeN1Z;oZhHZ^ z5t-Lw5dGKNAnLLVA+c?)lVoF9dJUNxCAKTZ%d>(h7rJ8>(bAnBd@=5h%m2l4q;a{5 zCGJ0#ZOqkg5e&o7`p@*4qAEs>L*{!I@_p`#ZQd7)baNi}6 z>3sxjkLy*#cZX3&GcK0xyzf`(>d5py0`gw^pIf1WiSPfnFil6M_Yu^h=51&jnII}s zf6{eict7jUQ8R>=&siP2POvYT-be5kyS1ZP^dr;zS*ha+jEAd(?@7b;G*jBXWO^UL zlC6Q;yd8ZXQ%+8;?4?k#w? z-0+~CwW~zxANC~4Ho|=-tWF9U{W!9nw!OI0^Fm? z-MbV$9*3_9=%0P)-Uwb3FdhH)k0FuQ1_UAb8h}$E`OZ}Ol4+3SgLWdxGzt0CDQQ4i674P*(HWmNTb1MEV|>jt<8=Y^uR6f<-!1^b3lig^OB z;MSQDQRar20c#;P2waC>Ndf#$LB_lJxu+!xDM|&d*yWU&cq!X+Lh(Krr_Dxi2dhhG5z1U0nRqGZ1ScEc*TqC`Yhjv> zOuRILnzy0t0-EIDl&&KKFMSR*LumVTtK-%a>`NwIdem<1Ct36(6ECHXa*T(ogZ!BH z{=cZzsZmp#HwgGC1;-VS|m~6DY?Y|<3eZ7$H7JO!9{~<-xuKixQVu^ zJk-CPU#|LFa!_@F%0byLrg6_f^^1ln9F#pD0SDcK>irz_b?);2gB;X7n%upG@Id2{ zgSxX1-OG}Ll8}*elCO{>7TM*Hl_ijTr4<<->xCg%uL6?XwbHJ4IcK%4_io5itd~(! zj!8F^!ZGQ7*s5%b`;V=1Gu#IBb2G~nQY;s^j{6@`h+j!;%He^2 z3icr7vsAP z4d3L!elvWt6zw@{gV??Y@(9cWR?NgjNhjl*wW#Hwb_6<@_|8fT({yCwoBS@p(`dUQ z3!Yb>fo~RK97E7CfrE$?1i#6&FPZq}GU#AB-RjUK`AyrGOnj3%0@$#tqX7M|v@u;r zdxIz+`t8sQF@PJfrouLqO8S$gBNN~J9CU=x=8o)i49hpa2OabxU&}&ACceqJ&GgGG zbY$Y2+34WF(2Z`e$Gs8qt>ByCM`sk>UG0An`Cv)Wu4?a#$Oj!fg@xfxctR)p=4lD~ zI5d9wKbS9iVE^jzOV^$0L}cffJd8u|)22%wz>+uf7f^?O^i&$kM^6v3;m~lVz8lp$ z>_<<%sUJP{4*lqgU+sIc7q0%eBqMd$BJ1aINNDvl+Gg z^{uVOd(kIR3t#VK-EMiwf2Z-Tp_W{{Y1RFvwzJYV7qKvKvF4QjDFPnneuNolvMQPdRx^574;! zPQZW#;9v|xVAr%>w;7*?=&EaN*@VxUq7vR3E7tl>NCJL3fL@ND44{`Ib*1Z}B*UZ( zL6XACfG9O3|8w8+?{ZCdnJkk{++{#X+#EOIegz-|OqK33pd=Dj)kq8w+_o0a`EP@eoX)PTpcIMz6@@-NGegN|Z74rx%WtwWXl0IF&;OrcJ^ueKCI8Qt zvd_x@u=3xm{GpYoGbmo@+UZF7+tP4Y=^Ng6)p>nOS3`5vN%`AhY@3OF*eWRfhvUHt zlrDc`eWq;qo7-NGgth~DidiH_h;<5}bTTAk496f-Vi-eb=6&~|i9g(R%Xppl zuj7!vHS>O5(i{Hy(m?pzG?yA(OpZWgK*~9-| z{?f(v_E5jSFJF@C@JBoELpUaMLX@NN_iV@ZC-e6q)Zsmfmmr7Ed$I;*ta9&T0F5kt zwdcJ_`umuzUnNy>ZYnsIhs7@b|{u@g0^oQH_h zl8PT&3>48gq)CJzU>Im6BJ~HRY9xL%(i$sjiU66ykEEh>W}THxD6LUjsYO-Y@0*8r z9d_6DVpo;gqn$Z-?mhR;z2`gU-gECx_4=I;b?>=7Qd_^KLDw==-_X?3Sg*G&_jo6j+k&EV~eM7D#EEf#qneB?%vKY(}MB=Rfp3pa@T z8oYg_$m`%OD@2ZfcU&*>H29z@(hY7c5qS(;mWk{K8^Oz)!7HL7Uk4vtfOmq&pply;^2pN_p;``1G_vSq`Zpz4*QKAMr&U2 z;fy46JyGWRN#r_DO>DQj=Ld)OHaMwXKXtf!-@#pO=ArNJ?d{&v!g4oxI4fPhHk04j zfWdZrmH2*G}T@De9I3UEg&Z!~NaQKm8X}D%apra1s8?xCkyuvWexq ziXr`M)vD4^@F)u;hWTUXv%sm9c5HDbxC@JLA2Y8R*<7|&M@7@E3rV_BWv$Z8~Qo+=PGO*M~;AIi_hAImP!9{-F*r?IsK=H z9nf68gqY4joydCP0Aul;B+a3Xl}t)-z8B`3<&(CO_)hY>nm@_g{cMCEg> zfzy9o+NiEjyNqsQ@v@({$_?_2j7P^P!Mtk+JB;lHCCB04l6)yG<1eH+MiS>MymvP} z9^-Jdgy$&7>0iFh)j4^t1~^V%7f@i_TQYVX>DlE#6Ytu)f7jmq--++p-E(j^bsXoi z;w>Nr=6jfBu64e-#g7U)BWMSU*4)^uj&ac5$cwSpI0Q1Hh z7#~!XH{Mu}G76CU_D6ZrOy*0!K5b``LXz;)%xAo@9*wfycHC%hg>Xmltf@-2j3U-L zy#ZX)+D_Ehm_HHC>4xh=0?L)V9L3!U3TAG5GVQy1+wRfOqZvR3;p`j;iRKcwoAO`1E+*>^T(1jN9ACD zN-WdHTyRCv-@B|NkESN{U`o;7y&RAo_CF>jDieuwW9&-?8*hJsyu9&7KL44D3w9@S zgNrkdpp)dq_>W(II$T!c9n?h&ZvP2f(4Q+4x{@L;J|>^%!-RW1P*MJpHLtllz`4Oi zV~3zC@?vmdJ=P~K8aRGjB$)2d@eMvIc-2@HZ%x-3DZ|POj|Kb8yI|Y zO2jIWPHPbU!SxI6KESqpKe;+Ka`oy(NzMv1d;iHk=Wv3k8N@#`nb&%#40N8n7@Yk2 z#Dn_->LC|Sy(pl}QE(M}K5!bk+q505qBnm${F-UUM(#?5fLmnHv_qmzVT_tdMEiC4&j8G)8+e?F!n&f^%czu!)HYcbxtl zKyUZX*$U6gx8>gNG&N?s)Iuwxqz*a5xUs*`o`4oBE|aYpG`ZO?6ef)u~dm{vmez>`!8637fPSaIRGchqvROg ztKtFZWlB8YpRcT@oDP+>FydYvG8{C3% zU>^Hxyp{j0kUAsY`Tw-`HWa~hdTBZohB~^FTXx< zsY5%?_;bVst5HCiP2ls17h^!idW`Le7h}6wVdm=AhtGN9Iqz)e_xk$VyanC$FSntL zixrF4N>1j`A$c))`Spp#$`D-(lmoAJ6!29&;48rk#c^zFwlo>XA$DH^%%ajirgsjc zgW3sO5O*nv;ora-FUfmS3q`QpZym*)3V!b>`V|QvCi|5Bh_j}kJTWG*fpi2h8vd@m zLK)BI3)v1-Xa;xemk|=+B=fCUDNumI}&Z`#SGkVwh#Yj%WPwY1AV$&q)AhIGJu;A9|Db8BZGDJq`qOuy zZy}vy+d7K1zf#d#@$NF}!x^XO!B|i;%S1QJqje(qp|)p{3(6We8;{Q?_kX3_pi$6PQ~hQrWCX6p)~=k8hs3F{b@z(OAT+peoP5k z>(FPlsm~tT5VV4lu-BvSz&gEdp=rMv4_a0Fen(bSP}UH%-drS>7=3m*-c_FcE{qFy zcG|%<`b0%N%Bx~{zXDsqdqp#WsoO65P^E25u`Rw&ZB01u;yfNT5yzu$6!?Z=3qM0Y zAMfb1Uj}~+?|lXQhlu$ejU7cl2gcZD2>Znn>=(n(g(6#05*tnpt>IbPz*s=X`;!5j z*#s@o0#?A-W(7OWTZ;JSr)hHH^q8?G6tyj(G4jMp+RyPnBX}4|L%yn_svF8xHkIB z7vjTi=ZlZI!F2~Uh>nsMgR5VkW6h$3pZ0Ox0RhVF!EHWpjh*fLh1>*GtAR`P1!LHG za?uQ^zcYSQv8c9^SZXNO-ZX->(F#5X9BgCiMI%_FsAYy#5vaK{{M$;U_Q$}o99YJ_ z@V~#S|Kj|!u_^OEs`tIl6d?1)A)2edeEwNOg+sUG#o*}ICq`M6@Y6nyeoV>#N#+Ab z{p=F;xwi28xGvVH$J>JM(}Ka9=wgIJ};G5b{u@g0^oQH_h zl8PT&3>48gq)CJzU>Im6BJ~HRY9xL%(i$sjiU66ykEEh>W}THxD6LUjsYO-Y@0*8r z9d_6DVpo;gqn$Z-?mhR;z2`gU-gECx_4=I;b?>=7Qd_^KLDw==-_X?3Sg*G&_jo6j+k&EV~eM7D#EEf#qneB?%vKY(}MB=Rfp3pa@T z8oYg_$m`%OD@2ZfcU&*>H29z@(hY7c5qS(;mWk{K8^Oz)!7HL7Uk4vtfOmq&pply;^2pN_p;``1G_vSq`Zpz4*QKAMr&U2 z;fy46JyGWRN#r_DO>DQj=Ld)OHaMwXKXtf!-@#pO=ArNJ?d{&v!g4oxI4fPhHk04j zfWdZrmH2*G}T@De9I3UEg&Z!~NaQKm8X}D%apra1s8?xCkyuvWexq ziXr`M)vD4^@F)u;hWTUXv%sm9c5HDbxC@JLA2Y8R*<7|&M@7@E3rV_BWv$Z8~Qo+=PGO*M~;AIi_hAImP!9{-F*r?IsK=H z9nf68gqY4joydCP0Aul;B+a3Xl}t)-z8B`3<&(CO_)hY>nm@_g{cMCEg> zfzy9o+NiEjyNqsQ@v@({$_?_2j7P^P!Mtk+JB;lHCCB04l6)yG<1eH+MiS>MymvP} z9^-Jdgy$&7>0iFh)j4^t1~^V%7f@i_TQYVX>DlE#6Ytu)f7jmq--++p-E(j^bsXoi z;w>Nr=6jfBu64e-#g7U)BWMSU*4)^uj&ac5$cwSpI0Q1Hh z7#~!XH{Mu}G76CU_D6ZrOy*0!K5b``LXz;)%xAo@9*wfycHC%hg>Xmltf@-2j3U-L zy#ZX)+D_Ehm_HHC>4xh=0?L)V9L3!U3TAG5GVQy1+wRfOqZvR3;p`j;iRKcwoAO`1E+*>^T(1jN9ACD zN-WdHTyRCv-@B|NkESN{U`o;7y&RAo_CF>jDieuwW9&-?8*hJsyu9&7KL44D3w9@S zgNrkdpp)dq_>W(II$T!c9n?h&ZvP2f(4Q+4x{@L;J|>^%!-RW1P*MJpHLtllz`4Oi zV~3zC@?vmdJ=P~K8aRGjB$)2d@eMvIc-2@HZ%x-3DZ|POj|Kb8yI|Y zO2jIWPHPbU!SxI6KESqpKe;+Ka`oy(NzMv1d;iHk=Wv3k8N@#`nb&%#40N8n7@Yk2 z#Dn_->LC|Sy(pl}QE(M}K5!bk+q505qBnm${F-UUM(#?5fLmnHv_qmzVT_tdMEiC4&j8G)8+e?F!n&f^%czu!)HYcbxtl zKyUZX*$U6gx8>gNG&N?s)Iuwxqz*a5xUs*`o`4oBE|aYpG`ZO?6ef)u~dm{vmez>`!8637fPSaIRGchqvROg ztKtFZWlB8YpRcT@oDP+>FydYvG8{C3% zU>^Hxyp{j0kUAsY`Tw-`HWa~hdTBZohB~^FTXx< zsY5%?_;bVst5HCiP2ls17h^!idW`Le7h}6wVdm=AhtGN9Iqz)e_xk$VyanC$FSntL zixrF4N>1j`A$c))`Spp#$`D-(lmoAJ6!29&;48rk#c^zFwlo>XA$DH^%%ajirgsjc zgW3sO5O*nv;ora-FUfmS3q`QpZym*)3V!b>`V|QvCi|5Bh_j}kJTWG*fpi2h8vd@m zLK)BI3)v1-Xa;xemk|=+B=fCUDNumI}&Z`#SGkVwh#Yj%WPwY1AV$&q)AhIGJu;A9|Db8BZGDJq`qOuy zZy}vy+d7K1zf#d#@$NF}!x^XO!B|i;%S1QJqje(qp|)p{3(6We8;{Q?_kX3_pi$6PQ~hQrWCX6p)~=k8hs3F{b@z(OAT+peoP5k z>(FPlsm~tT5VV4lu-BvSz&gEdp=rMv4_a0Fen(bSP}UH%-drS>7=3m*-c_FcE{qFy zcG|%<`b0%N%Bx~{zXDsqdqp#WsoO65P^E25u`Rw&ZB01u;yfNT5yzu$6!?Z=3qM0Y zAMfb1Uj}~+?|lXQhlu$ejU7cl2gcZD2>Znn>=(n(g(6#05*tnpt>IbPz*s=X`;!5j z*#s@o0#?A-W(7OWTZ;JSr)hHH^q8?G6tyj(G4jMp+RyPnBX}4|L%yn_svF8xHkIB z7vjTi=ZlZI!F2~Uh>nsMgR5VkW6h$3pZ0Ox0RhVF!EHWpjh*fLh1>*GtAR`P1!LHG za?uQ^zcYSQv8c9^SZXNO-ZX->(F#5X9BgCiMI%_FsAYy#5vaK{{M$;U_Q$}o99YJ_ z@V~#S|Kj|!u_^OEs`tIl6d?1)A)2edeEwNOg+sUG#o*}ICq`M6@Y6nyeoV>#N#+Ab z{p=F;xwi28xGvVH$J>JM(}Ka9=wgIJ};G5b Date: Fri, 27 Jan 2023 09:42:49 -0700 Subject: [PATCH 0557/1529] BaseTools: Remove CYGWIN_NT-5.1-i686 ref from Scripts/PatchCheck.py With the removal of RVCT support and the related Bin/CYGWIN_NT-5.1-i686 and Darwin-i386 directories, remove a leftover reference to CYGWIN_NT-5.1-i686 from Scripts/PatchCheck.py. Signed-off-by: Rebecca Cran Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao Acked-by: Bob Feng --- BaseTools/Scripts/PatchCheck.py | 1 - 1 file changed, 1 deletion(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 475b3a8c27..fcdabfc8ac 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -366,7 +366,6 @@ def run(self): if self.filename.endswith('.sh') or \ self.filename.startswith('BaseTools/BinWrappers/PosixLike/') or \ self.filename.startswith('BaseTools/BinPipWrappers/PosixLike/') or \ - self.filename.startswith('BaseTools/Bin/CYGWIN_NT-5.1-i686/') or \ self.filename == 'BaseTools/BuildEnv': # # Do not enforce CR/LF line endings for linux shell scripts. From 6ec1dc430f993d732ed6c1ef9432aa1851a693e5 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Fri, 27 Jan 2023 09:42:50 -0700 Subject: [PATCH 0558/1529] ArmPkg: Remove RealView Debugger support The RealView Debugger is related to RVCT, which is no longer supported. Given that, remove RvdPeCoffExtraActionLib and code from RvdPeCoffExtraActionLib which prints lines for use with the RealView Debugger. Signed-off-by: Rebecca Cran Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao Acked-by: Bob Feng --- ArmPkg/ArmPkg.dsc | 1 - .../DebugPeCoffExtraActionLib.c | 5 - .../RvdPeCoffExtraActionLib.c | 147 ------------------ .../RvdPeCoffExtraActionLib.inf | 35 ----- 4 files changed, 188 deletions(-) delete mode 100644 ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.c delete mode 100644 ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 1e873b90c5..3fb95d1951 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -113,7 +113,6 @@ ArmPkg/Library/DebugAgentSymbolsBaseLib/DebugAgentSymbolsBaseLib.inf ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf ArmPkg/Library/DefaultExceptionHandlerLib/DefaultExceptionHandlerLib.inf - ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf ArmPkg/Library/SemiHostingDebugLib/SemiHostingDebugLib.inf ArmPkg/Library/SemiHostingSerialPortLib/SemiHostingSerialPortLib.inf ArmPkg/Library/SemihostLib/SemihostLib.inf diff --git a/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c b/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c index 3827122a96..432112354f 100644 --- a/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c +++ b/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c @@ -77,13 +77,8 @@ PeCoffLoaderRelocateImageExtraAction ( if (ImageContext->PdbPointer) { #ifdef __CC_ARM - #if (__ARMCC_VERSION < 500000) - // Print out the command for the RVD debugger to load symbols for this image - DEBUG ((DEBUG_LOAD | DEBUG_INFO, "load /a /ni /np %a &0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders))); - #else // Print out the command for the DS-5 to load symbols for this image DEBUG ((DEBUG_LOAD | DEBUG_INFO, "add-symbol-file %a 0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders))); - #endif #elif __GNUC__ // This may not work correctly if you generate PE/COFF directly as then the Offset would not be required DEBUG ((DEBUG_LOAD | DEBUG_INFO, "add-symbol-file %a 0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders))); diff --git a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.c b/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.c deleted file mode 100644 index 6539c01763..0000000000 --- a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.c +++ /dev/null @@ -1,147 +0,0 @@ -/**@file - -Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.
-Portions copyright (c) 2008 - 2010, Apple Inc. All rights reserved.
-Portions copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.
- -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -#include -#include -#include -#include -#include -#include - -/** - Append string to debugger script file, create file if needed. - - This library can show up in multiple places so we need to append the file every time we write to it. - For example Sec can use this to load the DXE core, and the DXE core would use this to load all the - other modules. So we have two instances of the library in the system. - - @param Buffer Buffer to write to file. - @param Length Length of Buffer in bytes. -**/ -VOID -WriteStringToFile ( - IN VOID *Buffer, - IN UINT32 Length - ) -{ - // Working around and issue with the code that is commented out. For now send it to the console. - // You can copy the console into a file and source the file as a script and you get symbols. - // This gets you all the symbols except for SEC. To get SEC symbols you need to copy the - // debug print in the SEC into the debugger manually - SemihostWriteString (Buffer); - - /* - I'm currently having issues with this code crashing the debugger. Seems like it should work. - - UINT32 SemihostHandle; - UINT32 SemihostMode = SEMIHOST_FILE_MODE_WRITE | SEMIHOST_FILE_MODE_BINARY | SEMIHOST_FILE_MODE_UPDATE; - - SemihostFileOpen ("c:\rvi_symbols.inc", SemihostMode, &SemihostHandle); - SemihostFileWrite (SemihostHandle, &Length, Buffer); - SemihostFileClose (SemihostHandle); - */ -} - -/** - If the build is done on cygwin the paths are cygpaths. - /cygdrive/c/tmp.txt vs c:\tmp.txt so we need to convert - them to work with RVD commands - - @param Name Path to convert if needed - -**/ -CHAR8 * -DeCygwinPathIfNeeded ( - IN CHAR8 *Name - ) -{ - CHAR8 *Ptr; - UINTN Index; - UINTN Len; - - Ptr = AsciiStrStr (Name, "/cygdrive/"); - if (Ptr == NULL) { - return Name; - } - - Len = AsciiStrLen (Ptr); - - // convert "/cygdrive" to spaces - for (Index = 0; Index < 9; Index++) { - Ptr[Index] = ' '; - } - - // convert /c to c: - Ptr[9] = Ptr[10]; - Ptr[10] = ':'; - - // switch path separators - for (Index = 11; Index < Len; Index++) { - if (Ptr[Index] == '/') { - Ptr[Index] = '\\'; - } - } - - return Name; -} - -/** - Performs additional actions after a PE/COFF image has been loaded and relocated. - - If ImageContext is NULL, then ASSERT(). - - @param ImageContext Pointer to the image context structure that describes the - PE/COFF image that has already been loaded and relocated. - -**/ -VOID -EFIAPI -PeCoffLoaderRelocateImageExtraAction ( - IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext - ) -{ - CHAR8 Buffer[256]; - - #if (__ARMCC_VERSION < 500000) - AsciiSPrint (Buffer, sizeof (Buffer), "load /a /ni /np \"%a\" &0x%08x\n", ImageContext->PdbPointer, (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)); - #else - AsciiSPrint (Buffer, sizeof (Buffer), "add-symbol-file %a 0x%08x\n", ImageContext->PdbPointer, (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)); - #endif - DeCygwinPathIfNeeded (&Buffer[16]); - - WriteStringToFile (Buffer, AsciiStrSize (Buffer)); -} - -/** - Performs additional actions just before a PE/COFF image is unloaded. Any resources - that were allocated by PeCoffLoaderRelocateImageExtraAction() must be freed. - - If ImageContext is NULL, then ASSERT(). - - @param ImageContext Pointer to the image context structure that describes the - PE/COFF image that is being unloaded. - -**/ -VOID -EFIAPI -PeCoffLoaderUnloadImageExtraAction ( - IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext - ) -{ - CHAR8 Buffer[256]; - - AsciiSPrint (Buffer, sizeof (Buffer), "unload symbols_only \"%a\"\n", ImageContext->PdbPointer); - DeCygwinPathIfNeeded (Buffer); - - WriteStringToFile (Buffer, AsciiStrSize (Buffer)); -} diff --git a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf b/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf deleted file mode 100644 index 6b7ac87509..0000000000 --- a/ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf +++ /dev/null @@ -1,35 +0,0 @@ -#/** @file -# PeCoff extra action library for DXE phase that run Unix emulator. -# -# Lib to provide memory journal status code reporting Routines -# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.
-# Portions copyright (c) 2010, Apple Inc. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# -#**/ - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = RvdUnixPeCoffExtraActionLib - FILE_GUID = 5EDEB7E7-EA55-4E92-8216-335AC98A3B11 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = PeCoffExtraActionLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = ARM -# - -[Sources.common] - RvdPeCoffExtraActionLib.c - -[Packages] - MdePkg/MdePkg.dec - ArmPkg/ArmPkg.dec - -[LibraryClasses] - DebugLib - SemihostLib From 2741574a47de13007b927c8ad0080a347b190ffd Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Fri, 27 Jan 2023 09:42:51 -0700 Subject: [PATCH 0559/1529] ArmVirtPkg: Remove RealView Debugger lines from ArmVirtPkg.dsc.inc Since RvdPeCoffExtraActionLib has been deleted, remove lines referencing it and the RealView Debugger from ArmVirtPkg.dsc.inc. Signed-off-by: Rebecca Cran Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao Acked-by: Bob Feng --- ArmVirtPkg/ArmVirt.dsc.inc | 7 ------- 1 file changed, 7 deletions(-) diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc index 462073517a..74d98e6314 100644 --- a/ArmVirtPkg/ArmVirt.dsc.inc +++ b/ArmVirtPkg/ArmVirt.dsc.inc @@ -122,13 +122,6 @@ PL011UartLib|ArmPlatformPkg/Library/PL011UartLib/PL011UartLib.inf SerialPortLib|ArmVirtPkg/Library/FdtPL011SerialPortLib/FdtPL011SerialPortLib.inf - # - # Uncomment (and comment out the next line) For RealView Debugger. The Standard IO window - # in the debugger will show load and unload commands for symbols. You can cut and paste this - # into the command window to load symbols. We should be able to use a script to do this, but - # the version of RVD I have does not support scripts accessing system memory. - # - #PeCoffExtraActionLib|ArmPkg/Library/RvdPeCoffExtraActionLib/RvdPeCoffExtraActionLib.inf PeCoffExtraActionLib|ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.inf #PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf From ffe6034fac3e77162177f7d579f2cc132c70d0cd Mon Sep 17 00:00:00 2001 From: Chao Li Date: Sun, 29 Jan 2023 18:04:11 +0800 Subject: [PATCH 0560/1529] MdePkg: Add Acpi65.h to IgnoreFiles area Acpi65.h will causes ECC errors when CI uses Ubuntu GCC5 PR, add it to MdePkg.ci.yaml in "IgnreFiles" area to fix the ECC errors. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4306 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Liming Gao --- MdePkg/MdePkg.ci.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 19bc0138cb..6ba85ebe61 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -4,6 +4,7 @@ # Copyright (c) Microsoft Corporation # Copyright (c) 2020, Intel Corporation. All rights reserved.
# Copyright (c) 2021, Arm Limited. All rights reserved.
+# Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## { @@ -58,6 +59,7 @@ ## Both file path and directory path are accepted. "IgnoreFiles": [ "Include/IndustryStandard/Acpi64.h", + "Include/IndustryStandard/Acpi65.h", "Include/IndustryStandard/Tpm12.h", "Include/IndustryStandard/Tpm20.h", "Include/IndustryStandard/IoRemappingTable.h", From f0441bbe4c10b9d48bc158744e69b3793077a8b1 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 17 Jan 2023 16:05:52 +0800 Subject: [PATCH 0561/1529] MdePkg: Add ACPI 6.5 header Create Acpi65.h, which is copied from Acpi64.h, and make the following changes: 1. Replace all occurences of "6.4/6_4" with "6.5/6_5". 2. Incremented FADT minor revision. 3. Make Acpi65.h the latest ACPI definitions that Acpi.h contains. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4306 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/Acpi.h | 3 +- MdePkg/Include/IndustryStandard/Acpi65.h | 3163 ++++++++++++++++++++++ 2 files changed, 3165 insertions(+), 1 deletion(-) create mode 100644 MdePkg/Include/IndustryStandard/Acpi65.h diff --git a/MdePkg/Include/IndustryStandard/Acpi.h b/MdePkg/Include/IndustryStandard/Acpi.h index 05969a36b1..a0610d4a4c 100644 --- a/MdePkg/Include/IndustryStandard/Acpi.h +++ b/MdePkg/Include/IndustryStandard/Acpi.h @@ -4,6 +4,7 @@ Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.
Copyright (c) 2019 - 2021, ARM Ltd. All rights reserved.
+ Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -11,6 +12,6 @@ #ifndef _ACPI_H_ #define _ACPI_H_ -#include +#include #endif diff --git a/MdePkg/Include/IndustryStandard/Acpi65.h b/MdePkg/Include/IndustryStandard/Acpi65.h new file mode 100644 index 0000000000..fdca5316a9 --- /dev/null +++ b/MdePkg/Include/IndustryStandard/Acpi65.h @@ -0,0 +1,3163 @@ +/** @file + ACPI 6.5 definitions from the ACPI Specification Revision 6.5 Aug, 2022. + + Copyright (c) 2017 - 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2021, ARM Ltd. All rights reserved.
+ Copyright (c) 2023, Loongson Technology Corporation Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef ACPI_6_5_H_ +#define ACPI_6_5_H_ + +#include + +// +// Ensure proper structure formats +// +#pragma pack(1) + +/// +/// ACPI 6.5 Generic Address Space definition +/// +typedef struct { + UINT8 AddressSpaceId; + UINT8 RegisterBitWidth; + UINT8 RegisterBitOffset; + UINT8 AccessSize; + UINT64 Address; +} EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE; + +// +// Generic Address Space Address IDs +// +#define EFI_ACPI_6_5_SYSTEM_MEMORY 0x00 +#define EFI_ACPI_6_5_SYSTEM_IO 0x01 +#define EFI_ACPI_6_5_PCI_CONFIGURATION_SPACE 0x02 +#define EFI_ACPI_6_5_EMBEDDED_CONTROLLER 0x03 +#define EFI_ACPI_6_5_SMBUS 0x04 +#define EFI_ACPI_6_5_SYSTEM_CMOS 0x05 +#define EFI_ACPI_6_5_PCI_BAR_TARGET 0x06 +#define EFI_ACPI_6_5_IPMI 0x07 +#define EFI_ACPI_6_5_GENERAL_PURPOSE_IO 0x08 +#define EFI_ACPI_6_5_GENERIC_SERIAL_BUS 0x09 +#define EFI_ACPI_6_5_PLATFORM_COMMUNICATION_CHANNEL 0x0A +#define EFI_ACPI_6_5_FUNCTIONAL_FIXED_HARDWARE 0x7F + +// +// Generic Address Space Access Sizes +// +#define EFI_ACPI_6_5_UNDEFINED 0 +#define EFI_ACPI_6_5_BYTE 1 +#define EFI_ACPI_6_5_WORD 2 +#define EFI_ACPI_6_5_DWORD 3 +#define EFI_ACPI_6_5_QWORD 4 + +// +// ACPI 6.5 table structures +// + +/// +/// Root System Description Pointer Structure +/// +typedef struct { + UINT64 Signature; + UINT8 Checksum; + UINT8 OemId[6]; + UINT8 Revision; + UINT32 RsdtAddress; + UINT32 Length; + UINT64 XsdtAddress; + UINT8 ExtendedChecksum; + UINT8 Reserved[3]; +} EFI_ACPI_6_5_ROOT_SYSTEM_DESCRIPTION_POINTER; + +/// +/// RSD_PTR Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_ROOT_SYSTEM_DESCRIPTION_POINTER_REVISION 0x02 ///< ACPISpec (Revision 6.5) says current value is 2 + +/// +/// Common table header, this prefaces all ACPI tables, including FACS, but +/// excluding the RSD PTR structure +/// +typedef struct { + UINT32 Signature; + UINT32 Length; +} EFI_ACPI_6_5_COMMON_HEADER; + +// +// Root System Description Table +// No definition needed as it is a common description table header, the same with +// EFI_ACPI_DESCRIPTION_HEADER, followed by a variable number of UINT32 table pointers. +// + +/// +/// RSDT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_ROOT_SYSTEM_DESCRIPTION_TABLE_REVISION 0x01 + +// +// Extended System Description Table +// No definition needed as it is a common description table header, the same with +// EFI_ACPI_DESCRIPTION_HEADER, followed by a variable number of UINT64 table pointers. +// + +/// +/// XSDT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_EXTENDED_SYSTEM_DESCRIPTION_TABLE_REVISION 0x01 + +/// +/// Fixed ACPI Description Table Structure (FADT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 FirmwareCtrl; + UINT32 Dsdt; + UINT8 Reserved0; + UINT8 PreferredPmProfile; + UINT16 SciInt; + UINT32 SmiCmd; + UINT8 AcpiEnable; + UINT8 AcpiDisable; + UINT8 S4BiosReq; + UINT8 PstateCnt; + UINT32 Pm1aEvtBlk; + UINT32 Pm1bEvtBlk; + UINT32 Pm1aCntBlk; + UINT32 Pm1bCntBlk; + UINT32 Pm2CntBlk; + UINT32 PmTmrBlk; + UINT32 Gpe0Blk; + UINT32 Gpe1Blk; + UINT8 Pm1EvtLen; + UINT8 Pm1CntLen; + UINT8 Pm2CntLen; + UINT8 PmTmrLen; + UINT8 Gpe0BlkLen; + UINT8 Gpe1BlkLen; + UINT8 Gpe1Base; + UINT8 CstCnt; + UINT16 PLvl2Lat; + UINT16 PLvl3Lat; + UINT16 FlushSize; + UINT16 FlushStride; + UINT8 DutyOffset; + UINT8 DutyWidth; + UINT8 DayAlrm; + UINT8 MonAlrm; + UINT8 Century; + UINT16 IaPcBootArch; + UINT8 Reserved1; + UINT32 Flags; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ResetReg; + UINT8 ResetValue; + UINT16 ArmBootArch; + UINT8 MinorVersion; + UINT64 XFirmwareCtrl; + UINT64 XDsdt; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPm1aEvtBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPm1bEvtBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPm1aCntBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPm1bCntBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPm2CntBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XPmTmrBlk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XGpe0Blk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE XGpe1Blk; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE SleepControlReg; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE SleepStatusReg; + UINT64 HypervisorVendorIdentity; +} EFI_ACPI_6_5_FIXED_ACPI_DESCRIPTION_TABLE; + +/// +/// FADT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_FIXED_ACPI_DESCRIPTION_TABLE_REVISION 0x06 +#define EFI_ACPI_6_5_FIXED_ACPI_DESCRIPTION_TABLE_MINOR_REVISION 0x05 + +// +// Fixed ACPI Description Table Preferred Power Management Profile +// +#define EFI_ACPI_6_5_PM_PROFILE_UNSPECIFIED 0 +#define EFI_ACPI_6_5_PM_PROFILE_DESKTOP 1 +#define EFI_ACPI_6_5_PM_PROFILE_MOBILE 2 +#define EFI_ACPI_6_5_PM_PROFILE_WORKSTATION 3 +#define EFI_ACPI_6_5_PM_PROFILE_ENTERPRISE_SERVER 4 +#define EFI_ACPI_6_5_PM_PROFILE_SOHO_SERVER 5 +#define EFI_ACPI_6_5_PM_PROFILE_APPLIANCE_PC 6 +#define EFI_ACPI_6_5_PM_PROFILE_PERFORMANCE_SERVER 7 +#define EFI_ACPI_6_5_PM_PROFILE_TABLET 8 + +// +// Fixed ACPI Description Table Boot Architecture Flags +// All other bits are reserved and must be set to 0. +// +#define EFI_ACPI_6_5_LEGACY_DEVICES BIT0 +#define EFI_ACPI_6_5_8042 BIT1 +#define EFI_ACPI_6_5_VGA_NOT_PRESENT BIT2 +#define EFI_ACPI_6_5_MSI_NOT_SUPPORTED BIT3 +#define EFI_ACPI_6_5_PCIE_ASPM_CONTROLS BIT4 +#define EFI_ACPI_6_5_CMOS_RTC_NOT_PRESENT BIT5 + +// +// Fixed ACPI Description Table Arm Boot Architecture Flags +// All other bits are reserved and must be set to 0. +// +#define EFI_ACPI_6_5_ARM_PSCI_COMPLIANT BIT0 +#define EFI_ACPI_6_5_ARM_PSCI_USE_HVC BIT1 + +// +// Fixed ACPI Description Table Fixed Feature Flags +// All other bits are reserved and must be set to 0. +// +#define EFI_ACPI_6_5_WBINVD BIT0 +#define EFI_ACPI_6_5_WBINVD_FLUSH BIT1 +#define EFI_ACPI_6_5_PROC_C1 BIT2 +#define EFI_ACPI_6_5_P_LVL2_UP BIT3 +#define EFI_ACPI_6_5_PWR_BUTTON BIT4 +#define EFI_ACPI_6_5_SLP_BUTTON BIT5 +#define EFI_ACPI_6_5_FIX_RTC BIT6 +#define EFI_ACPI_6_5_RTC_S4 BIT7 +#define EFI_ACPI_6_5_TMR_VAL_EXT BIT8 +#define EFI_ACPI_6_5_DCK_CAP BIT9 +#define EFI_ACPI_6_5_RESET_REG_SUP BIT10 +#define EFI_ACPI_6_5_SEALED_CASE BIT11 +#define EFI_ACPI_6_5_HEADLESS BIT12 +#define EFI_ACPI_6_5_CPU_SW_SLP BIT13 +#define EFI_ACPI_6_5_PCI_EXP_WAK BIT14 +#define EFI_ACPI_6_5_USE_PLATFORM_CLOCK BIT15 +#define EFI_ACPI_6_5_S4_RTC_STS_VALID BIT16 +#define EFI_ACPI_6_5_REMOTE_POWER_ON_CAPABLE BIT17 +#define EFI_ACPI_6_5_FORCE_APIC_CLUSTER_MODEL BIT18 +#define EFI_ACPI_6_5_FORCE_APIC_PHYSICAL_DESTINATION_MODE BIT19 +#define EFI_ACPI_6_5_HW_REDUCED_ACPI BIT20 +#define EFI_ACPI_6_5_LOW_POWER_S0_IDLE_CAPABLE BIT21 + +/// +/// Firmware ACPI Control Structure +/// +typedef struct { + UINT32 Signature; + UINT32 Length; + UINT32 HardwareSignature; + UINT32 FirmwareWakingVector; + UINT32 GlobalLock; + UINT32 Flags; + UINT64 XFirmwareWakingVector; + UINT8 Version; + UINT8 Reserved0[3]; + UINT32 OspmFlags; + UINT8 Reserved1[24]; +} EFI_ACPI_6_5_FIRMWARE_ACPI_CONTROL_STRUCTURE; + +/// +/// FACS Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_FIRMWARE_ACPI_CONTROL_STRUCTURE_VERSION 0x02 + +/// +/// Firmware Control Structure Feature Flags +/// All other bits are reserved and must be set to 0. +/// +#define EFI_ACPI_6_5_S4BIOS_F BIT0 +#define EFI_ACPI_6_5_64BIT_WAKE_SUPPORTED_F BIT1 + +/// +/// OSPM Enabled Firmware Control Structure Flags +/// All other bits are reserved and must be set to 0. +/// +#define EFI_ACPI_6_5_OSPM_64BIT_WAKE_F BIT0 + +// +// Differentiated System Description Table, +// Secondary System Description Table +// and Persistent System Description Table, +// no definition needed as they are common description table header, the same with +// EFI_ACPI_DESCRIPTION_HEADER, followed by a definition block. +// +#define EFI_ACPI_6_5_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_REVISION 0x02 +#define EFI_ACPI_6_5_SECONDARY_SYSTEM_DESCRIPTION_TABLE_REVISION 0x02 + +/// +/// Multiple APIC Description Table header definition. The rest of the table +/// must be defined in a platform specific manner. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 LocalApicAddress; + UINT32 Flags; +} EFI_ACPI_6_5_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER; + +/// +/// MADT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_MULTIPLE_APIC_DESCRIPTION_TABLE_REVISION 0x05 + +/// +/// Multiple APIC Flags +/// All other bits are reserved and must be set to 0. +/// +#define EFI_ACPI_6_5_PCAT_COMPAT BIT0 + +// +// Multiple APIC Description Table APIC structure types +// All other values between 0x10 and 0x7F are reserved and +// will be ignored by OSPM. 0x80 ~ 0xFF are reserved for OEM. +// +#define EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC 0x00 +#define EFI_ACPI_6_5_IO_APIC 0x01 +#define EFI_ACPI_6_5_INTERRUPT_SOURCE_OVERRIDE 0x02 +#define EFI_ACPI_6_5_NON_MASKABLE_INTERRUPT_SOURCE 0x03 +#define EFI_ACPI_6_5_LOCAL_APIC_NMI 0x04 +#define EFI_ACPI_6_5_LOCAL_APIC_ADDRESS_OVERRIDE 0x05 +#define EFI_ACPI_6_5_IO_SAPIC 0x06 +#define EFI_ACPI_6_5_LOCAL_SAPIC 0x07 +#define EFI_ACPI_6_5_PLATFORM_INTERRUPT_SOURCES 0x08 +#define EFI_ACPI_6_5_PROCESSOR_LOCAL_X2APIC 0x09 +#define EFI_ACPI_6_5_LOCAL_X2APIC_NMI 0x0A +#define EFI_ACPI_6_5_GIC 0x0B +#define EFI_ACPI_6_5_GICD 0x0C +#define EFI_ACPI_6_5_GIC_MSI_FRAME 0x0D +#define EFI_ACPI_6_5_GICR 0x0E +#define EFI_ACPI_6_5_GIC_ITS 0x0F +#define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP 0x10 + +// +// APIC Structure Definitions +// + +/// +/// Processor Local APIC Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 AcpiProcessorUid; + UINT8 ApicId; + UINT32 Flags; +} EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC_STRUCTURE; + +/// +/// Local APIC Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_LOCAL_APIC_ENABLED BIT0 +#define EFI_ACPI_6_5_LOCAL_APIC_ONLINE_CAPABLE BIT1 + +/// +/// IO APIC Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 IoApicId; + UINT8 Reserved; + UINT32 IoApicAddress; + UINT32 GlobalSystemInterruptBase; +} EFI_ACPI_6_5_IO_APIC_STRUCTURE; + +/// +/// Interrupt Source Override Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Bus; + UINT8 Source; + UINT32 GlobalSystemInterrupt; + UINT16 Flags; +} EFI_ACPI_6_5_INTERRUPT_SOURCE_OVERRIDE_STRUCTURE; + +/// +/// Platform Interrupt Sources Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Flags; + UINT8 InterruptType; + UINT8 ProcessorId; + UINT8 ProcessorEid; + UINT8 IoSapicVector; + UINT32 GlobalSystemInterrupt; + UINT32 PlatformInterruptSourceFlags; + UINT8 CpeiProcessorOverride; + UINT8 Reserved[31]; +} EFI_ACPI_6_5_PLATFORM_INTERRUPT_APIC_STRUCTURE; + +// +// MPS INTI flags. +// All other bits are reserved and must be set to 0. +// +#define EFI_ACPI_6_5_POLARITY (3 << 0) +#define EFI_ACPI_6_5_TRIGGER_MODE (3 << 2) + +/// +/// Non-Maskable Interrupt Source Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Flags; + UINT32 GlobalSystemInterrupt; +} EFI_ACPI_6_5_NON_MASKABLE_INTERRUPT_SOURCE_STRUCTURE; + +/// +/// Local APIC NMI Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 AcpiProcessorUid; + UINT16 Flags; + UINT8 LocalApicLint; +} EFI_ACPI_6_5_LOCAL_APIC_NMI_STRUCTURE; + +/// +/// Local APIC Address Override Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved; + UINT64 LocalApicAddress; +} EFI_ACPI_6_5_LOCAL_APIC_ADDRESS_OVERRIDE_STRUCTURE; + +/// +/// IO SAPIC Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 IoApicId; + UINT8 Reserved; + UINT32 GlobalSystemInterruptBase; + UINT64 IoSapicAddress; +} EFI_ACPI_6_5_IO_SAPIC_STRUCTURE; + +/// +/// Local SAPIC Structure +/// This struct followed by a null-terminated ASCII string - ACPI Processor UID String +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 AcpiProcessorId; + UINT8 LocalSapicId; + UINT8 LocalSapicEid; + UINT8 Reserved[3]; + UINT32 Flags; + UINT32 ACPIProcessorUIDValue; +} EFI_ACPI_6_5_PROCESSOR_LOCAL_SAPIC_STRUCTURE; + +/// +/// Platform Interrupt Sources Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Flags; + UINT8 InterruptType; + UINT8 ProcessorId; + UINT8 ProcessorEid; + UINT8 IoSapicVector; + UINT32 GlobalSystemInterrupt; + UINT32 PlatformInterruptSourceFlags; +} EFI_ACPI_6_5_PLATFORM_INTERRUPT_SOURCES_STRUCTURE; + +/// +/// Platform Interrupt Source Flags. +/// All other bits are reserved and must be set to 0. +/// +#define EFI_ACPI_6_5_CPEI_PROCESSOR_OVERRIDE BIT0 + +/// +/// Processor Local x2APIC Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved[2]; + UINT32 X2ApicId; + UINT32 Flags; + UINT32 AcpiProcessorUid; +} EFI_ACPI_6_5_PROCESSOR_LOCAL_X2APIC_STRUCTURE; + +/// +/// Local x2APIC NMI Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Flags; + UINT32 AcpiProcessorUid; + UINT8 LocalX2ApicLint; + UINT8 Reserved[3]; +} EFI_ACPI_6_5_LOCAL_X2APIC_NMI_STRUCTURE; + +/// +/// GIC Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved; + UINT32 CPUInterfaceNumber; + UINT32 AcpiProcessorUid; + UINT32 Flags; + UINT32 ParkingProtocolVersion; + UINT32 PerformanceInterruptGsiv; + UINT64 ParkedAddress; + UINT64 PhysicalBaseAddress; + UINT64 GICV; + UINT64 GICH; + UINT32 VGICMaintenanceInterrupt; + UINT64 GICRBaseAddress; + UINT64 MPIDR; + UINT8 ProcessorPowerEfficiencyClass; + UINT8 Reserved2; + UINT16 SpeOverflowInterrupt; +} EFI_ACPI_6_5_GIC_STRUCTURE; + +/// +/// GIC Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GIC_ENABLED BIT0 +#define EFI_ACPI_6_5_PERFORMANCE_INTERRUPT_MODEL BIT1 +#define EFI_ACPI_6_5_VGIC_MAINTENANCE_INTERRUPT_MODE_FLAGS BIT2 + +/// +/// GIC Distributor Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved1; + UINT32 GicId; + UINT64 PhysicalBaseAddress; + UINT32 SystemVectorBase; + UINT8 GicVersion; + UINT8 Reserved2[3]; +} EFI_ACPI_6_5_GIC_DISTRIBUTOR_STRUCTURE; + +/// +/// GIC Version +/// +#define EFI_ACPI_6_5_GIC_V1 0x01 +#define EFI_ACPI_6_5_GIC_V2 0x02 +#define EFI_ACPI_6_5_GIC_V3 0x03 +#define EFI_ACPI_6_5_GIC_V4 0x04 + +/// +/// GIC MSI Frame Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved1; + UINT32 GicMsiFrameId; + UINT64 PhysicalBaseAddress; + UINT32 Flags; + UINT16 SPICount; + UINT16 SPIBase; +} EFI_ACPI_6_5_GIC_MSI_FRAME_STRUCTURE; + +/// +/// GIC MSI Frame Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_SPI_COUNT_BASE_SELECT BIT0 + +/// +/// GICR Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved; + UINT64 DiscoveryRangeBaseAddress; + UINT32 DiscoveryRangeLength; +} EFI_ACPI_6_5_GICR_STRUCTURE; + +/// +/// GIC Interrupt Translation Service Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Reserved; + UINT32 GicItsId; + UINT64 PhysicalBaseAddress; + UINT32 Reserved2; +} EFI_ACPI_6_5_GIC_ITS_STRUCTURE; + +/// +/// Multiprocessor Wakeup Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 MailBoxVersion; + UINT32 Reserved; + UINT64 MailBoxAddress; +} EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_STRUCTURE; + +/// +/// Multiprocessor Wakeup Mailbox Structure +/// +typedef struct { + UINT16 Command; + UINT16 Reserved; + UINT32 AcpiId; + UINT64 WakeupVector; + UINT8 ReservedForOs[2032]; + UINT8 ReservedForFirmware[2048]; +} EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_MAILBOX_STRUCTURE; + +#define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_MAILBOX_COMMAND_NOOP 0x0000 +#define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_MAILBOX_COMMAND_WAKEUP 0x0001 + +/// +/// Smart Battery Description Table (SBST) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 WarningEnergyLevel; + UINT32 LowEnergyLevel; + UINT32 CriticalEnergyLevel; +} EFI_ACPI_6_5_SMART_BATTERY_DESCRIPTION_TABLE; + +/// +/// SBST Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_SMART_BATTERY_DESCRIPTION_TABLE_REVISION 0x01 + +/// +/// Embedded Controller Boot Resources Table (ECDT) +/// The table is followed by a null terminated ASCII string that contains +/// a fully qualified reference to the name space object. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE EcControl; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE EcData; + UINT32 Uid; + UINT8 GpeBit; +} EFI_ACPI_6_5_EMBEDDED_CONTROLLER_BOOT_RESOURCES_TABLE; + +/// +/// ECDT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_EMBEDDED_CONTROLLER_BOOT_RESOURCES_TABLE_REVISION 0x01 + +/// +/// System Resource Affinity Table (SRAT). The rest of the table +/// must be defined in a platform specific manner. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 Reserved1; ///< Must be set to 1 + UINT64 Reserved2; +} EFI_ACPI_6_5_SYSTEM_RESOURCE_AFFINITY_TABLE_HEADER; + +/// +/// SRAT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_SYSTEM_RESOURCE_AFFINITY_TABLE_REVISION 0x03 + +// +// SRAT structure types. +// All other values between 0x06 an 0xFF are reserved and +// will be ignored by OSPM. +// +#define EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC_SAPIC_AFFINITY 0x00 +#define EFI_ACPI_6_5_MEMORY_AFFINITY 0x01 +#define EFI_ACPI_6_5_PROCESSOR_LOCAL_X2APIC_AFFINITY 0x02 +#define EFI_ACPI_6_5_GICC_AFFINITY 0x03 +#define EFI_ACPI_6_5_GIC_ITS_AFFINITY 0x04 +#define EFI_ACPI_6_5_GENERIC_INITIATOR_AFFINITY 0x05 + +/// +/// Processor Local APIC/SAPIC Affinity Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 ProximityDomain7To0; + UINT8 ApicId; + UINT32 Flags; + UINT8 LocalSapicEid; + UINT8 ProximityDomain31To8[3]; + UINT32 ClockDomain; +} EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC_SAPIC_AFFINITY_STRUCTURE; + +/// +/// Local APIC/SAPIC Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC_SAPIC_ENABLED (1 << 0) + +/// +/// Memory Affinity Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 ProximityDomain; + UINT16 Reserved1; + UINT32 AddressBaseLow; + UINT32 AddressBaseHigh; + UINT32 LengthLow; + UINT32 LengthHigh; + UINT32 Reserved2; + UINT32 Flags; + UINT64 Reserved3; +} EFI_ACPI_6_5_MEMORY_AFFINITY_STRUCTURE; + +// +// Memory Flags. All other bits are reserved and must be 0. +// +#define EFI_ACPI_6_5_MEMORY_ENABLED (1 << 0) +#define EFI_ACPI_6_5_MEMORY_HOT_PLUGGABLE (1 << 1) +#define EFI_ACPI_6_5_MEMORY_NONVOLATILE (1 << 2) + +/// +/// Processor Local x2APIC Affinity Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved1[2]; + UINT32 ProximityDomain; + UINT32 X2ApicId; + UINT32 Flags; + UINT32 ClockDomain; + UINT8 Reserved2[4]; +} EFI_ACPI_6_5_PROCESSOR_LOCAL_X2APIC_AFFINITY_STRUCTURE; + +/// +/// GICC Affinity Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 ProximityDomain; + UINT32 AcpiProcessorUid; + UINT32 Flags; + UINT32 ClockDomain; +} EFI_ACPI_6_5_GICC_AFFINITY_STRUCTURE; + +/// +/// GICC Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GICC_ENABLED (1 << 0) + +/// +/// GIC Interrupt Translation Service (ITS) Affinity Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 ProximityDomain; + UINT8 Reserved[2]; + UINT32 ItsId; +} EFI_ACPI_6_5_GIC_ITS_AFFINITY_STRUCTURE; + +// +// Generic Initiator Affinity Structure Device Handle Types +// All other values between 0x02 an 0xFF are reserved and +// will be ignored by OSPM. +// +#define EFI_ACPI_6_5_ACPI_DEVICE_HANDLE 0x00 +#define EFI_ACPI_6_5_PCI_DEVICE_HANDLE 0x01 + +/// +/// Device Handle - ACPI +/// +typedef struct { + UINT64 AcpiHid; + UINT32 AcpiUid; + UINT8 Reserved[4]; +} EFI_ACPI_6_5_DEVICE_HANDLE_ACPI; + +/// +/// Device Handle - PCI +/// +typedef struct { + UINT16 PciSegment; + UINT16 PciBdfNumber; + UINT8 Reserved[12]; +} EFI_ACPI_6_5_DEVICE_HANDLE_PCI; + +/// +/// Device Handle +/// +typedef union { + EFI_ACPI_6_5_DEVICE_HANDLE_ACPI Acpi; + EFI_ACPI_6_5_DEVICE_HANDLE_PCI Pci; +} EFI_ACPI_6_5_DEVICE_HANDLE; + +/// +/// Generic Initiator Affinity Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved1; + UINT8 DeviceHandleType; + UINT32 ProximityDomain; + EFI_ACPI_6_5_DEVICE_HANDLE DeviceHandle; + UINT32 Flags; + UINT8 Reserved2[4]; +} EFI_ACPI_6_5_GENERIC_INITIATOR_AFFINITY_STRUCTURE; + +/// +/// Generic Initiator Affinity Structure Flags. All other bits are reserved +/// and must be 0. +/// +#define EFI_ACPI_6_5_GENERIC_INITIATOR_AFFINITY_STRUCTURE_ENABLED BIT0 +#define EFI_ACPI_6_5_GENERIC_INITIATOR_AFFINITY_STRUCTURE_ARCHITECTURAL_TRANSACTIONS BIT1 + +/// +/// System Locality Distance Information Table (SLIT). +/// The rest of the table is a matrix. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT64 NumberOfSystemLocalities; +} EFI_ACPI_6_5_SYSTEM_LOCALITY_DISTANCE_INFORMATION_TABLE_HEADER; + +/// +/// SLIT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_SYSTEM_LOCALITY_DISTANCE_INFORMATION_TABLE_REVISION 0x01 + +/// +/// Corrected Platform Error Polling Table (CPEP) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT8 Reserved[8]; +} EFI_ACPI_6_5_CORRECTED_PLATFORM_ERROR_POLLING_TABLE_HEADER; + +/// +/// CPEP Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_CORRECTED_PLATFORM_ERROR_POLLING_TABLE_REVISION 0x01 + +// +// CPEP processor structure types. +// +#define EFI_ACPI_6_5_CPEP_PROCESSOR_APIC_SAPIC 0x00 + +/// +/// Corrected Platform Error Polling Processor Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 ProcessorId; + UINT8 ProcessorEid; + UINT32 PollingInterval; +} EFI_ACPI_6_5_CPEP_PROCESSOR_APIC_SAPIC_STRUCTURE; + +/// +/// Maximum System Characteristics Table (MSCT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 OffsetProxDomInfo; + UINT32 MaximumNumberOfProximityDomains; + UINT32 MaximumNumberOfClockDomains; + UINT64 MaximumPhysicalAddress; +} EFI_ACPI_6_5_MAXIMUM_SYSTEM_CHARACTERISTICS_TABLE_HEADER; + +/// +/// MSCT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_MAXIMUM_SYSTEM_CHARACTERISTICS_TABLE_REVISION 0x01 + +/// +/// Maximum Proximity Domain Information Structure Definition +/// +typedef struct { + UINT8 Revision; + UINT8 Length; + UINT32 ProximityDomainRangeLow; + UINT32 ProximityDomainRangeHigh; + UINT32 MaximumProcessorCapacity; + UINT64 MaximumMemoryCapacity; +} EFI_ACPI_6_5_MAXIMUM_PROXIMITY_DOMAIN_INFORMATION_STRUCTURE; + +/// +/// ACPI RAS Feature Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT8 PlatformCommunicationChannelIdentifier[12]; +} EFI_ACPI_6_5_RAS_FEATURE_TABLE; + +/// +/// RASF Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_RAS_FEATURE_TABLE_REVISION 0x01 + +/// +/// ACPI RASF Platform Communication Channel Shared Memory Region definition. +/// +typedef struct { + UINT32 Signature; + UINT16 Command; + UINT16 Status; + UINT16 Version; + UINT8 RASCapabilities[16]; + UINT8 SetRASCapabilities[16]; + UINT16 NumberOfRASFParameterBlocks; + UINT32 SetRASCapabilitiesStatus; +} EFI_ACPI_6_5_RASF_PLATFORM_COMMUNICATION_CHANNEL_SHARED_MEMORY_REGION; + +/// +/// ACPI RASF PCC command code +/// +#define EFI_ACPI_6_5_RASF_PCC_COMMAND_CODE_EXECUTE_RASF_COMMAND 0x01 + +/// +/// ACPI RASF Platform RAS Capabilities +/// +#define EFI_ACPI_6_5_RASF_PLATFORM_RAS_CAPABILITY_HARDWARE_BASED_PATROL_SCRUB_SUPPORTED BIT0 +#define EFI_ACPI_6_5_RASF_PLATFORM_RAS_CAPABILITY_HARDWARE_BASED_PATROL_SCRUB_SUPPORTED_AND_EXPOSED_TO_SOFTWARE BIT1 +#define EFI_ACPI_6_5_RASF_PLATFORM_RAS_CAPABILITY_CPU_CACHE_FLUSH_TO_NVDIMM_DURABILITY_ON_POWER_LOSS BIT2 +#define EFI_ACPI_6_5_RASF_PLATFORM_RAS_CAPABILITY_MEMORY_CONTROLLER_FLUSH_TO_NVDIMM_DURABILITY_ON_POWER_LOSS BIT3 +#define EFI_ACPI_6_5_RASF_PLATFORM_RAS_CAPABILITY_BYTE_ADDRESSABLE_PERSISTENT_MEMORY_HARDWARE_MIRRORING BIT4 + +/// +/// ACPI RASF Parameter Block structure for PATROL_SCRUB +/// +typedef struct { + UINT16 Type; + UINT16 Version; + UINT16 Length; + UINT16 PatrolScrubCommand; + UINT64 RequestedAddressRange[2]; + UINT64 ActualAddressRange[2]; + UINT16 Flags; + UINT8 RequestedSpeed; +} EFI_ACPI_6_5_RASF_PATROL_SCRUB_PLATFORM_BLOCK_STRUCTURE; + +/// +/// ACPI RASF Patrol Scrub command +/// +#define EFI_ACPI_6_5_RASF_PATROL_SCRUB_COMMAND_GET_PATROL_PARAMETERS 0x01 +#define EFI_ACPI_6_5_RASF_PATROL_SCRUB_COMMAND_START_PATROL_SCRUBBER 0x02 +#define EFI_ACPI_6_5_RASF_PATROL_SCRUB_COMMAND_STOP_PATROL_SCRUBBER 0x03 + +/// +/// Memory Power State Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT8 PlatformCommunicationChannelIdentifier; + UINT8 Reserved[3]; + // Memory Power Node Structure + // Memory Power State Characteristics +} EFI_ACPI_6_5_MEMORY_POWER_STATUS_TABLE; + +/// +/// MPST Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_MEMORY_POWER_STATE_TABLE_REVISION 0x01 + +/// +/// MPST Platform Communication Channel Shared Memory Region definition. +/// +typedef struct { + UINT32 Signature; + UINT16 Command; + UINT16 Status; + UINT32 MemoryPowerCommandRegister; + UINT32 MemoryPowerStatusRegister; + UINT32 PowerStateId; + UINT32 MemoryPowerNodeId; + UINT64 MemoryEnergyConsumed; + UINT64 ExpectedAveragePowerComsuned; +} EFI_ACPI_6_5_MPST_PLATFORM_COMMUNICATION_CHANNEL_SHARED_MEMORY_REGION; + +/// +/// ACPI MPST PCC command code +/// +#define EFI_ACPI_6_5_MPST_PCC_COMMAND_CODE_EXECUTE_MPST_COMMAND 0x03 + +/// +/// ACPI MPST Memory Power command +/// +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_COMMAND_GET_MEMORY_POWER_STATE 0x01 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_COMMAND_SET_MEMORY_POWER_STATE 0x02 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_COMMAND_GET_AVERAGE_POWER_CONSUMED 0x03 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_COMMAND_GET_MEMORY_ENERGY_CONSUMED 0x04 + +/// +/// MPST Memory Power Node Table +/// +typedef struct { + UINT8 PowerStateValue; + UINT8 PowerStateInformationIndex; +} EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE; + +typedef struct { + UINT8 Flag; + UINT8 Reserved; + UINT16 MemoryPowerNodeId; + UINT32 Length; + UINT64 AddressBase; + UINT64 AddressLength; + UINT32 NumberOfPowerStates; + UINT32 NumberOfPhysicalComponents; + // EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE MemoryPowerState[NumberOfPowerStates]; + // UINT16 PhysicalComponentIdentifier[NumberOfPhysicalComponents]; +} EFI_ACPI_6_5_MPST_MEMORY_POWER_STRUCTURE; + +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STRUCTURE_FLAG_ENABLE 0x01 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STRUCTURE_FLAG_POWER_MANAGED 0x02 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STRUCTURE_FLAG_HOT_PLUGGABLE 0x04 + +typedef struct { + UINT16 MemoryPowerNodeCount; + UINT8 Reserved[2]; +} EFI_ACPI_6_5_MPST_MEMORY_POWER_NODE_TABLE; + +/// +/// MPST Memory Power State Characteristics Table +/// +typedef struct { + UINT8 PowerStateStructureID; + UINT8 Flag; + UINT16 Reserved; + UINT32 AveragePowerConsumedInMPS0; + UINT32 RelativePowerSavingToMPS0; + UINT64 ExitLatencyToMPS0; +} EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE_CHARACTERISTICS_STRUCTURE; + +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE_CHARACTERISTICS_STRUCTURE_FLAG_MEMORY_CONTENT_PRESERVED 0x01 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE_CHARACTERISTICS_STRUCTURE_FLAG_AUTONOMOUS_MEMORY_POWER_STATE_ENTRY 0x02 +#define EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE_CHARACTERISTICS_STRUCTURE_FLAG_AUTONOMOUS_MEMORY_POWER_STATE_EXIT 0x04 + +typedef struct { + UINT16 MemoryPowerStateCharacteristicsCount; + UINT8 Reserved[2]; +} EFI_ACPI_6_5_MPST_MEMORY_POWER_STATE_CHARACTERISTICS_TABLE; + +/// +/// Platform Memory Topology Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 NumberOfMemoryDevices; + // EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE MemoryDeviceStructure[NumberOfMemoryDevices]; +} EFI_ACPI_6_5_PLATFORM_MEMORY_TOPOLOGY_TABLE; + +/// +/// PMTT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_MEMORY_TOPOLOGY_TABLE_REVISION 0x02 + +/// +/// Common Memory Device. +/// +typedef struct { + UINT8 Type; + UINT8 Reserved; + UINT16 Length; + UINT16 Flags; + UINT16 Reserved1; + UINT32 NumberOfMemoryDevices; + // UINT8 TypeSpecificData[]; + // EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE MemoryDeviceStructure[NumberOfMemoryDevices]; +} EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE; + +/// +/// Memory Device Type. +/// +#define EFI_ACPI_6_5_PMTT_MEMORY_DEVICE_TYPE_SOCKET 0x0 +#define EFI_ACPI_6_5_PMTT_MEMORY_DEVICE_TYPE_MEMORY_CONTROLLER 0x1 +#define EFI_ACPI_6_5_PMTT_MEMORY_DEVICE_TYPE_DIMM 0x2 +#define EFI_ACPI_6_5_PMTT_MEMORY_DEVICE_TYPE_VENDOR_SPECIFIC_TYPE 0xFF + +/// +/// Socket Type Data. +/// +typedef struct { + EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE CommonMemoryDeviceHeader; + UINT16 SocketIdentifier; + UINT16 Reserved; + // EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE MemoryDeviceStructure[]; +} EFI_ACPI_6_5_PMTT_SOCKET_TYPE_DATA; + +/// +/// Memory Controller Type Data. +/// +typedef struct { + EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE CommonMemoryDeviceHeader; + UINT16 MemoryControllerIdentifier; + UINT16 Reserved; + // EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE MemoryDeviceStructure[]; +} EFI_ACPI_6_5_PMTT_MEMORY_CONTROLLER_TYPE_DATA; + +/// +/// DIMM Type Specific Data. +/// +typedef struct { + EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE CommonMemoryDeviceHeader; + UINT32 SmbiosHandle; +} EFI_ACPI_6_5_PMTT_DIMM_TYPE_SPECIFIC_DATA; + +/// +/// Vendor Specific Type Data. +/// +typedef struct { + EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE CommonMemoryDeviceHeader; + UINT8 TypeUuid[16]; + // EFI_ACPI_6_5_PMTT_VENDOR_SPECIFIC_TYPE_DATA VendorSpecificData[]; + // EFI_ACPI_6_5_PMTT_COMMON_MEMORY_DEVICE MemoryDeviceStructure[]; +} EFI_ACPI_6_5_PMTT_VENDOR_SPECIFIC_TYPE_DATA; + +/// +/// Boot Graphics Resource Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + /// + /// 2-bytes (16 bit) version ID. This value must be 1. + /// + UINT16 Version; + /// + /// 1-byte status field indicating current status about the table. + /// Bits[7:3] = Reserved (must be zero) + /// Bits[2:1] = Orientation Offset. These bits describe the clockwise + /// degree offset from the image's default orientation. + /// [00] = 0, no offset + /// [01] = 90 + /// [10] = 180 + /// [11] = 270 + /// Bit [0] = Displayed. A one indicates the boot image graphic is + /// displayed. + /// + UINT8 Status; + /// + /// 1-byte enumerated type field indicating format of the image. + /// 0 = Bitmap + /// 1 - 255 Reserved (for future use) + /// + UINT8 ImageType; + /// + /// 8-byte (64 bit) physical address pointing to the firmware's in-memory copy + /// of the image bitmap. + /// + UINT64 ImageAddress; + /// + /// A 4-byte (32-bit) unsigned long describing the display X-offset of the boot image. + /// (X, Y) display offset of the top left corner of the boot image. + /// The top left corner of the display is at offset (0, 0). + /// + UINT32 ImageOffsetX; + /// + /// A 4-byte (32-bit) unsigned long describing the display Y-offset of the boot image. + /// (X, Y) display offset of the top left corner of the boot image. + /// The top left corner of the display is at offset (0, 0). + /// + UINT32 ImageOffsetY; +} EFI_ACPI_6_5_BOOT_GRAPHICS_RESOURCE_TABLE; + +/// +/// BGRT Revision +/// +#define EFI_ACPI_6_5_BOOT_GRAPHICS_RESOURCE_TABLE_REVISION 1 + +/// +/// BGRT Version +/// +#define EFI_ACPI_6_5_BGRT_VERSION 0x01 + +/// +/// BGRT Status +/// +#define EFI_ACPI_6_5_BGRT_STATUS_NOT_DISPLAYED 0x00 +#define EFI_ACPI_6_5_BGRT_STATUS_DISPLAYED 0x01 + +/// +/// BGRT Image Type +/// +#define EFI_ACPI_6_5_BGRT_IMAGE_TYPE_BMP 0x00 + +/// +/// FPDT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_FIRMWARE_PERFORMANCE_DATA_TABLE_REVISION 0x01 + +/// +/// FPDT Performance Record Types +/// +#define EFI_ACPI_6_5_FPDT_RECORD_TYPE_FIRMWARE_BASIC_BOOT_POINTER 0x0000 +#define EFI_ACPI_6_5_FPDT_RECORD_TYPE_S3_PERFORMANCE_TABLE_POINTER 0x0001 + +/// +/// FPDT Performance Record Revision +/// +#define EFI_ACPI_6_5_FPDT_RECORD_REVISION_FIRMWARE_BASIC_BOOT_POINTER 0x01 +#define EFI_ACPI_6_5_FPDT_RECORD_REVISION_S3_PERFORMANCE_TABLE_POINTER 0x01 + +/// +/// FPDT Runtime Performance Record Types +/// +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_TYPE_S3_RESUME 0x0000 +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_TYPE_S3_SUSPEND 0x0001 +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_TYPE_FIRMWARE_BASIC_BOOT 0x0002 + +/// +/// FPDT Runtime Performance Record Revision +/// +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_REVISION_S3_RESUME 0x01 +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_REVISION_S3_SUSPEND 0x01 +#define EFI_ACPI_6_5_FPDT_RUNTIME_RECORD_REVISION_FIRMWARE_BASIC_BOOT 0x02 + +/// +/// FPDT Performance Record header +/// +typedef struct { + UINT16 Type; + UINT8 Length; + UINT8 Revision; +} EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER; + +/// +/// FPDT Performance Table header +/// +typedef struct { + UINT32 Signature; + UINT32 Length; +} EFI_ACPI_6_5_FPDT_PERFORMANCE_TABLE_HEADER; + +/// +/// FPDT Firmware Basic Boot Performance Pointer Record Structure +/// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER Header; + UINT32 Reserved; + /// + /// 64-bit processor-relative physical address of the Basic Boot Performance Table. + /// + UINT64 BootPerformanceTablePointer; +} EFI_ACPI_6_5_FPDT_BOOT_PERFORMANCE_TABLE_POINTER_RECORD; + +/// +/// FPDT S3 Performance Table Pointer Record Structure +/// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER Header; + UINT32 Reserved; + /// + /// 64-bit processor-relative physical address of the S3 Performance Table. + /// + UINT64 S3PerformanceTablePointer; +} EFI_ACPI_6_5_FPDT_S3_PERFORMANCE_TABLE_POINTER_RECORD; + +/// +/// FPDT Firmware Basic Boot Performance Record Structure +/// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER Header; + UINT32 Reserved; + /// + /// Timer value logged at the beginning of firmware image execution. + /// This may not always be zero or near zero. + /// + UINT64 ResetEnd; + /// + /// Timer value logged just prior to loading the OS boot loader into memory. + /// For non-UEFI compatible boots, this field must be zero. + /// + UINT64 OsLoaderLoadImageStart; + /// + /// Timer value logged just prior to launching the previously loaded OS boot loader image. + /// For non-UEFI compatible boots, the timer value logged will be just prior + /// to the INT 19h handler invocation. + /// + UINT64 OsLoaderStartImageStart; + /// + /// Timer value logged at the point when the OS loader calls the + /// ExitBootServices function for UEFI compatible firmware. + /// For non-UEFI compatible boots, this field must be zero. + /// + UINT64 ExitBootServicesEntry; + /// + /// Timer value logged at the point just prior towhen the OS loader gaining + /// control back from calls the ExitBootServices function for UEFI compatible firmware. + /// For non-UEFI compatible boots, this field must be zero. + /// + UINT64 ExitBootServicesExit; +} EFI_ACPI_6_5_FPDT_FIRMWARE_BASIC_BOOT_RECORD; + +/// +/// FPDT Firmware Basic Boot Performance Table signature +/// +#define EFI_ACPI_6_5_FPDT_BOOT_PERFORMANCE_TABLE_SIGNATURE SIGNATURE_32('F', 'B', 'P', 'T') + +// +// FPDT Firmware Basic Boot Performance Table +// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_TABLE_HEADER Header; + // + // one or more Performance Records. + // +} EFI_ACPI_6_5_FPDT_FIRMWARE_BASIC_BOOT_TABLE; + +/// +/// FPDT "S3PT" S3 Performance Table +/// +#define EFI_ACPI_6_5_FPDT_S3_PERFORMANCE_TABLE_SIGNATURE SIGNATURE_32('S', '3', 'P', 'T') + +// +// FPDT Firmware S3 Boot Performance Table +// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_TABLE_HEADER Header; + // + // one or more Performance Records. + // +} EFI_ACPI_6_5_FPDT_FIRMWARE_S3_BOOT_TABLE; + +/// +/// FPDT Basic S3 Resume Performance Record +/// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER Header; + /// + /// A count of the number of S3 resume cycles since the last full boot sequence. + /// + UINT32 ResumeCount; + /// + /// Timer recorded at the end of BIOS S3 resume, just prior to handoff to the + /// OS waking vector. Only the most recent resume cycle's time is retained. + /// + UINT64 FullResume; + /// + /// Average timer value of all resume cycles logged since the last full boot + /// sequence, including the most recent resume. Note that the entire log of + /// timer values does not need to be retained in order to calculate this average. + /// + UINT64 AverageResume; +} EFI_ACPI_6_5_FPDT_S3_RESUME_RECORD; + +/// +/// FPDT Basic S3 Suspend Performance Record +/// +typedef struct { + EFI_ACPI_6_5_FPDT_PERFORMANCE_RECORD_HEADER Header; + /// + /// Timer value recorded at the OS write to SLP_TYP upon entry to S3. + /// Only the most recent suspend cycle's timer value is retained. + /// + UINT64 SuspendStart; + /// + /// Timer value recorded at the final firmware write to SLP_TYP (or other + /// mechanism) used to trigger hardware entry to S3. + /// Only the most recent suspend cycle's timer value is retained. + /// + UINT64 SuspendEnd; +} EFI_ACPI_6_5_FPDT_S3_SUSPEND_RECORD; + +/// +/// Firmware Performance Record Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; +} EFI_ACPI_6_5_FIRMWARE_PERFORMANCE_RECORD_TABLE; + +/// +/// Generic Timer Description Table definition. +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT64 CntControlBasePhysicalAddress; + UINT32 Reserved; + UINT32 SecurePL1TimerGSIV; + UINT32 SecurePL1TimerFlags; + UINT32 NonSecurePL1TimerGSIV; + UINT32 NonSecurePL1TimerFlags; + UINT32 VirtualTimerGSIV; + UINT32 VirtualTimerFlags; + UINT32 NonSecurePL2TimerGSIV; + UINT32 NonSecurePL2TimerFlags; + UINT64 CntReadBasePhysicalAddress; + UINT32 PlatformTimerCount; + UINT32 PlatformTimerOffset; + UINT32 VirtualPL2TimerGSIV; + UINT32 VirtualPL2TimerFlags; +} EFI_ACPI_6_5_GENERIC_TIMER_DESCRIPTION_TABLE; + +/// +/// GTDT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_GENERIC_TIMER_DESCRIPTION_TABLE_REVISION 0x03 + +/// +/// Timer Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GTDT_TIMER_FLAG_TIMER_INTERRUPT_MODE BIT0 +#define EFI_ACPI_6_5_GTDT_TIMER_FLAG_TIMER_INTERRUPT_POLARITY BIT1 +#define EFI_ACPI_6_5_GTDT_TIMER_FLAG_ALWAYS_ON_CAPABILITY BIT2 + +/// +/// Platform Timer Type +/// +#define EFI_ACPI_6_5_GTDT_GT_BLOCK 0 +#define EFI_ACPI_6_5_GTDT_ARM_GENERIC_WATCHDOG 1 + +/// +/// GT Block Structure +/// +typedef struct { + UINT8 Type; + UINT16 Length; + UINT8 Reserved; + UINT64 CntCtlBase; + UINT32 GTBlockTimerCount; + UINT32 GTBlockTimerOffset; +} EFI_ACPI_6_5_GTDT_GT_BLOCK_STRUCTURE; + +/// +/// GT Block Timer Structure +/// +typedef struct { + UINT8 GTFrameNumber; + UINT8 Reserved[3]; + UINT64 CntBaseX; + UINT64 CntEL0BaseX; + UINT32 GTxPhysicalTimerGSIV; + UINT32 GTxPhysicalTimerFlags; + UINT32 GTxVirtualTimerGSIV; + UINT32 GTxVirtualTimerFlags; + UINT32 GTxCommonFlags; +} EFI_ACPI_6_5_GTDT_GT_BLOCK_TIMER_STRUCTURE; + +/// +/// GT Block Physical Timers and Virtual Timers Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GTDT_GT_BLOCK_TIMER_FLAG_TIMER_INTERRUPT_MODE BIT0 +#define EFI_ACPI_6_5_GTDT_GT_BLOCK_TIMER_FLAG_TIMER_INTERRUPT_POLARITY BIT1 + +/// +/// Common Flags Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GTDT_GT_BLOCK_COMMON_FLAG_SECURE_TIMER BIT0 +#define EFI_ACPI_6_5_GTDT_GT_BLOCK_COMMON_FLAG_ALWAYS_ON_CAPABILITY BIT1 + +/// +/// Arm Generic Watchdog Structure +/// +typedef struct { + UINT8 Type; + UINT16 Length; + UINT8 Reserved; + UINT64 RefreshFramePhysicalAddress; + UINT64 WatchdogControlFramePhysicalAddress; + UINT32 WatchdogTimerGSIV; + UINT32 WatchdogTimerFlags; +} EFI_ACPI_6_5_GTDT_ARM_GENERIC_WATCHDOG_STRUCTURE; + +/// +/// Arm Generic Watchdog Timer Flags. All other bits are reserved and must be 0. +/// +#define EFI_ACPI_6_5_GTDT_ARM_GENERIC_WATCHDOG_FLAG_TIMER_INTERRUPT_MODE BIT0 +#define EFI_ACPI_6_5_GTDT_ARM_GENERIC_WATCHDOG_FLAG_TIMER_INTERRUPT_POLARITY BIT1 +#define EFI_ACPI_6_5_GTDT_ARM_GENERIC_WATCHDOG_FLAG_SECURE_TIMER BIT2 + +// +// NVDIMM Firmware Interface Table definition. +// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 Reserved; +} EFI_ACPI_6_5_NVDIMM_FIRMWARE_INTERFACE_TABLE; + +// +// NFIT Version (as defined in ACPI 6.5 spec.) +// +#define EFI_ACPI_6_5_NVDIMM_FIRMWARE_INTERFACE_TABLE_REVISION 0x1 + +// +// Definition for NFIT Table Structure Types +// +#define EFI_ACPI_6_5_NFIT_SYSTEM_PHYSICAL_ADDRESS_RANGE_STRUCTURE_TYPE 0 +#define EFI_ACPI_6_5_NFIT_NVDIMM_REGION_MAPPING_STRUCTURE_TYPE 1 +#define EFI_ACPI_6_5_NFIT_INTERLEAVE_STRUCTURE_TYPE 2 +#define EFI_ACPI_6_5_NFIT_SMBIOS_MANAGEMENT_INFORMATION_STRUCTURE_TYPE 3 +#define EFI_ACPI_6_5_NFIT_NVDIMM_CONTROL_REGION_STRUCTURE_TYPE 4 +#define EFI_ACPI_6_5_NFIT_NVDIMM_BLOCK_DATA_WINDOW_REGION_STRUCTURE_TYPE 5 +#define EFI_ACPI_6_5_NFIT_FLUSH_HINT_ADDRESS_STRUCTURE_TYPE 6 +#define EFI_ACPI_6_5_NFIT_PLATFORM_CAPABILITIES_STRUCTURE_TYPE 7 + +// +// Definition for NFIT Structure Header +// +typedef struct { + UINT16 Type; + UINT16 Length; +} EFI_ACPI_6_5_NFIT_STRUCTURE_HEADER; + +// +// Definition for System Physical Address Range Structure +// +#define EFI_ACPI_6_5_NFIT_SYSTEM_PHYSICAL_ADDRESS_RANGE_FLAGS_CONTROL_REGION_FOR_MANAGEMENT BIT0 +#define EFI_ACPI_6_5_NFIT_SYSTEM_PHYSICAL_ADDRESS_RANGE_FLAGS_PROXIMITY_DOMAIN_VALID BIT1 +#define EFI_ACPI_6_5_NFIT_SYSTEM_PHYSICAL_ADDRESS_RANGE_FLAGS_SPA_LOCATION_COOKIE_VALID BIT2 + +#define EFI_ACPI_6_5_NFIT_GUID_VOLATILE_MEMORY_REGION { 0x7305944F, 0xFDDA, 0x44E3, { 0xB1, 0x6C, 0x3F, 0x22, 0xD2, 0x52, 0xE5, 0xD0 }} +#define EFI_ACPI_6_5_NFIT_GUID_BYTE_ADDRESSABLE_PERSISTENT_MEMORY_REGION { 0x66F0D379, 0xB4F3, 0x4074, { 0xAC, 0x43, 0x0D, 0x33, 0x18, 0xB7, 0x8C, 0xDB }} +#define EFI_ACPI_6_5_NFIT_GUID_NVDIMM_CONTROL_REGION { 0x92F701F6, 0x13B4, 0x405D, { 0x91, 0x0B, 0x29, 0x93, 0x67, 0xE8, 0x23, 0x4C }} +#define EFI_ACPI_6_5_NFIT_GUID_NVDIMM_BLOCK_DATA_WINDOW_REGION { 0x91AF0530, 0x5D86, 0x470E, { 0xA6, 0xB0, 0x0A, 0x2D, 0xB9, 0x40, 0x82, 0x49 }} +#define EFI_ACPI_6_5_NFIT_GUID_RAM_DISK_SUPPORTING_VIRTUAL_DISK_REGION_VOLATILE { 0x77AB535A, 0x45FC, 0x6.5B, { 0x55, 0x60, 0xF7, 0xB2, 0x81, 0xD1, 0xF9, 0x6E }} +#define EFI_ACPI_6_5_NFIT_GUID_RAM_DISK_SUPPORTING_VIRTUAL_CD_REGION_VOLATILE { 0x3D5ABD30, 0x4175, 0x87CE, { 0x6D, 0x64, 0xD2, 0xAD, 0xE5, 0x23, 0xC4, 0xBB }} +#define EFI_ACPI_6_5_NFIT_GUID_RAM_DISK_SUPPORTING_VIRTUAL_DISK_REGION_PERSISTENT { 0x5CEA02C9, 0x4D07, 0x69D3, { 0x26, 0x9F ,0x44, 0x96, 0xFB, 0xE0, 0x96, 0xF9 }} +#define EFI_ACPI_6_5_NFIT_GUID_RAM_DISK_SUPPORTING_VIRTUAL_CD_REGION_PERSISTENT { 0x08018188, 0x42CD, 0xBB48, { 0x10, 0x0F, 0x53, 0x87, 0xD5, 0x3D, 0xED, 0x3D }} + +typedef struct { + UINT16 Type; + UINT16 Length; + UINT16 SPARangeStructureIndex; + UINT16 Flags; + UINT32 Reserved_8; + UINT32 ProximityDomain; + GUID AddressRangeTypeGUID; + UINT64 SystemPhysicalAddressRangeBase; + UINT64 SystemPhysicalAddressRangeLength; + UINT64 AddressRangeMemoryMappingAttribute; + UINT64 SPALocationCookie; +} EFI_ACPI_6_5_NFIT_SYSTEM_PHYSICAL_ADDRESS_RANGE_STRUCTURE; + +// +// Definition for Memory Device to System Physical Address Range Mapping Structure +// +typedef struct { + UINT32 DIMMNumber : 4; + UINT32 MemoryChannelNumber : 4; + UINT32 MemoryControllerID : 4; + UINT32 SocketID : 4; + UINT32 NodeControllerID : 12; + UINT32 Reserved_28 : 4; +} EFI_ACPI_6_5_NFIT_DEVICE_HANDLE; + +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_PREVIOUS_SAVE_FAIL BIT0 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_LAST_RESTORE_FAIL BIT1 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_PLATFORM_FLUSH_FAIL BIT2 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_NOT_ARMED_PRIOR_TO_OSPM_HAND_OFF BIT3 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_SMART_HEALTH_EVENTS_PRIOR_OSPM_HAND_OFF BIT4 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_FIRMWARE_ENABLED_TO_NOTIFY_OSPM_ON_SMART_HEALTH_EVENTS BIT5 +#define EFI_ACPI_6_5_NFIT_MEMORY_DEVICE_STATE_FLAGS_FIRMWARE_NOT_MAP_NVDIMM_TO_SPA BIT6 + +typedef struct { + UINT16 Type; + UINT16 Length; + EFI_ACPI_6_5_NFIT_DEVICE_HANDLE NFITDeviceHandle; + UINT16 NVDIMMPhysicalID; + UINT16 NVDIMMRegionID; + UINT16 SPARangeStructureIndex; + UINT16 NVDIMMControlRegionStructureIndex; + UINT64 NVDIMMRegionSize; + UINT64 RegionOffset; + UINT64 NVDIMMPhysicalAddressRegionBase; + UINT16 InterleaveStructureIndex; + UINT16 InterleaveWays; + UINT16 NVDIMMStateFlags; + UINT16 Reserved_46; +} EFI_ACPI_6_5_NFIT_NVDIMM_REGION_MAPPING_STRUCTURE; + +// +// Definition for Interleave Structure +// +typedef struct { + UINT16 Type; + UINT16 Length; + UINT16 InterleaveStructureIndex; + UINT16 Reserved_6; + UINT32 NumberOfLines; + UINT32 LineSize; + // UINT32 LineOffset[NumberOfLines]; +} EFI_ACPI_6_5_NFIT_INTERLEAVE_STRUCTURE; + +// +// Definition for SMBIOS Management Information Structure +// +typedef struct { + UINT16 Type; + UINT16 Length; + UINT32 Reserved_4; + // UINT8 Data[]; +} EFI_ACPI_6_5_NFIT_SMBIOS_MANAGEMENT_INFORMATION_STRUCTURE; + +// +// Definition for NVDIMM Control Region Structure +// +#define EFI_ACPI_6_5_NFIT_NVDIMM_CONTROL_REGION_VALID_FIELDS_MANUFACTURING BIT0 + +#define EFI_ACPI_6_5_NFIT_NVDIMM_CONTROL_REGION_FLAGS_BLOCK_DATA_WINDOWS_BUFFERED BIT0 + +typedef struct { + UINT16 Type; + UINT16 Length; + UINT16 NVDIMMControlRegionStructureIndex; + UINT16 VendorID; + UINT16 DeviceID; + UINT16 RevisionID; + UINT16 SubsystemVendorID; + UINT16 SubsystemDeviceID; + UINT16 SubsystemRevisionID; + UINT8 ValidFields; + UINT8 ManufacturingLocation; + UINT16 ManufacturingDate; + UINT8 Reserved_22[2]; + UINT32 SerialNumber; + UINT16 RegionFormatInterfaceCode; + UINT16 NumberOfBlockControlWindows; + UINT64 SizeOfBlockControlWindow; + UINT64 CommandRegisterOffsetInBlockControlWindow; + UINT64 SizeOfCommandRegisterInBlockControlWindows; + UINT64 StatusRegisterOffsetInBlockControlWindow; + UINT64 SizeOfStatusRegisterInBlockControlWindows; + UINT16 NVDIMMControlRegionFlag; + UINT8 Reserved_74[6]; +} EFI_ACPI_6_5_NFIT_NVDIMM_CONTROL_REGION_STRUCTURE; + +// +// Definition for NVDIMM Block Data Window Region Structure +// +typedef struct { + UINT16 Type; + UINT16 Length; + UINT16 NVDIMMControlRegionStructureIndex; + UINT16 NumberOfBlockDataWindows; + UINT64 BlockDataWindowStartOffset; + UINT64 SizeOfBlockDataWindow; + UINT64 BlockAccessibleMemoryCapacity; + UINT64 BeginningAddressOfFirstBlockInBlockAccessibleMemory; +} EFI_ACPI_6_5_NFIT_NVDIMM_BLOCK_DATA_WINDOW_REGION_STRUCTURE; + +// +// Definition for Flush Hint Address Structure +// +typedef struct { + UINT16 Type; + UINT16 Length; + EFI_ACPI_6_5_NFIT_DEVICE_HANDLE NFITDeviceHandle; + UINT16 NumberOfFlushHintAddresses; + UINT8 Reserved_10[6]; + // UINT64 FlushHintAddress[NumberOfFlushHintAddresses]; +} EFI_ACPI_6_5_NFIT_FLUSH_HINT_ADDRESS_STRUCTURE; + +// +// Definition for Platform Capabilities Structure +// +typedef struct { + UINT16 Type; + UINT16 Length; + UINT8 HighestValidCapability; + UINT8 Reserved_5[3]; + UINT32 Capabilities; + UINT8 Reserved_12[4]; +} EFI_ACPI_6_5_NFIT_PLATFORM_CAPABILITIES_STRUCTURE; + +#define EFI_ACPI_6_5_NFIT_PLATFORM_CAPABILITY_CPU_CACHE_FLUSH_TO_NVDIMM_DURABILITY_ON_POWER_LOSS BIT0 +#define EFI_ACPI_6_5_NFIT_PLATFORM_CAPABILITY_MEMORY_CONTROLLER_FLUSH_TO_NVDIMM_DURABILITY_ON_POWER_LOSS BIT1 +#define EFI_ACPI_6_5_NFIT_PLATFORM_CAPABILITY_BYTE_ADDRESSABLE_PERSISTENT_MEMORY_HARDWARE_MIRRORING BIT2 + +/// +/// Secure DEVices Table (SDEV) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; +} EFI_ACPI_6_5_SECURE_DEVICES_TABLE_HEADER; + +/// +/// SDEV Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_SECURE_DEVICES_TABLE_REVISION 0x01 + +/// +/// Secure Device types +/// +#define EFI_ACPI_6_5_SDEV_TYPE_ACPI_NAMESPACE_DEVICE 0x00 +#define EFI_ACPI_6_5_SDEV_TYPE_PCIE_ENDPOINT_DEVICE 0x01 + +/// +/// Secure Device flags +/// +#define EFI_ACPI_6_5_SDEV_FLAG_ALLOW_HANDOFF BIT0 +#define EFI_ACPI_6_5_SDEV_FLAG_SECURE_ACCESS_COMPONENTS_PRESENT BIT1 + +/// +/// SDEV Structure Header +/// +typedef struct { + UINT8 Type; + UINT8 Flags; + UINT16 Length; +} EFI_ACPI_6_5_SDEV_STRUCTURE_HEADER; + +/// +/// ACPI_NAMESPACE_DEVICE based Secure Device Structure +/// +typedef struct { + EFI_ACPI_6_5_SDEV_STRUCTURE_HEADER Header; + UINT16 DeviceIdentifierOffset; + UINT16 DeviceIdentifierLength; + UINT16 VendorSpecificDataOffset; + UINT16 VendorSpecificDataLength; + UINT16 SecureAccessComponentsOffset; + UINT16 SecureAccessComponentsLength; +} EFI_ACPI_6_5_SDEV_STRUCTURE_ACPI_NAMESPACE_DEVICE; + +/// +/// Secure Access Component Types +/// +#define EFI_ACPI_6_5_SDEV_SECURE_ACCESS_COMPONENT_TYPE_IDENTIFICATION 0x00 +#define EFI_ACPI_6_5_SDEV_SECURE_ACCESS_COMPONENT_TYPE_MEMORY 0x01 + +/// +/// Identification Based Secure Access Component +/// +typedef struct { + EFI_ACPI_6_5_SDEV_STRUCTURE_HEADER Header; + UINT16 HardwareIdentifierOffset; + UINT16 HardwareIdentifierLength; + UINT16 SubsystemIdentifierOffset; + UINT16 SubsystemIdentifierLength; + UINT16 HardwareRevision; + UINT8 HardwareRevisionPresent; + UINT8 ClassCodePresent; + UINT8 PciCompatibleBaseClass; + UINT8 PciCompatibleSubClass; + UINT8 PciCompatibleProgrammingInterface; +} EFI_ACPI_6_5_SDEV_SECURE_ACCESS_COMPONENT_IDENTIFICATION_STRUCTURE; + +/// +/// Memory-based Secure Access Component +/// +typedef struct { + EFI_ACPI_6_5_SDEV_STRUCTURE_HEADER Header; + UINT32 Reserved; + UINT64 MemoryAddressBase; + UINT64 MemoryLength; +} EFI_ACPI_6_5_SDEV_SECURE_ACCESS_COMPONENT_MEMORY_STRUCTURE; + +/// +/// PCIe Endpoint Device based Secure Device Structure +/// +typedef struct { + EFI_ACPI_6_5_SDEV_STRUCTURE_HEADER Header; + UINT16 PciSegmentNumber; + UINT16 StartBusNumber; + UINT16 PciPathOffset; + UINT16 PciPathLength; + UINT16 VendorSpecificDataOffset; + UINT16 VendorSpecificDataLength; +} EFI_ACPI_6_5_SDEV_STRUCTURE_PCIE_ENDPOINT_DEVICE; + +/// +/// Boot Error Record Table (BERT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 BootErrorRegionLength; + UINT64 BootErrorRegion; +} EFI_ACPI_6_5_BOOT_ERROR_RECORD_TABLE_HEADER; + +/// +/// BERT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_BOOT_ERROR_RECORD_TABLE_REVISION 0x01 + +/// +/// Boot Error Region Block Status Definition +/// +typedef struct { + UINT32 UncorrectableErrorValid : 1; + UINT32 CorrectableErrorValid : 1; + UINT32 MultipleUncorrectableErrors : 1; + UINT32 MultipleCorrectableErrors : 1; + UINT32 ErrorDataEntryCount : 10; + UINT32 Reserved : 18; +} EFI_ACPI_6_5_ERROR_BLOCK_STATUS; + +/// +/// Boot Error Region Definition +/// +typedef struct { + EFI_ACPI_6_5_ERROR_BLOCK_STATUS BlockStatus; + UINT32 RawDataOffset; + UINT32 RawDataLength; + UINT32 DataLength; + UINT32 ErrorSeverity; +} EFI_ACPI_6_5_BOOT_ERROR_REGION_STRUCTURE; + +// +// Boot Error Severity types +// +#define EFI_ACPI_6_5_ERROR_SEVERITY_RECOVERABLE 0x00 +#define EFI_ACPI_6_5_ERROR_SEVERITY_FATAL 0x01 +#define EFI_ACPI_6_5_ERROR_SEVERITY_CORRECTED 0x02 +#define EFI_ACPI_6_5_ERROR_SEVERITY_NONE 0x03 +// +// The term 'Correctable' is no longer being used as an error severity of the +// reported error since ACPI Specification Version 5.1 Errata B. +// The below macro is considered as deprecated and should no longer be used. +// +#define EFI_ACPI_6_5_ERROR_SEVERITY_CORRECTABLE 0x00 + +/// +/// Generic Error Data Entry Definition +/// +typedef struct { + UINT8 SectionType[16]; + UINT32 ErrorSeverity; + UINT16 Revision; + UINT8 ValidationBits; + UINT8 Flags; + UINT32 ErrorDataLength; + UINT8 FruId[16]; + UINT8 FruText[20]; + UINT8 Timestamp[8]; +} EFI_ACPI_6_5_GENERIC_ERROR_DATA_ENTRY_STRUCTURE; + +/// +/// Generic Error Data Entry Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_GENERIC_ERROR_DATA_ENTRY_REVISION 0x0300 + +/// +/// HEST - Hardware Error Source Table +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 ErrorSourceCount; +} EFI_ACPI_6_5_HARDWARE_ERROR_SOURCE_TABLE_HEADER; + +/// +/// HEST Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_HARDWARE_ERROR_SOURCE_TABLE_REVISION 0x01 + +// +// Error Source structure types. +// +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_EXCEPTION 0x00 +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_CORRECTED_MACHINE_CHECK 0x01 +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_NMI_ERROR 0x02 +#define EFI_ACPI_6_5_PCI_EXPRESS_ROOT_PORT_AER 0x06 +#define EFI_ACPI_6_5_PCI_EXPRESS_DEVICE_AER 0x07 +#define EFI_ACPI_6_5_PCI_EXPRESS_BRIDGE_AER 0x08 +#define EFI_ACPI_6_5_GENERIC_HARDWARE_ERROR 0x09 +#define EFI_ACPI_6_5_GENERIC_HARDWARE_ERROR_VERSION_2 0x0A +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_DEFERRED_MACHINE_CHECK 0x0B + +// +// Error Source structure flags. +// +#define EFI_ACPI_6_5_ERROR_SOURCE_FLAG_FIRMWARE_FIRST (1 << 0) +#define EFI_ACPI_6_5_ERROR_SOURCE_FLAG_GLOBAL (1 << 1) +#define EFI_ACPI_6_5_ERROR_SOURCE_FLAG_GHES_ASSIST (1 << 2) + +/// +/// IA-32 Architecture Machine Check Exception Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT64 GlobalCapabilityInitData; + UINT64 GlobalControlInitData; + UINT8 NumberOfHardwareBanks; + UINT8 Reserved1[7]; +} EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_EXCEPTION_STRUCTURE; + +/// +/// IA-32 Architecture Machine Check Bank Structure Definition +/// +typedef struct { + UINT8 BankNumber; + UINT8 ClearStatusOnInitialization; + UINT8 StatusDataFormat; + UINT8 Reserved0; + UINT32 ControlRegisterMsrAddress; + UINT64 ControlInitData; + UINT32 StatusRegisterMsrAddress; + UINT32 AddressRegisterMsrAddress; + UINT32 MiscRegisterMsrAddress; +} EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_ERROR_BANK_STRUCTURE; + +/// +/// IA-32 Architecture Machine Check Bank Structure MCA data format +/// +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_ERROR_DATA_FORMAT_IA32 0x00 +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_ERROR_DATA_FORMAT_INTEL64 0x01 +#define EFI_ACPI_6_5_IA32_ARCHITECTURE_MACHINE_CHECK_ERROR_DATA_FORMAT_AMD64 0x02 + +// +// Hardware Error Notification types. All other values are reserved +// +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_POLLED 0x00 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_EXTERNAL_INTERRUPT 0x01 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_LOCAL_INTERRUPT 0x02 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_SCI 0x03 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_NMI 0x04 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_CMCI 0x05 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_MCE 0x06 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_GPIO_SIGNAL 0x07 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_ARMV8_SEA 0x08 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_ARMV8_SEI 0x09 +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_GSIV 0x0A +#define EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_SOFTWARE_DELEGATED_EXCEPTION 0x0B + +/// +/// Hardware Error Notification Configuration Write Enable Structure Definition +/// +typedef struct { + UINT16 Type : 1; + UINT16 PollInterval : 1; + UINT16 SwitchToPollingThresholdValue : 1; + UINT16 SwitchToPollingThresholdWindow : 1; + UINT16 ErrorThresholdValue : 1; + UINT16 ErrorThresholdWindow : 1; + UINT16 Reserved : 10; +} EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_CONFIGURATION_WRITE_ENABLE_STRUCTURE; + +/// +/// Hardware Error Notification Structure Definition +/// +typedef struct { + UINT8 Type; + UINT8 Length; + EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_CONFIGURATION_WRITE_ENABLE_STRUCTURE ConfigurationWriteEnable; + UINT32 PollInterval; + UINT32 Vector; + UINT32 SwitchToPollingThresholdValue; + UINT32 SwitchToPollingThresholdWindow; + UINT32 ErrorThresholdValue; + UINT32 ErrorThresholdWindow; +} EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_STRUCTURE; + +/// +/// IA-32 Architecture Corrected Machine Check Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_STRUCTURE NotificationStructure; + UINT8 NumberOfHardwareBanks; + UINT8 Reserved1[3]; +} EFI_ACPI_6_5_IA32_ARCHITECTURE_CORRECTED_MACHINE_CHECK_STRUCTURE; + +/// +/// IA-32 Architecture NMI Error Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 MaxRawDataLength; +} EFI_ACPI_6_5_IA32_ARCHITECTURE_NMI_ERROR_STRUCTURE; + +/// +/// PCI Express Root Port AER Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 Bus; + UINT16 Device; + UINT16 Function; + UINT16 DeviceControl; + UINT8 Reserved1[2]; + UINT32 UncorrectableErrorMask; + UINT32 UncorrectableErrorSeverity; + UINT32 CorrectableErrorMask; + UINT32 AdvancedErrorCapabilitiesAndControl; + UINT32 RootErrorCommand; +} EFI_ACPI_6_5_PCI_EXPRESS_ROOT_PORT_AER_STRUCTURE; + +/// +/// PCI Express Device AER Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 Bus; + UINT16 Device; + UINT16 Function; + UINT16 DeviceControl; + UINT8 Reserved1[2]; + UINT32 UncorrectableErrorMask; + UINT32 UncorrectableErrorSeverity; + UINT32 CorrectableErrorMask; + UINT32 AdvancedErrorCapabilitiesAndControl; +} EFI_ACPI_6_5_PCI_EXPRESS_DEVICE_AER_STRUCTURE; + +/// +/// PCI Express Bridge AER Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 Bus; + UINT16 Device; + UINT16 Function; + UINT16 DeviceControl; + UINT8 Reserved1[2]; + UINT32 UncorrectableErrorMask; + UINT32 UncorrectableErrorSeverity; + UINT32 CorrectableErrorMask; + UINT32 AdvancedErrorCapabilitiesAndControl; + UINT32 SecondaryUncorrectableErrorMask; + UINT32 SecondaryUncorrectableErrorSeverity; + UINT32 SecondaryAdvancedErrorCapabilitiesAndControl; +} EFI_ACPI_6_5_PCI_EXPRESS_BRIDGE_AER_STRUCTURE; + +/// +/// Generic Hardware Error Source Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT16 RelatedSourceId; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 MaxRawDataLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ErrorStatusAddress; + EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_STRUCTURE NotificationStructure; + UINT32 ErrorStatusBlockLength; +} EFI_ACPI_6_5_GENERIC_HARDWARE_ERROR_SOURCE_STRUCTURE; + +/// +/// Generic Hardware Error Source Version 2 Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT16 RelatedSourceId; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + UINT32 MaxRawDataLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ErrorStatusAddress; + EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_STRUCTURE NotificationStructure; + UINT32 ErrorStatusBlockLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ReadAckRegister; + UINT64 ReadAckPreserve; + UINT64 ReadAckWrite; +} EFI_ACPI_6_5_GENERIC_HARDWARE_ERROR_SOURCE_VERSION_2_STRUCTURE; + +/// +/// Generic Error Status Definition +/// +typedef struct { + EFI_ACPI_6_5_ERROR_BLOCK_STATUS BlockStatus; + UINT32 RawDataOffset; + UINT32 RawDataLength; + UINT32 DataLength; + UINT32 ErrorSeverity; +} EFI_ACPI_6_5_GENERIC_ERROR_STATUS_STRUCTURE; + +/// +/// IA-32 Architecture Deferred Machine Check Structure Definition +/// +typedef struct { + UINT16 Type; + UINT16 SourceId; + UINT8 Reserved0[2]; + UINT8 Flags; + UINT8 Enabled; + UINT32 NumberOfRecordsToPreAllocate; + UINT32 MaxSectionsPerRecord; + EFI_ACPI_6_5_HARDWARE_ERROR_NOTIFICATION_STRUCTURE NotificationStructure; + UINT8 NumberOfHardwareBanks; + UINT8 Reserved1[3]; +} EFI_ACPI_6_5_IA32_ARCHITECTURE_DEFERRED_MACHINE_CHECK_STRUCTURE; + +/// +/// HMAT - Heterogeneous Memory Attribute Table +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT8 Reserved[4]; +} EFI_ACPI_6_5_HETEROGENEOUS_MEMORY_ATTRIBUTE_TABLE_HEADER; + +/// +/// HMAT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_HETEROGENEOUS_MEMORY_ATTRIBUTE_TABLE_REVISION 0x02 + +/// +/// HMAT types +/// +#define EFI_ACPI_6_5_HMAT_TYPE_MEMORY_PROXIMITY_DOMAIN_ATTRIBUTES 0x00 +#define EFI_ACPI_6_5_HMAT_TYPE_SYSTEM_LOCALITY_LATENCY_AND_BANDWIDTH_INFO 0x01 +#define EFI_ACPI_6_5_HMAT_TYPE_MEMORY_SIDE_CACHE_INFO 0x02 + +/// +/// HMAT Structure Header +/// +typedef struct { + UINT16 Type; + UINT8 Reserved[2]; + UINT32 Length; +} EFI_ACPI_6_5_HMAT_STRUCTURE_HEADER; + +/// +/// Memory Proximity Domain Attributes Structure flags +/// +typedef struct { + UINT16 InitiatorProximityDomainValid : 1; + UINT16 Reserved : 15; +} EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_PROXIMITY_DOMAIN_ATTRIBUTES_FLAGS; + +/// +/// Memory Proximity Domain Attributes Structure +/// +typedef struct { + UINT16 Type; + UINT8 Reserved[2]; + UINT32 Length; + EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_PROXIMITY_DOMAIN_ATTRIBUTES_FLAGS Flags; + UINT8 Reserved1[2]; + UINT32 InitiatorProximityDomain; + UINT32 MemoryProximityDomain; + UINT8 Reserved2[20]; +} EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_PROXIMITY_DOMAIN_ATTRIBUTES; + +/// +/// System Locality Latency and Bandwidth Information Structure flags +/// +typedef struct { + UINT8 MemoryHierarchy : 4; + UINT8 AccessAttributes : 2; + UINT8 Reserved : 2; +} EFI_ACPI_6_5_HMAT_STRUCTURE_SYSTEM_LOCALITY_LATENCY_AND_BANDWIDTH_INFO_FLAGS; + +/// +/// System Locality Latency and Bandwidth Information Structure +/// +typedef struct { + UINT16 Type; + UINT8 Reserved[2]; + UINT32 Length; + EFI_ACPI_6_5_HMAT_STRUCTURE_SYSTEM_LOCALITY_LATENCY_AND_BANDWIDTH_INFO_FLAGS Flags; + UINT8 DataType; + UINT8 MinTransferSize; + UINT8 Reserved1; + UINT32 NumberOfInitiatorProximityDomains; + UINT32 NumberOfTargetProximityDomains; + UINT8 Reserved2[4]; + UINT64 EntryBaseUnit; +} EFI_ACPI_6_5_HMAT_STRUCTURE_SYSTEM_LOCALITY_LATENCY_AND_BANDWIDTH_INFO; + +/// +/// Memory Side Cache Information Structure cache attributes +/// +typedef struct { + UINT32 TotalCacheLevels : 4; + UINT32 CacheLevel : 4; + UINT32 CacheAssociativity : 4; + UINT32 WritePolicy : 4; + UINT32 CacheLineSize : 16; +} EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_SIDE_CACHE_INFO_CACHE_ATTRIBUTES; + +/// +/// Memory Side Cache Information Structure +/// +typedef struct { + UINT16 Type; + UINT8 Reserved[2]; + UINT32 Length; + UINT32 MemoryProximityDomain; + UINT8 Reserved1[4]; + UINT64 MemorySideCacheSize; + EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_SIDE_CACHE_INFO_CACHE_ATTRIBUTES CacheAttributes; + UINT8 Reserved2[2]; + UINT16 NumberOfSmbiosHandles; +} EFI_ACPI_6_5_HMAT_STRUCTURE_MEMORY_SIDE_CACHE_INFO; + +/// +/// ERST - Error Record Serialization Table +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 SerializationHeaderSize; + UINT8 Reserved0[4]; + UINT32 InstructionEntryCount; +} EFI_ACPI_6_5_ERROR_RECORD_SERIALIZATION_TABLE_HEADER; + +/// +/// ERST Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_ERROR_RECORD_SERIALIZATION_TABLE_REVISION 0x01 + +/// +/// ERST Serialization Actions +/// +#define EFI_ACPI_6_5_ERST_BEGIN_WRITE_OPERATION 0x00 +#define EFI_ACPI_6_5_ERST_BEGIN_READ_OPERATION 0x01 +#define EFI_ACPI_6_5_ERST_BEGIN_CLEAR_OPERATION 0x02 +#define EFI_ACPI_6_5_ERST_END_OPERATION 0x03 +#define EFI_ACPI_6_5_ERST_SET_RECORD_OFFSET 0x04 +#define EFI_ACPI_6_5_ERST_EXECUTE_OPERATION 0x05 +#define EFI_ACPI_6_5_ERST_CHECK_BUSY_STATUS 0x06 +#define EFI_ACPI_6_5_ERST_GET_COMMAND_STATUS 0x07 +#define EFI_ACPI_6_5_ERST_GET_RECORD_IDENTIFIER 0x08 +#define EFI_ACPI_6_5_ERST_SET_RECORD_IDENTIFIER 0x09 +#define EFI_ACPI_6_5_ERST_GET_RECORD_COUNT 0x0A +#define EFI_ACPI_6_5_ERST_BEGIN_DUMMY_WRITE_OPERATION 0x0B +#define EFI_ACPI_6_5_ERST_GET_ERROR_LOG_ADDRESS_RANGE 0x0D +#define EFI_ACPI_6_5_ERST_GET_ERROR_LOG_ADDRESS_RANGE_LENGTH 0x0E +#define EFI_ACPI_6_5_ERST_GET_ERROR_LOG_ADDRESS_RANGE_ATTRIBUTES 0x0F +#define EFI_ACPI_6_5_ERST_GET_EXECUTE_OPERATION_TIMINGS 0x10 + +/// +/// ERST Action Command Status +/// +#define EFI_ACPI_6_5_ERST_STATUS_SUCCESS 0x00 +#define EFI_ACPI_6_5_ERST_STATUS_NOT_ENOUGH_SPACE 0x01 +#define EFI_ACPI_6_5_ERST_STATUS_HARDWARE_NOT_AVAILABLE 0x02 +#define EFI_ACPI_6_5_ERST_STATUS_FAILED 0x03 +#define EFI_ACPI_6_5_ERST_STATUS_RECORD_STORE_EMPTY 0x04 +#define EFI_ACPI_6_5_ERST_STATUS_RECORD_NOT_FOUND 0x05 + +/// +/// ERST Serialization Instructions +/// +#define EFI_ACPI_6_5_ERST_READ_REGISTER 0x00 +#define EFI_ACPI_6_5_ERST_READ_REGISTER_VALUE 0x01 +#define EFI_ACPI_6_5_ERST_WRITE_REGISTER 0x02 +#define EFI_ACPI_6_5_ERST_WRITE_REGISTER_VALUE 0x03 +#define EFI_ACPI_6_5_ERST_NOOP 0x04 +#define EFI_ACPI_6_5_ERST_LOAD_VAR1 0x05 +#define EFI_ACPI_6_5_ERST_LOAD_VAR2 0x06 +#define EFI_ACPI_6_5_ERST_STORE_VAR1 0x07 +#define EFI_ACPI_6_5_ERST_ADD 0x08 +#define EFI_ACPI_6_5_ERST_SUBTRACT 0x09 +#define EFI_ACPI_6_5_ERST_ADD_VALUE 0x0A +#define EFI_ACPI_6_5_ERST_SUBTRACT_VALUE 0x0B +#define EFI_ACPI_6_5_ERST_STALL 0x0C +#define EFI_ACPI_6_5_ERST_STALL_WHILE_TRUE 0x0D +#define EFI_ACPI_6_5_ERST_SKIP_NEXT_INSTRUCTION_IF_TRUE 0x0E +#define EFI_ACPI_6_5_ERST_GOTO 0x0F +#define EFI_ACPI_6_5_ERST_SET_SRC_ADDRESS_BASE 0x10 +#define EFI_ACPI_6_5_ERST_SET_DST_ADDRESS_BASE 0x11 +#define EFI_ACPI_6_5_ERST_MOVE_DATA 0x12 + +/// +/// ERST Instruction Flags +/// +#define EFI_ACPI_6_5_ERST_PRESERVE_REGISTER 0x01 + +/// +/// ERST Serialization Instruction Entry +/// +typedef struct { + UINT8 SerializationAction; + UINT8 Instruction; + UINT8 Flags; + UINT8 Reserved0; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE RegisterRegion; + UINT64 Value; + UINT64 Mask; +} EFI_ACPI_6_5_ERST_SERIALIZATION_INSTRUCTION_ENTRY; + +/// +/// EINJ - Error Injection Table +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 InjectionHeaderSize; + UINT8 InjectionFlags; + UINT8 Reserved0[3]; + UINT32 InjectionEntryCount; +} EFI_ACPI_6_5_ERROR_INJECTION_TABLE_HEADER; + +/// +/// EINJ Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_ERROR_INJECTION_TABLE_REVISION 0x01 + +/// +/// EINJ Error Injection Actions +/// +#define EFI_ACPI_6_5_EINJ_BEGIN_INJECTION_OPERATION 0x00 +#define EFI_ACPI_6_5_EINJ_GET_TRIGGER_ERROR_ACTION_TABLE 0x01 +#define EFI_ACPI_6_5_EINJ_SET_ERROR_TYPE 0x02 +#define EFI_ACPI_6_5_EINJ_GET_ERROR_TYPE 0x03 +#define EFI_ACPI_6_5_EINJ_END_OPERATION 0x04 +#define EFI_ACPI_6_5_EINJ_EXECUTE_OPERATION 0x05 +#define EFI_ACPI_6_5_EINJ_CHECK_BUSY_STATUS 0x06 +#define EFI_ACPI_6_5_EINJ_GET_COMMAND_STATUS 0x07 +#define EFI_ACPI_6_5_EINJ_TRIGGER_ERROR 0xFF + +/// +/// EINJ Action Command Status +/// +#define EFI_ACPI_6_5_EINJ_STATUS_SUCCESS 0x00 +#define EFI_ACPI_6_5_EINJ_STATUS_UNKNOWN_FAILURE 0x01 +#define EFI_ACPI_6_5_EINJ_STATUS_INVALID_ACCESS 0x02 + +/// +/// EINJ Error Type Definition +/// +#define EFI_ACPI_6_5_EINJ_ERROR_PROCESSOR_CORRECTABLE (1 << 0) +#define EFI_ACPI_6_5_EINJ_ERROR_PROCESSOR_UNCORRECTABLE_NONFATAL (1 << 1) +#define EFI_ACPI_6_5_EINJ_ERROR_PROCESSOR_UNCORRECTABLE_FATAL (1 << 2) +#define EFI_ACPI_6_5_EINJ_ERROR_MEMORY_CORRECTABLE (1 << 3) +#define EFI_ACPI_6_5_EINJ_ERROR_MEMORY_UNCORRECTABLE_NONFATAL (1 << 4) +#define EFI_ACPI_6_5_EINJ_ERROR_MEMORY_UNCORRECTABLE_FATAL (1 << 5) +#define EFI_ACPI_6_5_EINJ_ERROR_PCI_EXPRESS_CORRECTABLE (1 << 6) +#define EFI_ACPI_6_5_EINJ_ERROR_PCI_EXPRESS_UNCORRECTABLE_NONFATAL (1 << 7) +#define EFI_ACPI_6_5_EINJ_ERROR_PCI_EXPRESS_UNCORRECTABLE_FATAL (1 << 8) +#define EFI_ACPI_6_5_EINJ_ERROR_PLATFORM_CORRECTABLE (1 << 9) +#define EFI_ACPI_6_5_EINJ_ERROR_PLATFORM_UNCORRECTABLE_NONFATAL (1 << 10) +#define EFI_ACPI_6_5_EINJ_ERROR_PLATFORM_UNCORRECTABLE_FATAL (1 << 11) + +/// +/// EINJ Injection Instructions +/// +#define EFI_ACPI_6_5_EINJ_READ_REGISTER 0x00 +#define EFI_ACPI_6_5_EINJ_READ_REGISTER_VALUE 0x01 +#define EFI_ACPI_6_5_EINJ_WRITE_REGISTER 0x02 +#define EFI_ACPI_6_5_EINJ_WRITE_REGISTER_VALUE 0x03 +#define EFI_ACPI_6_5_EINJ_NOOP 0x04 + +/// +/// EINJ Instruction Flags +/// +#define EFI_ACPI_6_5_EINJ_PRESERVE_REGISTER 0x01 + +/// +/// EINJ Injection Instruction Entry +/// +typedef struct { + UINT8 InjectionAction; + UINT8 Instruction; + UINT8 Flags; + UINT8 Reserved0; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE RegisterRegion; + UINT64 Value; + UINT64 Mask; +} EFI_ACPI_6_5_EINJ_INJECTION_INSTRUCTION_ENTRY; + +/// +/// EINJ Trigger Action Table +/// +typedef struct { + UINT32 HeaderSize; + UINT32 Revision; + UINT32 TableSize; + UINT32 EntryCount; +} EFI_ACPI_6_5_EINJ_TRIGGER_ACTION_TABLE; + +/// +/// Platform Communications Channel Table (PCCT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT32 Flags; + UINT64 Reserved; +} EFI_ACPI_6_5_PLATFORM_COMMUNICATION_CHANNEL_TABLE_HEADER; + +/// +/// PCCT Version (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_PLATFORM_COMMUNICATION_CHANNEL_TABLE_REVISION 0x02 + +/// +/// PCCT Global Flags +/// +#define EFI_ACPI_6_5_PCCT_FLAGS_PLATFORM_INTERRUPT BIT0 + +// +// PCCT Subspace type +// +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_GENERIC 0x00 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_1_HW_REDUCED_COMMUNICATIONS 0x01 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_2_HW_REDUCED_COMMUNICATIONS 0x02 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_3_EXTENDED_PCC 0x03 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC 0x04 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_TYPE_5_HW_REGISTERS_COMMUNICATIONS 0x05 + +/// +/// PCC Subspace Structure Header +/// +typedef struct { + UINT8 Type; + UINT8 Length; +} EFI_ACPI_6_5_PCCT_SUBSPACE_HEADER; + +/// +/// Generic Communications Subspace Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved[6]; + UINT64 BaseAddress; + UINT64 AddressLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE DoorbellRegister; + UINT64 DoorbellPreserve; + UINT64 DoorbellWrite; + UINT32 NominalLatency; + UINT32 MaximumPeriodicAccessRate; + UINT16 MinimumRequestTurnaroundTime; +} EFI_ACPI_6_5_PCCT_SUBSPACE_GENERIC; + +/// +/// Generic Communications Channel Shared Memory Region +/// + +typedef struct { + UINT8 Command; + UINT8 Reserved : 7; + UINT8 NotifyOnCompletion : 1; +} EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_COMMAND; + +typedef struct { + UINT8 CommandComplete : 1; + UINT8 PlatformInterrupt : 1; + UINT8 Error : 1; + UINT8 PlatformNotification : 1; + UINT8 Reserved : 4; + UINT8 Reserved1; +} EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_STATUS; + +typedef struct { + UINT32 Signature; + EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_COMMAND Command; + EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_STATUS Status; +} EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_HEADER; + +#define EFI_ACPI_6_5_PCCT_SUBSPACE_PLATFORM_INTERRUPT_FLAGS_POLARITY BIT0 +#define EFI_ACPI_6_5_PCCT_SUBSPACE_PLATFORM_INTERRUPT_FLAGS_MODE BIT1 + +/// +/// Type 1 HW-Reduced Communications Subspace Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 PlatformInterrupt; + UINT8 PlatformInterruptFlags; + UINT8 Reserved; + UINT64 BaseAddress; + UINT64 AddressLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE DoorbellRegister; + UINT64 DoorbellPreserve; + UINT64 DoorbellWrite; + UINT32 NominalLatency; + UINT32 MaximumPeriodicAccessRate; + UINT16 MinimumRequestTurnaroundTime; +} EFI_ACPI_6_5_PCCT_SUBSPACE_1_HW_REDUCED_COMMUNICATIONS; + +/// +/// Type 2 HW-Reduced Communications Subspace Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 PlatformInterrupt; + UINT8 PlatformInterruptFlags; + UINT8 Reserved; + UINT64 BaseAddress; + UINT64 AddressLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE DoorbellRegister; + UINT64 DoorbellPreserve; + UINT64 DoorbellWrite; + UINT32 NominalLatency; + UINT32 MaximumPeriodicAccessRate; + UINT16 MinimumRequestTurnaroundTime; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE PlatformInterruptAckRegister; + UINT64 PlatformInterruptAckPreserve; + UINT64 PlatformInterruptAckWrite; +} EFI_ACPI_6_5_PCCT_SUBSPACE_2_HW_REDUCED_COMMUNICATIONS; + +/// +/// Type 3 Extended PCC Subspace Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT32 PlatformInterrupt; + UINT8 PlatformInterruptFlags; + UINT8 Reserved; + UINT64 BaseAddress; + UINT32 AddressLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE DoorbellRegister; + UINT64 DoorbellPreserve; + UINT64 DoorbellWrite; + UINT32 NominalLatency; + UINT32 MaximumPeriodicAccessRate; + UINT32 MinimumRequestTurnaroundTime; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE PlatformInterruptAckRegister; + UINT64 PlatformInterruptAckPreserve; + UINT64 PlatformInterruptAckSet; + UINT8 Reserved1[8]; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE CommandCompleteCheckRegister; + UINT64 CommandCompleteCheckMask; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE CommandCompleteUpdateRegister; + UINT64 CommandCompleteUpdatePreserve; + UINT64 CommandCompleteUpdateSet; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ErrorStatusRegister; + UINT64 ErrorStatusMask; +} EFI_ACPI_6_5_PCCT_SUBSPACE_3_EXTENDED_PCC; + +/// +/// Type 4 Extended PCC Subspace Structure +/// +typedef EFI_ACPI_6_5_PCCT_SUBSPACE_3_EXTENDED_PCC EFI_ACPI_6_5_PCCT_SUBSPACE_4_EXTENDED_PCC; + +#define EFI_ACPI_6_5_PCCT_MASTER_SLAVE_COMMUNICATIONS_CHANNEL_FLAGS_NOTIFY_ON_COMPLETION BIT0 + +typedef struct { + UINT32 Signature; + UINT32 Flags; + UINT32 Length; + UINT32 Command; +} EFI_ACPI_6_5_PCCT_EXTENDED_PCC_SHARED_MEMORY_REGION_HEADER; + +/// +/// Type 5 HW Registers based Communications Subspace Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT16 Version; + UINT64 BaseAddress; + UINT64 SharedMemoryRangeLength; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE DoorbellRegister; + UINT64 DoorbellPreserve; + UINT64 DoorbellWrite; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE CommandCompleteCheckRegister; + UINT64 CommandCompleteCheckMask; + EFI_ACPI_6_5_GENERIC_ADDRESS_STRUCTURE ErrorStatusRegister; + UINT64 ErrorStatusMask; + UINT32 NominalLatency; + UINT32 MinimumRequestTurnaroundTime; +} EFI_ACPI_6_5_PCCT_SUBSPACE_5_HW_REGISTERS_COMMUNICATIONS; + +/// +/// Reduced PCC Subspace Shared Memory Region +/// +typedef struct { + UINT32 Signature; + // UINT8 CommunicationSubspace[]; +} EFI_6_5_PCCT_REDUCED_PCC_SUBSPACE_SHARED_MEMORY_REGION; + +/// +/// Platform Debug Trigger Table (PDTT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + UINT8 TriggerCount; + UINT8 Reserved[3]; + UINT32 TriggerIdentifierArrayOffset; +} EFI_ACPI_6_5_PLATFORM_DEBUG_TRIGGER_TABLE_HEADER; + +/// +/// PDTT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_PLATFORM_DEBUG_TRIGGER_TABLE_REVISION 0x00 + +/// +/// PDTT Platform Communication Channel Identifier Structure +/// +typedef struct { + UINT16 SubChannelIdentifer : 8; + UINT16 Runtime : 1; + UINT16 WaitForCompletion : 1; + UINT16 TriggerOrder : 1; + UINT16 Reserved : 5; +} EFI_ACPI_6_5_PDTT_PCC_IDENTIFIER; + +/// +/// PCC Commands Codes used by Platform Debug Trigger Table +/// +#define EFI_ACPI_6_5_PDTT_PCC_COMMAND_DOORBELL_ONLY 0x00 +#define EFI_ACPI_6_5_PDTT_PCC_COMMAND_VENDOR_SPECIFIC 0x01 + +/// +/// PDTT Platform Communication Channel +/// +typedef EFI_ACPI_6_5_PCCT_GENERIC_SHARED_MEMORY_REGION_HEADER EFI_ACPI_6_5_PDTT_PCC; + +/// +/// Processor Properties Topology Table (PPTT) +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; +} EFI_ACPI_6_5_PROCESSOR_PROPERTIES_TOPOLOGY_TABLE_HEADER; + +/// +/// PPTT Revision (as defined in ACPI 6.5 spec.) +/// +#define EFI_ACPI_6_5_PROCESSOR_PROPERTIES_TOPOLOGY_TABLE_REVISION 0x03 + +/// +/// PPTT types +/// +#define EFI_ACPI_6_5_PPTT_TYPE_PROCESSOR 0x00 +#define EFI_ACPI_6_5_PPTT_TYPE_CACHE 0x01 + +/// +/// PPTT Structure Header +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved[2]; +} EFI_ACPI_6_5_PPTT_STRUCTURE_HEADER; + +/// +/// For PPTT struct processor flags +/// +#define EFI_ACPI_6_5_PPTT_PACKAGE_NOT_PHYSICAL 0x0 +#define EFI_ACPI_6_5_PPTT_PACKAGE_PHYSICAL 0x1 +#define EFI_ACPI_6_5_PPTT_PROCESSOR_ID_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_PROCESSOR_ID_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_PROCESSOR_IS_NOT_THREAD 0x0 +#define EFI_ACPI_6_5_PPTT_PROCESSOR_IS_THREAD 0x1 +#define EFI_ACPI_6_5_PPTT_NODE_IS_NOT_LEAF 0x0 +#define EFI_ACPI_6_5_PPTT_NODE_IS_LEAF 0x1 +#define EFI_ACPI_6_5_PPTT_IMPLEMENTATION_NOT_IDENTICAL 0x0 +#define EFI_ACPI_6_5_PPTT_IMPLEMENTATION_IDENTICAL 0x1 + +/// +/// Processor hierarchy node structure flags +/// +typedef struct { + UINT32 PhysicalPackage : 1; + UINT32 AcpiProcessorIdValid : 1; + UINT32 ProcessorIsAThread : 1; + UINT32 NodeIsALeaf : 1; + UINT32 IdenticalImplementation : 1; + UINT32 Reserved : 27; +} EFI_ACPI_6_5_PPTT_STRUCTURE_PROCESSOR_FLAGS; + +/// +/// Processor hierarchy node structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved[2]; + EFI_ACPI_6_5_PPTT_STRUCTURE_PROCESSOR_FLAGS Flags; + UINT32 Parent; + UINT32 AcpiProcessorId; + UINT32 NumberOfPrivateResources; +} EFI_ACPI_6_5_PPTT_STRUCTURE_PROCESSOR; + +/// +/// For PPTT struct cache flags +/// +#define EFI_ACPI_6_5_PPTT_CACHE_SIZE_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_CACHE_SIZE_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_NUMBER_OF_SETS_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_NUMBER_OF_SETS_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_ASSOCIATIVITY_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_ASSOCIATIVITY_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_ALLOCATION_TYPE_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_ALLOCATION_TYPE_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_CACHE_TYPE_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_CACHE_TYPE_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_WRITE_POLICY_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_WRITE_POLICY_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_LINE_SIZE_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_LINE_SIZE_VALID 0x1 +#define EFI_ACPI_6_5_PPTT_CACHE_ID_INVALID 0x0 +#define EFI_ACPI_6_5_PPTT_CACHE_ID_VALID 0x1 + +/// +/// Cache Type Structure flags +/// +typedef struct { + UINT32 SizePropertyValid : 1; + UINT32 NumberOfSetsValid : 1; + UINT32 AssociativityValid : 1; + UINT32 AllocationTypeValid : 1; + UINT32 CacheTypeValid : 1; + UINT32 WritePolicyValid : 1; + UINT32 LineSizeValid : 1; + UINT32 CacheIdValid : 1; + UINT32 Reserved : 24; +} EFI_ACPI_6_5_PPTT_STRUCTURE_CACHE_FLAGS; + +/// +/// For cache attributes +/// +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_ALLOCATION_READ 0x0 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_ALLOCATION_WRITE 0x1 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_ALLOCATION_READ_WRITE 0x2 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_CACHE_TYPE_DATA 0x0 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_CACHE_TYPE_INSTRUCTION 0x1 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_CACHE_TYPE_UNIFIED 0x2 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_WRITE_POLICY_WRITE_BACK 0x0 +#define EFI_ACPI_6_5_CACHE_ATTRIBUTES_WRITE_POLICY_WRITE_THROUGH 0x1 + +/// +/// Cache Type Structure cache attributes +/// +typedef struct { + UINT8 AllocationType : 2; + UINT8 CacheType : 2; + UINT8 WritePolicy : 1; + UINT8 Reserved : 3; +} EFI_ACPI_6_5_PPTT_STRUCTURE_CACHE_ATTRIBUTES; + +/// +/// Cache Type Structure +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Reserved[2]; + EFI_ACPI_6_5_PPTT_STRUCTURE_CACHE_FLAGS Flags; + UINT32 NextLevelOfCache; + UINT32 Size; + UINT32 NumberOfSets; + UINT8 Associativity; + EFI_ACPI_6_5_PPTT_STRUCTURE_CACHE_ATTRIBUTES Attributes; + UINT16 LineSize; + UINT32 CacheId; +} EFI_ACPI_6_5_PPTT_STRUCTURE_CACHE; + +/// +/// Platform Health Assessment Table (PHAT) Format +/// +typedef struct { + EFI_ACPI_DESCRIPTION_HEADER Header; + // UINT8 PlatformTelemetryRecords[]; +} EFI_ACPI_6_5_PLATFORM_HEALTH_ASSESSMENT_TABLE; + +#define EFI_ACPI_6_5_PLATFORM_HEALTH_ASSESSMENT_TABLE_REVISION 0x01 + +/// +/// PHAT Record Format +/// +typedef struct { + UINT16 PlatformHealthAssessmentRecordType; + UINT16 RecordLength; + UINT8 Revision; + // UINT8 Data[]; +} EFI_ACPI_6_5_PHAT_RECORD; + +/// +/// PHAT Record Type Format +/// +#define EFI_ACPI_6_5_PHAT_RECORD_TYPE_FIRMWARE_VERSION_DATA_RECORD 0x0000 +#define EFI_ACPI_6_5_PHAT_RECORD_TYPE_FIRMWARE_HEALTH_DATA_RECORD 0x0001 + +/// +/// PHAT Version Element +/// +typedef struct { + GUID ComponentId; + UINT64 VersionValue; + UINT32 ProducerId; +} EFI_ACPI_6_5_PHAT_VERSION_ELEMENT; + +/// +/// PHAT Firmware Version Data Record +/// +typedef struct { + UINT16 PlatformRecordType; + UINT16 RecordLength; + UINT8 Revision; + UINT8 Reserved[3]; + UINT32 RecordCount; + // UINT8 PhatVersionElement[]; +} EFI_ACPI_6_5_PHAT_FIRMWARE_VERISON_DATA_RECORD; + +#define EFI_ACPI_6_5_PHAT_FIRMWARE_VERSION_DATA_RECORD_REVISION 0x01 + +/// +/// Firmware Health Data Record Structure +/// +typedef struct { + UINT16 PlatformRecordType; + UINT16 RecordLength; + UINT8 Revision; + UINT16 Reserved; + UINT8 AmHealthy; + GUID DeviceSignature; + UINT32 DeviceSpecificDataOffset; + // UINT8 DevicePath[]; + // UINT8 DeviceSpecificData[]; +} EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_STRUCTURE; + +#define EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_REVISION 0x01 + +/// +/// Firmware Health Data Record device health state +/// +#define EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_ERRORS_FOUND 0x00 +#define EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_NO_ERRORS_FOUND 0x01 +#define EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_UNKNOWN 0x02 +#define EFI_ACPI_6_5_PHAT_FIRMWARE_HEALTH_DATA_RECORD_ADVISORY 0x03 + +// +// Known table signatures +// + +/// +/// "RSD PTR " Root System Description Pointer +/// +#define EFI_ACPI_6_5_ROOT_SYSTEM_DESCRIPTION_POINTER_SIGNATURE SIGNATURE_64('R', 'S', 'D', ' ', 'P', 'T', 'R', ' ') + +/// +/// "APIC" Multiple APIC Description Table +/// +#define EFI_ACPI_6_5_MULTIPLE_APIC_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('A', 'P', 'I', 'C') + +/// +/// "APMT" Arm Performance Monitoring Unit Table +/// +#define EFI_ACPI_6_5_ARM_PERFORMANCE_MONITORING_UNIT_TABLE_SIGNATURE SIGNATURE_32('A', 'P', 'M', 'T') + +/// +/// "BERT" Boot Error Record Table +/// +#define EFI_ACPI_6_5_BOOT_ERROR_RECORD_TABLE_SIGNATURE SIGNATURE_32('B', 'E', 'R', 'T') + +/// +/// "BGRT" Boot Graphics Resource Table +/// +#define EFI_ACPI_6_5_BOOT_GRAPHICS_RESOURCE_TABLE_SIGNATURE SIGNATURE_32('B', 'G', 'R', 'T') + +/// +/// "CDIT" Component Distance Information Table +/// +#define EFI_ACPI_6_5_COMPONENT_DISTANCE_INFORMATION_TABLE_SIGNATURE SIGNATURE_32('C', 'D', 'I', 'T') + +/// +/// "CPEP" Corrected Platform Error Polling Table +/// +#define EFI_ACPI_6_5_CORRECTED_PLATFORM_ERROR_POLLING_TABLE_SIGNATURE SIGNATURE_32('C', 'P', 'E', 'P') + +/// +/// "CRAT" Component Resource Attribute Table +/// +#define EFI_ACPI_6_5_COMPONENT_RESOURCE_ATTRIBUTE_TABLE_SIGNATURE SIGNATURE_32('C', 'R', 'A', 'T') + +/// +/// "DSDT" Differentiated System Description Table +/// +#define EFI_ACPI_6_5_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('D', 'S', 'D', 'T') + +/// +/// "ECDT" Embedded Controller Boot Resources Table +/// +#define EFI_ACPI_6_5_EMBEDDED_CONTROLLER_BOOT_RESOURCES_TABLE_SIGNATURE SIGNATURE_32('E', 'C', 'D', 'T') + +/// +/// "EINJ" Error Injection Table +/// +#define EFI_ACPI_6_5_ERROR_INJECTION_TABLE_SIGNATURE SIGNATURE_32('E', 'I', 'N', 'J') + +/// +/// "ERST" Error Record Serialization Table +/// +#define EFI_ACPI_6_5_ERROR_RECORD_SERIALIZATION_TABLE_SIGNATURE SIGNATURE_32('E', 'R', 'S', 'T') + +/// +/// "FACP" Fixed ACPI Description Table +/// +#define EFI_ACPI_6_5_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('F', 'A', 'C', 'P') + +/// +/// "FACS" Firmware ACPI Control Structure +/// +#define EFI_ACPI_6_5_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE SIGNATURE_32('F', 'A', 'C', 'S') + +/// +/// "FPDT" Firmware Performance Data Table +/// +#define EFI_ACPI_6_5_FIRMWARE_PERFORMANCE_DATA_TABLE_SIGNATURE SIGNATURE_32('F', 'P', 'D', 'T') + +/// +/// "GTDT" Generic Timer Description Table +/// +#define EFI_ACPI_6_5_GENERIC_TIMER_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('G', 'T', 'D', 'T') + +/// +/// "HEST" Hardware Error Source Table +/// +#define EFI_ACPI_6_5_HARDWARE_ERROR_SOURCE_TABLE_SIGNATURE SIGNATURE_32('H', 'E', 'S', 'T') + +/// +/// "HMAT" Heterogeneous Memory Attribute Table +/// +#define EFI_ACPI_6_5_HETEROGENEOUS_MEMORY_ATTRIBUTE_TABLE_SIGNATURE SIGNATURE_32('H', 'M', 'A', 'T') + +/// +/// "MPST" Memory Power State Table +/// +#define EFI_ACPI_6_5_MEMORY_POWER_STATE_TABLE_SIGNATURE SIGNATURE_32('M', 'P', 'S', 'T') + +/// +/// "MSCT" Maximum System Characteristics Table +/// +#define EFI_ACPI_6_5_MAXIMUM_SYSTEM_CHARACTERISTICS_TABLE_SIGNATURE SIGNATURE_32('M', 'S', 'C', 'T') + +/// +/// "NFIT" NVDIMM Firmware Interface Table +/// +#define EFI_ACPI_6_5_NVDIMM_FIRMWARE_INTERFACE_TABLE_STRUCTURE_SIGNATURE SIGNATURE_32('N', 'F', 'I', 'T') + +/// +/// "PDTT" Platform Debug Trigger Table +/// +#define EFI_ACPI_6_5_PLATFORM_DEBUG_TRIGGER_TABLE_STRUCTURE_SIGNATURE SIGNATURE_32('P', 'D', 'T', 'T') + +/// +/// "PMTT" Platform Memory Topology Table +/// +#define EFI_ACPI_6_5_PLATFORM_MEMORY_TOPOLOGY_TABLE_SIGNATURE SIGNATURE_32('P', 'M', 'T', 'T') + +/// +/// "PPTT" Processor Properties Topology Table +/// +#define EFI_ACPI_6_5_PROCESSOR_PROPERTIES_TOPOLOGY_TABLE_STRUCTURE_SIGNATURE SIGNATURE_32('P', 'P', 'T', 'T') + +/// +/// "PSDT" Persistent System Description Table +/// +#define EFI_ACPI_6_5_PERSISTENT_SYSTEM_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('P', 'S', 'D', 'T') + +/// +/// "RASF" ACPI RAS Feature Table +/// +#define EFI_ACPI_6_5_ACPI_RAS_FEATURE_TABLE_SIGNATURE SIGNATURE_32('R', 'A', 'S', 'F') + +/// +/// "RSDT" Root System Description Table +/// +#define EFI_ACPI_6_5_ROOT_SYSTEM_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('R', 'S', 'D', 'T') + +/// +/// "SBST" Smart Battery Specification Table +/// +#define EFI_ACPI_6_5_SMART_BATTERY_SPECIFICATION_TABLE_SIGNATURE SIGNATURE_32('S', 'B', 'S', 'T') + +/// +/// "SDEV" Secure DEVices Table +/// +#define EFI_ACPI_6_5_SECURE_DEVICES_TABLE_SIGNATURE SIGNATURE_32('S', 'D', 'E', 'V') + +/// +/// "SLIT" System Locality Information Table +/// +#define EFI_ACPI_6_5_SYSTEM_LOCALITY_INFORMATION_TABLE_SIGNATURE SIGNATURE_32('S', 'L', 'I', 'T') + +/// +/// "SRAT" System Resource Affinity Table +/// +#define EFI_ACPI_6_5_SYSTEM_RESOURCE_AFFINITY_TABLE_SIGNATURE SIGNATURE_32('S', 'R', 'A', 'T') + +/// +/// "SSDT" Secondary System Description Table +/// +#define EFI_ACPI_6_5_SECONDARY_SYSTEM_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('S', 'S', 'D', 'T') + +/// +/// "XSDT" Extended System Description Table +/// +#define EFI_ACPI_6_5_EXTENDED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('X', 'S', 'D', 'T') + +/// +/// "BOOT" MS Simple Boot Spec +/// +#define EFI_ACPI_6_5_SIMPLE_BOOT_FLAG_TABLE_SIGNATURE SIGNATURE_32('B', 'O', 'O', 'T') + +/// +/// "CSRT" MS Core System Resource Table +/// +#define EFI_ACPI_6_5_CORE_SYSTEM_RESOURCE_TABLE_SIGNATURE SIGNATURE_32('C', 'S', 'R', 'T') + +/// +/// "DBG2" MS Debug Port 2 Spec +/// +#define EFI_ACPI_6_5_DEBUG_PORT_2_TABLE_SIGNATURE SIGNATURE_32('D', 'B', 'G', '2') + +/// +/// "DBGP" MS Debug Port Spec +/// +#define EFI_ACPI_6_5_DEBUG_PORT_TABLE_SIGNATURE SIGNATURE_32('D', 'B', 'G', 'P') + +/// +/// "DMAR" DMA Remapping Table +/// +#define EFI_ACPI_6_5_DMA_REMAPPING_TABLE_SIGNATURE SIGNATURE_32('D', 'M', 'A', 'R') + +/// +/// "DRTM" Dynamic Root of Trust for Measurement Table +/// +#define EFI_ACPI_6_5_DYNAMIC_ROOT_OF_TRUST_FOR_MEASUREMENT_TABLE_SIGNATURE SIGNATURE_32('D', 'R', 'T', 'M') + +/// +/// "ETDT" Event Timer Description Table +/// +#define EFI_ACPI_6_5_EVENT_TIMER_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('E', 'T', 'D', 'T') + +/// +/// "HPET" IA-PC High Precision Event Timer Table +/// +#define EFI_ACPI_6_5_HIGH_PRECISION_EVENT_TIMER_TABLE_SIGNATURE SIGNATURE_32('H', 'P', 'E', 'T') + +/// +/// "iBFT" iSCSI Boot Firmware Table +/// +#define EFI_ACPI_6_5_ISCSI_BOOT_FIRMWARE_TABLE_SIGNATURE SIGNATURE_32('i', 'B', 'F', 'T') + +/// +/// "IORT" I/O Remapping Table +/// +#define EFI_ACPI_6_5_IO_REMAPPING_TABLE_SIGNATURE SIGNATURE_32('I', 'O', 'R', 'T') + +/// +/// "IVRS" I/O Virtualization Reporting Structure +/// +#define EFI_ACPI_6_5_IO_VIRTUALIZATION_REPORTING_STRUCTURE_SIGNATURE SIGNATURE_32('I', 'V', 'R', 'S') + +/// +/// "LPIT" Low Power Idle Table +/// +#define EFI_ACPI_6_5_LOW_POWER_IDLE_TABLE_STRUCTURE_SIGNATURE SIGNATURE_32('L', 'P', 'I', 'T') + +/// +/// "MCFG" PCI Express Memory Mapped Configuration Space Base Address Description Table +/// +#define EFI_ACPI_6_5_PCI_EXPRESS_MEMORY_MAPPED_CONFIGURATION_SPACE_BASE_ADDRESS_DESCRIPTION_TABLE_SIGNATURE SIGNATURE_32('M', 'C', 'F', 'G') + +/// +/// "MCHI" Management Controller Host Interface Table +/// +#define EFI_ACPI_6_5_MANAGEMENT_CONTROLLER_HOST_INTERFACE_TABLE_SIGNATURE SIGNATURE_32('M', 'C', 'H', 'I') + +/// +/// "MSDM" MS Data Management Table +/// +#define EFI_ACPI_6_5_DATA_MANAGEMENT_TABLE_SIGNATURE SIGNATURE_32('M', 'S', 'D', 'M') + +/// +/// "PCCT" Platform Communications Channel Table +/// +#define EFI_ACPI_6_5_PLATFORM_COMMUNICATIONS_CHANNEL_TABLE_SIGNATURE SIGNATURE_32('P', 'C', 'C', 'T') + +/// +/// "PHAT" Platform Health Assessment Table +/// +#define EFI_ACPI_6_5_PLATFORM_HEALTH_ASSESSMENT_TABLE_SIGNATURE SIGNATURE_32('P', 'H', 'A', 'T') + +/// +/// "SDEI" Software Delegated Exceptions Interface Table +/// +#define EFI_ACPI_6_5_SOFTWARE_DELEGATED_EXCEPTIONS_INTERFACE_TABLE_SIGNATURE SIGNATURE_32('S', 'D', 'E', 'I') + +/// +/// "SLIC" MS Software Licensing Table Specification +/// +#define EFI_ACPI_6_5_SOFTWARE_LICENSING_TABLE_SIGNATURE SIGNATURE_32('S', 'L', 'I', 'C') + +/// +/// "SPCR" Serial Port Concole Redirection Table +/// +#define EFI_ACPI_6_5_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_SIGNATURE SIGNATURE_32('S', 'P', 'C', 'R') + +/// +/// "SPMI" Server Platform Management Interface Table +/// +#define EFI_ACPI_6_5_SERVER_PLATFORM_MANAGEMENT_INTERFACE_TABLE_SIGNATURE SIGNATURE_32('S', 'P', 'M', 'I') + +/// +/// "STAO" _STA Override Table +/// +#define EFI_ACPI_6_5_STA_OVERRIDE_TABLE_SIGNATURE SIGNATURE_32('S', 'T', 'A', 'O') + +/// +/// "TCPA" Trusted Computing Platform Alliance Capabilities Table +/// +#define EFI_ACPI_6_5_TRUSTED_COMPUTING_PLATFORM_ALLIANCE_CAPABILITIES_TABLE_SIGNATURE SIGNATURE_32('T', 'C', 'P', 'A') + +/// +/// "TPM2" Trusted Computing Platform 1 Table +/// +#define EFI_ACPI_6_5_TRUSTED_COMPUTING_PLATFORM_2_TABLE_SIGNATURE SIGNATURE_32('T', 'P', 'M', '2') + +/// +/// "UEFI" UEFI ACPI Data Table +/// +#define EFI_ACPI_6_5_UEFI_ACPI_DATA_TABLE_SIGNATURE SIGNATURE_32('U', 'E', 'F', 'I') + +/// +/// "WAET" Windows ACPI Emulated Devices Table +/// +#define EFI_ACPI_6_5_WINDOWS_ACPI_EMULATED_DEVICES_TABLE_SIGNATURE SIGNATURE_32('W', 'A', 'E', 'T') + +/// +/// "WDAT" Watchdog Action Table +/// +#define EFI_ACPI_6_5_WATCHDOG_ACTION_TABLE_SIGNATURE SIGNATURE_32('W', 'D', 'A', 'T') + +/// +/// "WDRT" Watchdog Resource Table +/// +#define EFI_ACPI_6_5_WATCHDOG_RESOURCE_TABLE_SIGNATURE SIGNATURE_32('W', 'D', 'R', 'T') + +/// +/// "WPBT" MS Platform Binary Table +/// +#define EFI_ACPI_6_5_PLATFORM_BINARY_TABLE_SIGNATURE SIGNATURE_32('W', 'P', 'B', 'T') + +/// +/// "WSMT" Windows SMM Security Mitigation Table +/// +#define EFI_ACPI_6_5_WINDOWS_SMM_SECURITY_MITIGATION_TABLE_SIGNATURE SIGNATURE_32('W', 'S', 'M', 'T') + +/// +/// "XENV" Xen Project Table +/// +#define EFI_ACPI_6_5_XEN_PROJECT_TABLE_SIGNATURE SIGNATURE_32('X', 'E', 'N', 'V') + +#pragma pack() + +#endif From 5477eb01887849cc74e6985567219ea914fab75e Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 17 Jan 2023 16:39:11 +0800 Subject: [PATCH 0562/1529] MdePkg: Added serveral tables to MATD used by LoongArch64 Add CORE_PIC, LIO_PIC, HT_PIC, EIO_PIC, MSI_PIC, BIO_PIC and LPC_PIC tables for LoongArch64 as defined in ACPI SPEC 6.5. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4306 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/Acpi65.h | 95 +++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/IndustryStandard/Acpi65.h b/MdePkg/Include/IndustryStandard/Acpi65.h index fdca5316a9..1e41ae9a27 100644 --- a/MdePkg/Include/IndustryStandard/Acpi65.h +++ b/MdePkg/Include/IndustryStandard/Acpi65.h @@ -303,7 +303,7 @@ typedef struct { // // Multiple APIC Description Table APIC structure types -// All other values between 0x10 and 0x7F are reserved and +// All other values between 0x18 and 0x7F are reserved and // will be ignored by OSPM. 0x80 ~ 0xFF are reserved for OEM. // #define EFI_ACPI_6_5_PROCESSOR_LOCAL_APIC 0x00 @@ -323,6 +323,13 @@ typedef struct { #define EFI_ACPI_6_5_GICR 0x0E #define EFI_ACPI_6_5_GIC_ITS 0x0F #define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP 0x10 +#define EFI_ACPI_6_5_CORE_PIC 0x11 +#define EFI_ACPI_6_5_LIO_PIC 0x12 +#define EFI_ACPI_6_5_HT_PIC 0x13 +#define EFI_ACPI_6_5_EIO_PIC 0x14 +#define EFI_ACPI_6_5_MSI_PIC 0x15 +#define EFI_ACPI_6_5_BIO_PIC 0x16 +#define EFI_ACPI_6_5_LPC_PIC 0x17 // // APIC Structure Definitions @@ -617,6 +624,92 @@ typedef struct { #define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_MAILBOX_COMMAND_NOOP 0x0000 #define EFI_ACPI_6_5_MULTIPROCESSOR_WAKEUP_MAILBOX_COMMAND_WAKEUP 0x0001 +/// +/// Core Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT32 ProcessorId; + UINT32 CoreId; + UINT32 Flags; +} EFI_ACPI_6_5_CORE_PIC_STRUCTURE; + +/// +/// Legacy I/O Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT64 Address; + UINT16 Size; + UINT8 Cascade[2]; + UINT32 CascadeMap[2]; +} EFI_ACPI_6_5_LIO_PIC_STRUCTURE; + +/// +/// HyperTransport Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT64 Address; + UINT16 Size; + UINT8 Cascade[8]; +} EFI_ACPI_6_5_HT_PIC_STRUCTURE; + +/// +/// Extend I/O Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT8 Cascade; + UINT8 Node; + UINT64 NodeMap; +} EFI_ACPI_6_5_EIO_PIC_STRUCTURE; + +/// +/// MSI Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT64 MsgAddress; + UINT32 Start; + UINT32 Count; +} EFI_ACPI_6_5_MSI_PIC_STRUCTURE; + +/// +/// Bridge I/O Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT64 Address; + UINT16 Size; + UINT16 Id; + UINT16 GsiBase; +} EFI_ACPI_6_5_BIO_PIC_STRUCTURE; + +/// +/// Low Pin Count Programmable Interrupt Controller +/// +typedef struct { + UINT8 Type; + UINT8 Length; + UINT8 Version; + UINT64 Address; + UINT16 Size; + UINT8 Cascade; +} EFI_ACPI_6_5_LPC_PIC_STRUCTURE; + /// /// Smart Battery Description Table (SBST) /// From f46003d9df265931e18ff3dadaf3c940082bba80 Mon Sep 17 00:00:00 2001 From: KasimX Liu Date: Tue, 17 Jan 2023 17:09:11 +0800 Subject: [PATCH 0563/1529] UefiPayloadPkg: Set RTC dynamic PCD to PeiPCDdatabase REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4193 In order to remove RTC_INDEX/RTC_TARGET from the UplBuild macro list,change the RTC_INDEX /RTC_TARGET type from PcdsFixedAtBuild to PcdsDynamicEx Reviewed-by: Guo Dong Cc: Ray Ni Cc: James Lu Reviewed-by: Gua Guo Signed-off-by: KasimX Liu --- UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf index 73f76064a0..06e83dbadc 100644 --- a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf +++ b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf @@ -37,6 +37,7 @@ [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec + PcAtChipsetPkg/PcAtChipsetPkg.dec UefiPayloadPkg/UefiPayloadPkg.dec [LibraryClasses] @@ -52,6 +53,10 @@ [Ppis] gEfiPeiLoadFilePpiGuid ## PRODUCES +[Pcd] + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister + [Guids] gUniversalPayloadExtraDataGuid ## PRODUCES From bd5da82cd256ef4d1c6e1c8309a95048aa131785 Mon Sep 17 00:00:00 2001 From: Chao Li Date: Tue, 31 Jan 2023 18:27:40 +0800 Subject: [PATCH 0564/1529] MdePkg: Fix UINT64 and INT64 word length for LoongArch64 The UINT64 and INT64 should be defined as unsigned long long and long long in the linux64 bit environment, but now defined as unsigned long and long, so fix it. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4330 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chao Li Reviewed-by: Michael D Kinney --- MdePkg/Include/LoongArch64/ProcessorBind.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/MdePkg/Include/LoongArch64/ProcessorBind.h b/MdePkg/Include/LoongArch64/ProcessorBind.h index 502d479099..7064fd1e7c 100644 --- a/MdePkg/Include/LoongArch64/ProcessorBind.h +++ b/MdePkg/Include/LoongArch64/ProcessorBind.h @@ -28,17 +28,17 @@ // Assume standard LoongArch 64-bit alignment. // Need to check portability of long long // -typedef unsigned long UINT64; -typedef long INT64; -typedef unsigned int UINT32; -typedef int INT32; -typedef unsigned short UINT16; -typedef unsigned short CHAR16; -typedef short INT16; -typedef unsigned char BOOLEAN; -typedef unsigned char UINT8; -typedef char CHAR8; -typedef char INT8; +typedef unsigned long long UINT64; +typedef long long INT64; +typedef unsigned int UINT32; +typedef int INT32; +typedef unsigned short UINT16; +typedef unsigned short CHAR16; +typedef short INT16; +typedef unsigned char BOOLEAN; +typedef unsigned char UINT8; +typedef char CHAR8; +typedef char INT8; // // Unsigned value of native width. (4 bytes on supported 32-bit processor instructions, From 687cccbf0b5a5984e9b1149c98d0ea189d4d5aa9 Mon Sep 17 00:00:00 2001 From: Yuan Yu Date: Tue, 31 Jan 2023 14:03:47 +0800 Subject: [PATCH 0565/1529] MdeModulePkg: ScsiBusDxe: Refactor DiscoverScsiDevice() Currently DiscoverScsiDevice() returns a boolean which cannot distinguish a "not found" situation from a real problem like memory allocation failures. This patch changes the return value to an EFI_STATUS so that when memory allocation fails, it will return EFI_OUT_OF_RESOURCES. Without this change, any FALSE returned by DiscoverScsiDevice() will result in EFI_OUT_OF_RESOURCES being returned by ScsiScanCreateDevice(), which will cause a while loop in SCSIBusDriverBindingStart() to abort before other possible Puns in the SCSI channel are scanned, which means good devices may not have a chance to be discovered. If this good device is the boot device, boot will fail. Cc: Ard Biesheuvel Cc: Liming Gao Cc: Hao A Wu Cc: Ray Ni Cc: Sivaparvathi chellaiah Signed-off-by: Yuan Yu Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c | 33 +++++++++++----------- MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h | 10 ++++--- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c index fbe14c7724..d6c965def3 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c @@ -1105,7 +1105,8 @@ ScsiExecuteSCSICommand ( @retval EFI_SUCCESS Successfully to discover the device and attach ScsiIoProtocol to it. - @retval EFI_OUT_OF_RESOURCES Fail to discover the device. + @retval EFI_NOT_FOUND Fail to discover the device. + @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resources. **/ EFI_STATUS @@ -1210,8 +1211,8 @@ ScsiScanCreateDevice ( ScsiBusDev->DevicePath ); - if (!DiscoverScsiDevice (ScsiIoDevice)) { - Status = EFI_OUT_OF_RESOURCES; + Status = DiscoverScsiDevice (ScsiIoDevice); + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -1276,11 +1277,12 @@ ScsiScanCreateDevice ( @param ScsiIoDevice The pointer of SCSI_IO_DEV - @retval TRUE Find SCSI Device and verify it. - @retval FALSE Unable to find SCSI Device. + @retval EFI_SUCCESS Find SCSI Device and verify it. + @retval EFI_NOT_FOUND Unable to find SCSI Device. + @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resources. **/ -BOOLEAN +EFI_STATUS DiscoverScsiDevice ( IN OUT SCSI_IO_DEV *ScsiIoDevice ) @@ -1294,7 +1296,6 @@ DiscoverScsiDevice ( EFI_SCSI_SENSE_DATA *SenseData; UINT8 MaxRetry; UINT8 Index; - BOOLEAN ScsiDeviceFound; HostAdapterStatus = 0; TargetStatus = 0; @@ -1302,7 +1303,7 @@ DiscoverScsiDevice ( InquiryData = AllocateAlignedBuffer (ScsiIoDevice, sizeof (EFI_SCSI_INQUIRY_DATA)); if (InquiryData == NULL) { - ScsiDeviceFound = FALSE; + Status = EFI_OUT_OF_RESOURCES; goto Done; } @@ -1311,7 +1312,7 @@ DiscoverScsiDevice ( sizeof (EFI_SCSI_SENSE_DATA) ); if (SenseData == NULL) { - ScsiDeviceFound = FALSE; + Status = EFI_OUT_OF_RESOURCES; goto Done; } @@ -1342,7 +1343,7 @@ DiscoverScsiDevice ( (SenseData->Error_Code == 0x70) && (SenseData->Sense_Key == EFI_SCSI_SK_ILLEGAL_REQUEST)) { - ScsiDeviceFound = FALSE; + Status = EFI_NOT_FOUND; goto Done; } @@ -1353,13 +1354,13 @@ DiscoverScsiDevice ( (Status == EFI_INVALID_PARAMETER) || (Status == EFI_UNSUPPORTED)) { - ScsiDeviceFound = FALSE; + Status = EFI_NOT_FOUND; goto Done; } } if (Index == MaxRetry) { - ScsiDeviceFound = FALSE; + Status = EFI_NOT_FOUND; goto Done; } @@ -1367,14 +1368,14 @@ DiscoverScsiDevice ( // Retrieved inquiry data successfully // if (InquiryData->Peripheral_Qualifier != 0) { - ScsiDeviceFound = FALSE; + Status = EFI_NOT_FOUND; goto Done; } if ((InquiryData->Peripheral_Type >= EFI_SCSI_TYPE_RESERVED_LOW) && (InquiryData->Peripheral_Type <= EFI_SCSI_TYPE_RESERVED_HIGH)) { - ScsiDeviceFound = FALSE; + Status = EFI_NOT_FOUND; goto Done; } @@ -1392,13 +1393,13 @@ DiscoverScsiDevice ( ScsiIoDevice->ScsiVersion = (UINT8)(InquiryData->Version & 0x07); } - ScsiDeviceFound = TRUE; + Status = EFI_SUCCESS; Done: FreeAlignedBuffer (SenseData, sizeof (EFI_SCSI_SENSE_DATA)); FreeAlignedBuffer (InquiryData, sizeof (EFI_SCSI_INQUIRY_DATA)); - return ScsiDeviceFound; + return Status; } /** diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h index 68c5c02a91..35a8a46ca7 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h @@ -455,7 +455,8 @@ ScsiExecuteSCSICommand ( @retval EFI_SUCCESS Successfully to discover the device and attach ScsiIoProtocol to it. - @retval EFI_OUT_OF_RESOURCES Fail to discover the device. + @retval EFI_NOT_FOUND Fail to discover the device. + @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resources. **/ EFI_STATUS @@ -473,11 +474,12 @@ ScsiScanCreateDevice ( @param ScsiIoDevice The pointer of SCSI_IO_DEV - @retval TRUE Find SCSI Device and verify it. - @retval FALSE Unable to find SCSI Device. + @retval EFI_SUCCESS Find SCSI Device and verify it. + @retval EFI_NOT_FOUND Unable to find SCSI Device. + @retval EFI_OUT_OF_RESOURCES Fail to allocate memory resources. **/ -BOOLEAN +EFI_STATUS DiscoverScsiDevice ( IN OUT SCSI_IO_DEV *ScsiIoDevice ); From 9f74382e55e6b8ea3398d25d6cf13d0a9aa06b36 Mon Sep 17 00:00:00 2001 From: Jeshua Smith Date: Thu, 3 Nov 2022 18:14:26 +0000 Subject: [PATCH 0566/1529] ShellPkg/AcpiView: ERST Parser Add a new parser for the Error Record Serialization Table. The ERST table describes how an OS can save and retrieve hardware error information to and from a persistent store. Signed-off-by: Jeshua Smith Reviewed-by: Zhichao Gao --- .../UefiShellAcpiViewCommandLib/AcpiParser.h | 22 ++ .../Parsers/Erst/ErstParser.c | 278 ++++++++++++++++++ .../UefiShellAcpiViewCommandLib.c | 2 + .../UefiShellAcpiViewCommandLib.inf | 2 + 4 files changed, 304 insertions(+) create mode 100644 ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Erst/ErstParser.c diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h index 6a1de4e12b..4b4397961b 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h @@ -1,6 +1,7 @@ /** @file Header file for ACPI parser + Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. Copyright (c) 2016 - 2020, Arm Limited. All rights reserved. Copyright (c) 2022, AMD Incorporated. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -615,6 +616,27 @@ ParseAcpiDsdt ( IN UINT8 AcpiTableRevision ); +/** + This function parses the ACPI ERST table. + When trace is enabled this function parses the ERST table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiErst ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ); + /** This function parses the ACPI FACS table. When trace is enabled this function parses the FACS table and diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Erst/ErstParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Erst/ErstParser.c new file mode 100644 index 0000000000..f3ae09309c --- /dev/null +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Erst/ErstParser.c @@ -0,0 +1,278 @@ +/** @file + ERST table parser + + Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + Copyright (c) 2016 - 2018, ARM Limited. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.5 Specification - August 2022 +**/ + +#include +#include +#include "AcpiParser.h" +#include "AcpiTableParser.h" + +// Local variables +STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; +STATIC UINT32 *InstructionEntryCount; + +/** + An array of strings describing the Erst actions +**/ +STATIC CONST CHAR16 *ErstActionTable[] = { + L"BEGIN_WRITE_OPERATION", + L"BEGIN_READ_OPERATION", + L"BEGIN_CLEAR_OPERATION", + L"END_OPERATION", + L"SET_RECORD_OFFSET", + L"EXECUTE_OPERATION", + L"CHECK_BUSY_STATUS", + L"GET_COMMAND_STATUS", + L"GET_RECORD_IDENTIFIER", + L"SET_RECORD_IDENTIFIER", + L"GET_RECORD_COUNT", + L"BEGIN_DUMMY_WRITE_OPERATION", + L"RESERVED", + L"GET_ERROR_LOG_ADDRESS_RANGE", + L"GET_ERROR_LOG_ADDRESS_RANGE_LENGTH", + L"GET_ERROR_LOG_ADDRESS_RANGE_ATTRIBUTES", + L"GET_EXECUTE_OPERATION_TIMINGS" +}; + +/** + An array of strings describing the Erst instructions +**/ +STATIC CONST CHAR16 *ErstInstructionTable[] = { + L"READ_REGISTER", + L"READ_REGISTER_VALUE", + L"WRITE_REGISTER", + L"WRITE_REGISTER_VALUE", + L"NOOP", + L"LOAD_VAR1", + L"LOAD_VAR2", + L"STORE_VAR1", + L"ADD", + L"SUBTRACT", + L"ADD_VALUE", + L"SUBTRACT_VALUE", + L"STALL", + L"STALL_WHILE_TRUE", + L"SKIP_NEXT_INSTRUCTION_IF_TRUE", + L"GOTO", + L"SET_SRC_ADDRESS_BASE", + L"SET_DST_ADDRESS_BASE", + L"MOVE_DATA" +}; + +/** + Validate Erst action. + + @param [in] Ptr Pointer to the start of the field data. + @param [in] Context Pointer to context specific information e.g. this + could be a pointer to the ACPI table header. +**/ +STATIC +VOID +EFIAPI +ValidateErstAction ( + IN UINT8 *Ptr, + IN VOID *Context + ) +{ + if (*Ptr > EFI_ACPI_6_4_ERST_GET_EXECUTE_OPERATION_TIMINGS) { + IncrementErrorCount (); + Print (L"\nError: 0x%02x is not a valid action encoding", *Ptr); + } +} + +/** + Validate Erst instruction. + + @param [in] Ptr Pointer to the start of the field data. + @param [in] Context Pointer to context specific information e.g. this + could be a pointer to the ACPI table header. +**/ +STATIC +VOID +EFIAPI +ValidateErstInstruction ( + IN UINT8 *Ptr, + IN VOID *Context + ) +{ + if (*Ptr > EFI_ACPI_6_4_ERST_MOVE_DATA) { + IncrementErrorCount (); + Print (L"\nError: 0x%02x is not a valid instruction encoding", *Ptr); + } +} + +/** + Validate Erst flags. + + @param [in] Ptr Pointer to the start of the field data. + @param [in] Context Pointer to context specific information e.g. this + could be a pointer to the ACPI table header. +**/ +STATIC +VOID +EFIAPI +ValidateErstFlags ( + IN UINT8 *Ptr, + IN VOID *Context + ) +{ + if ((*Ptr & 0xfe) != 0) { + IncrementErrorCount (); + Print (L"\nError: Reserved Flag bits not set to 0"); + } +} + +/** + Looks up and prints the string corresponding to the index. + + @param [in] Table Lookup table. + @param [in] Index Entry to print. + @param [in] NumEntries Number of valid entries in the table. +**/ +STATIC +VOID +EFIAPI +FormatByte ( + IN CONST CHAR16 *Table[], + IN UINT8 Index, + IN UINT8 NumEntries + ) +{ + CONST CHAR16 *String; + + if (Index < NumEntries) { + String = Table[Index]; + } else { + String = L"**INVALID**"; + } + + Print ( + L"0x%02x (%s)", + Index, + String + ); +} + +/** + Prints the Erst Action. + + @param [in] Format Optional format string for tracing the data. + @param [in] Ptr Pointer to the Action byte. +**/ +STATIC +VOID +EFIAPI +DumpErstAction ( + IN CONST CHAR16 *Format OPTIONAL, + IN UINT8 *Ptr + ) +{ + FormatByte (ErstActionTable, *Ptr, ARRAY_SIZE (ErstActionTable)); +} + +/** + Prints the Erst Instruction. + + @param [in] Format Optional format string for tracing the data. + @param [in] Ptr Pointer to the Instruction byte. +**/ +STATIC +VOID +EFIAPI +DumpErstInstruction ( + IN CONST CHAR16 *Format OPTIONAL, + IN UINT8 *Ptr + ) +{ + FormatByte (ErstInstructionTable, *Ptr, ARRAY_SIZE (ErstInstructionTable)); +} + +/** + An ACPI_PARSER array describing the ACPI ERST Table. +**/ +STATIC CONST ACPI_PARSER ErstParser[] = { + PARSE_ACPI_HEADER (&AcpiHdrInfo), + { L"Serialization Header Size", 4, 36, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Reserved", 4, 40, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Instruction Entry Count", 4, 44, L"0x%x", NULL, (VOID **)&InstructionEntryCount, NULL, NULL } +}; + +/** + An ACPI_PARSER array describing the Serialization Instruction Entry structure. +**/ +STATIC CONST ACPI_PARSER SerializationInstructionEntryParser[] = { + { L"Serialization Action", 1, 0, L"0x%x", DumpErstAction, NULL, ValidateErstAction, NULL }, + { L"Instruction", 1, 1, L"0x%x", DumpErstInstruction, NULL, ValidateErstInstruction, NULL }, + { L"Flags", 1, 2, L"0x%x", NULL, NULL, ValidateErstFlags, NULL }, + { L"Reserved", 1, 3, L"0x%x", NULL, NULL, NULL, NULL }, + { L"Register Region", 12, 4, NULL, DumpGas, NULL, NULL, NULL }, + { L"Value", 8, 16, L"0x%llx", NULL, NULL, NULL, NULL }, + { L"Mask", 8, 24, L"0x%llx", NULL, NULL, NULL, NULL } +}; + +/** + This function parses the ACPI ERST table. + When trace is enabled this function parses the ERST table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiErst ( + IN BOOLEAN Trace, + IN UINT8 *Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ) +{ + UINT32 Offset; + + if (!Trace) { + return; + } + + Offset = ParseAcpi ( + Trace, + 0, + "ERST", + Ptr, + AcpiTableLength, + PARSER_PARAMS (ErstParser) + ); + + if (sizeof (EFI_ACPI_6_4_ERST_SERIALIZATION_INSTRUCTION_ENTRY)*(*InstructionEntryCount) != (AcpiTableLength - Offset)) { + IncrementErrorCount (); + Print ( + L"ERROR: Invalid InstructionEntryCount. " \ + L"Count = %d. Offset = %d. AcpiTableLength = %d.\n", + *InstructionEntryCount, + Offset, + AcpiTableLength + ); + return; + } + + while (Offset < AcpiTableLength) { + Offset += ParseAcpi ( + Trace, + 2, + "Serialization Action", + Ptr + Offset, + (AcpiTableLength - Offset), + PARSER_PARAMS (SerializationInstructionEntryParser) + ); + } +} diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c index 53f06fc757..bbac125bb9 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c @@ -1,6 +1,7 @@ /** @file Main file for 'acpiview' Shell command function. + Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. Copyright (c) 2016 - 2021, Arm Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -53,6 +54,7 @@ ACPI_TABLE_PARSER ParserList[] = { { EFI_ACPI_6_2_DEBUG_PORT_2_TABLE_SIGNATURE, ParseAcpiDbg2 }, { EFI_ACPI_6_2_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiDsdt }, + { EFI_ACPI_6_4_ERROR_RECORD_SERIALIZATION_TABLE_SIGNATURE, ParseAcpiErst }, { EFI_ACPI_6_3_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE, ParseAcpiFacs }, { EFI_ACPI_6_2_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiFadt }, { EFI_ACPI_6_4_GENERIC_TIMER_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiGtdt }, diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf index b03ec1a31b..a38965a4bf 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf @@ -1,6 +1,7 @@ ## @file # Provides Shell 'acpiview' command functions # +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2016 - 2020, Arm Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -32,6 +33,7 @@ Parsers/Bgrt/BgrtParser.c Parsers/Dbg2/Dbg2Parser.c Parsers/Dsdt/DsdtParser.c + Parsers/Erst/ErstParser.c Parsers/Facs/FacsParser.c Parsers/Fadt/FadtParser.c Parsers/Gtdt/GtdtParser.c From 566525a2d4112bc73ca64b6865b29835ccb27193 Mon Sep 17 00:00:00 2001 From: Ranbir Singh Date: Thu, 22 Dec 2022 13:42:39 +0530 Subject: [PATCH 0567/1529] MdeModulePkg/Bus/Ata/AhciPei: Fix DEADCODE Coverity issue REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4201 The code can reach line 69 only through the else path above at line 57. The else path already has the same NULL check at line 59 and hence the duplicate code lines are totally redundant which can be deleted. Signed-off-by: Ranbir Singh Reviewed-by: Liming Gao --- MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c index 42e4203a22..6013af858d 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c @@ -66,10 +66,6 @@ AhciS3GetEumeratePorts ( } } - if (S3InitDevices == NULL) { - return 0; - } - // // Only enumerate the ports that exist in the device list. // From 995c9ef9ef7969c0ff1ba67872de280e43865ecb Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Sat, 24 Dec 2022 07:48:12 +0800 Subject: [PATCH 0568/1529] MdePkg: Label CreateEvent NotifyFunction and NotifyContext optional According to the UEFI 2.10 Specification, the EFI_BOOT_SERVICES_TABLE CreateEvent function has the following signature: typedef EFI_STATUS (EFIAPI *EFI_CREATE_EVENT) ( IN UINT32 Type, IN EFI_TPL NotifyTpl, IN EFI_EVENT_NOTIFY NotifyFunction, OPTIONAL IN VOID *NotifyContext, OPTIONAL OUT EFI_EVENT *Event ); Fix the prototype in UefiSpec.h to match, by labeling the NotifyFunction and NotifyContext parameters as OPTIONAL. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- MdePkg/Include/Uefi/UefiSpec.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/Uefi/UefiSpec.h b/MdePkg/Include/Uefi/UefiSpec.h index 3abebbb8d9..7dfe35b499 100644 --- a/MdePkg/Include/Uefi/UefiSpec.h +++ b/MdePkg/Include/Uefi/UefiSpec.h @@ -465,8 +465,8 @@ EFI_STATUS (EFIAPI *EFI_CREATE_EVENT)( IN UINT32 Type, IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction, - IN VOID *NotifyContext, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN VOID *NotifyContext OPTIONAL, OUT EFI_EVENT *Event ); From 2392b6467862860700a2021b8982df0a77f686ca Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Wed, 4 Jan 2023 11:42:43 +0800 Subject: [PATCH 0569/1529] UefiCpuPkg: Fix SMM code hangs when InitPaging REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4246 In function InitPaging, NumberOfPml5Entries is calculated by below code NumberOfPml5Entries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 48); If the SizeOfMemorySpace is larger than 48, NumberOfPml5Entries will be larger than 1. However, this doesn't make sense if the hardware doesn't support 5 level page table. Cc: Gerd Hoffmann Cc: Rahul Kumar Reviewed-by: Star Zeng Reviewed-by: Wu, Jiaxin Reviewed-by: Ray Ni Acked-by: Gerd Hoffmann Signed-off-by: Eric Dong Signed-off-by: Zhiguang Liu --- UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c index c1efda7126..1b0b6673e1 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c @@ -1,7 +1,7 @@ /** @file Enable SMM profile. -Copyright (c) 2012 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2012 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2017 - 2020, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -587,13 +587,18 @@ InitPaging ( } SizeOfMemorySpace = HighBitSet64 (gPhyMask) + 1; + ASSERT (SizeOfMemorySpace <= 52); + // - // Calculate the table entries of PML4E and PDPTE. + // Calculate the table entries of PML5E, PML4E and PDPTE. // NumberOfPml5Entries = 1; if (SizeOfMemorySpace > 48) { - NumberOfPml5Entries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 48); - SizeOfMemorySpace = 48; + if (Enable5LevelPaging) { + NumberOfPml5Entries = (UINTN)LShiftU64 (1, SizeOfMemorySpace - 48); + } + + SizeOfMemorySpace = 48; } NumberOfPml4Entries = 1; From 8a011bccf9b5c049dde75afecce45e6ea2f8a3b0 Mon Sep 17 00:00:00 2001 From: Yuan Yu Date: Wed, 1 Feb 2023 14:31:17 +0800 Subject: [PATCH 0570/1529] MdeModulePkg: ScsiDiskDxe: clean up comment in ScsiDisk.c Comment of MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c was polluted by some previous merge. This patch clean it up. Cc: Ard Biesheuvel Cc: Liming Gao Cc: Hao A Wu Cc: Ray Ni Cc: Sivaparvathi chellaiah Signed-off-by: Yuan Yu Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index 6555aeed7d..fbc236cb46 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -3,10 +3,6 @@ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
Copyright (c) 1985 - 2022, American Megatrends International LLC.
-<<<<<<< HEAD -======= - ->>>>>>> ace365b4e0 (MdeModulePkg/scsi :Coverity scan flags multiple issues in edk2-stable202205) SPDX-License-Identifier: BSD-2-Clause-Patent **/ From f4c81befb34a51db31bbc07f7bbaa94fb98cf0a2 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 2 Feb 2023 17:03:14 +0800 Subject: [PATCH 0571/1529] OvmfPkg/AcpiPlatformDxe: Measure ACPI table from QEMU in TDVF https://bugzilla.tianocore.org/show_bug.cgi?id=4245 QEMU provides the following three files for guest to install the ACPI tables: - etc/acpi/rsdp - etc/acpi/tables - etc/table-loader "etc/acpi/rsdp" and "etc/acpi/tables" are similar, they are only kept separate because they have different allocation requirements in SeaBIOS. Both of these fw_cfg files contain preformatted ACPI payload. "etc/acpi/rsdp" contains only the RSDP table, while "etc/acpi/tables" contains all other tables, concatenated. To be noted, the tables in these two files have been filled in by qemu, but two kinds of fields are incomplete: pointers to other tables and checksums (which depend on the pointers). "/etc/table-loader" is a linker/loader which provides the commands to "patch" the tables in "etc/acpi/tables" and then install them. "Patch" means to fill the pointers and compute the checksum. From the security perspective these 3 files are the raw data downloaded from qemu. They should be measured and extended before they're consumed. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann --- OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf | 1 + OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 32 +++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf index 8939dde425..3fd0483b50 100644 --- a/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf +++ b/OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf @@ -46,6 +46,7 @@ UefiBootServicesTableLib UefiDriverEntryPoint HobLib + TpmMeasurementLib [Protocols] gEfiAcpiTableProtocolGuid # PROTOCOL ALWAYS_CONSUMED diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index f0d81d6fd7..68abc34f22 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -10,6 +10,7 @@ #include // EFI_ACPI_DESCRIPTION_HEADER #include // QEMU_LOADER_FNAME_SIZE +#include #include // AsciiStrCmp() #include // CopyMem() #include // DEBUG() @@ -18,6 +19,7 @@ #include // QemuFwCfgFindFile() #include // QemuFwCfgS3Enabled() #include // gBS +#include #include "AcpiPlatform.h" @@ -415,6 +417,21 @@ ProcessCmdAllocate ( (UINT64)Blob->Size, (UINT64)(UINTN)Blob->Base )); + + // + // Measure the data which is downloaded from QEMU. + // It has to be done before it is consumed. Because the data will + // be updated in the following operations. + // + TpmMeasureAndLogData ( + 1, + EV_PLATFORM_CONFIG_FLAGS, + EV_POSTCODE_INFO_ACPI_DATA, + ACPI_DATA_LEN, + (VOID *)(UINTN)Blob->Base, + Blob->Size + ); + return EFI_SUCCESS; FreeBlob: @@ -1126,6 +1143,21 @@ InstallQemuFwCfgTables ( QemuFwCfgSelectItem (FwCfgItem); QemuFwCfgReadBytes (FwCfgSize, LoaderStart); RestorePciDecoding (OriginalPciAttributes, OriginalPciAttributesCount); + + // + // Measure the "etc/table-loader" which is downloaded from QEMU. + // It has to be done before it is consumed. Because it would be + // updated in the following operations. + // + TpmMeasureAndLogData ( + 1, + EV_PLATFORM_CONFIG_FLAGS, + EV_POSTCODE_INFO_ACPI_DATA, + ACPI_DATA_LEN, + (VOID *)(UINTN)LoaderStart, + FwCfgSize + ); + LoaderEnd = LoaderStart + FwCfgSize / sizeof *LoaderEntry; AllocationsRestrictedTo32Bit = NULL; From c6b4b6557be74aab3153dbdad9f60e028c1b552c Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:36 +0800 Subject: [PATCH 0572/1529] OvmfPkg: Add Tdx measurement data structure in WorkArea BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 From the perspective of security any external input should be measured and extended to some registers (TPM PCRs or TDX RTMR registers). There are below 2 external input in a Td guest: - TdHob - Configuration FV (CFV) TdHob contains the resource information passed from VMM, such as unaccepted memory region. CFV contains the configurations, such as secure boot variables. TdHob and CFV should be measured and extended to RTMRs before they're consumed. TdHob is consumed in the very early stage of boot process. At that moment the memory service is not ready. Cfv is consumed in PlatformPei to initialize the EmuVariableNvStore. To make the implementation simple and clean, these 2 external input are measured and extended to RTMRs in SEC phase. That is to say the tdx measurement is only supported in SEC phase. After the measurement the hash values are stored in WorkArea. Then after the Hob service is available, these 2 measurement values are retrieved and GuidHobs for these 2 tdx measurements are generated. This patch defines the structure of TDX_MEASUREMENTS_DATA in SEC_TDX_WORK_AREA to store above 2 tdx measurements. It can be extended to store more tdx measurements if needed in the future. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Include/WorkArea.h | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/Include/WorkArea.h b/OvmfPkg/Include/WorkArea.h index 6c3702b716..b1c7045ce1 100644 --- a/OvmfPkg/Include/WorkArea.h +++ b/OvmfPkg/Include/WorkArea.h @@ -11,6 +11,7 @@ #define __OVMF_WORK_AREA_H__ #include +#include // // Confidential computing work area header definition. Any change @@ -64,13 +65,27 @@ typedef struct _SEV_WORK_AREA { SEC_SEV_ES_WORK_AREA SevEsWorkArea; } SEV_WORK_AREA; +// +// Start of TDX Specific WorkArea definition +// + +#define TDX_MEASUREMENT_TDHOB_BITMASK 0x1 +#define TDX_MEASUREMENT_CFVIMG_BITMASK 0x2 + +typedef struct _TDX_MEASUREMENTS_DATA { + UINT32 MeasurementsBitmap; + UINT8 TdHobHashValue[SHA384_DIGEST_SIZE]; + UINT8 CfvImgHashValue[SHA384_DIGEST_SIZE]; +} TDX_MEASUREMENTS_DATA; + // // The TDX work area definition // typedef struct _SEC_TDX_WORK_AREA { - UINT32 PageTableReady; - UINT32 Gpaw; - UINT64 HobList; + UINT32 PageTableReady; + UINT32 Gpaw; + UINT64 HobList; + TDX_MEASUREMENTS_DATA TdxMeasurementsData; } SEC_TDX_WORK_AREA; typedef struct _TDX_WORK_AREA { @@ -78,6 +93,10 @@ typedef struct _TDX_WORK_AREA { SEC_TDX_WORK_AREA SecTdxWorkArea; } TDX_WORK_AREA; +// +// End of TDX Specific WorkArea definition +// + typedef union { CONFIDENTIAL_COMPUTING_WORK_AREA_HEADER Header; SEV_WORK_AREA SevWorkArea; From 86670be5b48ed9c707b5a1c64a9977ca3af0d6b2 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:37 +0800 Subject: [PATCH 0573/1529] OvmfPkg/IntelTdx: Add TdxHelperLibNull BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdxHelperLib provides below helper functions for a td-guest. - TdxHelperProcessTdHob - TdxHelperMeasureTdHob - TdxHelperMeasureCfvImage - TdxHelperBuildGuidHobForTdxMeasurement TdxHelperLibNull is the NULL instance of TdxHelperLib. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Include/Library/TdxHelperLib.h | 70 ++++++++++++++++ .../TdxHelperLib/TdxHelperLibNull.inf | 32 ++++++++ OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperNull.c | 79 +++++++++++++++++++ OvmfPkg/OvmfPkg.dec | 4 + 4 files changed, 185 insertions(+) create mode 100644 OvmfPkg/Include/Library/TdxHelperLib.h create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperNull.c diff --git a/OvmfPkg/Include/Library/TdxHelperLib.h b/OvmfPkg/Include/Library/TdxHelperLib.h new file mode 100644 index 0000000000..199aade42f --- /dev/null +++ b/OvmfPkg/Include/Library/TdxHelperLib.h @@ -0,0 +1,70 @@ +/** @file + TdxHelperLib header file + + Copyright (c) 2021 - 2023, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef TDX_HELPER_LIB_H +#define TDX_HELPER_LIB_H + +#include + +/** + In Tdx guest, some information need to be passed from host VMM to guest + firmware. For example, the memory resource, etc. These information are + prepared by host VMM and put in TdHob which is described in TdxMetadata. + TDVF processes the TdHob to accept memories. + + @retval EFI_SUCCESS Successfully process the TdHob + @retval Others Other error as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperProcessTdHob ( + VOID + ); + +/** + In Tdx guest, TdHob is passed from host VMM to guest firmware and it contains + the information of the memory resource. From the security perspective before + it is consumed, it should be measured and extended. + * + * @retval EFI_SUCCESS Successfully measure the TdHob + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureTdHob ( + VOID + ); + +/** + * In Tdx guest, Configuration FV (CFV) is treated as external input because it + * may contain the data provided by VMM. From the sucurity perspective Cfv image + * should be measured before it is consumed. + * + * @retval EFI_SUCCESS Successfully measure the CFV image + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureCfvImage ( + VOID + ); + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperBuildGuidHobForTdxMeasurement ( + VOID + ); + +#endif diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf b/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf new file mode 100644 index 0000000000..27d07b3886 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf @@ -0,0 +1,32 @@ +## @file +# TdxHelperLib NULL instance +# +# Copyright (c) 2021 - 2023, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TdxHelperLibNull + FILE_GUID = 853603b2-53ea-463d-93e6-35d09a79e358 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = TdxHelperLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = X64 +# + +[Sources] + TdxHelperNull.c + +[Packages] + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperNull.c b/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperNull.c new file mode 100644 index 0000000000..a2125190d6 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperNull.c @@ -0,0 +1,79 @@ +/** @file + NULL instance of TdxHelperLib + + Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + In Tdx guest, some information need to be passed from host VMM to guest + firmware. For example, the memory resource, etc. These information are + prepared by host VMM and put in TdHob which is described in TdxMetadata. + TDVF processes the TdHob to accept memories. + + @retval EFI_SUCCESS Successfully process the TdHob + @retval Others Other error as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperProcessTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + In Tdx guest, TdHob is passed from host VMM to guest firmware and it contains + the information of the memory resource. From the security perspective before + it is consumed, it should be measured and extended. + * + * @retval EFI_SUCCESS Successfully measure the TdHob + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + * In Tdx guest, Configuration FV (CFV) is treated as external input because it + * may contain the data provided by VMM. From the sucurity perspective Cfv image + * should be measured before it is consumed. + * + * @retval EFI_SUCCESS Successfully measure the CFV image + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureCfvImage ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperBuildGuidHobForTdxMeasurement ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index a22eb246c6..be30547474 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -98,6 +98,10 @@ # SerializeVariablesLib|Include/Library/SerializeVariablesLib.h + ## @libraryclass TdxHelper + # + TdxHelperLib|Include/Library/TdxHelperLib.h + ## @libraryclass Declares utility functions for virtio device drivers. VirtioLib|Include/Library/VirtioLib.h From bc6d3e101b3097e982cb436a56b87db6506fa882 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:38 +0800 Subject: [PATCH 0574/1529] OvmfPkg/IntelTdx: Add SecTdxHelperLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdxHelperLib provides below helper functions for a td-guest. - TdxHelperProcessTdHob - TdxHelperMeasureTdHob - TdxHelperMeasureCfvImage - TdxHelperBuildGuidHobForTdxMeasurement SecTdxHelperLib is the SEC instance of TdxHelperLib. It implements 4 functions for tdx in SEC phase: - TdxHelperProcessTdHob consumes TdHob to accept un-accepted memories. Before the TdHob is consumed, it is first validated. - TdxHelperMeasureTdHob measure/extend TdHob and store the measurement value in workarea. - TdxHelperMeasureCfvImage measure/extend the Configuration FV image and store the measurement value in workarea. - TdxHelperBuildGuidHobForTdxMeasurement builds GuidHob for tdx measurement. This patch implements the stubs of the functions. The actual implementations are in the following patches. Because they are moved from other files. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c | 78 +++++++++++++++++++ .../IntelTdx/TdxHelperLib/SecTdxHelperLib.inf | 52 +++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c new file mode 100644 index 0000000000..ef958b3359 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c @@ -0,0 +1,78 @@ +/** @file + TdxHelper Functions which are used in SEC phase + + Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +/** + In Tdx guest, some information need to be passed from host VMM to guest + firmware. For example, the memory resource, etc. These information are + prepared by host VMM and put in TdHob which is described in TdxMetadata. + TDVF processes the TdHob to accept memories. + + @retval EFI_SUCCESS Successfully process the TdHob + @retval Others Other error as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperProcessTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + In Tdx guest, TdHob is passed from host VMM to guest firmware and it contains + the information of the memory resource. From the security perspective before + it is consumed, it should be measured and extended. + * + * @retval EFI_SUCCESS Successfully measure the TdHob + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + * In Tdx guest, Configuration FV (CFV) is treated as external input because it + * may contain the data provided by VMM. From the sucurity perspective Cfv image + * should be measured before it is consumed. + * + * @retval EFI_SUCCESS Successfully measure the CFV image + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureCfvImage ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperBuildGuidHobForTdxMeasurement ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf new file mode 100644 index 0000000000..3c6b96f775 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf @@ -0,0 +1,52 @@ +## @file +# TdxHelperLib SEC instance +# +# This module provides Tdx helper functions in SEC phase. +# Copyright (c) 2021 - 2023, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SecTdxHelperLib + FILE_GUID = ba69ac6b-0c59-4472-899d-b684590ec1e9 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = TdxHelperLib|SEC + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = X64 +# + +[Sources] + SecTdxHelper.c + +[Packages] + CryptoPkg/CryptoPkg.dec + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + SecurityPkg/SecurityPkg.dec + +[LibraryClasses] + BaseLib + BaseCryptLib + DebugLib + HobLib + PcdLib + TdxMailboxLib + TdxLib + +[FixedPcd] + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase + gUefiOvmfPkgTokenSpaceGuid.PcdTdxAcceptPageSize + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFlashNvStorageVariableBase + gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataSize + +[Guids] + gCcEventEntryHobGuid From 5ae780423b021157b496438521d26f22726d0701 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:39 +0800 Subject: [PATCH 0575/1529] OvmfPkg/PeilessStartupLib: Update the define of FV_HANDOFF_TABLE_POINTERS2 BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 FV_HANDOFF_TABLE_POINTERS2 once was defined in IntelTdx.c. Its structure is same as PLATFORM_FIRMWARE_BLOB2_STRUCT which is defined in Library/TcgEventLogRecordLib.h. So this patch reuse the define of PLATFORM_FIRMWARE_BLOB2_STRUCT as FV_HANDOFF_TABLE_POINTERS2. Furthermore FV_HANDOFF_TABLE_POINTERS2 is renamed as CFV_HANDOFF_TABLE_POINTERS2 so that the name is more meaningful. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Library/PeilessStartupLib/IntelTdx.c | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c index 216c413caa..4e8dca3d77 100644 --- a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c +++ b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include "PeilessStartupInternal.h" @@ -25,16 +26,11 @@ typedef struct { EFI_CONFIGURATION_TABLE TableEntry[1]; } TDX_HANDOFF_TABLE_POINTERS2; -#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" -typedef struct { - UINT8 BlobDescriptionSize; - UINT8 BlobDescription[sizeof (FV_HANDOFF_TABLE_DESC)]; - EFI_PHYSICAL_ADDRESS BlobBase; - UINT64 BlobLength; -} FV_HANDOFF_TABLE_POINTERS2; - #pragma pack() +#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" +typedef PLATFORM_FIRMWARE_BLOB2_STRUCT CFV_HANDOFF_TABLE_POINTERS2; + /** Measure the Hoblist passed from the VMM. @@ -161,9 +157,9 @@ MeasureFvImage ( IN UINT8 PcrIndex ) { - EFI_STATUS Status; - FV_HANDOFF_TABLE_POINTERS2 FvBlob2; - VOID *FvName; + EFI_STATUS Status; + CFV_HANDOFF_TABLE_POINTERS2 FvBlob2; + VOID *FvName; // // Init the log event for FV measurement From 409136f4321bf4c43cb85399c4bf5f0b56dff8a9 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:40 +0800 Subject: [PATCH 0576/1529] OvmfPkg: Refactor MeasureHobList BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 MeasureHobList once was implemented in PeilessStartupLib and it does measurement and logging for TdHob in one go, using TpmMeasureAndLogData(). But it doesn't work in SEC. This patch splits MeasureHobList into 2 functions and implement them in SecTdxHelperLib. - TdxHelperMeasureTdHob - TdxHelperBuildGuidHobForTdxMeasurement TdxHelperMeasureTdHob measures the TdHob and stores the hash value in WorkArea. TdxHelperBuildGuidHobForTdxMeasurement builds GuidHob for the measurement based on the hash value in WorkArea. After these 2 functions are introduced, PeilessStartupLib should also be updated: - Call these 2 functions instead of the MeasureHobList - Delete the duplicated codes in PeilessStartupLib Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 1 + OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c | 123 ++++++++++++- .../IntelTdx/TdxHelperLib/SecTdxHelperLib.inf | 1 + .../IntelTdx/TdxHelperLib/TdxMeasurementHob.c | 173 ++++++++++++++++++ OvmfPkg/Library/PeilessStartupLib/IntelTdx.c | 71 ------- .../PeilessStartupLib/PeilessStartup.c | 12 +- .../PeilessStartupInternal.h | 15 -- 7 files changed, 308 insertions(+), 88 deletions(-) create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 0f1e970fbb..920f1c6080 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -549,6 +549,7 @@ NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf TpmMeasurementLib|SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.inf + NULL|OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf HashLib|SecurityPkg/Library/HashLibTdx/HashLibTdx.inf NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c index ef958b3359..6ca6f01aff 100644 --- a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c @@ -8,6 +8,31 @@ **/ #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +InternalBuildGuidHobForTdxMeasurement ( + VOID + ); /** In Tdx guest, some information need to be passed from host VMM to guest @@ -27,6 +52,58 @@ TdxHelperProcessTdHob ( return EFI_UNSUPPORTED; } +/** + * Calculate the sha384 of input Data and extend it to RTMR register. + * + * @param RtmrIndex Index of the RTMR register + * @param DataToHash Data to be hashed + * @param DataToHashLen Length of the data + * @param Digest Hash value of the input data + * @param DigestLen Length of the hash value + * + * @retval EFI_SUCCESS Successfully hash and extend to RTMR + * @retval Others Other errors as indicated + */ +STATIC +EFI_STATUS +HashAndExtendToRtmr ( + IN UINT32 RtmrIndex, + IN VOID *DataToHash, + IN UINTN DataToHashLen, + OUT UINT8 *Digest, + IN UINTN DigestLen + ) +{ + EFI_STATUS Status; + + if ((DataToHash == NULL) || (DataToHashLen == 0)) { + return EFI_INVALID_PARAMETER; + } + + if ((Digest == NULL) || (DigestLen != SHA384_DIGEST_SIZE)) { + return EFI_INVALID_PARAMETER; + } + + // + // Calculate the sha384 of the data + // + if (!Sha384HashAll (DataToHash, DataToHashLen, Digest)) { + return EFI_ABORTED; + } + + // + // Extend to RTMR + // + Status = TdExtendRtmr ( + (UINT32 *)Digest, + SHA384_DIGEST_SIZE, + (UINT8)RtmrIndex + ); + + ASSERT (!EFI_ERROR (Status)); + return Status; +} + /** In Tdx guest, TdHob is passed from host VMM to guest firmware and it contains the information of the memory resource. From the security perspective before @@ -41,7 +118,47 @@ TdxHelperMeasureTdHob ( VOID ) { - return EFI_UNSUPPORTED; + EFI_PEI_HOB_POINTERS Hob; + EFI_STATUS Status; + UINT8 Digest[SHA384_DIGEST_SIZE]; + OVMF_WORK_AREA *WorkArea; + VOID *TdHob; + + TdHob = (VOID *)(UINTN)FixedPcdGet32 (PcdOvmfSecGhcbBase); + Hob.Raw = (UINT8 *)TdHob; + + // + // Walk thru the TdHob list until end of list. + // + while (!END_OF_HOB_LIST (Hob)) { + Hob.Raw = GET_NEXT_HOB (Hob); + } + + Status = HashAndExtendToRtmr ( + 0, + (UINT8 *)TdHob, + (UINTN)((UINT8 *)Hob.Raw - (UINT8 *)TdHob), + Digest, + SHA384_DIGEST_SIZE + ); + + if (EFI_ERROR (Status)) { + return Status; + } + + // + // This function is called in SEC phase and at that moment the Hob service + // is not available. So the TdHob measurement value is stored in workarea. + // + WorkArea = (OVMF_WORK_AREA *)FixedPcdGet32 (PcdOvmfWorkAreaBase); + if (WorkArea == NULL) { + return EFI_DEVICE_ERROR; + } + + WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.MeasurementsBitmap |= TDX_MEASUREMENT_TDHOB_BITMASK; + CopyMem (WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.TdHobHashValue, Digest, SHA384_DIGEST_SIZE); + + return EFI_SUCCESS; } /** @@ -74,5 +191,9 @@ TdxHelperBuildGuidHobForTdxMeasurement ( VOID ) { + #ifdef TDX_PEI_LESS_BOOT + return InternalBuildGuidHobForTdxMeasurement (); + #else return EFI_UNSUPPORTED; + #endif } diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf index 3c6b96f775..d17b84c01f 100644 --- a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf @@ -24,6 +24,7 @@ [Sources] SecTdxHelper.c + TdxMeasurementHob.c [Packages] CryptoPkg/CryptoPkg.dec diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c b/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c new file mode 100644 index 0000000000..6cbc7600ad --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c @@ -0,0 +1,173 @@ +/** @file + Build GuidHob for tdx measurement. + + Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma pack(1) + +#define HANDOFF_TABLE_DESC "TdxTable" +typedef struct { + UINT8 TableDescriptionSize; + UINT8 TableDescription[sizeof (HANDOFF_TABLE_DESC)]; + UINT64 NumberOfTables; + EFI_CONFIGURATION_TABLE TableEntry[1]; +} TDX_HANDOFF_TABLE_POINTERS2; + +#pragma pack() + +/** + * Build GuidHob for Tdx measurement. + * + * Tdx measurement includes the measurement of TdHob and CFV. They're measured + * and extended to RTMR registers in SEC phase. Because at that moment the Hob + * service are not available. So the values of the measurement are saved in + * workarea and will be built into GuidHob after the Hob service is ready. + * + * @param RtmrIndex RTMR index + * @param EventType Event type + * @param EventData Event data + * @param EventSize Size of event data + * @param HashValue Hash value + * @param HashSize Size of hash + * + * @retval EFI_SUCCESS Successfully build the GuidHobs + * @retval Others Other error as indicated + */ +STATIC +EFI_STATUS +BuildTdxMeasurementGuidHob ( + UINT32 RtmrIndex, + UINT32 EventType, + UINT8 *EventData, + UINT32 EventSize, + UINT8 *HashValue, + UINT32 HashSize + ) +{ + VOID *EventHobData; + UINT8 *Ptr; + TPML_DIGEST_VALUES *TdxDigest; + + if (HashSize != SHA384_DIGEST_SIZE) { + return EFI_INVALID_PARAMETER; + } + + #define TDX_DIGEST_VALUE_LEN (sizeof (UINT32) + sizeof (TPMI_ALG_HASH) + SHA384_DIGEST_SIZE) + + EventHobData = BuildGuidHob ( + &gCcEventEntryHobGuid, + sizeof (TCG_PCRINDEX) + sizeof (TCG_EVENTTYPE) + + TDX_DIGEST_VALUE_LEN + + sizeof (UINT32) + EventSize + ); + + if (EventHobData == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + Ptr = (UINT8 *)EventHobData; + + // + // There are 2 types of measurement registers in TDX: MRTD and RTMR[0-3]. + // According to UEFI Spec 2.10 Section 38.4.1, RTMR[0-3] is mapped to MrIndex[1-4]. + // So RtmrIndex must be increased by 1 before the event log is created. + // + RtmrIndex++; + CopyMem (Ptr, &RtmrIndex, sizeof (UINT32)); + Ptr += sizeof (UINT32); + + CopyMem (Ptr, &EventType, sizeof (TCG_EVENTTYPE)); + Ptr += sizeof (TCG_EVENTTYPE); + + TdxDigest = (TPML_DIGEST_VALUES *)Ptr; + TdxDigest->count = 1; + TdxDigest->digests[0].hashAlg = TPM_ALG_SHA384; + CopyMem ( + TdxDigest->digests[0].digest.sha384, + HashValue, + SHA384_DIGEST_SIZE + ); + Ptr += TDX_DIGEST_VALUE_LEN; + + CopyMem (Ptr, &EventSize, sizeof (UINT32)); + Ptr += sizeof (UINT32); + + CopyMem (Ptr, (VOID *)EventData, EventSize); + Ptr += EventSize; + + return EFI_SUCCESS; +} + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +InternalBuildGuidHobForTdxMeasurement ( + VOID + ) +{ + EFI_STATUS Status; + OVMF_WORK_AREA *WorkArea; + VOID *TdHobList; + TDX_HANDOFF_TABLE_POINTERS2 HandoffTables; + UINT8 *HashValue; + + if (!TdIsEnabled ()) { + ASSERT (FALSE); + return EFI_UNSUPPORTED; + } + + WorkArea = (OVMF_WORK_AREA *)FixedPcdGet32 (PcdOvmfWorkAreaBase); + if (WorkArea == NULL) { + return EFI_ABORTED; + } + + Status = EFI_SUCCESS; + + // + // Build the GuidHob for TdHob measurement + // + TdHobList = (VOID *)(UINTN)FixedPcdGet32 (PcdOvmfSecGhcbBase); + if (WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.MeasurementsBitmap & TDX_MEASUREMENT_TDHOB_BITMASK) { + HashValue = WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.TdHobHashValue; + HandoffTables.TableDescriptionSize = sizeof (HandoffTables.TableDescription); + CopyMem (HandoffTables.TableDescription, HANDOFF_TABLE_DESC, sizeof (HandoffTables.TableDescription)); + HandoffTables.NumberOfTables = 1; + CopyGuid (&(HandoffTables.TableEntry[0].VendorGuid), &gUefiOvmfPkgTokenSpaceGuid); + HandoffTables.TableEntry[0].VendorTable = TdHobList; + + Status = BuildTdxMeasurementGuidHob ( + 0, // RtmrIndex + EV_EFI_HANDOFF_TABLES2, // EventType + (UINT8 *)(UINTN)&HandoffTables, // EventData + sizeof (HandoffTables), // EventSize + HashValue, // HashValue + SHA384_DIGEST_SIZE // HashSize + ); + } + + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + return Status; + } + + return EFI_SUCCESS; +} diff --git a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c index 4e8dca3d77..ae0ffcc95d 100644 --- a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c +++ b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c @@ -16,80 +16,9 @@ #include "PeilessStartupInternal.h" -#pragma pack(1) - -#define HANDOFF_TABLE_DESC "TdxTable" -typedef struct { - UINT8 TableDescriptionSize; - UINT8 TableDescription[sizeof (HANDOFF_TABLE_DESC)]; - UINT64 NumberOfTables; - EFI_CONFIGURATION_TABLE TableEntry[1]; -} TDX_HANDOFF_TABLE_POINTERS2; - -#pragma pack() - #define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" typedef PLATFORM_FIRMWARE_BLOB2_STRUCT CFV_HANDOFF_TABLE_POINTERS2; -/** - Measure the Hoblist passed from the VMM. - - @param[in] VmmHobList The Hoblist pass the firmware - - @retval EFI_SUCCESS Fv image is measured successfully - or it has been already measured. - @retval Others Other errors as indicated -**/ -EFI_STATUS -EFIAPI -MeasureHobList ( - IN CONST VOID *VmmHobList - ) -{ - EFI_PEI_HOB_POINTERS Hob; - TDX_HANDOFF_TABLE_POINTERS2 HandoffTables; - EFI_STATUS Status; - - if (!TdIsEnabled ()) { - ASSERT (FALSE); - return EFI_UNSUPPORTED; - } - - Hob.Raw = (UINT8 *)VmmHobList; - - // - // Parse the HOB list until end of list. - // - while (!END_OF_HOB_LIST (Hob)) { - Hob.Raw = GET_NEXT_HOB (Hob); - } - - // - // Init the log event for HOB measurement - // - - HandoffTables.TableDescriptionSize = sizeof (HandoffTables.TableDescription); - CopyMem (HandoffTables.TableDescription, HANDOFF_TABLE_DESC, sizeof (HandoffTables.TableDescription)); - HandoffTables.NumberOfTables = 1; - CopyGuid (&(HandoffTables.TableEntry[0].VendorGuid), &gUefiOvmfPkgTokenSpaceGuid); - HandoffTables.TableEntry[0].VendorTable = (VOID *)VmmHobList; - - Status = TpmMeasureAndLogData ( - 1, // PCRIndex - EV_EFI_HANDOFF_TABLES2, // EventType - (VOID *)&HandoffTables, // EventData - sizeof (HandoffTables), // EventSize - (UINT8 *)(UINTN)VmmHobList, // HashData - (UINTN)((UINT8 *)Hob.Raw - (UINT8 *)VmmHobList) // HashDataLen - ); - - if (EFI_ERROR (Status)) { - ASSERT (FALSE); - } - - return Status; -} - /** Get the FvName from the FV header. diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c index 928120d183..4efbc14d59 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -179,7 +180,16 @@ PeilessStartup ( // // Measure HobList // - Status = MeasureHobList (VmmHobList); + Status = TdxHelperMeasureTdHob (); + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + CpuDeadLoop (); + } + + // + // Build GuidHob for tdx measurement + // + Status = TdxHelperBuildGuidHobForTdxMeasurement (); if (EFI_ERROR (Status)) { ASSERT (FALSE); CpuDeadLoop (); diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h index f56bc3578e..a2d2c1c914 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h @@ -58,21 +58,6 @@ EFIAPI ConstructSecHobList ( ); -/** - Measure the Hoblist passed from the VMM. - - @param[in] VmmHobList The Hoblist pass the firmware - - @retval EFI_SUCCESS Fv image is measured successfully - or it has been already measured. - @retval Others Other errors as indicated -**/ -EFI_STATUS -EFIAPI -MeasureHobList ( - IN CONST VOID *VmmHobList - ); - /** Measure FV image. From 9ead763a61a979fff668b64152bdf24adfad049b Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:41 +0800 Subject: [PATCH 0577/1529] OvmfPkg: Refactor MeaureFvImage BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 MeasureFvImage once was implemented in PeilessStartupLib and it does measurement and logging for Configuration FV (Cfv) image in one go, using TpmMeasureAndLogData(). But it doesn't work in SEC. This patch splits MeasureFvImage into 2 functions and implement them in SecTdxHelperLib. - TdxHelperMeasureCfvImage - TdxHelperBuildGuidHobForTdxMeasurement TdxHelperMeasureCfvImage measures the Cfv image and stores the hash value in WorkArea. TdxHelperBuildGuidHobForTdxMeasurement builds GuidHob for the measurement based on the hash value in WorkArea. After these 2 functions are introduced, PeilessStartupLib should also be updated: - Call these 2 functions instead of the MeasureFvImage - Delete the duplicated codes in PeilessStartupLib Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c | 30 ++++- .../IntelTdx/TdxHelperLib/TdxMeasurementHob.c | 86 +++++++++++++ OvmfPkg/Library/PeilessStartupLib/IntelTdx.c | 121 ------------------ .../PeilessStartupLib/PeilessStartup.c | 10 +- .../PeilessStartupInternal.h | 21 --- .../PeilessStartupLib/PeilessStartupLib.inf | 4 - 6 files changed, 119 insertions(+), 153 deletions(-) delete mode 100644 OvmfPkg/Library/PeilessStartupLib/IntelTdx.c diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c index 6ca6f01aff..1929093f91 100644 --- a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c @@ -175,7 +175,35 @@ TdxHelperMeasureCfvImage ( VOID ) { - return EFI_UNSUPPORTED; + EFI_STATUS Status; + UINT8 Digest[SHA384_DIGEST_SIZE]; + OVMF_WORK_AREA *WorkArea; + + Status = HashAndExtendToRtmr ( + 0, + (UINT8 *)(UINTN)PcdGet32 (PcdOvmfFlashNvStorageVariableBase), + (UINT64)PcdGet32 (PcdCfvRawDataSize), + Digest, + SHA384_DIGEST_SIZE + ); + + if (EFI_ERROR (Status)) { + return Status; + } + + // + // This function is called in SEC phase and at that moment the Hob service + // is not available. So CfvImage measurement value is stored in workarea. + // + WorkArea = (OVMF_WORK_AREA *)FixedPcdGet32 (PcdOvmfWorkAreaBase); + if (WorkArea == NULL) { + return EFI_DEVICE_ERROR; + } + + WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.MeasurementsBitmap |= TDX_MEASUREMENT_CFVIMG_BITMASK; + CopyMem (WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.CfvImgHashValue, Digest, SHA384_DIGEST_SIZE); + + return EFI_SUCCESS; } /** diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c b/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c index 6cbc7600ad..a4c7095cff 100644 --- a/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c +++ b/OvmfPkg/IntelTdx/TdxHelperLib/TdxMeasurementHob.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #pragma pack(1) @@ -29,6 +30,9 @@ typedef struct { #pragma pack() +#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" +typedef PLATFORM_FIRMWARE_BLOB2_STRUCT CFV_HANDOFF_TABLE_POINTERS2; + /** * Build GuidHob for Tdx measurement. * @@ -112,6 +116,52 @@ BuildTdxMeasurementGuidHob ( return EFI_SUCCESS; } +/** + Get the FvName from the FV header. + + Causion: The FV is untrusted input. + + @param[in] FvBase Base address of FV image. + @param[in] FvLength Length of FV image. + + @return FvName pointer + @retval NULL FvName is NOT found +**/ +VOID * +GetFvName ( + IN EFI_PHYSICAL_ADDRESS FvBase, + IN UINT64 FvLength + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; + + if (FvBase >= MAX_ADDRESS) { + return NULL; + } + + if (FvLength >= MAX_ADDRESS - FvBase) { + return NULL; + } + + if (FvLength < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) { + return NULL; + } + + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase; + if (FvHeader->ExtHeaderOffset < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) { + return NULL; + } + + if (FvHeader->ExtHeaderOffset + sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER) > FvLength) { + return NULL; + } + + FvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(UINTN)(FvBase + FvHeader->ExtHeaderOffset); + + return &FvExtHeader->FvName; +} + /** Build the GuidHob for tdx measurements which were done in SEC phase. The measurement values are stored in WorkArea. @@ -128,6 +178,10 @@ InternalBuildGuidHobForTdxMeasurement ( OVMF_WORK_AREA *WorkArea; VOID *TdHobList; TDX_HANDOFF_TABLE_POINTERS2 HandoffTables; + VOID *FvName; + CFV_HANDOFF_TABLE_POINTERS2 FvBlob2; + EFI_PHYSICAL_ADDRESS FvBase; + UINT64 FvLength; UINT8 *HashValue; if (!TdIsEnabled ()) { @@ -169,5 +223,37 @@ InternalBuildGuidHobForTdxMeasurement ( return Status; } + // + // Build the GuidHob for Cfv measurement + // + if (WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.MeasurementsBitmap & TDX_MEASUREMENT_CFVIMG_BITMASK) { + HashValue = WorkArea->TdxWorkArea.SecTdxWorkArea.TdxMeasurementsData.CfvImgHashValue; + FvBase = (UINT64)PcdGet32 (PcdOvmfFlashNvStorageVariableBase); + FvLength = (UINT64)PcdGet32 (PcdCfvRawDataSize); + FvBlob2.BlobDescriptionSize = sizeof (FvBlob2.BlobDescription); + CopyMem (FvBlob2.BlobDescription, FV_HANDOFF_TABLE_DESC, sizeof (FvBlob2.BlobDescription)); + FvName = GetFvName (FvBase, FvLength); + if (FvName != NULL) { + AsciiSPrint ((CHAR8 *)FvBlob2.BlobDescription, sizeof (FvBlob2.BlobDescription), "Fv(%g)", FvName); + } + + FvBlob2.BlobBase = FvBase; + FvBlob2.BlobLength = FvLength; + + Status = BuildTdxMeasurementGuidHob ( + 0, // RtmrIndex + EV_EFI_PLATFORM_FIRMWARE_BLOB2, // EventType + (VOID *)&FvBlob2, // EventData + sizeof (FvBlob2), // EventSize + HashValue, // HashValue + SHA384_DIGEST_SIZE // HashSize + ); + } + + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + return Status; + } + return EFI_SUCCESS; } diff --git a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c deleted file mode 100644 index ae0ffcc95d..0000000000 --- a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c +++ /dev/null @@ -1,121 +0,0 @@ -/** @file - Copyright (c) 2022, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "PeilessStartupInternal.h" - -#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" -typedef PLATFORM_FIRMWARE_BLOB2_STRUCT CFV_HANDOFF_TABLE_POINTERS2; - -/** - Get the FvName from the FV header. - - Causion: The FV is untrusted input. - - @param[in] FvBase Base address of FV image. - @param[in] FvLength Length of FV image. - - @return FvName pointer - @retval NULL FvName is NOT found -**/ -VOID * -GetFvName ( - IN EFI_PHYSICAL_ADDRESS FvBase, - IN UINT64 FvLength - ) -{ - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; - - if (FvBase >= MAX_ADDRESS) { - return NULL; - } - - if (FvLength >= MAX_ADDRESS - FvBase) { - return NULL; - } - - if (FvLength < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) { - return NULL; - } - - FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase; - if (FvHeader->ExtHeaderOffset < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) { - return NULL; - } - - if (FvHeader->ExtHeaderOffset + sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER) > FvLength) { - return NULL; - } - - FvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(UINTN)(FvBase + FvHeader->ExtHeaderOffset); - - return &FvExtHeader->FvName; -} - -/** - Measure FV image. - - @param[in] FvBase Base address of FV image. - @param[in] FvLength Length of FV image. - @param[in] PcrIndex Index of PCR - - @retval EFI_SUCCESS Fv image is measured successfully - or it has been already measured. - @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event. - @retval EFI_DEVICE_ERROR The command was unsuccessful. - -**/ -EFI_STATUS -EFIAPI -MeasureFvImage ( - IN EFI_PHYSICAL_ADDRESS FvBase, - IN UINT64 FvLength, - IN UINT8 PcrIndex - ) -{ - EFI_STATUS Status; - CFV_HANDOFF_TABLE_POINTERS2 FvBlob2; - VOID *FvName; - - // - // Init the log event for FV measurement - // - FvBlob2.BlobDescriptionSize = sizeof (FvBlob2.BlobDescription); - CopyMem (FvBlob2.BlobDescription, FV_HANDOFF_TABLE_DESC, sizeof (FvBlob2.BlobDescription)); - FvName = GetFvName (FvBase, FvLength); - if (FvName != NULL) { - AsciiSPrint ((CHAR8 *)FvBlob2.BlobDescription, sizeof (FvBlob2.BlobDescription), "Fv(%g)", FvName); - } - - FvBlob2.BlobBase = FvBase; - FvBlob2.BlobLength = FvLength; - - Status = TpmMeasureAndLogData ( - 1, // PCRIndex - EV_EFI_PLATFORM_FIRMWARE_BLOB2, // EventType - (VOID *)&FvBlob2, // EventData - sizeof (FvBlob2), // EventSize - (UINT8 *)(UINTN)FvBase, // HashData - (UINTN)(FvLength) // HashDataLen - ); - - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "The FV which failed to be measured starts at: 0x%x\n", FvBase)); - ASSERT (FALSE); - } - - return Status; -} diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c index 4efbc14d59..79d3a178a6 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c @@ -140,13 +140,11 @@ PeilessStartup ( UINT32 DxeCodeSize; TD_RETURN_DATA TdReturnData; VOID *VmmHobList; - UINT8 *CfvBase; Status = EFI_SUCCESS; BootFv = NULL; VmmHobList = NULL; SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Context; - CfvBase = (UINT8 *)(UINTN)FixedPcdGet32 (PcdCfvBase); ZeroMem (&PlatformInfoHob, sizeof (PlatformInfoHob)); @@ -187,18 +185,18 @@ PeilessStartup ( } // - // Build GuidHob for tdx measurement + // Measure Tdx CFV // - Status = TdxHelperBuildGuidHobForTdxMeasurement (); + Status = TdxHelperMeasureCfvImage (); if (EFI_ERROR (Status)) { ASSERT (FALSE); CpuDeadLoop (); } // - // Measure Tdx CFV + // Build GuidHob for tdx measurement // - Status = MeasureFvImage ((EFI_PHYSICAL_ADDRESS)(UINTN)CfvBase, FixedPcdGet32 (PcdCfvRawDataSize), 1); + Status = TdxHelperBuildGuidHobForTdxMeasurement (); if (EFI_ERROR (Status)) { ASSERT (FALSE); CpuDeadLoop (); diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h index a2d2c1c914..1581962719 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h @@ -58,25 +58,4 @@ EFIAPI ConstructSecHobList ( ); -/** - Measure FV image. - - @param[in] FvBase Base address of FV image. - @param[in] FvLength Length of FV image. - @param[in] PcrIndex Index of PCR - - @retval EFI_SUCCESS Fv image is measured successfully - or it has been already measured. - @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event. - @retval EFI_DEVICE_ERROR The command was unsuccessful. - -**/ -EFI_STATUS -EFIAPI -MeasureFvImage ( - IN EFI_PHYSICAL_ADDRESS FvBase, - IN UINT64 FvLength, - IN UINT8 PcrIndex - ); - #endif diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf index 5c6eb1597b..4ced5dda99 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf @@ -29,7 +29,6 @@ PeilessStartup.c Hob.c DxeLoad.c - IntelTdx.c X64/VirtualMemory.c [Packages] @@ -70,9 +69,6 @@ gEfiNonCcFvGuid [Pcd] - gUefiOvmfPkgTokenSpaceGuid.PcdCfvBase - gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataOffset - gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataSize gUefiOvmfPkgTokenSpaceGuid.PcdBfvBase gUefiOvmfPkgTokenSpaceGuid.PcdBfvRawDataOffset gUefiOvmfPkgTokenSpaceGuid.PcdBfvRawDataSize From 8fc255cbec4a8e84ba38ee507e5a3942de352c81 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:42 +0800 Subject: [PATCH 0578/1529] OvmfPkg: Refactor ProcessHobList BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 ProcessHobList once was implemented in PlatformInitLib and it walks thru TdHob list and accept un-accepted memories. This patch moves the codes to SecTdxHelperLib and rename ProcessHobList as TdxHelperProcessTdHob After TdxHelperProcessTdHob is introduced, below changes are applied: - Call TdxHelperProcessTdHob instead of ProcessHobList in SecMain.c (in both OvmfPkgX64/Sec and IntelTdx/Sec). - Delete the duplicated codes in PlatformInitLib Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Include/Library/PlatformInitLib.h | 17 - OvmfPkg/IntelTdx/Sec/SecMain.c | 4 +- OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c | 754 ++++++++++++++++- OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 768 ------------------ .../Library/PlatformInitLib/IntelTdxNull.c | 20 - .../PlatformInitLib/PlatformInitLib.inf | 1 - OvmfPkg/OvmfPkgX64.dsc | 3 +- OvmfPkg/Sec/SecMain.c | 4 +- 8 files changed, 759 insertions(+), 812 deletions(-) diff --git a/OvmfPkg/Include/Library/PlatformInitLib.h b/OvmfPkg/Include/Library/PlatformInitLib.h index 051b311911..57b18b94d9 100644 --- a/OvmfPkg/Include/Library/PlatformInitLib.h +++ b/OvmfPkg/Include/Library/PlatformInitLib.h @@ -210,23 +210,6 @@ PlatformMaxCpuCountInitialization ( IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob ); -/** - In Tdx guest, some information need to be passed from host VMM to guest - firmware. For example, the memory resource, etc. These information are - prepared by host VMM and put in HobList which is described in TdxMetadata. - - Information in HobList is treated as external input. From the security - perspective before it is consumed, it should be validated. - - @retval EFI_SUCCESS Successfully process the hoblist - @retval Others Other error as indicated -**/ -EFI_STATUS -EFIAPI -ProcessTdxHobList ( - VOID - ); - /** In Tdx guest, the system memory is passed in TdHob by host VMM. So the major task of PlatformTdxPublishRamRegions is to walk thru the diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index ab01ec9ab1..41bd5c66ba 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -24,7 +24,7 @@ #include #include #include -#include +#include #include #include @@ -67,7 +67,7 @@ SecCoreStartupWithStack ( // first so that the memory is accepted. Otherwise access to the unaccepted // memory will trigger tripple fault. // - if (ProcessTdxHobList () != EFI_SUCCESS) { + if (TdxHelperProcessTdHob () != EFI_SUCCESS) { CpuDeadLoop (); } } diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c index 1929093f91..3372cee2f7 100644 --- a/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c +++ b/OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelper.c @@ -17,11 +17,20 @@ #include #include #include +#include +#include #include #include #include #include +#define ALIGNED_2MB_MASK 0x1fffff +#define MEGABYTE_SHIFT 20 + +#define ACCEPT_CHUNK_SIZE SIZE_32MB +#define AP_STACK_SIZE SIZE_16KB +#define APS_STACK_SIZE(CpusNum) (ALIGN_VALUE(CpusNum*AP_STACK_SIZE, SIZE_2MB)) + /** Build the GuidHob for tdx measurements which were done in SEC phase. The measurement values are stored in WorkArea. @@ -34,6 +43,720 @@ InternalBuildGuidHobForTdxMeasurement ( VOID ); +/** + This function will be called to accept pages. Only BSP accepts pages. + + TDCALL(ACCEPT_PAGE) supports the accept page size of 4k and 2M. To + simplify the implementation, the Memory to be accpeted is splitted + into 3 parts: + ----------------- <-- StartAddress1 (not 2M aligned) + | part 1 | Length1 < 2M + |---------------| <-- StartAddress2 (2M aligned) + | | Length2 = Integer multiples of 2M + | part 2 | + | | + |---------------| <-- StartAddress3 + | part 3 | Length3 < 2M + |---------------| + + @param[in] PhysicalAddress Start physical adress + @param[in] PhysicalEnd End physical address + + @retval EFI_SUCCESS Accept memory successfully + @retval Others Other errors as indicated +**/ +STATIC +EFI_STATUS +EFIAPI +BspAcceptMemoryResourceRange ( + IN EFI_PHYSICAL_ADDRESS PhysicalAddress, + IN EFI_PHYSICAL_ADDRESS PhysicalEnd + ) +{ + EFI_STATUS Status; + UINT32 AcceptPageSize; + UINT64 StartAddress1; + UINT64 StartAddress2; + UINT64 StartAddress3; + UINT64 TotalLength; + UINT64 Length1; + UINT64 Length2; + UINT64 Length3; + UINT64 Pages; + + AcceptPageSize = FixedPcdGet32 (PcdTdxAcceptPageSize); + TotalLength = PhysicalEnd - PhysicalAddress; + StartAddress1 = 0; + StartAddress2 = 0; + StartAddress3 = 0; + Length1 = 0; + Length2 = 0; + Length3 = 0; + + if (TotalLength == 0) { + return EFI_SUCCESS; + } + + if (ALIGN_VALUE (PhysicalAddress, SIZE_2MB) != PhysicalAddress) { + StartAddress1 = PhysicalAddress; + Length1 = ALIGN_VALUE (PhysicalAddress, SIZE_2MB) - PhysicalAddress; + if (Length1 >= TotalLength) { + Length1 = TotalLength; + } + + PhysicalAddress += Length1; + TotalLength -= Length1; + } + + if (TotalLength > SIZE_2MB) { + StartAddress2 = PhysicalAddress; + Length2 = TotalLength & ~(UINT64)ALIGNED_2MB_MASK; + PhysicalAddress += Length2; + TotalLength -= Length2; + } + + if (TotalLength) { + StartAddress3 = PhysicalAddress; + Length3 = TotalLength; + } + + Status = EFI_SUCCESS; + if (Length1 > 0) { + Pages = Length1 / SIZE_4KB; + Status = TdAcceptPages (StartAddress1, Pages, SIZE_4KB); + if (EFI_ERROR (Status)) { + return Status; + } + } + + if (Length2 > 0) { + Pages = Length2 / AcceptPageSize; + Status = TdAcceptPages (StartAddress2, Pages, AcceptPageSize); + if (EFI_ERROR (Status)) { + return Status; + } + } + + if (Length3 > 0) { + Pages = Length3 / SIZE_4KB; + Status = TdAcceptPages (StartAddress3, Pages, SIZE_4KB); + ASSERT (!EFI_ERROR (Status)); + if (EFI_ERROR (Status)) { + return Status; + } + } + + return Status; +} + +/** + * This function is called by BSP and APs to accept memory. + * Note: + * The input PhysicalStart/PhysicalEnd indicates the whole memory region + * to be accepted. BSP or AP only accepts one piece in the whole memory region. + * + * @param CpuIndex vCPU index + * @param CpusNum Total vCPU number of a Tdx guest + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Other Other errors as indicated + */ +STATIC +EFI_STATUS +EFIAPI +BspApAcceptMemoryResourceRange ( + UINT32 CpuIndex, + UINT32 CpusNum, + EFI_PHYSICAL_ADDRESS PhysicalStart, + EFI_PHYSICAL_ADDRESS PhysicalEnd + ) +{ + UINT64 Status; + UINT64 Pages; + UINT64 Stride; + UINT64 AcceptPageSize; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + + AcceptPageSize = (UINT64)(UINTN)FixedPcdGet32 (PcdTdxAcceptPageSize); + + Status = EFI_SUCCESS; + Stride = (UINTN)CpusNum * ACCEPT_CHUNK_SIZE; + PhysicalAddress = PhysicalStart + ACCEPT_CHUNK_SIZE * (UINTN)CpuIndex; + + while (!EFI_ERROR (Status) && PhysicalAddress < PhysicalEnd) { + Pages = MIN (ACCEPT_CHUNK_SIZE, PhysicalEnd - PhysicalAddress) / AcceptPageSize; + Status = TdAcceptPages (PhysicalAddress, Pages, (UINT32)(UINTN)AcceptPageSize); + ASSERT (!EFI_ERROR (Status)); + PhysicalAddress += Stride; + } + + return EFI_SUCCESS; +} + +/** + * This function is called by APs to accept memory. + * + * @param CpuIndex vCPU index of an AP + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Others Other errors as indicated + */ +STATIC +EFI_STATUS +EFIAPI +ApAcceptMemoryResourceRange ( + UINT32 CpuIndex, + EFI_PHYSICAL_ADDRESS PhysicalStart, + EFI_PHYSICAL_ADDRESS PhysicalEnd + ) +{ + UINT64 Status; + TD_RETURN_DATA TdReturnData; + + Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (Status != TDX_EXIT_REASON_SUCCESS) { + ASSERT (FALSE); + return EFI_ABORTED; + } + + if ((CpuIndex == 0) || (CpuIndex >= TdReturnData.TdInfo.NumVcpus)) { + ASSERT (FALSE); + return EFI_ABORTED; + } + + return BspApAcceptMemoryResourceRange (CpuIndex, TdReturnData.TdInfo.NumVcpus, PhysicalStart, PhysicalEnd); +} + +/** + * This function is called by BSP. It coordinates BSP/APs to accept memory together. + * + * @param PhysicalStart Start address of a memory region which is to be accepted + * @param PhysicalEnd End address of a memory region which is to be accepted + * @param APsStackAddress APs stack address + * @param CpusNum Total vCPU number of the Tdx guest + * + * @retval EFI_SUCCESS Successfully accept the memory + * @retval Others Other errors as indicated + */ +STATIC +EFI_STATUS +EFIAPI +MpAcceptMemoryResourceRange ( + IN EFI_PHYSICAL_ADDRESS PhysicalStart, + IN EFI_PHYSICAL_ADDRESS PhysicalEnd, + IN OUT EFI_PHYSICAL_ADDRESS APsStackAddress, + IN UINT32 CpusNum + ) +{ + UINT64 Length; + EFI_STATUS Status; + + Length = PhysicalEnd - PhysicalStart; + + DEBUG ((DEBUG_INFO, "MpAccept : 0x%llx - 0x%llx (0x%llx)\n", PhysicalStart, PhysicalEnd, Length)); + + if (Length == 0) { + return EFI_SUCCESS; + } + + // + // The start address is not 2M aligned. BSP first accept the part which is not 2M aligned. + // + if (ALIGN_VALUE (PhysicalStart, SIZE_2MB) != PhysicalStart) { + Length = MIN (ALIGN_VALUE (PhysicalStart, SIZE_2MB) - PhysicalStart, Length); + Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalStart + Length); + ASSERT (Status == EFI_SUCCESS); + + PhysicalStart += Length; + Length = PhysicalEnd - PhysicalStart; + } + + if (Length == 0) { + return EFI_SUCCESS; + } + + // + // BSP will accept the memory by itself if the memory is not big enough compared with a chunk. + // + if (Length <= ACCEPT_CHUNK_SIZE) { + return BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); + } + + // + // Now APs are asked to accept the memory together. + // + MpSerializeStart (); + + MpSendWakeupCommand ( + MpProtectedModeWakeupCommandAcceptPages, + (UINT64)(UINTN)ApAcceptMemoryResourceRange, + PhysicalStart, + PhysicalEnd, + APsStackAddress, + AP_STACK_SIZE + ); + + // + // Now BSP does its job. + // + BspApAcceptMemoryResourceRange (0, CpusNum, PhysicalStart, PhysicalEnd); + + MpSerializeEnd (); + + return EFI_SUCCESS; +} + +/** + BSP accept a small piece of memory which will be used as APs stack. + + @param[in] VmmHobList The Hoblist pass the firmware + @param[in] APsStackSize APs stack size + @param[out] PhysicalAddressEnd The physical end address of accepted memory in phase-1 + + @retval EFI_SUCCESS Process the HobList successfully + @retval Others Other errors as indicated +**/ +STATIC +EFI_STATUS +EFIAPI +AcceptMemoryForAPsStack ( + IN CONST VOID *VmmHobList, + IN UINT32 APsStackSize, + OUT EFI_PHYSICAL_ADDRESS *PhysicalAddressEnd + ) +{ + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + EFI_PHYSICAL_ADDRESS PhysicalStart; + UINT64 ResourceLength; + BOOLEAN MemoryRegionFound; + + ASSERT (VmmHobList != NULL); + + Status = EFI_SUCCESS; + Hob.Raw = (UINT8 *)VmmHobList; + MemoryRegionFound = FALSE; + + DEBUG ((DEBUG_INFO, "AcceptMemoryForAPsStack with APsStackSize=0x%x\n", APsStackSize)); + + // + // Parse the HOB list until end of list or matching type is found. + // + while (!END_OF_HOB_LIST (Hob) && !MemoryRegionFound) { + if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { + DEBUG ((DEBUG_INFO, "\nResourceType: 0x%x\n", Hob.ResourceDescriptor->ResourceType)); + + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { + ResourceLength = Hob.ResourceDescriptor->ResourceLength; + PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; + PhysicalEnd = PhysicalStart + ResourceLength; + + DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); + DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", PhysicalStart)); + DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", ResourceLength)); + DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); + + if (ResourceLength >= APsStackSize) { + MemoryRegionFound = TRUE; + if (ResourceLength > ACCEPT_CHUNK_SIZE) { + PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + APsStackSize; + } + } + + Status = BspAcceptMemoryResourceRange ( + Hob.ResourceDescriptor->PhysicalStart, + PhysicalEnd + ); + if (EFI_ERROR (Status)) { + break; + } + } + } + + Hob.Raw = GET_NEXT_HOB (Hob); + } + + ASSERT (MemoryRegionFound); + *PhysicalAddressEnd = PhysicalEnd; + + return Status; +} + +/** + BSP and APs work togeter to accept memory which is under the address of 4G. + + @param[in] VmmHobList The Hoblist pass the firmware + @param[in] CpusNum Number of vCPUs + @param[in] APsStackStartAddres Start address of APs stack + @param[in] PhysicalAddressStart Start physical address which to be accepted + + @retval EFI_SUCCESS Process the HobList successfully + @retval Others Other errors as indicated +**/ +STATIC +EFI_STATUS +EFIAPI +AcceptMemory ( + IN CONST VOID *VmmHobList, + IN UINT32 CpusNum, + IN EFI_PHYSICAL_ADDRESS APsStackStartAddress, + IN EFI_PHYSICAL_ADDRESS PhysicalAddressStart + ) +{ + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS PhysicalStart; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + EFI_PHYSICAL_ADDRESS AcceptMemoryEndAddress; + + Status = EFI_SUCCESS; + AcceptMemoryEndAddress = BASE_4GB; + + ASSERT (VmmHobList != NULL); + Hob.Raw = (UINT8 *)VmmHobList; + + DEBUG ((DEBUG_INFO, "AcceptMemory under address of 4G\n")); + + // + // Parse the HOB list until end of list or matching type is found. + // + while (!END_OF_HOB_LIST (Hob)) { + if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { + if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { + PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; + PhysicalEnd = PhysicalStart + Hob.ResourceDescriptor->ResourceLength; + + if (PhysicalEnd <= PhysicalAddressStart) { + // this memory region has been accepted. Skipped it. + Hob.Raw = GET_NEXT_HOB (Hob); + continue; + } + + if (PhysicalStart >= AcceptMemoryEndAddress) { + // this memory region is not to be accepted. And we're done. + break; + } + + if (PhysicalStart >= PhysicalAddressStart) { + // this memory region has not been acceted. + } else if ((PhysicalStart < PhysicalAddressStart) && (PhysicalEnd > PhysicalAddressStart)) { + // part of the memory region has been accepted. + PhysicalStart = PhysicalAddressStart; + } + + // then compare the PhysicalEnd with AcceptMemoryEndAddress + if (PhysicalEnd >= AcceptMemoryEndAddress) { + PhysicalEnd = AcceptMemoryEndAddress; + } + + DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); + DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", Hob.ResourceDescriptor->PhysicalStart)); + DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); + DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); + + // Now we're ready to accept memory [PhysicalStart, PhysicalEnd) + if (CpusNum == 1) { + Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); + } else { + Status = MpAcceptMemoryResourceRange ( + PhysicalStart, + PhysicalEnd, + APsStackStartAddress, + CpusNum + ); + } + + if (EFI_ERROR (Status)) { + ASSERT (FALSE); + break; + } + + if (PhysicalEnd == AcceptMemoryEndAddress) { + break; + } + } + } + + Hob.Raw = GET_NEXT_HOB (Hob); + } + + return Status; +} + +/** + Check the value whether in the valid list. + + @param[in] Value A value + @param[in] ValidList A pointer to valid list + @param[in] ValidListLength Length of valid list + + @retval TRUE The value is in valid list. + @retval FALSE The value is not in valid list. + +**/ +STATIC +BOOLEAN +EFIAPI +IsInValidList ( + IN UINT32 Value, + IN UINT32 *ValidList, + IN UINT32 ValidListLength + ) +{ + UINT32 index; + + if (ValidList == NULL) { + return FALSE; + } + + for (index = 0; index < ValidListLength; index++) { + if (ValidList[index] == Value) { + return TRUE; + } + } + + return FALSE; +} + +/** + Check the integrity of VMM Hob List. + + @param[in] VmmHobList A pointer to Hob List + + @retval TRUE The Hob List is valid. + @retval FALSE The Hob List is invalid. + +**/ +STATIC +BOOLEAN +EFIAPI +ValidateHobList ( + IN CONST VOID *VmmHobList + ) +{ + EFI_PEI_HOB_POINTERS Hob; + UINT32 EFI_BOOT_MODE_LIST[] = { + BOOT_WITH_FULL_CONFIGURATION, + BOOT_WITH_MINIMAL_CONFIGURATION, + BOOT_ASSUMING_NO_CONFIGURATION_CHANGES, + BOOT_WITH_FULL_CONFIGURATION_PLUS_DIAGNOSTICS, + BOOT_WITH_DEFAULT_SETTINGS, + BOOT_ON_S4_RESUME, + BOOT_ON_S5_RESUME, + BOOT_WITH_MFG_MODE_SETTINGS, + BOOT_ON_S2_RESUME, + BOOT_ON_S3_RESUME, + BOOT_ON_FLASH_UPDATE, + BOOT_IN_RECOVERY_MODE + }; + + UINT32 EFI_RESOURCE_TYPE_LIST[] = { + EFI_RESOURCE_SYSTEM_MEMORY, + EFI_RESOURCE_MEMORY_MAPPED_IO, + EFI_RESOURCE_IO, + EFI_RESOURCE_FIRMWARE_DEVICE, + EFI_RESOURCE_MEMORY_MAPPED_IO_PORT, + EFI_RESOURCE_MEMORY_RESERVED, + EFI_RESOURCE_IO_RESERVED, + BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED + }; + + if (VmmHobList == NULL) { + DEBUG ((DEBUG_ERROR, "HOB: HOB data pointer is NULL\n")); + return FALSE; + } + + Hob.Raw = (UINT8 *)VmmHobList; + + // + // Parse the HOB list until end of list or matching type is found. + // + while (!END_OF_HOB_LIST (Hob)) { + if (Hob.Header->Reserved != (UINT32)0) { + DEBUG ((DEBUG_ERROR, "HOB: Hob header Reserved filed should be zero\n")); + return FALSE; + } + + if (Hob.Header->HobLength == 0) { + DEBUG ((DEBUG_ERROR, "HOB: Hob header LEANGTH should not be zero\n")); + return FALSE; + } + + switch (Hob.Header->HobType) { + case EFI_HOB_TYPE_HANDOFF: + if (Hob.Header->HobLength != sizeof (EFI_HOB_HANDOFF_INFO_TABLE)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_HANDOFF)); + return FALSE; + } + + if (IsInValidList (Hob.HandoffInformationTable->BootMode, EFI_BOOT_MODE_LIST, ARRAY_SIZE (EFI_BOOT_MODE_LIST)) == FALSE) { + DEBUG ((DEBUG_ERROR, "HOB: Unknow HandoffInformationTable BootMode type. Type: 0x%08x\n", Hob.HandoffInformationTable->BootMode)); + return FALSE; + } + + if ((Hob.HandoffInformationTable->EfiFreeMemoryTop % 4096) != 0) { + DEBUG ((DEBUG_ERROR, "HOB: HandoffInformationTable EfiFreeMemoryTop address must be 4-KB aligned to meet page restrictions of UEFI.\ + Address: 0x%016lx\n", Hob.HandoffInformationTable->EfiFreeMemoryTop)); + return FALSE; + } + + break; + + case EFI_HOB_TYPE_RESOURCE_DESCRIPTOR: + if (Hob.Header->HobLength != sizeof (EFI_HOB_RESOURCE_DESCRIPTOR)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_RESOURCE_DESCRIPTOR)); + return FALSE; + } + + if (IsInValidList (Hob.ResourceDescriptor->ResourceType, EFI_RESOURCE_TYPE_LIST, ARRAY_SIZE (EFI_RESOURCE_TYPE_LIST)) == FALSE) { + DEBUG ((DEBUG_ERROR, "HOB: Unknow ResourceDescriptor ResourceType type. Type: 0x%08x\n", Hob.ResourceDescriptor->ResourceType)); + return FALSE; + } + + if ((Hob.ResourceDescriptor->ResourceAttribute & (~(EFI_RESOURCE_ATTRIBUTE_PRESENT | + EFI_RESOURCE_ATTRIBUTE_INITIALIZED | + EFI_RESOURCE_ATTRIBUTE_TESTED | + EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED | + EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED | + EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED | + EFI_RESOURCE_ATTRIBUTE_PERSISTENT | + EFI_RESOURCE_ATTRIBUTE_SINGLE_BIT_ECC | + EFI_RESOURCE_ATTRIBUTE_MULTIPLE_BIT_ECC | + EFI_RESOURCE_ATTRIBUTE_ECC_RESERVED_1 | + EFI_RESOURCE_ATTRIBUTE_ECC_RESERVED_2 | + EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE | + EFI_RESOURCE_ATTRIBUTE_16_BIT_IO | + EFI_RESOURCE_ATTRIBUTE_32_BIT_IO | + EFI_RESOURCE_ATTRIBUTE_64_BIT_IO | + EFI_RESOURCE_ATTRIBUTE_UNCACHED_EXPORTED | + EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE | + EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE | + EFI_RESOURCE_ATTRIBUTE_PERSISTABLE | + EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTED | + EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE | + EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE))) != 0) + { + DEBUG ((DEBUG_ERROR, "HOB: Unknow ResourceDescriptor ResourceAttribute type. Type: 0x%08x\n", Hob.ResourceDescriptor->ResourceAttribute)); + return FALSE; + } + + break; + + // EFI_HOB_GUID_TYPE is variable length data, so skip check + case EFI_HOB_TYPE_GUID_EXTENSION: + break; + + case EFI_HOB_TYPE_FV: + if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV)); + return FALSE; + } + + break; + + case EFI_HOB_TYPE_FV2: + if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME2)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV2)); + return FALSE; + } + + break; + + case EFI_HOB_TYPE_FV3: + if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME3)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV3)); + return FALSE; + } + + break; + + case EFI_HOB_TYPE_CPU: + if (Hob.Header->HobLength != sizeof (EFI_HOB_CPU)) { + DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_CPU)); + return FALSE; + } + + for (UINT32 index = 0; index < 6; index++) { + if (Hob.Cpu->Reserved[index] != 0) { + DEBUG ((DEBUG_ERROR, "HOB: Cpu Reserved field will always be set to zero.\n")); + return FALSE; + } + } + + break; + + default: + DEBUG ((DEBUG_ERROR, "HOB: Hob type is not know. Type: 0x%04x\n", Hob.Header->HobType)); + return FALSE; + } + + // Get next HOB + Hob.Raw = (UINT8 *)(Hob.Raw + Hob.Header->HobLength); + } + + return TRUE; +} + +/** + Processing the incoming HobList for the TDX + + Firmware must parse list, and accept the pages of memory before their can be + use by the guest. + + @param[in] VmmHobList The Hoblist pass the firmware + + @retval EFI_SUCCESS Process the HobList successfully + @retval Others Other errors as indicated + +**/ +STATIC +EFI_STATUS +EFIAPI +ProcessHobList ( + IN CONST VOID *VmmHobList + ) +{ + EFI_STATUS Status; + UINT32 CpusNum; + EFI_PHYSICAL_ADDRESS PhysicalEnd; + EFI_PHYSICAL_ADDRESS APsStackStartAddress; + + CpusNum = GetCpusNum (); + + // + // If there are mutli-vCPU in a TDX guest, accept memory is split into 2 phases. + // Phase-1 accepts a small piece of memory by BSP. This piece of memory + // is used to setup AP's stack. + // After that phase-2 accepts a big piece of memory by BSP/APs. + // + // TDVF supports 4K and 2M accept-page-size. The memory which can be accpeted + // in 2M accept-page-size must be 2M aligned and multiple 2M. So we align + // APsStackSize to 2M size aligned. + // + if (CpusNum > 1) { + Status = AcceptMemoryForAPsStack (VmmHobList, APS_STACK_SIZE (CpusNum), &PhysicalEnd); + ASSERT (Status == EFI_SUCCESS); + APsStackStartAddress = PhysicalEnd - APS_STACK_SIZE (CpusNum); + } else { + PhysicalEnd = 0; + APsStackStartAddress = 0; + } + + Status = AcceptMemory (VmmHobList, CpusNum, APsStackStartAddress, PhysicalEnd); + ASSERT (Status == EFI_SUCCESS); + + return Status; +} + /** In Tdx guest, some information need to be passed from host VMM to guest firmware. For example, the memory resource, etc. These information are @@ -49,7 +772,36 @@ TdxHelperProcessTdHob ( VOID ) { - return EFI_UNSUPPORTED; + EFI_STATUS Status; + VOID *TdHob; + TD_RETURN_DATA TdReturnData; + + TdHob = (VOID *)(UINTN)FixedPcdGet32 (PcdOvmfSecGhcbBase); + Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); + if (EFI_ERROR (Status)) { + return Status; + } + + DEBUG (( + DEBUG_INFO, + "Intel Tdx Started with (GPAW: %d, Cpus: %d)\n", + TdReturnData.TdInfo.Gpaw, + TdReturnData.TdInfo.NumVcpus + )); + + // + // Validate HobList + // + if (ValidateHobList (TdHob) == FALSE) { + return EFI_INVALID_PARAMETER; + } + + // + // Process Hoblist to accept memory + // + Status = ProcessHobList (TdHob); + + return Status; } /** diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c index 6cb63139cb..ada8592ddd 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdx.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdx.c @@ -16,779 +16,11 @@ #include #include #include -#include -#include #include -#include -#include -#include #include #include #include -#define ALIGNED_2MB_MASK 0x1fffff -#define MEGABYTE_SHIFT 20 - -#define ACCEPT_CHUNK_SIZE SIZE_32MB -#define AP_STACK_SIZE SIZE_16KB -#define APS_STACK_SIZE(CpusNum) (ALIGN_VALUE(CpusNum*AP_STACK_SIZE, SIZE_2MB)) - -/** - This function will be called to accept pages. Only BSP accepts pages. - - TDCALL(ACCEPT_PAGE) supports the accept page size of 4k and 2M. To - simplify the implementation, the Memory to be accpeted is splitted - into 3 parts: - ----------------- <-- StartAddress1 (not 2M aligned) - | part 1 | Length1 < 2M - |---------------| <-- StartAddress2 (2M aligned) - | | Length2 = Integer multiples of 2M - | part 2 | - | | - |---------------| <-- StartAddress3 - | part 3 | Length3 < 2M - |---------------| - - @param[in] PhysicalAddress Start physical adress - @param[in] PhysicalEnd End physical address - - @retval EFI_SUCCESS Accept memory successfully - @retval Others Other errors as indicated -**/ -EFI_STATUS -EFIAPI -BspAcceptMemoryResourceRange ( - IN EFI_PHYSICAL_ADDRESS PhysicalAddress, - IN EFI_PHYSICAL_ADDRESS PhysicalEnd - ) -{ - EFI_STATUS Status; - UINT32 AcceptPageSize; - UINT64 StartAddress1; - UINT64 StartAddress2; - UINT64 StartAddress3; - UINT64 TotalLength; - UINT64 Length1; - UINT64 Length2; - UINT64 Length3; - UINT64 Pages; - - AcceptPageSize = FixedPcdGet32 (PcdTdxAcceptPageSize); - TotalLength = PhysicalEnd - PhysicalAddress; - StartAddress1 = 0; - StartAddress2 = 0; - StartAddress3 = 0; - Length1 = 0; - Length2 = 0; - Length3 = 0; - - if (TotalLength == 0) { - return EFI_SUCCESS; - } - - if (ALIGN_VALUE (PhysicalAddress, SIZE_2MB) != PhysicalAddress) { - StartAddress1 = PhysicalAddress; - Length1 = ALIGN_VALUE (PhysicalAddress, SIZE_2MB) - PhysicalAddress; - if (Length1 >= TotalLength) { - Length1 = TotalLength; - } - - PhysicalAddress += Length1; - TotalLength -= Length1; - } - - if (TotalLength > SIZE_2MB) { - StartAddress2 = PhysicalAddress; - Length2 = TotalLength & ~(UINT64)ALIGNED_2MB_MASK; - PhysicalAddress += Length2; - TotalLength -= Length2; - } - - if (TotalLength) { - StartAddress3 = PhysicalAddress; - Length3 = TotalLength; - } - - Status = EFI_SUCCESS; - if (Length1 > 0) { - Pages = Length1 / SIZE_4KB; - Status = TdAcceptPages (StartAddress1, Pages, SIZE_4KB); - if (EFI_ERROR (Status)) { - return Status; - } - } - - if (Length2 > 0) { - Pages = Length2 / AcceptPageSize; - Status = TdAcceptPages (StartAddress2, Pages, AcceptPageSize); - if (EFI_ERROR (Status)) { - return Status; - } - } - - if (Length3 > 0) { - Pages = Length3 / SIZE_4KB; - Status = TdAcceptPages (StartAddress3, Pages, SIZE_4KB); - ASSERT (!EFI_ERROR (Status)); - if (EFI_ERROR (Status)) { - return Status; - } - } - - return Status; -} - -/** - * This function is called by BSP and APs to accept memory. - * Note: - * The input PhysicalStart/PhysicalEnd indicates the whole memory region - * to be accepted. BSP or AP only accepts one piece in the whole memory region. - * - * @param CpuIndex vCPU index - * @param CpusNum Total vCPU number of a Tdx guest - * @param PhysicalStart Start address of a memory region which is to be accepted - * @param PhysicalEnd End address of a memory region which is to be accepted - * - * @retval EFI_SUCCESS Successfully accept the memory - * @retval Other Other errors as indicated - */ -STATIC -EFI_STATUS -EFIAPI -BspApAcceptMemoryResourceRange ( - UINT32 CpuIndex, - UINT32 CpusNum, - EFI_PHYSICAL_ADDRESS PhysicalStart, - EFI_PHYSICAL_ADDRESS PhysicalEnd - ) -{ - UINT64 Status; - UINT64 Pages; - UINT64 Stride; - UINT64 AcceptPageSize; - EFI_PHYSICAL_ADDRESS PhysicalAddress; - - AcceptPageSize = (UINT64)(UINTN)FixedPcdGet32 (PcdTdxAcceptPageSize); - - Status = EFI_SUCCESS; - Stride = (UINTN)CpusNum * ACCEPT_CHUNK_SIZE; - PhysicalAddress = PhysicalStart + ACCEPT_CHUNK_SIZE * (UINTN)CpuIndex; - - while (!EFI_ERROR (Status) && PhysicalAddress < PhysicalEnd) { - Pages = MIN (ACCEPT_CHUNK_SIZE, PhysicalEnd - PhysicalAddress) / AcceptPageSize; - Status = TdAcceptPages (PhysicalAddress, Pages, (UINT32)(UINTN)AcceptPageSize); - ASSERT (!EFI_ERROR (Status)); - PhysicalAddress += Stride; - } - - return EFI_SUCCESS; -} - -/** - * This function is called by APs to accept memory. - * - * @param CpuIndex vCPU index of an AP - * @param PhysicalStart Start address of a memory region which is to be accepted - * @param PhysicalEnd End address of a memory region which is to be accepted - * - * @retval EFI_SUCCESS Successfully accept the memory - * @retval Others Other errors as indicated - */ -STATIC -EFI_STATUS -EFIAPI -ApAcceptMemoryResourceRange ( - UINT32 CpuIndex, - EFI_PHYSICAL_ADDRESS PhysicalStart, - EFI_PHYSICAL_ADDRESS PhysicalEnd - ) -{ - UINT64 Status; - TD_RETURN_DATA TdReturnData; - - Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); - if (Status != TDX_EXIT_REASON_SUCCESS) { - ASSERT (FALSE); - return EFI_ABORTED; - } - - if ((CpuIndex == 0) || (CpuIndex >= TdReturnData.TdInfo.NumVcpus)) { - ASSERT (FALSE); - return EFI_ABORTED; - } - - return BspApAcceptMemoryResourceRange (CpuIndex, TdReturnData.TdInfo.NumVcpus, PhysicalStart, PhysicalEnd); -} - -/** - * This function is called by BSP. It coordinates BSP/APs to accept memory together. - * - * @param PhysicalStart Start address of a memory region which is to be accepted - * @param PhysicalEnd End address of a memory region which is to be accepted - * @param APsStackAddress APs stack address - * @param CpusNum Total vCPU number of the Tdx guest - * - * @retval EFI_SUCCESS Successfully accept the memory - * @retval Others Other errors as indicated - */ -EFI_STATUS -EFIAPI -MpAcceptMemoryResourceRange ( - IN EFI_PHYSICAL_ADDRESS PhysicalStart, - IN EFI_PHYSICAL_ADDRESS PhysicalEnd, - IN OUT EFI_PHYSICAL_ADDRESS APsStackAddress, - IN UINT32 CpusNum - ) -{ - UINT64 Length; - EFI_STATUS Status; - - Length = PhysicalEnd - PhysicalStart; - - DEBUG ((DEBUG_INFO, "MpAccept : 0x%llx - 0x%llx (0x%llx)\n", PhysicalStart, PhysicalEnd, Length)); - - if (Length == 0) { - return EFI_SUCCESS; - } - - // - // The start address is not 2M aligned. BSP first accept the part which is not 2M aligned. - // - if (ALIGN_VALUE (PhysicalStart, SIZE_2MB) != PhysicalStart) { - Length = MIN (ALIGN_VALUE (PhysicalStart, SIZE_2MB) - PhysicalStart, Length); - Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalStart + Length); - ASSERT (Status == EFI_SUCCESS); - - PhysicalStart += Length; - Length = PhysicalEnd - PhysicalStart; - } - - if (Length == 0) { - return EFI_SUCCESS; - } - - // - // BSP will accept the memory by itself if the memory is not big enough compared with a chunk. - // - if (Length <= ACCEPT_CHUNK_SIZE) { - return BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); - } - - // - // Now APs are asked to accept the memory together. - // - MpSerializeStart (); - - MpSendWakeupCommand ( - MpProtectedModeWakeupCommandAcceptPages, - (UINT64)(UINTN)ApAcceptMemoryResourceRange, - PhysicalStart, - PhysicalEnd, - APsStackAddress, - AP_STACK_SIZE - ); - - // - // Now BSP does its job. - // - BspApAcceptMemoryResourceRange (0, CpusNum, PhysicalStart, PhysicalEnd); - - MpSerializeEnd (); - - return EFI_SUCCESS; -} - -/** - BSP accept a small piece of memory which will be used as APs stack. - - @param[in] VmmHobList The Hoblist pass the firmware - @param[in] APsStackSize APs stack size - @param[out] PhysicalAddressEnd The physical end address of accepted memory in phase-1 - - @retval EFI_SUCCESS Process the HobList successfully - @retval Others Other errors as indicated -**/ -EFI_STATUS -EFIAPI -AcceptMemoryForAPsStack ( - IN CONST VOID *VmmHobList, - IN UINT32 APsStackSize, - OUT EFI_PHYSICAL_ADDRESS *PhysicalAddressEnd - ) -{ - EFI_STATUS Status; - EFI_PEI_HOB_POINTERS Hob; - EFI_PHYSICAL_ADDRESS PhysicalEnd; - EFI_PHYSICAL_ADDRESS PhysicalStart; - UINT64 ResourceLength; - BOOLEAN MemoryRegionFound; - - ASSERT (VmmHobList != NULL); - - Status = EFI_SUCCESS; - Hob.Raw = (UINT8 *)VmmHobList; - MemoryRegionFound = FALSE; - - DEBUG ((DEBUG_INFO, "AcceptMemoryForAPsStack with APsStackSize=0x%x\n", APsStackSize)); - - // - // Parse the HOB list until end of list or matching type is found. - // - while (!END_OF_HOB_LIST (Hob) && !MemoryRegionFound) { - if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - DEBUG ((DEBUG_INFO, "\nResourceType: 0x%x\n", Hob.ResourceDescriptor->ResourceType)); - - if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { - ResourceLength = Hob.ResourceDescriptor->ResourceLength; - PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; - PhysicalEnd = PhysicalStart + ResourceLength; - - DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); - DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", PhysicalStart)); - DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", ResourceLength)); - DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); - - if (ResourceLength >= APsStackSize) { - MemoryRegionFound = TRUE; - if (ResourceLength > ACCEPT_CHUNK_SIZE) { - PhysicalEnd = Hob.ResourceDescriptor->PhysicalStart + APsStackSize; - } - } - - Status = BspAcceptMemoryResourceRange ( - Hob.ResourceDescriptor->PhysicalStart, - PhysicalEnd - ); - if (EFI_ERROR (Status)) { - break; - } - } - } - - Hob.Raw = GET_NEXT_HOB (Hob); - } - - ASSERT (MemoryRegionFound); - *PhysicalAddressEnd = PhysicalEnd; - - return Status; -} - -/** - BSP and APs work togeter to accept memory which is under the address of 4G. - - @param[in] VmmHobList The Hoblist pass the firmware - @param[in] CpusNum Number of vCPUs - @param[in] APsStackStartAddres Start address of APs stack - @param[in] PhysicalAddressStart Start physical address which to be accepted - - @retval EFI_SUCCESS Process the HobList successfully - @retval Others Other errors as indicated -**/ -EFI_STATUS -EFIAPI -AcceptMemory ( - IN CONST VOID *VmmHobList, - IN UINT32 CpusNum, - IN EFI_PHYSICAL_ADDRESS APsStackStartAddress, - IN EFI_PHYSICAL_ADDRESS PhysicalAddressStart - ) -{ - EFI_STATUS Status; - EFI_PEI_HOB_POINTERS Hob; - EFI_PHYSICAL_ADDRESS PhysicalStart; - EFI_PHYSICAL_ADDRESS PhysicalEnd; - EFI_PHYSICAL_ADDRESS AcceptMemoryEndAddress; - - Status = EFI_SUCCESS; - AcceptMemoryEndAddress = BASE_4GB; - - ASSERT (VmmHobList != NULL); - Hob.Raw = (UINT8 *)VmmHobList; - - DEBUG ((DEBUG_INFO, "AcceptMemory under address of 4G\n")); - - // - // Parse the HOB list until end of list or matching type is found. - // - while (!END_OF_HOB_LIST (Hob)) { - if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - if (Hob.ResourceDescriptor->ResourceType == BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED) { - PhysicalStart = Hob.ResourceDescriptor->PhysicalStart; - PhysicalEnd = PhysicalStart + Hob.ResourceDescriptor->ResourceLength; - - if (PhysicalEnd <= PhysicalAddressStart) { - // this memory region has been accepted. Skipped it. - Hob.Raw = GET_NEXT_HOB (Hob); - continue; - } - - if (PhysicalStart >= AcceptMemoryEndAddress) { - // this memory region is not to be accepted. And we're done. - break; - } - - if (PhysicalStart >= PhysicalAddressStart) { - // this memory region has not been acceted. - } else if ((PhysicalStart < PhysicalAddressStart) && (PhysicalEnd > PhysicalAddressStart)) { - // part of the memory region has been accepted. - PhysicalStart = PhysicalAddressStart; - } - - // then compare the PhysicalEnd with AcceptMemoryEndAddress - if (PhysicalEnd >= AcceptMemoryEndAddress) { - PhysicalEnd = AcceptMemoryEndAddress; - } - - DEBUG ((DEBUG_INFO, "ResourceAttribute: 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); - DEBUG ((DEBUG_INFO, "PhysicalStart: 0x%llx\n", Hob.ResourceDescriptor->PhysicalStart)); - DEBUG ((DEBUG_INFO, "ResourceLength: 0x%llx\n", Hob.ResourceDescriptor->ResourceLength)); - DEBUG ((DEBUG_INFO, "Owner: %g\n\n", &Hob.ResourceDescriptor->Owner)); - - // Now we're ready to accept memory [PhysicalStart, PhysicalEnd) - if (CpusNum == 1) { - Status = BspAcceptMemoryResourceRange (PhysicalStart, PhysicalEnd); - } else { - Status = MpAcceptMemoryResourceRange ( - PhysicalStart, - PhysicalEnd, - APsStackStartAddress, - CpusNum - ); - } - - if (EFI_ERROR (Status)) { - ASSERT (FALSE); - break; - } - - if (PhysicalEnd == AcceptMemoryEndAddress) { - break; - } - } - } - - Hob.Raw = GET_NEXT_HOB (Hob); - } - - return Status; -} - -/** - Check the value whether in the valid list. - - @param[in] Value A value - @param[in] ValidList A pointer to valid list - @param[in] ValidListLength Length of valid list - - @retval TRUE The value is in valid list. - @retval FALSE The value is not in valid list. - -**/ -BOOLEAN -EFIAPI -IsInValidList ( - IN UINT32 Value, - IN UINT32 *ValidList, - IN UINT32 ValidListLength - ) -{ - UINT32 index; - - if (ValidList == NULL) { - return FALSE; - } - - for (index = 0; index < ValidListLength; index++) { - if (ValidList[index] == Value) { - return TRUE; - } - } - - return FALSE; -} - -/** - Check the integrity of VMM Hob List. - - @param[in] VmmHobList A pointer to Hob List - - @retval TRUE The Hob List is valid. - @retval FALSE The Hob List is invalid. - -**/ -BOOLEAN -EFIAPI -ValidateHobList ( - IN CONST VOID *VmmHobList - ) -{ - EFI_PEI_HOB_POINTERS Hob; - UINT32 EFI_BOOT_MODE_LIST[] = { - BOOT_WITH_FULL_CONFIGURATION, - BOOT_WITH_MINIMAL_CONFIGURATION, - BOOT_ASSUMING_NO_CONFIGURATION_CHANGES, - BOOT_WITH_FULL_CONFIGURATION_PLUS_DIAGNOSTICS, - BOOT_WITH_DEFAULT_SETTINGS, - BOOT_ON_S4_RESUME, - BOOT_ON_S5_RESUME, - BOOT_WITH_MFG_MODE_SETTINGS, - BOOT_ON_S2_RESUME, - BOOT_ON_S3_RESUME, - BOOT_ON_FLASH_UPDATE, - BOOT_IN_RECOVERY_MODE - }; - - UINT32 EFI_RESOURCE_TYPE_LIST[] = { - EFI_RESOURCE_SYSTEM_MEMORY, - EFI_RESOURCE_MEMORY_MAPPED_IO, - EFI_RESOURCE_IO, - EFI_RESOURCE_FIRMWARE_DEVICE, - EFI_RESOURCE_MEMORY_MAPPED_IO_PORT, - EFI_RESOURCE_MEMORY_RESERVED, - EFI_RESOURCE_IO_RESERVED, - BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED - }; - - if (VmmHobList == NULL) { - DEBUG ((DEBUG_ERROR, "HOB: HOB data pointer is NULL\n")); - return FALSE; - } - - Hob.Raw = (UINT8 *)VmmHobList; - - // - // Parse the HOB list until end of list or matching type is found. - // - while (!END_OF_HOB_LIST (Hob)) { - if (Hob.Header->Reserved != (UINT32)0) { - DEBUG ((DEBUG_ERROR, "HOB: Hob header Reserved filed should be zero\n")); - return FALSE; - } - - if (Hob.Header->HobLength == 0) { - DEBUG ((DEBUG_ERROR, "HOB: Hob header LEANGTH should not be zero\n")); - return FALSE; - } - - switch (Hob.Header->HobType) { - case EFI_HOB_TYPE_HANDOFF: - if (Hob.Header->HobLength != sizeof (EFI_HOB_HANDOFF_INFO_TABLE)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_HANDOFF)); - return FALSE; - } - - if (IsInValidList (Hob.HandoffInformationTable->BootMode, EFI_BOOT_MODE_LIST, ARRAY_SIZE (EFI_BOOT_MODE_LIST)) == FALSE) { - DEBUG ((DEBUG_ERROR, "HOB: Unknow HandoffInformationTable BootMode type. Type: 0x%08x\n", Hob.HandoffInformationTable->BootMode)); - return FALSE; - } - - if ((Hob.HandoffInformationTable->EfiFreeMemoryTop % 4096) != 0) { - DEBUG ((DEBUG_ERROR, "HOB: HandoffInformationTable EfiFreeMemoryTop address must be 4-KB aligned to meet page restrictions of UEFI.\ - Address: 0x%016lx\n", Hob.HandoffInformationTable->EfiFreeMemoryTop)); - return FALSE; - } - - break; - - case EFI_HOB_TYPE_RESOURCE_DESCRIPTOR: - if (Hob.Header->HobLength != sizeof (EFI_HOB_RESOURCE_DESCRIPTOR)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_RESOURCE_DESCRIPTOR)); - return FALSE; - } - - if (IsInValidList (Hob.ResourceDescriptor->ResourceType, EFI_RESOURCE_TYPE_LIST, ARRAY_SIZE (EFI_RESOURCE_TYPE_LIST)) == FALSE) { - DEBUG ((DEBUG_ERROR, "HOB: Unknow ResourceDescriptor ResourceType type. Type: 0x%08x\n", Hob.ResourceDescriptor->ResourceType)); - return FALSE; - } - - if ((Hob.ResourceDescriptor->ResourceAttribute & (~(EFI_RESOURCE_ATTRIBUTE_PRESENT | - EFI_RESOURCE_ATTRIBUTE_INITIALIZED | - EFI_RESOURCE_ATTRIBUTE_TESTED | - EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED | - EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED | - EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED | - EFI_RESOURCE_ATTRIBUTE_PERSISTENT | - EFI_RESOURCE_ATTRIBUTE_SINGLE_BIT_ECC | - EFI_RESOURCE_ATTRIBUTE_MULTIPLE_BIT_ECC | - EFI_RESOURCE_ATTRIBUTE_ECC_RESERVED_1 | - EFI_RESOURCE_ATTRIBUTE_ECC_RESERVED_2 | - EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE | - EFI_RESOURCE_ATTRIBUTE_16_BIT_IO | - EFI_RESOURCE_ATTRIBUTE_32_BIT_IO | - EFI_RESOURCE_ATTRIBUTE_64_BIT_IO | - EFI_RESOURCE_ATTRIBUTE_UNCACHED_EXPORTED | - EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE | - EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE | - EFI_RESOURCE_ATTRIBUTE_PERSISTABLE | - EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTED | - EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE | - EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE))) != 0) - { - DEBUG ((DEBUG_ERROR, "HOB: Unknow ResourceDescriptor ResourceAttribute type. Type: 0x%08x\n", Hob.ResourceDescriptor->ResourceAttribute)); - return FALSE; - } - - break; - - // EFI_HOB_GUID_TYPE is variable length data, so skip check - case EFI_HOB_TYPE_GUID_EXTENSION: - break; - - case EFI_HOB_TYPE_FV: - if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV)); - return FALSE; - } - - break; - - case EFI_HOB_TYPE_FV2: - if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME2)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV2)); - return FALSE; - } - - break; - - case EFI_HOB_TYPE_FV3: - if (Hob.Header->HobLength != sizeof (EFI_HOB_FIRMWARE_VOLUME3)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_FV3)); - return FALSE; - } - - break; - - case EFI_HOB_TYPE_CPU: - if (Hob.Header->HobLength != sizeof (EFI_HOB_CPU)) { - DEBUG ((DEBUG_ERROR, "HOB: Hob length is not equal corresponding hob structure. Type: 0x%04x\n", EFI_HOB_TYPE_CPU)); - return FALSE; - } - - for (UINT32 index = 0; index < 6; index++) { - if (Hob.Cpu->Reserved[index] != 0) { - DEBUG ((DEBUG_ERROR, "HOB: Cpu Reserved field will always be set to zero.\n")); - return FALSE; - } - } - - break; - - default: - DEBUG ((DEBUG_ERROR, "HOB: Hob type is not know. Type: 0x%04x\n", Hob.Header->HobType)); - return FALSE; - } - - // Get next HOB - Hob.Raw = (UINT8 *)(Hob.Raw + Hob.Header->HobLength); - } - - return TRUE; -} - -/** - Processing the incoming HobList for the TDX - - Firmware must parse list, and accept the pages of memory before their can be - use by the guest. - - @param[in] VmmHobList The Hoblist pass the firmware - - @retval EFI_SUCCESS Process the HobList successfully - @retval Others Other errors as indicated - -**/ -EFI_STATUS -EFIAPI -ProcessHobList ( - IN CONST VOID *VmmHobList - ) -{ - EFI_STATUS Status; - UINT32 CpusNum; - EFI_PHYSICAL_ADDRESS PhysicalEnd; - EFI_PHYSICAL_ADDRESS APsStackStartAddress; - - CpusNum = GetCpusNum (); - - // - // If there are mutli-vCPU in a TDX guest, accept memory is split into 2 phases. - // Phase-1 accepts a small piece of memory by BSP. This piece of memory - // is used to setup AP's stack. - // After that phase-2 accepts a big piece of memory by BSP/APs. - // - // TDVF supports 4K and 2M accept-page-size. The memory which can be accpeted - // in 2M accept-page-size must be 2M aligned and multiple 2M. So we align - // APsStackSize to 2M size aligned. - // - if (CpusNum > 1) { - Status = AcceptMemoryForAPsStack (VmmHobList, APS_STACK_SIZE (CpusNum), &PhysicalEnd); - ASSERT (Status == EFI_SUCCESS); - APsStackStartAddress = PhysicalEnd - APS_STACK_SIZE (CpusNum); - } else { - PhysicalEnd = 0; - APsStackStartAddress = 0; - } - - Status = AcceptMemory (VmmHobList, CpusNum, APsStackStartAddress, PhysicalEnd); - ASSERT (Status == EFI_SUCCESS); - - return Status; -} - -/** - In Tdx guest, some information need to be passed from host VMM to guest - firmware. For example, the memory resource, etc. These information are - prepared by host VMM and put in HobList which is described in TdxMetadata. - - Information in HobList is treated as external input. From the security - perspective before it is consumed, it should be validated. - - @retval EFI_SUCCESS Successfully process the hoblist - @retval Others Other error as indicated -**/ -EFI_STATUS -EFIAPI -ProcessTdxHobList ( - VOID - ) -{ - EFI_STATUS Status; - VOID *TdHob; - TD_RETURN_DATA TdReturnData; - - TdHob = (VOID *)(UINTN)FixedPcdGet32 (PcdOvmfSecGhcbBase); - Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData); - if (EFI_ERROR (Status)) { - return Status; - } - - DEBUG (( - DEBUG_INFO, - "Intel Tdx Started with (GPAW: %d, Cpus: %d)\n", - TdReturnData.TdInfo.Gpaw, - TdReturnData.TdInfo.NumVcpus - )); - - // - // Validate HobList - // - if (ValidateHobList (TdHob) == FALSE) { - return EFI_INVALID_PARAMETER; - } - - // - // Process Hoblist to accept memory - // - Status = ProcessHobList (TdHob); - - return Status; -} - /** * Build ResourceDescriptorHob for the unaccepted memory region. * This memory region may be splitted into 2 parts because of lazy accept. diff --git a/OvmfPkg/Library/PlatformInitLib/IntelTdxNull.c b/OvmfPkg/Library/PlatformInitLib/IntelTdxNull.c index 3ebe582af8..7a7c2fb1f6 100644 --- a/OvmfPkg/Library/PlatformInitLib/IntelTdxNull.c +++ b/OvmfPkg/Library/PlatformInitLib/IntelTdxNull.c @@ -9,26 +9,6 @@ #include -/** - In Tdx guest, some information need to be passed from host VMM to guest - firmware. For example, the memory resource, etc. These information are - prepared by host VMM and put in HobList which is described in TdxMetadata. - - Information in HobList is treated as external input. From the security - perspective before it is consumed, it should be validated. - - @retval EFI_SUCCESS Successfully process the hoblist - @retval Others Other error as indicated -**/ -EFI_STATUS -EFIAPI -ProcessTdxHobList ( - VOID - ) -{ - return EFI_UNSUPPORTED; -} - /** In Tdx guest, the system memory is passed in TdHob by host VMM. So the major task of PlatformTdxPublishRamRegions is to walk thru the diff --git a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf index 140216979a..86a82ad3e0 100644 --- a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf +++ b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf @@ -52,7 +52,6 @@ PcdLib PciLib PeiHardwareInfoLib - TdxMailboxLib [LibraryClasses.X64] TdxLib diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 3f970a79a0..d87013a442 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -724,7 +724,8 @@ OvmfPkg/Sec/SecMain.inf { NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf - NULL|OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf + NULL|OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf } # diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index 1167d22a68..a27dc9406b 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include "AmdSev.h" @@ -765,7 +765,7 @@ SecCoreStartupWithStack ( // first so that the memory is accepted. Otherwise access to the unaccepted // memory will trigger tripple fault. // - if (ProcessTdxHobList () != EFI_SUCCESS) { + if (TdxHelperProcessTdHob () != EFI_SUCCESS) { CpuDeadLoop (); } } From 19ce838cf0b51756fda5c6c5e709dae735ffeca8 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:43 +0800 Subject: [PATCH 0579/1529] OvmfPkg/IntelTdx: Measure TdHob and Configuration FV in SecMain BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdHob and Configuration FV (Cfv) are external inputs from VMM. From the security perspective, they should be measured before they're consumed. This patch measures TdHob and Cfv and stores the measurement values in WorkArea. After TdHob and Configuration FV (Cfv) are measured in SecMain, the same measurements in PeilessStartupLib are deleted. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Reviewed-by: Jiewen Yao Signed-off-by: Min Xu Acked-by: Gerd Hoffmann --- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 3 --- OvmfPkg/IntelTdx/Sec/SecMain.c | 13 ++++++++++++ .../PeilessStartupLib/PeilessStartup.c | 20 +------------------ .../PeilessStartupLib/PeilessStartupLib.inf | 2 -- 4 files changed, 14 insertions(+), 24 deletions(-) diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 920f1c6080..41de2e9428 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -548,11 +548,8 @@ OvmfPkg/IntelTdx/Sec/SecMain.inf { NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf - TpmMeasurementLib|SecurityPkg/Library/SecTpmMeasurementLib/SecTpmMeasurementLibTdx.inf NULL|OvmfPkg/IntelTdx/TdxHelperLib/SecTdxHelperLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf - HashLib|SecurityPkg/Library/HashLibTdx/HashLibTdx.inf - NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf } # diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index 41bd5c66ba..ccb217b709 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -62,6 +62,19 @@ SecCoreStartupWithStack ( volatile UINT8 *Table; if (CcProbe () == CcGuestTypeIntelTdx) { + // + // From the security perspective all the external input should be measured before + // it is consumed. TdHob and Configuration FV (Cfv) image are passed from VMM + // and should be measured here. + // + if (EFI_ERROR (TdxHelperMeasureTdHob ())) { + CpuDeadLoop (); + } + + if (EFI_ERROR (TdxHelperMeasureCfvImage ())) { + CpuDeadLoop (); + } + // // For Td guests, the memory map info is in TdHobLib. It should be processed // first so that the memory is accepted. Otherwise access to the unaccepted diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c index 79d3a178a6..164aa2d619 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c @@ -176,25 +176,7 @@ PeilessStartup ( if (TdIsEnabled ()) { // - // Measure HobList - // - Status = TdxHelperMeasureTdHob (); - if (EFI_ERROR (Status)) { - ASSERT (FALSE); - CpuDeadLoop (); - } - - // - // Measure Tdx CFV - // - Status = TdxHelperMeasureCfvImage (); - if (EFI_ERROR (Status)) { - ASSERT (FALSE); - CpuDeadLoop (); - } - - // - // Build GuidHob for tdx measurement + // Build GuidHob for the tdx measurements which were done in SEC phase. // Status = TdxHelperBuildGuidHobForTdxMeasurement (); if (EFI_ERROR (Status)) { diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf index 4ced5dda99..e77ad7bc92 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf @@ -56,8 +56,6 @@ PrePiLib QemuFwCfgLib PlatformInitLib - HashLib - TpmMeasurementLib [Guids] gEfiHobMemoryAllocModuleGuid From 4edd47b89e19175847c3fae1e84b69707b8c9aeb Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:44 +0800 Subject: [PATCH 0580/1529] OvmfPkg/IntelTdx: Add PeiTdxHelperLib BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdxHelperLib provides below helper functions for a td-guest. - TdxHelperProcessTdHob - TdxHelperMeasureTdHob - TdxHelperMeasureCfvImage - TdxHelperBuildGuidHobForTdxMeasurement PeiTdxHelperLib is the PEI instance of TdxHelperLib. It implements 1 function for tdx in PEI phase. Other functions are not supported in PEI phase. - TdxHelperBuildGuidHobForTdxMeasurement builds GuidHob for tdx measurement in PEI phase. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelper.c | 91 +++++++++++++++++++ .../IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf | 48 ++++++++++ 2 files changed, 139 insertions(+) create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelper.c create mode 100644 OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelper.c b/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelper.c new file mode 100644 index 0000000000..91ab53ed14 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelper.c @@ -0,0 +1,91 @@ +/** @file + TdxHelper Functions which are used in PEI phase + + Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +InternalBuildGuidHobForTdxMeasurement ( + VOID + ); + +/** + In Tdx guest, some information need to be passed from host VMM to guest + firmware. For example, the memory resource, etc. These information are + prepared by host VMM and put in TdHob which is described in TdxMetadata. + TDVF processes the TdHob to accept memories. + + @retval EFI_SUCCESS Successfully process the TdHob + @retval Others Other error as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperProcessTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + In Tdx guest, TdHob is passed from host VMM to guest firmware and it contains + the information of the memory resource. From the security perspective before + it is consumed, it should be measured and extended. + * + * @retval EFI_SUCCESS Successfully measure the TdHob + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureTdHob ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + * In Tdx guest, Configuration FV (CFV) is treated as external input because it + * may contain the data provided by VMM. From the sucurity perspective Cfv image + * should be measured before it is consumed. + * + * @retval EFI_SUCCESS Successfully measure the CFV image + * @retval Others Other error as indicated + */ +EFI_STATUS +EFIAPI +TdxHelperMeasureCfvImage ( + VOID + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Build the GuidHob for tdx measurements which were done in SEC phase. + The measurement values are stored in WorkArea. + + @retval EFI_SUCCESS The GuidHob is built successfully + @retval Others Other errors as indicated +**/ +EFI_STATUS +EFIAPI +TdxHelperBuildGuidHobForTdxMeasurement ( + VOID + ) +{ + return InternalBuildGuidHobForTdxMeasurement (); +} diff --git a/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf b/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf new file mode 100644 index 0000000000..ad3b6c1da6 --- /dev/null +++ b/OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf @@ -0,0 +1,48 @@ +## @file +# TdxHelperLib PEI instance +# +# This module provides Tdx helper functions in PEI phase. +# Copyright (c) 2021 - 2023, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = PeiTdxHelperLib + FILE_GUID = 4d22289d-3bde-4501-a737-7719f3215065 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = TdxHelperLib|PEIM + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = X64 +# + +[Sources] + PeiTdxHelper.c + TdxMeasurementHob.c + +[Packages] + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + SecurityPkg/SecurityPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + HobLib + PcdLib + +[FixedPcd] + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFlashNvStorageVariableBase + gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataSize + +[Guids] + gCcEventEntryHobGuid From cd2b2ed2882a6e650476e1149768d93df791ff4f Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:45 +0800 Subject: [PATCH 0581/1529] OvmfPkg/OvmfPkgX64: Measure TdHob and Configuration FV in SecMain BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdHob and Configuration FV (Cfv) are external inputs from VMM. From the security perspective, they should be measured before they're consumed. This patch measures TdHob and Cfv and stores the measurement values in WorkArea. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Sec/SecMain.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index a27dc9406b..4bb3b64170 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -760,6 +760,19 @@ SecCoreStartupWithStack ( #if defined (TDX_GUEST_SUPPORTED) if (CcProbe () == CcGuestTypeIntelTdx) { + // + // From the security perspective all the external input should be measured before + // it is consumed. TdHob and Configuration FV (Cfv) image are passed from VMM + // and should be measured here. + // + if (EFI_ERROR (TdxHelperMeasureTdHob ())) { + CpuDeadLoop (); + } + + if (EFI_ERROR (TdxHelperMeasureCfvImage ())) { + CpuDeadLoop (); + } + // // For Td guests, the memory map info is in TdHobLib. It should be processed // first so that the memory is accepted. Otherwise access to the unaccepted From 65471775038fc859b5807c79223a98e1656e4c5d Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:46 +0800 Subject: [PATCH 0582/1529] OvmfPkg/PlatformPei: Build GuidHob for Tdx measurement BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 TdxHelperBuildGuidHobForTdxMeasurement is called in PlatformPei to build GuidHob for Tdx measurement. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/AmdSev/AmdSevX64.dsc | 5 ++++- OvmfPkg/CloudHv/CloudHvX64.dsc | 5 ++++- OvmfPkg/Microvm/MicrovmX64.dsc | 5 ++++- OvmfPkg/OvmfPkgX64.dsc | 5 ++++- OvmfPkg/PlatformPei/IntelTdx.c | 3 +++ 5 files changed, 19 insertions(+), 4 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 36100f5fdc..1cebd6b4bc 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -570,7 +570,10 @@ } MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf - OvmfPkg/PlatformPei/PlatformPei.inf + OvmfPkg/PlatformPei/PlatformPei.inf { + + NULL|OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf + } UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf UefiCpuPkg/CpuMpPei/CpuMpPei.inf OvmfPkg/AmdSev/SecretPei/SecretPei.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 7326417eab..fc5e73158a 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -678,7 +678,10 @@ } MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf - OvmfPkg/PlatformPei/PlatformPei.inf + OvmfPkg/PlatformPei/PlatformPei.inf { + + NULL|OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf + } UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf { !if $(SMM_REQUIRE) == TRUE diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 2d53b5c295..1161e1f39b 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -679,7 +679,10 @@ } MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf - OvmfPkg/PlatformPei/PlatformPei.inf + OvmfPkg/PlatformPei/PlatformPei.inf { + + NULL|OvmfPkg/IntelTdx/TdxHelperLib/TdxHelperLibNull.inf + } UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf UefiCpuPkg/CpuMpPei/CpuMpPei.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index d87013a442..a13299c18c 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -746,7 +746,10 @@ } MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf - OvmfPkg/PlatformPei/PlatformPei.inf + OvmfPkg/PlatformPei/PlatformPei.inf { + + NULL|OvmfPkg/IntelTdx/TdxHelperLib/PeiTdxHelperLib.inf + } UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf { !if $(SMM_REQUIRE) == TRUE diff --git a/OvmfPkg/PlatformPei/IntelTdx.c b/OvmfPkg/PlatformPei/IntelTdx.c index 3c1ddbfafd..3d625cabd8 100644 --- a/OvmfPkg/PlatformPei/IntelTdx.c +++ b/OvmfPkg/PlatformPei/IntelTdx.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -39,6 +40,8 @@ IntelTdxInitialize ( return; } + TdxHelperBuildGuidHobForTdxMeasurement (); + PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCAttrIntelTdx); ASSERT_RETURN_ERROR (PcdStatus); From a0c5c84eb4b71c4820b6a458881ac7ab52fe0327 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 11:31:47 +0800 Subject: [PATCH 0583/1529] OvmfPkg: Support Tdx measurement in OvmfPkgX64 BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4243 This patch enables Tdx measurement in OvmfPkgX64 with below changes: 1) CC_MEASUREMENT_ENABLE is introduced in OvmfPkgX64.dsc. This flag indicates if Intel TDX measurement is enabled in OvmfPkgX64. Its default value is FALSE. 2) Include TdTcg2Dxe in OvmfPkgX64 so that CC_MEASUREMENT_PROTOCOL is installed in a Td-guest. TdTcg2Dxe is controlled by TDX_MEASUREMENT_ENABLE because it is only valid when Intel TDX measurement is enabled. 3) OvmfTpmLibs.dsc.inc and OvmfTpmSecurityStub.dsc.inc are updated because DxeTpm2MeasureBootLib.inf and DxeTpmMeasurementLib.inf should be included to support CC_MEASUREMENT_PROTOCOL. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Signed-off-by: Min Xu --- OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc | 10 +++++++++- OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc | 8 ++++++++ OvmfPkg/OvmfPkgX64.dsc | 12 ++++++++++++ OvmfPkg/OvmfPkgX64.fdf | 7 +++++++ 4 files changed, 36 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc index cd1a899d68..b97244695b 100644 --- a/OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc +++ b/OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc @@ -10,9 +10,17 @@ Tpm2CommandLib|SecurityPkg/Library/Tpm2CommandLib/Tpm2CommandLib.inf Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibQemu/DxeTcg2PhysicalPresenceLib.inf Tcg2PpVendorLib|SecurityPkg/Library/Tcg2PpVendorLibNull/Tcg2PpVendorLibNull.inf - TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf !else Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibNull/DxeTcg2PhysicalPresenceLib.inf +!endif + +!if $(TPM2_ENABLE) == TRUE || $(CC_MEASUREMENT_ENABLE) == TRUE + # + # DxeTpmMeasurementLib supports measurement functions for both TPM and Confidential Computing. + # It should be controlled by TPM2_ENABLE and CC_MEASUREMENT_ENABLE. + # + TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf +!else TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf !endif diff --git a/OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc b/OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc index e9ab2fca7b..89455feca4 100644 --- a/OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc +++ b/OvmfPkg/Include/Dsc/OvmfTpmSecurityStub.dsc.inc @@ -6,5 +6,13 @@ !if $(TPM1_ENABLE) == TRUE NULL|SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.inf !endif +!endif + +!if $(TPM2_ENABLE) == TRUE || $(CC_MEASUREMENT_ENABLE) == TRUE + # + # DxeTpm2MeasureBootLib provides security service of TPM2 measure boot and + # Confidential Computing (CC) measure boot. It should be controlled by + # TPM2_ENABLE and CC_MEASUREMENT_ENABLE + # NULL|SecurityPkg/Library/DxeTpm2MeasureBootLib/DxeTpm2MeasureBootLib.inf !endif diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index a13299c18c..8f9355f544 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -32,6 +32,7 @@ DEFINE SECURE_BOOT_ENABLE = FALSE DEFINE SMM_REQUIRE = FALSE DEFINE SOURCE_DEBUG_ENABLE = FALSE + DEFINE CC_MEASUREMENT_ENABLE = FALSE !include OvmfPkg/Include/Dsc/OvmfTpmDefines.dsc.inc @@ -1104,6 +1105,17 @@ } !endif + # + # Cc Measurement Protocol for Td guest + # +!if $(CC_MEASUREMENT_ENABLE) == TRUE + SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf { + + HashLib|SecurityPkg/Library/HashLibTdx/HashLibTdx.inf + NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf + } +!endif + # # TPM support # diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf index 8c02dfe11e..16666ba244 100644 --- a/OvmfPkg/OvmfPkgX64.fdf +++ b/OvmfPkg/OvmfPkgX64.fdf @@ -402,6 +402,13 @@ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf !endif +# +# EFI_CC_MEASUREMENT_PROTOCOL +# +!if $(CC_MEASUREMENT_ENABLE) == TRUE +INF SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.inf +!endif + # # TPM support # From e6084f333cb9ea88b3774ffe4999e3c767d668d3 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 3 Feb 2023 12:02:57 +0100 Subject: [PATCH 0584/1529] EmbeddedPkg/PrePiLib: Drop unused PCD PcdPrePiCpuIoSize The code never references the PCD so the INF should not reference it either. The last reference was moved to PrePiHobLib in commit 05e48e00834b32e4bd2 (dated 2011!) and dropped from there as well in commit 97106391955337155e7. Cc: Leif Lindholm Cc: Abner Chang Cc: Daniel Schaefer Reported-by: Sunil V L Signed-off-by: Ard Biesheuvel Reviewed-by: Sunil V L --- EmbeddedPkg/Library/PrePiLib/PrePiLib.inf | 2 -- 1 file changed, 2 deletions(-) diff --git a/EmbeddedPkg/Library/PrePiLib/PrePiLib.inf b/EmbeddedPkg/Library/PrePiLib/PrePiLib.inf index 3c749ca229..090bfe888f 100644 --- a/EmbeddedPkg/Library/PrePiLib/PrePiLib.inf +++ b/EmbeddedPkg/Library/PrePiLib/PrePiLib.inf @@ -58,8 +58,6 @@ [FixedPcd.common] - gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize - gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType From dacea357ccaaee84d787fe5d88d4dfc43d26c49c Mon Sep 17 00:00:00 2001 From: Jan Bobek Date: Sat, 21 Jan 2023 06:58:32 +0800 Subject: [PATCH 0585/1529] SecurityPkg: limit verification of enrolled PK in setup mode REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2506 Per UEFI spec, enrolling a new PK in setup mode should not require a self-signature. Introduce a feature PCD called PcdRequireSelfSignedPk to control this requirement. Default to TRUE in order to preserve the legacy behavior. Cc: Jiewen Yao Cc: Jian J Wang Cc: Min Xu Co-authored-by: Matthew Carlson Signed-off-by: Jan Bobek Reviewed-by: Sean Brogan Acked-by: Jiewen Yao --- SecurityPkg/Library/AuthVariableLib/AuthService.c | 9 +++++++-- SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf | 3 +++ SecurityPkg/SecurityPkg.dec | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/SecurityPkg/Library/AuthVariableLib/AuthService.c b/SecurityPkg/Library/AuthVariableLib/AuthService.c index 9beeca09ae..452ed491ea 100644 --- a/SecurityPkg/Library/AuthVariableLib/AuthService.c +++ b/SecurityPkg/Library/AuthVariableLib/AuthService.c @@ -603,7 +603,10 @@ ProcessVarWithPk ( // Init state of Del. State may change due to secure check // Del = FALSE; - if ((InCustomMode () && UserPhysicalPresent ()) || ((mPlatformMode == SETUP_MODE) && !IsPk)) { + if ( (InCustomMode () && UserPhysicalPresent ()) + || ( (mPlatformMode == SETUP_MODE) + && !(FeaturePcdGet (PcdRequireSelfSignedPk) && IsPk))) + { Payload = (UINT8 *)Data + AUTHINFO2_SIZE (Data); PayloadSize = DataSize - AUTHINFO2_SIZE (Data); if (PayloadSize == 0) { @@ -627,7 +630,9 @@ ProcessVarWithPk ( return Status; } - if ((mPlatformMode != SETUP_MODE) || IsPk) { + if ( (mPlatformMode != SETUP_MODE) + || (FeaturePcdGet (PcdRequireSelfSignedPk) && IsPk)) + { Status = VendorKeyIsModified (); } } else if (mPlatformMode == USER_MODE) { diff --git a/SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf b/SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf index 8eadeebceb..e5985c5f8b 100644 --- a/SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf +++ b/SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf @@ -86,3 +86,6 @@ gEfiCertTypeRsa2048Sha256Guid ## SOMETIMES_CONSUMES ## GUID # Unique ID for the type of the certificate. gEfiCertPkcs7Guid ## SOMETIMES_CONSUMES ## GUID # Unique ID for the type of the certificate. gEfiCertX509Guid ## SOMETIMES_CONSUMES ## GUID # Unique ID for the type of the signature. + +[FeaturePcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 8257f11d17..d3b7ad7ff6 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -580,5 +580,12 @@ ## This PCD records LASA field in CC EVENTLOG ACPI table. gEfiSecurityPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa|0|UINT64|0x00010026 +[PcdsFeatureFlag] + ## Indicates if the platform requires PK to be self-signed when setting the PK in setup mode. + # TRUE - Require PK to be self-signed. + # FALSE - Do not require PK to be self-signed. + # @Prompt Require PK to be self-signed + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE|BOOLEAN|0x00010027 + [UserExtensions.TianoCore."ExtraFiles"] SecurityPkgExtra.uni From 0327059bb9e56bd1a828f706bc59af215b8ad9e5 Mon Sep 17 00:00:00 2001 From: Jan Bobek Date: Sat, 21 Jan 2023 06:58:33 +0800 Subject: [PATCH 0586/1529] OvmfPkg: require self-signed PK when secure boot is enabled REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2506 In all DSC files that define SECURE_BOOT_ENABLE, opt-in into requiring self-signed PK when SECURE_BOOT_ENABLE is TRUE. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: Rebecca Cran Cc: Peter Grehan Cc: Sebastien Boeuf Signed-off-by: Jan Bobek Reviewed-by: Sean Brogan Acked-by: Jiewen Yao --- OvmfPkg/Bhyve/BhyveX64.dsc | 3 +++ OvmfPkg/CloudHv/CloudHvX64.dsc | 3 +++ OvmfPkg/IntelTdx/IntelTdxX64.dsc | 3 +++ OvmfPkg/Microvm/MicrovmX64.dsc | 3 +++ OvmfPkg/OvmfPkgIa32.dsc | 3 +++ OvmfPkg/OvmfPkgIa32X64.dsc | 3 +++ OvmfPkg/OvmfPkgX64.dsc | 3 +++ 7 files changed, 21 insertions(+) diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc index befec670d4..66a2ae8868 100644 --- a/OvmfPkg/Bhyve/BhyveX64.dsc +++ b/OvmfPkg/Bhyve/BhyveX64.dsc @@ -422,6 +422,9 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index fc5e73158a..fda7d2b9e5 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -480,6 +480,9 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 41de2e9428..95b9594ddc 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -390,6 +390,9 @@ !ifdef $(CSM_ENABLE) gUefiOvmfPkgTokenSpaceGuid.PcdCsmEnable|TRUE !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 1161e1f39b..0d65d21e65 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -476,6 +476,9 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index f232de13a7..22dc29330d 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -488,6 +488,9 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index a9d422bd91..6b539814bd 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -493,6 +493,9 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 8f9355f544..e3c64456df 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -514,6 +514,9 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif +!if $(SECURE_BOOT_ENABLE) == TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE +!endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 From 2e769895ddb7ee21f2082c4bd49ee6b51781a21a Mon Sep 17 00:00:00 2001 From: Jan Bobek Date: Sat, 21 Jan 2023 06:58:35 +0800 Subject: [PATCH 0587/1529] SecurityPkg: don't require PK to be self-signed by default REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2506 Change the default value of PcdRequireSelfSignedPk to FALSE in accordance with UEFI spec, which states that PK need not be self-signed when enrolling in setup mode. Note that this relaxes the legacy behavior, which required the PK to be self-signed in this case. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Jan Bobek Reviewed-by: Sean Brogan Acked-by: Jiewen Yao --- SecurityPkg/SecurityPkg.dec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index d3b7ad7ff6..0382090f4e 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -585,7 +585,7 @@ # TRUE - Require PK to be self-signed. # FALSE - Do not require PK to be self-signed. # @Prompt Require PK to be self-signed - gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|TRUE|BOOLEAN|0x00010027 + gEfiMdeModulePkgTokenSpaceGuid.PcdRequireSelfSignedPk|FALSE|BOOLEAN|0x00010027 [UserExtensions.TianoCore."ExtraFiles"] SecurityPkgExtra.uni From 4917f474d9ffab888742e10c53cd2d3bdb25a532 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Thu, 2 Feb 2023 17:04:14 +0800 Subject: [PATCH 0588/1529] SecurityPkg/TdTcg2Dxe: td-guest shall halt when CcMeasurement install fail BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4335 CcMeasurement protocol is installed when it is supported in a td-guest. If the installation of the protocol failed, the guest shall go into CpuDeadLoop. Because the measurement feature is crucial to a td-guest and it shall stop running immediately at this situation. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Min Xu Reviewed-by: Jiewen Yao --- SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c index 59341a8c02..b34da724ac 100644 --- a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c +++ b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c @@ -2510,6 +2510,12 @@ DriverEntry ( // // Create event callback to install CC EventLog ACPI Table EfiCreateProtocolNotifyEvent (&gEfiAcpiTableProtocolGuid, TPL_CALLBACK, InstallAcpiTable, NULL, &Registration); + } else { + // + // Cc measurement feature is crucial to a td-guest and it shall stop running immediately + // when it is failed to be installed. + DEBUG ((DEBUG_ERROR, "%a: CcMeasurement protocol failed to be installed - %r\n", __FUNCTION__, Status)); + CpuDeadLoop (); } return Status; From cc80e8bf5f0aa39b4da4caf3f83db40496a3a13b Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Fri, 3 Feb 2023 22:04:25 +0800 Subject: [PATCH 0589/1529] OvmfPkg/IntelTdx: Update README TDVF's README is updated based on the latest feature. - RTMR based measurement is supported in OvmfPkgX64 (Config-A) - Features of Config-B have all been implemented, such as removing unnecessary attack surfaces. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Signed-off-by: Min Xu Reviewed-by: Jiewen Yao Acked-by: Gerd Hoffmann --- OvmfPkg/IntelTdx/README | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/OvmfPkg/IntelTdx/README b/OvmfPkg/IntelTdx/README index cc01ebca5c..7307ede78f 100644 --- a/OvmfPkg/IntelTdx/README +++ b/OvmfPkg/IntelTdx/README @@ -26,17 +26,19 @@ There are 2 configurations for TDVF. - The OvmfX64Pkg.dsc includes SEV/TDX/normal OVMF basic boot capability. The final binary can run on SEV/TDX/normal OVMF. - No changes to existing OvmfPkgX64 image layout. - - No need to add additional security features if they do not exist today. - No need to remove features if they exist today. - - RTMR is not supported. - PEI phase is NOT skipped in either Td or Non-Td. + - RTMR based measurement is supported. + - External inputs from Host VMM are measured, such as TdHob, CFV. + - Other external inputs are measured, such as FW_CFG data, os loader, + initrd, etc. Config-B: - - (*) Add a standalone IntelTdx.dsc to a TDX specific directory for a *full* + - Add a standalone IntelTdx.dsc to a TDX specific directory for a *full* feature TDVF.(Align with existing SEV) - - (*) Threat model: VMM is out of TCB. (We need necessary change to prevent + - Threat model: VMM is out of TCB. (We need necessary change to prevent attack from VMM) - - (*) IntelTdx.dsc includes TDX/normal OVMF basic boot capability. The final + - IntelTdx.dsc includes TDX/normal OVMF basic boot capability. The final binary can run on TDX/normal OVMF. - It might eventually merge with AmdSev.dsc, but NOT at this point of time. And we don?t know when it will happen. We need sync with AMD in @@ -48,13 +50,6 @@ There are 2 configurations for TDVF. initrd, etc. - Need to remove unnecessary attack surfaces, such as network stack. -In current stage, Config-A has been merged into edk2-master branch. -The corresponding pkg file is OvmfPkg/OvmfPkgX64.dsc. - -Config-B is split into several waves. The corresponding pkg file is -OvmfPkg/IntelTdx/IntelTdxX64.dsc. The features with (*) have been implemented -and merged into edk2-master branch. Others are in upstreaming progress. - Build ------ - Build the TDVF (Config-A) target: From e7cdbf6aeadbd465299f2cd266e403e81168ce9b Mon Sep 17 00:00:00 2001 From: Sudeep Holla Date: Fri, 3 Feb 2023 14:23:38 +0000 Subject: [PATCH 0590/1529] ArmPkg/ArmScmiDxe: Fix the calculation of RequiredArraySize As per the SCMI specification, section CLOCK_DESCRIBE_RATES mentions that the value of num_rates_flags[11:0] in the response must be 3 if the return format is the triplet. Due to the buggy firmware, this was not noticed for long time. The firmware is now fixed resulting in ClockDescribeRates() to fail with "Buffer Too Small" error as the RequiredArraySize gets miscalculated as 72 instead of 24. Fix the issue by reusing the logic for both the return format which must work if num_rates_flags has correct value as expected from the specification. Cc: Girish Pathak Cc: Jeff Brasen Reviewed-by: Pierre Gondois Tested-by: Pierre Gondois Reported-by: Sami Mujawar Signed-off-by: Sudeep Holla Reviewed-by: Sami Mujawar Tested-by: Sami Mujawar --- ArmPkg/Drivers/ArmScmiDxe/ScmiClockProtocol.c | 39 ++++++++----------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/ArmPkg/Drivers/ArmScmiDxe/ScmiClockProtocol.c b/ArmPkg/Drivers/ArmScmiDxe/ScmiClockProtocol.c index 12a7e6df5d..f092208a66 100644 --- a/ArmPkg/Drivers/ArmScmiDxe/ScmiClockProtocol.c +++ b/ArmPkg/Drivers/ArmScmiDxe/ScmiClockProtocol.c @@ -236,12 +236,7 @@ ClockDescribeRates ( *TotalRates = NUM_RATES (DescribeRates->NumRatesFlags) + NUM_REMAIN_RATES (DescribeRates->NumRatesFlags); - if (*Format == ScmiClockRateFormatDiscrete) { - RequiredArraySize = (*TotalRates) * sizeof (UINT64); - } else { - // We need to return triplet of 64 bit value for each rate - RequiredArraySize = (*TotalRates) * 3 * sizeof (UINT64); - } + RequiredArraySize = (*TotalRates) * sizeof (UINT64); if (RequiredArraySize > (*RateArraySize)) { *RateArraySize = RequiredArraySize; @@ -259,23 +254,21 @@ ClockDescribeRates ( ConvertTo64Bit (Rate->Low, Rate->High); } } else { - for (RateNo = 0; RateNo < NUM_RATES (DescribeRates->NumRatesFlags); RateNo++) { - // Linear clock rates from minimum to maximum in steps - // Minimum clock rate. - Rate = &DescribeRates->Rates[RateOffset++]; - RateArray[RateIndex].ContinuousRate.Min = - ConvertTo64Bit (Rate->Low, Rate->High); - - Rate = &DescribeRates->Rates[RateOffset++]; - // Maximum clock rate. - RateArray[RateIndex].ContinuousRate.Max = - ConvertTo64Bit (Rate->Low, Rate->High); - - Rate = &DescribeRates->Rates[RateOffset++]; - // Step. - RateArray[RateIndex++].ContinuousRate.Step = - ConvertTo64Bit (Rate->Low, Rate->High); - } + // Linear clock rates from minimum to maximum in steps + // Minimum clock rate. + Rate = &DescribeRates->Rates[RateOffset++]; + RateArray[RateIndex].ContinuousRate.Min = + ConvertTo64Bit (Rate->Low, Rate->High); + + Rate = &DescribeRates->Rates[RateOffset++]; + // Maximum clock rate. + RateArray[RateIndex].ContinuousRate.Max = + ConvertTo64Bit (Rate->Low, Rate->High); + + Rate = &DescribeRates->Rates[RateOffset++]; + // Step. + RateArray[RateIndex++].ContinuousRate.Step = + ConvertTo64Bit (Rate->Low, Rate->High); } } while (NUM_REMAIN_RATES (DescribeRates->NumRatesFlags) != 0); From 1e3d78a4c58356e0bda3f0da460662e93da2001f Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Wed, 1 Feb 2023 10:26:45 +0800 Subject: [PATCH 0591/1529] RedfishPkg: fix multiple SMBIOS type 42 version issue RedfishHostInterfaceDxe does not close protocol notify event in event callback function. This could cause multiple version of type 42 records issue if the protocol is installed more than once. Close the event in callback function so we only create one type 42 record. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang --- .../RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c index 3e12e0c8b9..872cf3ae06 100644 --- a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c +++ b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c @@ -7,6 +7,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -260,6 +261,13 @@ PlatformHostInterfaceInformationReady ( DEBUG ((DEBUG_INFO, "%a: Platform Redfish Host Interface informtion is ready\n", __FUNCTION__)); RedfishCreateSmbiosTable42 (); + + // + // Close event so we don't create multiple type 42 records + // + gBS->CloseEvent (Event); + mPlatformHostInterfaceReadylEvent = NULL; + return; } From 4925eaad8c22889df63403239808c9e4fb2a8fa6 Mon Sep 17 00:00:00 2001 From: Thierry LARONDE Date: Tue, 31 Jan 2023 19:14:21 +0100 Subject: [PATCH 0592/1529] BaseTools: remove useless dependency on libuuid Signed-off-by: Thierry LARONDE Reviewed-by: Liming Gao --- BaseTools/Source/C/GenFv/GNUmakefile | 6 +----- BaseTools/Source/C/GenFv/GenFvInternalLib.c | 5 ----- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/BaseTools/Source/C/GenFv/GNUmakefile b/BaseTools/Source/C/GenFv/GNUmakefile index 7c7b95ba1b..872b981f6a 100644 --- a/BaseTools/Source/C/GenFv/GNUmakefile +++ b/BaseTools/Source/C/GenFv/GNUmakefile @@ -14,10 +14,6 @@ include $(MAKEROOT)/Makefiles/app.makefile LIBS = -lCommon ifeq ($(CYGWIN), CYGWIN) - LIBS += -L/lib/e2fsprogs -luuid -endif - -ifeq ($(LINUX), Linux) - LIBS += -luuid + LIBS += -L/lib/e2fsprogs endif diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index 6bd59515b1..2df7182f8b 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -14,11 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Include files // -#if defined(__FreeBSD__) -#include -#elif defined(__GNUC__) -#include -#endif #ifdef __GNUC__ #include #endif From b215946ecb25261dd11e36f9b7394827e0d7b9b5 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Mon, 9 Jan 2023 11:34:22 +0800 Subject: [PATCH 0593/1529] MdeModulePkg: Disambiguate the meaning of PcdDxeIplSwitchToLongMode Literally, the meaning of PcdDxeIplSwitchToLongMode is clear, indicating whether need switch to long mode when loading DxeCore. However, the comments in dec are confusing for the case where PEI core and DXE core are both in 64-bit. This patch makes it clear. PcdDxeIplSwitchToLongMode is true only when PEI core is 32-bit, and switch to long mode to load 64-bit DXE core. In other cases, this PCD is false. This also aligns with current usage in OvmfPkg. Cc: Jian J Wang Cc: Liming Gao Cc: Ray Ni Signed-off-by: Zhiguang Liu Reviewed-by: Liming Gao Reviewed-by: Ray Ni --- MdeModulePkg/MdeModulePkg.dec | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 9605c617b7..e8058c8bfa 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -927,10 +927,8 @@ [PcdsFeatureFlag.IA32, PcdsFeatureFlag.X64] ## Indicates if DxeIpl should switch to long mode to enter DXE phase. - # It is assumed that 64-bit DxeCore is built in firmware if it is true; otherwise 32-bit DxeCore - # is built in firmware.

# TRUE - DxeIpl will load a 64-bit DxeCore and switch to long mode to hand over to DxeCore.
- # FALSE - DxeIpl will load a 32-bit DxeCore and perform stack switch to hand over to DxeCore.
+ # FALSE - DxeIpl will load a 32-bit or 64-bit DxeCore and perform stack switch to hand over to DxeCore.
# @Prompt DxeIpl switch to long mode. gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode|TRUE|BOOLEAN|0x0001003b From 6998a1581a83559e465e0079e848815824b13f27 Mon Sep 17 00:00:00 2001 From: Min M Xu Date: Wed, 18 Jan 2023 16:41:58 +0800 Subject: [PATCH 0594/1529] MdeModulePkg: EfiUnacceptedMemoryType is not allowed in AllocatePool BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4315 MemoryType of EfiUnacceptedMemoryType should not be allocated in AllocatePool. Instead it should return EFI_INVALID_PARAMETER. Cc: Liming Gao Cc: Dandan Bi Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Gerd Hoffmann Cc: Tom Lendacky Cc: Michael Roth Reported-by: Liming Gao Signed-off-by: Min Xu Acked-by: Gerd Hoffmann Reviewed-by: Jiewen Yao Reviewed-by: Liming Gao --- MdeModulePkg/Core/Dxe/Mem/Pool.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Core/Dxe/Mem/Pool.c b/MdeModulePkg/Core/Dxe/Mem/Pool.c index 7aaf501600..b20cbfdedb 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Pool.c +++ b/MdeModulePkg/Core/Dxe/Mem/Pool.c @@ -213,7 +213,7 @@ CoreInternalAllocatePool ( // If it's not a valid type, fail it // if (((PoolType >= EfiMaxMemoryType) && (PoolType < MEMORY_TYPE_OEM_RESERVED_MIN)) || - (PoolType == EfiConventionalMemory) || (PoolType == EfiPersistentMemory)) + (PoolType == EfiConventionalMemory) || (PoolType == EfiPersistentMemory) || (PoolType == EfiUnacceptedMemoryType)) { return EFI_INVALID_PARAMETER; } From 2e9c93276c936bdea947b6c58c1d61a0f3838434 Mon Sep 17 00:00:00 2001 From: Swatisri Kantamsetti Date: Thu, 26 Jan 2023 02:40:54 +0800 Subject: [PATCH 0595/1529] MdePkg:IORT header update for IORT Rev E.e spec The IO Remapping Table, Platform Design Document, Revision E.e, Sept 2022 (https://developer.arm.com/documentation/den0049/ee) added flags in SMMUv3 node for validity of ID mappings for MSIs related to control interrupts. Therefore, update the IORT header file to: - increment IORT table revision to 6 - add support for DeviceId valid flag Signed-off-by: Swatisri Kantamsetti Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/IoRemappingTable.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/MdePkg/Include/IndustryStandard/IoRemappingTable.h b/MdePkg/Include/IndustryStandard/IoRemappingTable.h index f48a4a95cd..544aa67a05 100644 --- a/MdePkg/Include/IndustryStandard/IoRemappingTable.h +++ b/MdePkg/Include/IndustryStandard/IoRemappingTable.h @@ -9,6 +9,8 @@ @par Reference(s): - IO Remapping Table, Platform Design Document, Revision E.d, Feb 2022 (https://developer.arm.com/documentation/den0049/) + - IO Remapping Table, Platform Design Document, Revision E.e, Sept 2022 + (https://developer.arm.com/documentation/den0049/) @par Glossary: - Ref : Reference @@ -24,6 +26,7 @@ #define EFI_ACPI_IO_REMAPPING_TABLE_REVISION_00 0x0 #define EFI_ACPI_IO_REMAPPING_TABLE_REVISION_04 0x4 // Deprecated #define EFI_ACPI_IO_REMAPPING_TABLE_REVISION_05 0x5 +#define EFI_ACPI_IO_REMAPPING_TABLE_REVISION_06 0x6 #define EFI_ACPI_IORT_TYPE_ITS_GROUP 0x0 #define EFI_ACPI_IORT_TYPE_NAMED_COMP 0x1 @@ -59,6 +62,7 @@ #define EFI_ACPI_IORT_SMMUv3_FLAG_COHAC_OVERRIDE BIT0 #define EFI_ACPI_IORT_SMMUv3_FLAG_HTTU_OVERRIDE BIT1 #define EFI_ACPI_IORT_SMMUv3_FLAG_PROXIMITY_DOMAIN BIT3 +#define EFI_ACPI_IORT_SMMUv3_FLAG_DEVICEID_VALID BIT4 #define EFI_ACPI_IORT_SMMUv3_MODEL_GENERIC 0x0 #define EFI_ACPI_IORT_SMMUv3_MODEL_HISILICON_HI161X 0x1 From 206b9f05ebf610bd300073b6144adbc362ccf854 Mon Sep 17 00:00:00 2001 From: Marvin Ha?user Date: Wed, 1 Feb 2023 06:47:50 -0800 Subject: [PATCH 0596/1529] .pytool/Plugin/EccCheck: Add PACKAGES_PATH support REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4326 EccBuild currently assumes all packages reside in WORKSPACE. However, this is obviously not the case for many setups. Most notably, Ext4Pkg is located in edk2-platforms/Features and thus cannot be in WORKSPACE in any reasonable setup. Use Edk2Path to locate the package in WORKSPACE and PACKAGES_PATH. Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Cc: Liming Gao Cc: Pedro Falcato Signed-off-by: Marvin H?user Acked-by: Pedro Falcato Reviewed-by: Michael Kubacki --- .pytool/Plugin/EccCheck/EccCheck.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.pytool/Plugin/EccCheck/EccCheck.py b/.pytool/Plugin/EccCheck/EccCheck.py index 4fbc67765f..7235fcb55c 100644 --- a/.pytool/Plugin/EccCheck/EccCheck.py +++ b/.pytool/Plugin/EccCheck/EccCheck.py @@ -69,6 +69,13 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, env.set_shell_var('PACKAGES_PATH', os.pathsep.join(Edk2pathObj.PackagePathList)) self.ECC_PASS = True + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSystemFromEdk2RelativePath(packagename) + + if abs_pkg_path is None: + tc.SetSkipped() + tc.LogStdError("No Package folder {0}".format(abs_pkg_path)) + return 0 + # Create temp directory temp_path = os.path.join(workspace_path, 'Build', '.pytool', 'Plugin', 'EccCheck') try: @@ -77,7 +84,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, shutil.rmtree(temp_path) # Copy package being scanned to temp_path shutil.copytree ( - os.path.join(workspace_path, packagename), + abs_pkg_path, os.path.join(temp_path, packagename), symlinks=True ) From dcc43d50e1985bda3b34cc3f736d9975fdc19252 Mon Sep 17 00:00:00 2001 From: Deric Cole Date: Wed, 8 Feb 2023 08:41:03 -0800 Subject: [PATCH 0597/1529] EmulatorPkg/PeiTimerLib: Bug fix in NanoSecondDelay REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4339 Thunk->Sleep is expecting nanoseconds, no need to multiply by 100. Cc: Andrew Fish Cc: Ray Ni Signed-off-by: Deric Cole Reviewed-by: Michael D Kinney Reviewed-by: Ray Ni --- EmulatorPkg/Include/Protocol/EmuThunk.h | 2 +- EmulatorPkg/Library/PeiTimerLib/PeiTimerLib.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/EmulatorPkg/Include/Protocol/EmuThunk.h b/EmulatorPkg/Include/Protocol/EmuThunk.h index b720023ac9..c419d0a677 100644 --- a/EmulatorPkg/Include/Protocol/EmuThunk.h +++ b/EmulatorPkg/Include/Protocol/EmuThunk.h @@ -130,7 +130,7 @@ UINT64 typedef VOID (EFIAPI *EMU_SLEEP)( - IN UINT64 Milliseconds + IN UINT64 Nanoseconds ); typedef diff --git a/EmulatorPkg/Library/PeiTimerLib/PeiTimerLib.c b/EmulatorPkg/Library/PeiTimerLib/PeiTimerLib.c index 8c4f20f42b..5344719f98 100644 --- a/EmulatorPkg/Library/PeiTimerLib/PeiTimerLib.c +++ b/EmulatorPkg/Library/PeiTimerLib/PeiTimerLib.c @@ -1,7 +1,7 @@ /** @file A non-functional instance of the Timer Library. - Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2007 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -65,7 +65,7 @@ NanoSecondDelay ( ); if (!EFI_ERROR (Status)) { Thunk = (EMU_THUNK_PROTOCOL *)ThunkPpi->Thunk (); - Thunk->Sleep (NanoSeconds * 100); + Thunk->Sleep (NanoSeconds); return NanoSeconds; } From b4f5bdd8036c4b512c6ec356453338d74d80de02 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Wed, 8 Feb 2023 11:01:38 -0700 Subject: [PATCH 0598/1529] OvmfPkg: Update build.sh to allow building OVMF then running QEMU Allow users to build OVMF then run QEMU by moving the build block above the run block and removing the exit line. Signed-off-by: Rebecca Cran Acked-by: Gerd Hoffmann --- OvmfPkg/build.sh | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/OvmfPkg/build.sh b/OvmfPkg/build.sh index 91b1442ade..b0334fb76e 100755 --- a/OvmfPkg/build.sh +++ b/OvmfPkg/build.sh @@ -245,6 +245,11 @@ else echo using prebuilt tools fi +# +# Build the edk2 OvmfPkg +# +echo Running edk2 build for OvmfPkg$Processor +build -p $PLATFORMFILE $BUILD_OPTIONS -b $BUILDTARGET -t $TARGET_TOOLS -n $THREADNUMBER -DDEBUG_ON_SERIAL_PORT=TRUE if [[ "$RUN_QEMU" == "yes" ]]; then if [[ ! -d $QEMU_FIRMWARE_DIR ]]; then @@ -260,11 +265,3 @@ if [[ "$RUN_QEMU" == "yes" ]]; then $QEMU_COMMAND "$@" exit $? fi - -# -# Build the edk2 OvmfPkg -# -echo Running edk2 build for OvmfPkg$Processor -build -p $PLATFORMFILE $BUILD_OPTIONS -b $BUILDTARGET -t $TARGET_TOOLS -n $THREADNUMBER -exit $? - From f0c0c9816f9561b0eafb3cafa443676a53b62d57 Mon Sep 17 00:00:00 2001 From: Girish Mahadevan Date: Mon, 30 Jan 2023 16:28:58 +0000 Subject: [PATCH 0599/1529] StandaloneMmPkg/StandaloneMmMemLib: Change max address computation Currently the standalonemmlibinternal assumes the max physical bits to be 36 which is causing issues on v8 architectures. Instead use the MAX_ALLOC_ADDRESS macro to determine the maximum allowed address rather than recomputing it locally. Signed-off-by: Girish Mahadevan Reviewed-by: Ard Biesheuvel --- .../ArmStandaloneMmMemLibInternal.c | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c b/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c index 297cfae916..fddcecf6da 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/ArmStandaloneMmMemLibInternal.c @@ -20,13 +20,6 @@ // extern EFI_PHYSICAL_ADDRESS mMmMemLibInternalMaximumSupportAddress; -#ifdef MDE_CPU_AARCH64 -#define ARM_PHYSICAL_ADDRESS_BITS 36 -#endif -#ifdef MDE_CPU_ARM -#define ARM_PHYSICAL_ADDRESS_BITS 32 -#endif - /** Calculate and save the maximum support address. @@ -36,14 +29,8 @@ MmMemLibInternalCalculateMaximumSupportAddress ( VOID ) { - UINT8 PhysicalAddressBits; - - PhysicalAddressBits = ARM_PHYSICAL_ADDRESS_BITS; + mMmMemLibInternalMaximumSupportAddress = MAX_ALLOC_ADDRESS; - // - // Save the maximum support address in one global variable - // - mMmMemLibInternalMaximumSupportAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)(LShiftU64 (1, PhysicalAddressBits) - 1); DEBUG ((DEBUG_INFO, "mMmMemLibInternalMaximumSupportAddress = 0x%lx\n", mMmMemLibInternalMaximumSupportAddress)); } From a62acc4e648649fcf55bc111fa2072f6fe6d4c28 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 10 Feb 2023 02:05:12 +0800 Subject: [PATCH 0600/1529] RedfishPkg/RedfishRestExDxe: Two PCDs for controlling the requests Since BIOS should work with different BMC implementation chunked requests as well as Expect header should be optional. - One PCD is used to enable/disable Expect header. - Another PCD is used to enable/disable chunked requests. Reviewed-by: Abner Chang Cc: Abner Chang Cc: Nickle Wang Signed-off-by: Igor Kulchytskyy --- RedfishPkg/RedfishPkg.dec | 11 ++ .../RedfishRestExDxe/RedfishRestExDxe.inf | 5 +- .../RedfishRestExDxe/RedfishRestExImpl.c | 24 ++- .../RedfishRestExDxe/RedfishRestExProtocol.c | 138 +++++++++++------- 4 files changed, 116 insertions(+), 62 deletions(-) diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index d2b189b13d..130e7ec260 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -3,6 +3,7 @@ # # Copyright (c) 2019, Intel Corporation. All rights reserved.
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2023, American Megatrends International LLC. # # SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -97,3 +98,13 @@ # protocol instance. # gEfiRedfishPkgTokenSpaceGuid.PcdRedfishDiscoverAccessModeInBand|FALSE|BOOLEAN|0x00001002 + # + # This PCD indicates if the EFI REST EX sends chunk request to Redfish service. + # Default is set to non chunk mode. + # + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExChunkRequestMode|FALSE|BOOLEAN|0x00001003 + # + # This PCD indicates if the EFI REST EX adds Expect header to the POST, PATCH, PUT requests to Redfish service. + # Default is set to not add. + # + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExAddingExpect|FALSE|BOOLEAN|0x00001004 diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf b/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf index 75437b086a..2f7a2188e8 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf @@ -3,6 +3,7 @@ # # Copyright (c) 2019, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2023, American Megatrends International LLC. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -56,7 +57,9 @@ gEfiDevicePathProtocolGuid ## TO_START [Pcd] - gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExServiceAccessModeInBand ## CONSUMES + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExServiceAccessModeInBand ## CONSUMES + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExChunkRequestMode ## CONSUMES + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExAddingExpect ## CONSUMES [UserExtensions.TianoCore."ExtraFiles"] RedfishRestExDxeExtra.uni diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c b/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c index 952e9d103a..75b3f1fab8 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c @@ -3,6 +3,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, American Megatrends International LLC. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -140,9 +141,6 @@ RedfishHttpAddExpectation ( } *ItsWrite = FALSE; - if (PreservedRequestHeaders != NULL) { - *PreservedRequestHeaders = RequestMessage->Headers; - } if ((RequestMessage->Data.Request->Method != HttpMethodPut) && (RequestMessage->Data.Request->Method != HttpMethodPost) && (RequestMessage->Data.Request->Method != HttpMethodPatch)) @@ -152,10 +150,20 @@ RedfishHttpAddExpectation ( *ItsWrite = TRUE; - NewHeaders = AllocateZeroPool ((RequestMessage->HeaderCount + 1) * sizeof (EFI_HTTP_HEADER)); - CopyMem ((VOID *)NewHeaders, (VOID *)RequestMessage->Headers, RequestMessage->HeaderCount * sizeof (EFI_HTTP_HEADER)); - HttpSetFieldNameAndValue (NewHeaders + RequestMessage->HeaderCount, HTTP_HEADER_EXPECT, HTTP_EXPECT_100_CONTINUE); - RequestMessage->HeaderCount++; - RequestMessage->Headers = NewHeaders; + // + // Check PCD before adding Expect header + // + if (FixedPcdGetBool (PcdRedfishRestExAddingExpect)) { + if (PreservedRequestHeaders != NULL) { + *PreservedRequestHeaders = RequestMessage->Headers; + } + + NewHeaders = AllocateZeroPool ((RequestMessage->HeaderCount + 1) * sizeof (EFI_HTTP_HEADER)); + CopyMem ((VOID *)NewHeaders, (VOID *)RequestMessage->Headers, RequestMessage->HeaderCount * sizeof (EFI_HTTP_HEADER)); + HttpSetFieldNameAndValue (NewHeaders + RequestMessage->HeaderCount, HTTP_HEADER_EXPECT, HTTP_EXPECT_100_CONTINUE); + RequestMessage->HeaderCount++; + RequestMessage->Headers = NewHeaders; + } + return EFI_SUCCESS; } diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c index 4b61fc01ad..1c3deab09a 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c @@ -3,6 +3,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, American Megatrends International LLC. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -66,11 +67,13 @@ RedfishRestExSendReceive ( HTTP_IO_SEND_NON_CHUNK_PROCESS SendNonChunkProcess; EFI_HTTP_MESSAGE ChunkTransferRequestMessage; - Status = EFI_SUCCESS; - ResponseData = NULL; - IsGetChunkedTransfer = FALSE; - SendChunkProcess = HttpIoSendChunkNone; - SendNonChunkProcess = HttpIoSendNonChunkNone; + Status = EFI_SUCCESS; + ResponseData = NULL; + IsGetChunkedTransfer = FALSE; + SendChunkProcess = HttpIoSendChunkNone; + SendNonChunkProcess = HttpIoSendNonChunkNone; + ItsWrite = FALSE; + PreservedRequestHeaders = NULL; // // Validate the parameters @@ -94,67 +97,84 @@ RedfishRestExSendReceive ( DEBUG ((DEBUG_INFO, "\nRedfishRestExSendReceive():\n")); DEBUG ((DEBUG_INFO, "*** Perform HTTP Request Method - %d, URL: %s\n", RequestMessage->Data.Request->Method, RequestMessage->Data.Request->Url)); - // - // Add header "Expect" to server, only for URL write. - // - Status = RedfishHttpAddExpectation (This, RequestMessage, &PreservedRequestHeaders, &ItsWrite); - if (EFI_ERROR (Status)) { - return Status; - } + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode)) { + // + // Add header "Expect" to server, only for URL write. + // + Status = RedfishHttpAddExpectation (This, RequestMessage, &PreservedRequestHeaders, &ItsWrite); + if (EFI_ERROR (Status)) { + return Status; + } - if (ItsWrite == TRUE) { - if (RequestMessage->BodyLength > HTTP_IO_MAX_SEND_PAYLOAD) { - // - // Send chunked transfer. - // - SendChunkProcess++; - CopyMem ((VOID *)&ChunkTransferRequestMessage, (VOID *)RequestMessage, sizeof (EFI_HTTP_MESSAGE)); - } else { - SendNonChunkProcess++; + if (ItsWrite == TRUE) { + if (RequestMessage->BodyLength > HTTP_IO_MAX_SEND_PAYLOAD) { + // + // Send chunked transfer. + // + SendChunkProcess++; + CopyMem ((VOID *)&ChunkTransferRequestMessage, (VOID *)RequestMessage, sizeof (EFI_HTTP_MESSAGE)); + } else { + SendNonChunkProcess++; + } } } ReSendRequest:; - // - // Send out the request to REST service. - // - if (ItsWrite == TRUE) { + + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode)) { // - // This is write to URI + // Send the chunked request to REST service. // - if (SendChunkProcess > HttpIoSendChunkNone) { + if (ItsWrite == TRUE) { // - // This is chunk transfer for writing large payload. - // Send request header first and then handle the - // following request message body using chunk transfer. + // This is write to URI // - do { - Status = HttpIoSendChunkedTransfer ( + if (SendChunkProcess > HttpIoSendChunkNone) { + // + // This is chunk transfer for writing large payload. + // Send request header first and then handle the + // following request message body using chunk transfer. + // + do { + Status = HttpIoSendChunkedTransfer ( + &(Instance->HttpIo), + &SendChunkProcess, + &ChunkTransferRequestMessage + ); + if (EFI_ERROR (Status)) { + goto ON_EXIT; + } + } while (SendChunkProcess == HttpIoSendChunkContent || SendChunkProcess == HttpIoSendChunkEndChunk); + } else { + // + // This is the non-chunk transfer, send request header first and then + // handle the following request message body using chunk transfer. + // + Status = HttpIoSendRequest ( &(Instance->HttpIo), - &SendChunkProcess, - &ChunkTransferRequestMessage + (SendNonChunkProcess == HttpIoSendNonChunkContent) ? NULL : RequestMessage->Data.Request, + (SendNonChunkProcess == HttpIoSendNonChunkContent) ? 0 : RequestMessage->HeaderCount, + (SendNonChunkProcess == HttpIoSendNonChunkContent) ? NULL : RequestMessage->Headers, + (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent) ? 0 : RequestMessage->BodyLength, + (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent) ? NULL : RequestMessage->Body ); - if (EFI_ERROR (Status)) { - goto ON_EXIT; - } - } while (SendChunkProcess == HttpIoSendChunkContent || SendChunkProcess == HttpIoSendChunkEndChunk); + } } else { // - // This is the non-chunk transfer, send request header first and then - // handle the following request message body using chunk transfer. + // This is read from URI. // Status = HttpIoSendRequest ( &(Instance->HttpIo), - (SendNonChunkProcess == HttpIoSendNonChunkContent) ? NULL : RequestMessage->Data.Request, - (SendNonChunkProcess == HttpIoSendNonChunkContent) ? 0 : RequestMessage->HeaderCount, - (SendNonChunkProcess == HttpIoSendNonChunkContent) ? NULL : RequestMessage->Headers, - (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent) ? 0 : RequestMessage->BodyLength, - (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent) ? NULL : RequestMessage->Body + RequestMessage->Data.Request, + RequestMessage->HeaderCount, + RequestMessage->Headers, + RequestMessage->BodyLength, + RequestMessage->Body ); } } else { // - // This is read from URI. + // This is normal request to URI. // Status = HttpIoSendRequest ( &(Instance->HttpIo), @@ -213,7 +233,7 @@ ReSendRequest:; // // Restore the headers if it ever changed in RedfishHttpAddExpectation(). // - if (RequestMessage->Headers != PreservedRequestHeaders) { + if (FixedPcdGetBool (PcdRedfishRestExAddingExpect) && (RequestMessage->Headers != PreservedRequestHeaders)) { FreePool (RequestMessage->Headers); RequestMessage->Headers = PreservedRequestHeaders; // Restore headers before we adding "Expect". RequestMessage->HeaderCount--; // Minus one header count for "Expect". @@ -223,11 +243,23 @@ ReSendRequest:; if (ResponseData->Response.StatusCode == HTTP_STATUS_200_OK) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_200_OK\n")); - if (SendChunkProcess == HttpIoSendChunkHeaderZeroContent) { - DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks.")); + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { + DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks - %d.", ResponseData->Response.StatusCode)); + SendChunkProcess++; + goto ReSendRequest; + } + } else if (ResponseData->Response.StatusCode == HTTP_STATUS_204_NO_CONTENT) { + DEBUG ((DEBUG_INFO, "HTTP_STATUS_204_NO_CONTENT\n")); + + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { + DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks - %d.", ResponseData->Response.StatusCode)); SendChunkProcess++; goto ReSendRequest; } + } else if (ResponseData->Response.StatusCode == HTTP_STATUS_201_CREATED) { + DEBUG ((DEBUG_INFO, "HTTP_STATUS_201_CREATED\n")); + } else if (ResponseData->Response.StatusCode == HTTP_STATUS_202_ACCEPTED) { + DEBUG ((DEBUG_INFO, "HTTP_STATUS_202_ACCEPTED\n")); } else if (ResponseData->Response.StatusCode == HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE\n")); @@ -240,14 +272,14 @@ ReSendRequest:; goto ON_EXIT; } else if (ResponseData->Response.StatusCode == HTTP_STATUS_400_BAD_REQUEST) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_400_BAD_REQUEST\n")); - if (SendChunkProcess == HttpIoSendChunkHeaderZeroContent) { + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { DEBUG ((DEBUG_INFO, "Bad request may caused by zero length chunk. Try to send all chunks...\n")); SendChunkProcess++; goto ReSendRequest; } } else if (ResponseData->Response.StatusCode == HTTP_STATUS_100_CONTINUE) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_100_CONTINUE\n")); - if (SendChunkProcess == HttpIoSendChunkHeaderZeroContent) { + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { // // We get HTTP_STATUS_100_CONTINUE to send the body using chunk transfer. // @@ -256,7 +288,7 @@ ReSendRequest:; goto ReSendRequest; } - if (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent) { + if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent)) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_100_CONTINUE for non chunk transfer...\n")); SendNonChunkProcess++; goto ReSendRequest; @@ -394,7 +426,7 @@ ReSendRequest:; TotalReceivedSize += ResponseData->BodyLength; } - DEBUG ((DEBUG_INFO, "Total of lengh of Response :%d\n", TotalReceivedSize)); + DEBUG ((DEBUG_INFO, "Total of length of Response :%d\n", TotalReceivedSize)); } DEBUG ((DEBUG_INFO, "RedfishRestExSendReceive()- EFI_STATUS: %r\n", Status)); From 8ae4d35a201787d33b3a71dab94e7d257eb243dd Mon Sep 17 00:00:00 2001 From: Weipu Zhu Date: Wed, 1 Feb 2023 22:41:40 -0800 Subject: [PATCH 0601/1529] MdePkg: Add RPMB related commands and DCB definition for NVMe REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4303 Add RPMB(Replay Protected Memory Block) access commands, result and DCB(Device Configuration Block) definition for NVMe according to the NVMe spec 2.0. Cc: Hao Wu Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Weipu Zhu Reviewed-by: Hao A Wu Acked-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Nvme.h | 46 +++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/IndustryStandard/Nvme.h b/MdePkg/Include/IndustryStandard/Nvme.h index 4a1d92c45d..3b4e9fe67c 100644 --- a/MdePkg/Include/IndustryStandard/Nvme.h +++ b/MdePkg/Include/IndustryStandard/Nvme.h @@ -2,12 +2,13 @@ Definitions based on NVMe spec. version 1.1. (C) Copyright 2016 Hewlett Packard Enterprise Development LP
- Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.
+ Copyright (c) 2017 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Specification Reference: NVMe Specification 1.1 NVMe Specification 1.4 + NVMe Specification 2.0 **/ @@ -502,6 +503,49 @@ typedef struct { // UINT8 *Data; /* Data to be written or read by signed access where M = 512 * Sector Count. */ } NVME_RPMB_DATA_FRAME; +// +// RPMB Device Configuration Block Data Structure. +// (ref. NVMe Base spec. v2.0 Figure 460). +// +typedef struct { + UINT8 BPPEnable; /* Boot Partition Protection Enabled */ + UINT8 BPLock; /* Boot Partition Lock */ + UINT8 NameSpaceWrP; /* Namespace Write Protection */ + UINT8 Rsvd1[509]; /* Reserved as of Nvm Express 2.0 Spec */ +} NVME_RPMB_DCB; + +// +// RPMB Request and Response Message Types. +// (ref. NVMe Base spec. v2.0 Figure 461). +// +#define NVME_RPMB_AUTHKEY_PROGRAM 0x0001 +#define NVME_RPMB_COUNTER_READ 0x0002 +#define NVME_RPMB_AUTHDATA_WRITE 0x0003 +#define NVME_RPMB_AUTHDATA_READ 0x0004 +#define NVME_RPMB_RESULT_READ 0x0005 +#define NVME_RPMB_DCB_WRITE 0x0006 +#define NVME_RPMB_DCB_READ 0x0007 +#define NVME_RPMB_AUTHKEY_PROGRAM_RESPONSE 0x0100 +#define NVME_RPMB_COUNTER_READ_RESPONSE 0x0200 +#define NVME_RPMB_AUTHDATA_WRITE_RESPONSE 0x0300 +#define NVME_RPMB_AUTHDATA_READ_RESPONSE 0x0400 +#define NVME_RPMB_DCB_WRITE_RESPONSE 0x0600 +#define NVME_RPMB_DCB_READ_RESPONSE 0x0700 + +// +// RPMB Operation Result. +// (ref. NVMe Base spec. v2.0 Figure 462). +// +#define NVME_RPMB_RESULT_SUCCESS 0x00 +#define NVME_RPMB_RESULT_GENERAL_FAILURE 0x01 +#define NVME_RPMB_RESULT_AHTHENTICATION_FAILURE 0x02 +#define NVME_RPMB_RESULT_COUNTER_FAILURE 0x03 +#define NVME_RPMB_RESULT_ADDRESS_FAILURE 0x04 +#define NVME_RPMB_RESULT_WRITE_FAILURE 0x05 +#define NVME_RPMB_RESULT_READ_FAILURE 0x06 +#define NVME_RPMB_RESULT_AUTHKEY_NOT_PROGRAMMED 0x07 +#define NVME_RPMB_RESULT_INVALID_DCB 0x08 + // // NvmExpress Admin Identify Cmd // From 2513908d1f22d465a257733227798da95b63199c Mon Sep 17 00:00:00 2001 From: Weipu Zhu Date: Wed, 1 Feb 2023 22:41:54 -0800 Subject: [PATCH 0602/1529] MdePkg: Add NVMe boot partition header definition REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4304 Add NVMe boot partition header definition to NVMe.h according to NVMe spec 2.0. Cc: Hao Wu Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Weipu Zhu Reviewed-by: Hao A Wu Acked-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Nvme.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/MdePkg/Include/IndustryStandard/Nvme.h b/MdePkg/Include/IndustryStandard/Nvme.h index 3b4e9fe67c..8b8a1bb7f3 100644 --- a/MdePkg/Include/IndustryStandard/Nvme.h +++ b/MdePkg/Include/IndustryStandard/Nvme.h @@ -546,6 +546,19 @@ typedef struct { #define NVME_RPMB_RESULT_AUTHKEY_NOT_PROGRAMMED 0x07 #define NVME_RPMB_RESULT_INVALID_DCB 0x08 +// +// Get Log Page - Boot Partition Log Header. +// (ref. NVMe Base spec. v2.0 Figure 262). +// +typedef struct { + UINT8 LogIdentifier; /* Log Identifier, shall be set to 15h */ + UINT8 Rsvd1[3]; + UINT32 Bpsz : 15; /* Boot Partition Size */ + UINT32 Rsvd2 : 16; + UINT32 Abpid : 1; /* Active Boot Partition ID */ + UINT8 Rsvd3[8]; +} NVME_BOOT_PARTITION_HEADER; + // // NvmExpress Admin Identify Cmd // From eadbb024629541ea0b64318e57f60d9bc040ae8a Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 13 Feb 2023 08:04:41 -0800 Subject: [PATCH 0603/1529] .mergify/config.yml: Remove rebase_fallback attribute (deprecated) PR builds and CI are currently broken due to a mergify brownout today because edk2 uses the `rebase_fallback` attribute of the `queue` action. Message from Mergify/Summary: ``` The configuration uses the deprecated rebase_fallback attribute of the queue action. A brownout is planned on February 13th, 2023. This option will be removed on March 13th, 2023. For more information: https://docs.mergify.com/actions/queue/ ``` Therefore, this change removes the attribute per the guidance in the following changelog message to retain existing behavior. https://changelog.mergify.com/changelog/rebasefallback-is-deprecated ``` The option rebase_fallback is now deprecated and should not be used anymore. Mergify will always report errors in the future if a rebase merge is impossible. ``` Cc: Michael D Kinney Cc: Liming Gao Cc: Sean Brogan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Rebecca Cran --- .mergify/config.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.mergify/config.yml b/.mergify/config.yml index bd6da4c779..3471896a34 100644 --- a/.mergify/config.yml +++ b/.mergify/config.yml @@ -38,7 +38,6 @@ pull_request_rules: actions: queue: method: rebase - rebase_fallback: none name: default - name: Post a comment on a PR that can not be merged due to a merge conflict From 8f6e730fcc4394a1340642afd3e75f27961c4db6 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 20 Jan 2023 12:07:22 -0500 Subject: [PATCH 0604/1529] .devcontainer/devcontainer.json: Add devcontainer file Tianocore maintains container images in the tianocore/containers repo and stores container images within the GitHub container registry. https://github.com/tianocore/containers This change adds a devcontainer.json file to the edk2 repo. This file's metadata and settings to configurate a development container for a given well-defined tool and runtime stack. More information about the devcontainer.json file is available here: https://containers.dev/implementors/json_reference/ This file is recognized by popular tools such as GitHub Codespaces and VS Code. In VS Code in particular, it makes it much easier for a user to be aware a dev container exists (via UI notifications) and to load the container. A minimal number of VS Code extensions are specified that are useful for edk2 development or to assist in complying with CI checks in place in edk2. Cc: Andrew Fish Cc: Chris Fernald Cc: Leif Lindholm Cc: Michael D Kinney Cc: Oliver Steffen Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .devcontainer/devcontainer.json | 16 ++++++++++++++++ Maintainers.txt | 5 +++++ 2 files changed, 21 insertions(+) create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..592bb8cf66 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,16 @@ +{ + "image": "ghcr.io/tianocore/containers/fedora-35-dev:latest", + "postCreateCommand": "git config --global --add safe.directory * && pip install --upgrade -r pip-requirements.txt", + "customizations": { + "vscode": { + "extensions": [ + "DavidAnson.vscode-markdownlint", + "ms-azuretools.vscode-docker", + "ms-vscode-remote.remote-containers", + "ms-vscode.cpptools", + "walonli.edk2-vscode", + "zachflower.uncrustify" + ] + } + } +} diff --git a/Maintainers.txt b/Maintainers.txt index 68f603b483..4aa7973d51 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -117,6 +117,11 @@ M: Michael Kubacki [makubacki] R: Michael D Kinney [mdkinney] R: Liming Gao [lgao4] +.devcontainer/ +F: .devcontainer/ +M: Michael Kubacki [makubacki] +R: Chris Fernald [cfernald] + .github/ F: .github/ M: Sean Brogan [spbrogan] From 8dc40c2195b0f353346ab6f49fc25d26ea92f486 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Tue, 31 Jan 2023 19:08:37 +0000 Subject: [PATCH 0605/1529] OvmfPkg: Fix SevMemoryAcceptance memory attributes The hard-coded attributes for the re-added memory space should instead forward the replaced descriptor's capabilities. Tested on Linux with efi=debug. Prior to this change, an 8GiB VM running a kernel without unaccepted memory support shows this entry efi: mem94: [Conventional| | |CC| | | | | | | | | | | ] range=[0x0000000100000000-0x000000023fffffff] (5120MB) This does not have the cache capabilities one would expect for system memory, UC|WC|WT|WB. After this change, the same entry becomes efi: mem94: [Conventional| | |CC| | | | | | | |WB|WT|WC|UC] range=[0x0000000100000000-0x000000023fffffff] (5120MB) This has all the expected attributes. Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Min Xu Cc: Tom Lendacky Cc: Michael Roth Signed-off-by: Dionna Glaze [ardb: drop the EFI_MEMORY_CPU_CRYPTO flag - it isn't used anywhere else in EDK2 or Linux so it doesn't actually do anything, and it is unclear whether it is intended for use by the guest in the first place] Reviewed-by: Ard Biesheuvel --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 6391d1f775..9c4e3bb406 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -23,6 +23,10 @@ #include #include #include +#include + +// Present, initialized, tested bits defined in MdeModulePkg/Core/Dxe/DxeMain.h +#define EFI_MEMORY_INTERNAL_MASK 0x0700000000000000ULL STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { SIGNATURE_32 ('A', 'M', 'D', 'E'), @@ -116,7 +120,9 @@ AcceptAllMemory ( EfiGcdMemoryTypeSystemMemory, Desc->BaseAddress, Desc->Length, - EFI_MEMORY_CPU_CRYPTO | EFI_MEMORY_XP | EFI_MEMORY_RO | EFI_MEMORY_RP + // Allocable system memory resource capabilities as masked + // in MdeModulePkg/Core/Dxe/Mem/Page.c:PromoteMemoryResource + Desc->Capabilities & ~(EFI_MEMORY_INTERNAL_MASK | EFI_MEMORY_RUNTIME) ); if (EFI_ERROR (Status)) { break; From cc05ad4cb049a4272e03734de2ef8c6f9526f328 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Tue, 14 Feb 2023 23:07:19 +0000 Subject: [PATCH 0606/1529] OvmfPkg/AmdSevDxe: Close mAcceptAllMemoryEvent This event should only trigger once. It should be idempotent, but the allocation of the memory map itself is observable and can cause ExitBootServices to fail with a modified map key. Cc: Thomas Lendacky Cc: Erdem Aktas Cc: James Bottomley Cc: Jiewen Yao Cc: Min Xu Cc: Michael Roth Signed-off-by: Dionna Glaze Reviewed-by: Ard Biesheuvel --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 1 + 1 file changed, 1 insertion(+) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 9c4e3bb406..a726498e27 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -130,6 +130,7 @@ AcceptAllMemory ( } gBS->FreePool (AllDescMap); + gBS->CloseEvent (mAcceptAllMemoryEvent); return Status; } From 65b79f3f2ea4bebe48ddb9584a9adf381a43926b Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Wed, 11 Jan 2023 21:14:17 -0800 Subject: [PATCH 0607/1529] MdeModulePkg/Pci: Display more information of PCIe devices In V4: Update the copyright to 2023. In V3: Add AMD copyright. In V2: Remove the signed-off-by: Abner Chang Display PCIe Vendor ID and Device ID in DEBUG message. Signed-off-by: Jiangang He Cc: Hao A Wu Cc: Ray Ni Cc: Garrett Kirkendall Cc: Abner Chang Reviewed-by: Ray Ni Acked-by: Michael D Kinney --- MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index 8eca859695..6594b8eae8 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -3,6 +3,7 @@ Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
(C) Copyright 2015 Hewlett Packard Enterprise Development LP
+Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -227,13 +228,15 @@ PciSearchDevice ( DEBUG (( DEBUG_INFO, - "PciBus: Discovered %s @ [%02x|%02x|%02x]\n", + "PciBus: Discovered %s @ [%02x|%02x|%02x] [VID = 0x%x, DID = 0x%0x]\n", IS_PCI_BRIDGE (Pci) ? L"PPB" : IS_CARDBUS_BRIDGE (Pci) ? L"P2C" : L"PCI", Bus, Device, - Func + Func, + Pci->Hdr.VendorId, + Pci->Hdr.DeviceId )); if (!IS_PCI_BRIDGE (Pci)) { From d337556bfaa49999af5724e6390fa60e662118b6 Mon Sep 17 00:00:00 2001 From: "devel@edk2.groups.io" Date: Mon, 12 Dec 2022 11:27:26 -0800 Subject: [PATCH 0608/1529] MdeModulePkg/EsrtFmpDxe: Support multiple devices with 0 HardwareInstance Skip error check if HardwareInstance is 0 as this either means that FmpVersion < 3 and not supported or, "A zero means the FMP provider is not able to determine a unique hardware instance number or a hardware instance number is not needed." per UEFI specification. As the FmpInstances are merged and HardwareInstance is not used remove error check in this case. Signed-off-by: Jeff Brasen Reviewed-by: Michael D Kinney --- MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c | 22 ++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c b/MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c index 4f47c55cce..5bc627461d 100644 --- a/MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c +++ b/MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c @@ -153,16 +153,20 @@ CreateEsrtEntry ( // // Check to see of FmpImageInfoBuf GUID/HardwareInstance is unique + // Skip if HardwareInstance is 0 as this is the case if FmpVersion < 3 + // or the device can not create a unique ID per UEFI specification // - for (Index = 0; Index < *NumberOfDescriptors; Index++) { - if (CompareGuid (&HardwareInstances[Index].ImageTypeGuid, &FmpImageInfoBuf->ImageTypeId)) { - if (HardwareInstances[Index].HardwareInstance == FmpHardwareInstance) { - DEBUG ((DEBUG_ERROR, "EsrtFmpDxe: Duplicate firmware image descriptor with GUID %g HardwareInstance:0x%x\n", &FmpImageInfoBuf->ImageTypeId, FmpHardwareInstance)); - ASSERT ( - !CompareGuid (&HardwareInstances[Index].ImageTypeGuid, &FmpImageInfoBuf->ImageTypeId) || - HardwareInstances[Index].HardwareInstance != FmpHardwareInstance - ); - return EFI_UNSUPPORTED; + if (FmpHardwareInstance != 0) { + for (Index = 0; Index < *NumberOfDescriptors; Index++) { + if (CompareGuid (&HardwareInstances[Index].ImageTypeGuid, &FmpImageInfoBuf->ImageTypeId)) { + if (HardwareInstances[Index].HardwareInstance == FmpHardwareInstance) { + DEBUG ((DEBUG_ERROR, "EsrtFmpDxe: Duplicate firmware image descriptor with GUID %g HardwareInstance:0x%x\n", &FmpImageInfoBuf->ImageTypeId, FmpHardwareInstance)); + ASSERT ( + !CompareGuid (&HardwareInstances[Index].ImageTypeGuid, &FmpImageInfoBuf->ImageTypeId) || + HardwareInstances[Index].HardwareInstance != FmpHardwareInstance + ); + return EFI_UNSUPPORTED; + } } } } From 50ac17f5d51d2aec0bf86c468247fb41e5696810 Mon Sep 17 00:00:00 2001 From: Stuart Yoder Date: Fri, 10 Feb 2023 06:30:58 +0800 Subject: [PATCH 0609/1529] MdeModulePkg/Variable: Attribute combination should return EFI_UNSUPPORTED REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4341 Commit 21320ef66989 broke some tests in the AuthVar_Conf test in edk2-test. There are 2 testcases that invoke SetVariable with the following attribute value: (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is deprecated and the UEFI spec says this should return EFI_UNSUPPORTED. Cc: Liming Gao Cc: Hao A Wu Cc: Sunny Wang Signed-off-by: Stuart Yoder Reviewed-by: Liming Gao Reviewed-by: Sunny Wang --- MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 6c1a3440ac..14c176887a 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -2676,7 +2676,11 @@ VariableServiceSetVariable ( // // Only EFI_VARIABLE_NON_VOLATILE attribute is invalid // - return EFI_INVALID_PARAMETER; + if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) { + return EFI_UNSUPPORTED; + } else { + return EFI_INVALID_PARAMETER; + } } else if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) { if (!mVariableModuleGlobal->VariableGlobal.AuthSupport) { // From ca5939203b542ac8ab8e3eb9432dd4f00e684840 Mon Sep 17 00:00:00 2001 From: lijun10x Date: Thu, 2 Feb 2023 14:20:57 +0800 Subject: [PATCH 0610/1529] MdeModulePkg/Library: PcdAcpiS3Enable set FALSE cause Assert Some platforms don't support S3 with PcdAcpiS3Enable set as False. Debug mode bios will ASSERT at this time as Follows. ASSERT_RETURN_ERROR (Status = Out of Resources) DXE_ASSERT!: Edk2\MdePkg\Library\BaseS3PciSegmentLib\S3PciSegmentLib.c (61): !(((INTN)(RETURN_STATUS)(Status)) < 0) Steps to reproduce the issue: 1.Set PcdAcpiS3Enable to FALSE. 2.Build the bios in debug mode. 3.Power on and Check the serial log. Note: Prerequisite is that S3PciSegmentLib is Called and the caller's code is run. Root Cause: S3PciSegmentLib call S3BootScriptLib controlled by PcdAcpiS3Enable. If PcdAcpiS3Enable set as false, S3BootScriptLib will return error status(Out of Resources). S3PciSegmentLib will ASSERT if S3BootScriptLib return error. Solution: Make S3BootScriptLib return success if PcdAcpiS3Enable was disabled, which behave as a null S3BootScriptLib instance which just return success for no action is required to do. Signed-off-by: JunX1 Li Cc: Liming Gao Cc: Sunny Wang Cc: Heinrich Schuchardt Cc: G Edhaya Chandran Cc: Samer El-Haj-Mahmoud Reviewed-by: Liming Gao --- .../PiDxeS3BootScriptLib/BootScriptSave.c | 132 ++++++++++++++---- 1 file changed, 108 insertions(+), 24 deletions(-) diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c index f8d4983d81..8c7b58b2f9 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c @@ -1004,7 +1004,7 @@ S3BootScriptCloseTable ( @param Buffer The source buffer from which to write data. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1021,6 +1021,10 @@ S3BootScriptSaveIoWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_IO_WRITE ScriptIoWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // @@ -1064,7 +1068,7 @@ S3BootScriptSaveIoWrite ( @param DataMask A pointer to the data mask to be AND-ed with the data read from the register @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1080,6 +1084,10 @@ S3BootScriptSaveIoReadWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_IO_READ_WRITE ScriptIoReadWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE) + (WidthInByte * 2)); @@ -1114,7 +1122,7 @@ S3BootScriptSaveIoReadWrite ( @param Buffer The source buffer from which to write the data. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1130,6 +1138,10 @@ S3BootScriptSaveMemWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_MEM_WRITE ScriptMemWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // @@ -1174,7 +1186,7 @@ S3BootScriptSaveMemWrite ( @param DataMask A pointer to the data mask to be AND-ed with the data read from the register. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1190,6 +1202,10 @@ S3BootScriptSaveMemReadWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_MEM_READ_WRITE ScriptMemReadWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE) + (WidthInByte * 2)); @@ -1224,7 +1240,7 @@ S3BootScriptSaveMemReadWrite ( @param Buffer The source buffer from which to write the data. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -1242,6 +1258,10 @@ S3BootScriptSavePciCfgWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE ScriptPciWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -1293,7 +1313,7 @@ S3BootScriptSavePciCfgWrite ( @param DataMask A pointer to the data mask to be AND-ed. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN__SUCCESS Opcode is added. + @retval RETURN__SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -1311,6 +1331,10 @@ S3BootScriptSavePciCfgReadWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE ScriptPciReadWrite; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -1357,7 +1381,7 @@ S3BootScriptSavePciCfgReadWrite ( @param Buffer The source buffer from which to write the data. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -1376,6 +1400,10 @@ S3BootScriptSavePciCfg2Write ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE ScriptPciWrite2; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -1429,7 +1457,7 @@ S3BootScriptSavePciCfg2Write ( @param DataMask A pointer to the data mask to be AND-ed. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -1448,6 +1476,10 @@ S3BootScriptSavePciCfg2ReadWrite ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE ScriptPciReadWrite2; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -1601,7 +1633,7 @@ CheckParameters ( @param Buffer Contains the value of data to execute to the SMBUS slave device. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1618,6 +1650,10 @@ S3BootScriptSaveSmbusExecute ( UINT8 *Script; EFI_BOOT_SCRIPT_SMBUS_EXECUTE ScriptSmbusExecute; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if (Length == NULL) { BufferLength = 0; } else { @@ -1670,7 +1706,7 @@ S3BootScriptSaveSmbusExecute ( @param Duration Duration in microseconds of the stall @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1682,6 +1718,10 @@ S3BootScriptSaveStall ( UINT8 *Script; EFI_BOOT_SCRIPT_STALL ScriptStall; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_STALL)); Script = S3BootScriptGetEntryAddAddress (Length); @@ -1710,7 +1750,7 @@ S3BootScriptSaveStall ( @param Context Argument to be passed into the EntryPoint of the code to be dispatched. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1723,6 +1763,10 @@ S3BootScriptSaveDispatch2 ( UINT8 *Script; EFI_BOOT_SCRIPT_DISPATCH_2 ScriptDispatch2; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_DISPATCH_2)); Script = S3BootScriptGetEntryAddAddress (Length); @@ -1762,7 +1806,7 @@ S3BootScriptSaveDispatch2 ( @param LoopTimes The times of the register polling. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS @@ -1781,6 +1825,10 @@ S3BootScriptSaveMemPoll ( UINT8 WidthInByte; EFI_BOOT_SCRIPT_MEM_POLL ScriptMemPoll; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_POLL) + (WidthInByte * 2)); @@ -1817,7 +1865,7 @@ S3BootScriptSaveMemPoll ( @param Information Information to be logged in the boot scrpit @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS @@ -1831,6 +1879,10 @@ S3BootScriptSaveInformation ( UINT8 *Script; EFI_BOOT_SCRIPT_INFORMATION ScriptInformation; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + // // Truncation check // @@ -1868,7 +1920,7 @@ S3BootScriptSaveInformation ( @param String The string to save to boot script table @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS @@ -1889,7 +1941,7 @@ S3BootScriptSaveInformationAsciiString ( @param EntryPoint Entry point of the code to be dispatched. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -1901,6 +1953,10 @@ S3BootScriptSaveDispatch ( UINT8 *Script; EFI_BOOT_SCRIPT_DISPATCH ScriptDispatch; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_DISPATCH)); Script = S3BootScriptGetEntryAddAddress (Length); @@ -1935,7 +1991,7 @@ S3BootScriptSaveDispatch ( granularity so the delay may be longer. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS @@ -1953,6 +2009,10 @@ S3BootScriptSaveIoPoll ( UINT8 Length; EFI_BOOT_SCRIPT_IO_POLL ScriptIoPoll; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_POLL) + (WidthInByte * 2)); @@ -1992,7 +2052,7 @@ S3BootScriptSaveIoPoll ( granularity so the delay may be longer. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -2011,6 +2071,10 @@ S3BootScriptSavePciPoll ( UINT8 Length; EFI_BOOT_SCRIPT_PCI_CONFIG_POLL ScriptPciPoll; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -2058,7 +2122,7 @@ S3BootScriptSavePciPoll ( granularity so the delay may be longer. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. @note A known Limitations in the implementation which is 64bits operations are not supported. **/ @@ -2078,6 +2142,10 @@ S3BootScriptSavePci2Poll ( UINT8 Length; EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL ScriptPci2Poll; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if ((Width == S3BootScriptWidthUint64) || (Width == S3BootScriptWidthFifoUint64) || (Width == S3BootScriptWidthFillUint64)) @@ -2192,7 +2260,7 @@ S3BootScriptCalculateInsertAddress ( @retval RETURN_OUT_OF_RESOURCES The table is not available. @retval RETURN_INVALID_PARAMETER The Position is not a valid position in the boot script table. - @retval RETURN_SUCCESS Opcode is inserted. + @retval RETURN_SUCCESS Opcode is inserted no action is required as ACPI S3 was disabled. **/ RETURN_STATUS EFIAPI @@ -2210,6 +2278,10 @@ S3BootScriptMoveLastOpcode ( UINT8 *LastOpcode; UINT8 TempBootScriptEntry[BOOT_SCRIPT_NODE_MAX_LENGTH]; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + ValidatePosition = FALSE; TempPosition = (Position == NULL) ? NULL : (*Position); @@ -2297,7 +2369,7 @@ S3BootScriptMoveLastOpcode ( @retval RETURN_INVALID_PARAMETER The Position is not a valid position in the boot script table. @retval RETURN_OUT_OF_RESOURCES Not enough memory for the table do operation. - @retval RETURN_SUCCESS Opcode is added. + @retval RETURN_SUCCESS Opcode is added or no action is required as ACPI S3 was disabled. **/ RETURN_STATUS @@ -2313,6 +2385,10 @@ S3BootScriptLabelInternal ( UINT8 *Script; EFI_BOOT_SCRIPT_INFORMATION ScriptInformation; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + // // Truncation check // @@ -2357,8 +2433,8 @@ S3BootScriptLabelInternal ( of the inserted opcode in the boot script table. @param Label Points to the label which will be inserted in the boot script table. - @retval EFI_SUCCESS The operation succeeded. A record was added into the - specified script table. + @retval EFI_SUCCESS The operation succeeded or no action is required. + A record was added into the specified script table if ACPI S3 was enabled. @retval EFI_INVALID_PARAMETER The parameter is illegal or the given boot script is not supported. If the opcode is unknow or not supported because of the PCD Feature Flags. @@ -2381,6 +2457,10 @@ S3BootScriptLabel ( EFI_BOOT_SCRIPT_TABLE_HEADER TableHeader; UINT32 LabelLength; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + // // Check NULL Label // @@ -2443,8 +2523,8 @@ S3BootScriptLabel ( @param Position2 The positions in the boot script table to compare @param RelativePosition On return, points to the result of the comparison - @retval EFI_SUCCESS The operation succeeded. A record was added into the - specified script table. + @retval EFI_SUCCESS The operation succeeded or no action is required. + A record was added into the specified script table if ACPI S3 was enabled. @retval EFI_INVALID_PARAMETER The parameter is illegal or the given boot script is not supported. If the opcode is unknow or not supported because of the PCD Feature Flags. @@ -2462,6 +2542,10 @@ S3BootScriptCompare ( UINT8 *Script; UINT32 TableLength; + if (!mS3BootScriptAcpiS3Enable) { + return RETURN_SUCCESS; + } + if (RelativePosition == NULL) { return EFI_INVALID_PARAMETER; } From 57c246c99b16ec568713423fcc9936ec018301ce Mon Sep 17 00:00:00 2001 From: Robert Phelps Date: Thu, 10 Nov 2022 05:46:09 +0800 Subject: [PATCH 0611/1529] MdePkg: Add After Ready To Boot Event Definition from UEFI 2.9 Add After Ready To Boot Event Definitions Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Robert Phelps Reviewed-by: Liming Gao --- MdePkg/Include/Guid/EventGroup.h | 5 +++++ MdePkg/MdePkg.dec | 3 +++ 2 files changed, 8 insertions(+) diff --git a/MdePkg/Include/Guid/EventGroup.h b/MdePkg/Include/Guid/EventGroup.h index 64bfd4bab9..b0dc002a18 100644 --- a/MdePkg/Include/Guid/EventGroup.h +++ b/MdePkg/Include/Guid/EventGroup.h @@ -34,6 +34,11 @@ extern EFI_GUID gEfiEventMemoryMapChangeGuid; extern EFI_GUID gEfiEventReadyToBootGuid; +#define EFI_EVENT_GROUP_AFTER_READY_TO_BOOT \ + { 0x3a2a00ad, 0x98b9, 0x4cdf, { 0xa4, 0x78, 0x70, 0x27, 0x77, 0xf1, 0xc1, 0xb } } + +extern EFI_GUID gEfiEventAfterReadyToBootGuid; + #define EFI_EVENT_GROUP_DXE_DISPATCH_GUID \ { 0x7081e22f, 0xcac6, 0x4053, { 0x94, 0x68, 0x67, 0x57, 0x82, 0xcf, 0x88, 0xe5 }} diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 3d08f20d15..a7ad520419 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -413,6 +413,9 @@ ## Include/Guid/EventGroup.h gEfiEventReadyToBootGuid = { 0x7CE88FB3, 0x4BD7, 0x4679, { 0x87, 0xA8, 0xA8, 0xD8, 0xDE, 0xE5, 0x0D, 0x2B }} + ## Include/Guid/EventGroup.h + gEfiEventAfterReadyToBootGuid = { 0x3a2a00ad, 0x98b9, 0x4cdf, { 0xa4, 0x78, 0x70, 0x27, 0x77, 0xf1, 0xc1, 0x0b }} + ## Include/Guid/EventGroup.h gEfiEventMemoryMapChangeGuid = { 0x78BEE926, 0x692F, 0x48FD, { 0x9E, 0xDB, 0x01, 0x42, 0x2E, 0xF0, 0xD7, 0xAB }} From fc0276b0f1802bb895fe0b997bc3c98eac472a1b Mon Sep 17 00:00:00 2001 From: Robert Phelps Date: Thu, 22 Dec 2022 04:28:06 +0800 Subject: [PATCH 0612/1529] MdePkg: Added Call for AfterReadyToBoot Event In the function EfiSignalEventReadyToBoot, Code was added to also create, signal, and close the AfterReadyToBoot event. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Robert Phelps Reviewed-by: Liming Gao --- MdePkg/Library/UefiLib/UefiLib.inf | 1 + MdePkg/Library/UefiLib/UefiNotTiano.c | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/MdePkg/Library/UefiLib/UefiLib.inf b/MdePkg/Library/UefiLib/UefiLib.inf index 01ed92092d..3aced47d2e 100644 --- a/MdePkg/Library/UefiLib/UefiLib.inf +++ b/MdePkg/Library/UefiLib/UefiLib.inf @@ -56,6 +56,7 @@ [Guids] gEfiEventReadyToBootGuid ## SOMETIMES_CONSUMES ## Event + gEfiEventAfterReadyToBootGuid ## SOMETIMES_CONSUMES ## Event gEfiEventLegacyBootGuid ## SOMETIMES_CONSUMES ## Event gEfiGlobalVariableGuid ## SOMETIMES_CONSUMES ## Variable gEfiAcpi20TableGuid ## SOMETIMES_CONSUMES ## SystemTable diff --git a/MdePkg/Library/UefiLib/UefiNotTiano.c b/MdePkg/Library/UefiLib/UefiNotTiano.c index d84e91fd01..8c8d9b29f8 100644 --- a/MdePkg/Library/UefiLib/UefiNotTiano.c +++ b/MdePkg/Library/UefiLib/UefiNotTiano.c @@ -222,12 +222,26 @@ EfiSignalEventReadyToBoot ( { EFI_STATUS Status; EFI_EVENT ReadyToBootEvent; + EFI_EVENT AfterReadyToBootEvent; Status = EfiCreateEventReadyToBoot (&ReadyToBootEvent); if (!EFI_ERROR (Status)) { gBS->SignalEvent (ReadyToBootEvent); gBS->CloseEvent (ReadyToBootEvent); } + + Status = gBS->CreateEventEx ( + EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + EfiEventEmptyFunction, + NULL, + &gEfiEventAfterReadyToBootGuid, + &AfterReadyToBootEvent + ); + if (!EFI_ERROR (Status)) { + gBS->SignalEvent (AfterReadyToBootEvent); + gBS->CloseEvent (AfterReadyToBootEvent); + } } /** From c3850fd5b57d8d6fee3abdd6cc9d75bd0d479ae1 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Tue, 23 Aug 2022 22:14:08 +0530 Subject: [PATCH 0613/1529] MdePkg/Register: Add register definition header files for RISC-V REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 Add register definitions and access routines for RISC-V. These headers are leveraged from opensbi repo. Cc: Daniel Schaefer Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Reviewed-by: Michael D Kinney --- .../Include/Register/RiscV64/RiscVEncoding.h | 119 ++++++++++++++++++ MdePkg/Include/Register/RiscV64/RiscVImpl.h | 25 ++++ 2 files changed, 144 insertions(+) create mode 100644 MdePkg/Include/Register/RiscV64/RiscVEncoding.h create mode 100644 MdePkg/Include/Register/RiscV64/RiscVImpl.h diff --git a/MdePkg/Include/Register/RiscV64/RiscVEncoding.h b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h new file mode 100644 index 0000000000..5c2989b797 --- /dev/null +++ b/MdePkg/Include/Register/RiscV64/RiscVEncoding.h @@ -0,0 +1,119 @@ +/** @file + RISC-V CSR encodings + + Copyright (c) 2019, Western Digital Corporation or its affiliates. All rights reserved.
+ Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef RISCV_ENCODING_H_ +#define RISCV_ENCODING_H_ + +#define MSTATUS_SIE 0x00000002UL +#define MSTATUS_MIE 0x00000008UL +#define MSTATUS_SPIE_SHIFT 5 +#define MSTATUS_SPIE (1UL << MSTATUS_SPIE_SHIFT) +#define MSTATUS_UBE 0x00000040UL +#define MSTATUS_MPIE 0x00000080UL +#define MSTATUS_SPP_SHIFT 8 +#define MSTATUS_SPP (1UL << MSTATUS_SPP_SHIFT) +#define MSTATUS_MPP_SHIFT 11 +#define MSTATUS_MPP (3UL << MSTATUS_MPP_SHIFT) + +#define SSTATUS_SIE MSTATUS_SIE +#define SSTATUS_SPIE_SHIFT MSTATUS_SPIE_SHIFT +#define SSTATUS_SPIE MSTATUS_SPIE +#define SSTATUS_SPP_SHIFT MSTATUS_SPP_SHIFT +#define SSTATUS_SPP MSTATUS_SPP + +#define IRQ_S_SOFT 1 +#define IRQ_VS_SOFT 2 +#define IRQ_M_SOFT 3 +#define IRQ_S_TIMER 5 +#define IRQ_VS_TIMER 6 +#define IRQ_M_TIMER 7 +#define IRQ_S_EXT 9 +#define IRQ_VS_EXT 10 +#define IRQ_M_EXT 11 +#define IRQ_S_GEXT 12 +#define IRQ_PMU_OVF 13 + +#define MIP_SSIP (1UL << IRQ_S_SOFT) +#define MIP_VSSIP (1UL << IRQ_VS_SOFT) +#define MIP_MSIP (1UL << IRQ_M_SOFT) +#define MIP_STIP (1UL << IRQ_S_TIMER) +#define MIP_VSTIP (1UL << IRQ_VS_TIMER) +#define MIP_MTIP (1UL << IRQ_M_TIMER) +#define MIP_SEIP (1UL << IRQ_S_EXT) +#define MIP_VSEIP (1UL << IRQ_VS_EXT) +#define MIP_MEIP (1UL << IRQ_M_EXT) +#define MIP_SGEIP (1UL << IRQ_S_GEXT) +#define MIP_LCOFIP (1UL << IRQ_PMU_OVF) + +#define SIP_SSIP MIP_SSIP +#define SIP_STIP MIP_STIP + +#define PRV_U 0UL +#define PRV_S 1UL +#define PRV_M 3UL + +#define SATP64_MODE 0xF000000000000000ULL +#define SATP64_ASID 0x0FFFF00000000000ULL +#define SATP64_PPN 0x00000FFFFFFFFFFFULL + +#define SATP_MODE_OFF 0UL +#define SATP_MODE_SV32 1UL +#define SATP_MODE_SV39 8UL +#define SATP_MODE_SV48 9UL +#define SATP_MODE_SV57 10UL +#define SATP_MODE_SV64 11UL + +#define SATP_MODE SATP64_MODE + +/* User Counters/Timers */ +#define CSR_CYCLE 0xc00 +#define CSR_TIME 0xc01 + +/* Supervisor Trap Setup */ +#define CSR_SSTATUS 0x100 +#define CSR_SEDELEG 0x102 +#define CSR_SIDELEG 0x103 +#define CSR_SIE 0x104 +#define CSR_STVEC 0x105 + +/* Supervisor Configuration */ +#define CSR_SENVCFG 0x10a + +/* Supervisor Trap Handling */ +#define CSR_SSCRATCH 0x140 +#define CSR_SEPC 0x141 +#define CSR_SCAUSE 0x142 +#define CSR_STVAL 0x143 +#define CSR_SIP 0x144 + +/* Supervisor Protection and Translation */ +#define CSR_SATP 0x180 + +/* Trap/Exception Causes */ +#define CAUSE_MISALIGNED_FETCH 0x0 +#define CAUSE_FETCH_ACCESS 0x1 +#define CAUSE_ILLEGAL_INSTRUCTION 0x2 +#define CAUSE_BREAKPOINT 0x3 +#define CAUSE_MISALIGNED_LOAD 0x4 +#define CAUSE_LOAD_ACCESS 0x5 +#define CAUSE_MISALIGNED_STORE 0x6 +#define CAUSE_STORE_ACCESS 0x7 +#define CAUSE_USER_ECALL 0x8 +#define CAUSE_SUPERVISOR_ECALL 0x9 +#define CAUSE_VIRTUAL_SUPERVISOR_ECALL 0xa +#define CAUSE_MACHINE_ECALL 0xb +#define CAUSE_FETCH_PAGE_FAULT 0xc +#define CAUSE_LOAD_PAGE_FAULT 0xd +#define CAUSE_STORE_PAGE_FAULT 0xf +#define CAUSE_FETCH_GUEST_PAGE_FAULT 0x14 +#define CAUSE_LOAD_GUEST_PAGE_FAULT 0x15 +#define CAUSE_VIRTUAL_INST_FAULT 0x16 +#define CAUSE_STORE_GUEST_PAGE_FAULT 0x17 + +#endif diff --git a/MdePkg/Include/Register/RiscV64/RiscVImpl.h b/MdePkg/Include/Register/RiscV64/RiscVImpl.h new file mode 100644 index 0000000000..ee5c2ba603 --- /dev/null +++ b/MdePkg/Include/Register/RiscV64/RiscVImpl.h @@ -0,0 +1,25 @@ +/** @file + RISC-V package definitions. + + Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef RISCV_IMPL_H_ +#define RISCV_IMPL_H_ + +#include + +#define _ASM_FUNC(Name, Section) \ + .global Name ; \ + .section #Section, "ax" ; \ + .type Name, %function ; \ + .p2align 2 ; \ + Name: + +#define ASM_FUNC(Name) _ASM_FUNC(ASM_PFX(Name), .text. ## Name) +#define RISCV_TIMER_COMPARE_BITS 32 + +#endif From b657dafb293d96b8b32a6bdcde5869cf867131c5 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Tue, 6 Sep 2022 10:48:12 +0530 Subject: [PATCH 0614/1529] MdePkg/BaseLib: RISC-V: Add few more helper functions REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 Few of the basic helper functions required for any RISC-V CPU were added in edk2-platforms. To support qemu virt, they need to be added in BaseLib. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Daniel Schaefer Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Reviewed-by: Michael D Kinney --- MdePkg/Include/Library/BaseLib.h | 50 +++++++++++++++++ MdePkg/Library/BaseLib/BaseLib.inf | 3 ++ MdePkg/Library/BaseLib/RiscV64/CpuScratch.S | 31 +++++++++++ MdePkg/Library/BaseLib/RiscV64/ReadTimer.S | 23 ++++++++ .../Library/BaseLib/RiscV64/RiscVInterrupt.S | 53 +++++++++++++++++-- MdePkg/Library/BaseLib/RiscV64/RiscVMmu.S | 23 ++++++++ 6 files changed, 179 insertions(+), 4 deletions(-) create mode 100644 MdePkg/Library/BaseLib/RiscV64/CpuScratch.S create mode 100644 MdePkg/Library/BaseLib/RiscV64/ReadTimer.S create mode 100644 MdePkg/Library/BaseLib/RiscV64/RiscVMmu.S diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h index f3f59f21c2..8f2df76c29 100644 --- a/MdePkg/Include/Library/BaseLib.h +++ b/MdePkg/Include/Library/BaseLib.h @@ -151,6 +151,56 @@ typedef struct { #define BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT 8 +VOID +RiscVSetSupervisorScratch ( + IN UINT64 + ); + +UINT64 +RiscVGetSupervisorScratch ( + VOID + ); + +VOID +RiscVSetSupervisorStvec ( + IN UINT64 + ); + +UINT64 +RiscVGetSupervisorStvec ( + VOID + ); + +UINT64 +RiscVGetSupervisorTrapCause ( + VOID + ); + +VOID +RiscVSetSupervisorAddressTranslationRegister ( + IN UINT64 + ); + +UINT64 +RiscVReadTimer ( + VOID + ); + +VOID +RiscVEnableTimerInterrupt ( + VOID + ); + +VOID +RiscVDisableTimerInterrupt ( + VOID + ); + +VOID +RiscVClearPendingTimerInterrupt ( + VOID + ); + #endif // defined (MDE_CPU_RISCV64) #if defined (MDE_CPU_LOONGARCH64) diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf index 9ed46a584a..3a48492b1a 100644 --- a/MdePkg/Library/BaseLib/BaseLib.inf +++ b/MdePkg/Library/BaseLib/BaseLib.inf @@ -401,6 +401,9 @@ RiscV64/RiscVCpuPause.S | GCC RiscV64/RiscVInterrupt.S | GCC RiscV64/FlushCache.S | GCC + RiscV64/CpuScratch.S | GCC + RiscV64/ReadTimer.S | GCC + RiscV64/RiscVMmu.S | GCC [Sources.LOONGARCH64] Math64.c diff --git a/MdePkg/Library/BaseLib/RiscV64/CpuScratch.S b/MdePkg/Library/BaseLib/RiscV64/CpuScratch.S new file mode 100644 index 0000000000..5492a500eb --- /dev/null +++ b/MdePkg/Library/BaseLib/RiscV64/CpuScratch.S @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// CPU scratch register related functions for RISC-V +// +// Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +//------------------------------------------------------------------------------ + +#include + +.data +.align 3 +.section .text + +// +// Set Supervisor mode scratch. +// @param a0 : Value set to Supervisor mode scratch +// +ASM_FUNC (RiscVSetSupervisorScratch) + csrw CSR_SSCRATCH, a0 + ret + +// +// Get Supervisor mode scratch. +// @retval a0 : Value in Supervisor mode scratch +// +ASM_FUNC (RiscVGetSupervisorScratch) + csrr a0, CSR_SSCRATCH + ret diff --git a/MdePkg/Library/BaseLib/RiscV64/ReadTimer.S b/MdePkg/Library/BaseLib/RiscV64/ReadTimer.S new file mode 100644 index 0000000000..39a06efa51 --- /dev/null +++ b/MdePkg/Library/BaseLib/RiscV64/ReadTimer.S @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// Read CPU timer +// +// Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +//------------------------------------------------------------------------------ + +#include + +.data +.align 3 +.section .text + +// +// Read TIME CSR. +// @retval a0 : 64-bit timer. +// +ASM_FUNC (RiscVReadTimer) + csrr a0, CSR_TIME + ret diff --git a/MdePkg/Library/BaseLib/RiscV64/RiscVInterrupt.S b/MdePkg/Library/BaseLib/RiscV64/RiscVInterrupt.S index 87b3468fc7..6a1b90a7e4 100644 --- a/MdePkg/Library/BaseLib/RiscV64/RiscVInterrupt.S +++ b/MdePkg/Library/BaseLib/RiscV64/RiscVInterrupt.S @@ -8,13 +8,13 @@ // //------------------------------------------------------------------------------ +#include + ASM_GLOBAL ASM_PFX(RiscVDisableSupervisorModeInterrupts) ASM_GLOBAL ASM_PFX(RiscVEnableSupervisorModeInterrupt) ASM_GLOBAL ASM_PFX(RiscVGetSupervisorModeInterrupts) -#define SSTATUS_SIE 0x00000002 -#define CSR_SSTATUS 0x100 - #define SSTATUS_SPP_BIT_POSITION 8 +#define SSTATUS_SPP_BIT_POSITION 8 // // This routine disables supervisor mode interrupt @@ -53,11 +53,56 @@ InTrap: ret // +// Set Supervisor mode trap vector. +// @param a0 : Value set to Supervisor mode trap vector +// +ASM_FUNC (RiscVSetSupervisorStvec) + csrrw a1, CSR_STVEC, a0 + ret + +// +// Get Supervisor mode trap vector. +// @retval a0 : Value in Supervisor mode trap vector +// +ASM_FUNC (RiscVGetSupervisorStvec) + csrr a0, CSR_STVEC + ret + +// +// Get Supervisor trap cause CSR. +// +ASM_FUNC (RiscVGetSupervisorTrapCause) + csrrs a0, CSR_SCAUSE, 0 + ret +// // This routine returns supervisor mode interrupt // status. // -ASM_PFX(RiscVGetSupervisorModeInterrupts): +ASM_FUNC (RiscVGetSupervisorModeInterrupts) csrr a0, CSR_SSTATUS andi a0, a0, SSTATUS_SIE ret +// +// This routine disables supervisor mode timer interrupt +// +ASM_FUNC (RiscVDisableTimerInterrupt) + li a0, SIP_STIP + csrc CSR_SIE, a0 + ret + +// +// This routine enables supervisor mode timer interrupt +// +ASM_FUNC (RiscVEnableTimerInterrupt) + li a0, SIP_STIP + csrs CSR_SIE, a0 + ret + +// +// This routine clears pending supervisor mode timer interrupt +// +ASM_FUNC (RiscVClearPendingTimerInterrupt) + li a0, SIP_STIP + csrc CSR_SIP, a0 + ret diff --git a/MdePkg/Library/BaseLib/RiscV64/RiscVMmu.S b/MdePkg/Library/BaseLib/RiscV64/RiscVMmu.S new file mode 100644 index 0000000000..ac8f92f38a --- /dev/null +++ b/MdePkg/Library/BaseLib/RiscV64/RiscVMmu.S @@ -0,0 +1,23 @@ +//------------------------------------------------------------------------------ +// +// CPU scratch register related functions for RISC-V +// +// Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +//------------------------------------------------------------------------------ + +#include + +.data +.align 3 +.section .text + +// +// Set Supervisor Address Translation and +// Protection Register. +// +ASM_FUNC (RiscVSetSupervisorAddressTranslationRegister) + csrw CSR_SATP, a0 + ret From 4e3500ff1198c5db8c2d939e77eca3844cc676e7 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 7 Sep 2022 12:23:32 +0530 Subject: [PATCH 0615/1529] MdePkg: Add BaseRiscVSbiLib Library for RISC-V REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 This library is required to make SBI ecalls from the S-mode EDK2. This is mostly copied from edk2-platforms/Silicon/RISC-V/ProcessorPkg/Library/RiscVEdk2SbiLib Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Reviewed-by: Michael D Kinney --- MdePkg/Include/Library/BaseRiscVSbiLib.h | 154 ++++++++++++ .../Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c | 231 ++++++++++++++++++ .../BaseRiscVSbiLib/BaseRiscVSbiLib.inf | 26 ++ .../Library/BaseRiscVSbiLib/RiscVSbiEcall.S | 42 ++++ MdePkg/MdePkg.dec | 4 + MdePkg/MdePkg.dsc | 3 + 6 files changed, 460 insertions(+) create mode 100644 MdePkg/Include/Library/BaseRiscVSbiLib.h create mode 100644 MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c create mode 100644 MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf create mode 100644 MdePkg/Library/BaseRiscVSbiLib/RiscVSbiEcall.S diff --git a/MdePkg/Include/Library/BaseRiscVSbiLib.h b/MdePkg/Include/Library/BaseRiscVSbiLib.h new file mode 100644 index 0000000000..e75520b4b8 --- /dev/null +++ b/MdePkg/Include/Library/BaseRiscVSbiLib.h @@ -0,0 +1,154 @@ +/** @file + Library to call the RISC-V SBI ecalls + + Copyright (c) 2021-2022, Hewlett Packard Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Glossary: + - Hart - Hardware Thread, similar to a CPU core + + Currently, EDK2 needs to call SBI only to set the time and to do system reset. + +**/ + +#ifndef RISCV_SBI_LIB_H_ +#define RISCV_SBI_LIB_H_ + +#include + +/* SBI Extension IDs */ +#define SBI_EXT_TIME 0x54494D45 +#define SBI_EXT_SRST 0x53525354 + +/* SBI function IDs for TIME extension*/ +#define SBI_EXT_TIME_SET_TIMER 0x0 + +/* SBI function IDs for SRST extension */ +#define SBI_EXT_SRST_RESET 0x0 + +#define SBI_SRST_RESET_TYPE_SHUTDOWN 0x0 +#define SBI_SRST_RESET_TYPE_COLD_REBOOT 0x1 +#define SBI_SRST_RESET_TYPE_WARM_REBOOT 0x2 + +#define SBI_SRST_RESET_REASON_NONE 0x0 +#define SBI_SRST_RESET_REASON_SYSFAIL 0x1 + +/* SBI return error codes */ +#define SBI_SUCCESS 0 +#define SBI_ERR_FAILED -1 +#define SBI_ERR_NOT_SUPPORTED -2 +#define SBI_ERR_INVALID_PARAM -3 +#define SBI_ERR_DENIED -4 +#define SBI_ERR_INVALID_ADDRESS -5 +#define SBI_ERR_ALREADY_AVAILABLE -6 +#define SBI_ERR_ALREADY_STARTED -7 +#define SBI_ERR_ALREADY_STOPPED -8 + +#define SBI_LAST_ERR SBI_ERR_ALREADY_STOPPED + +typedef struct { + UINT64 BootHartId; + VOID *PeiServiceTable; // PEI Service table + VOID *PrePiHobList; // Pre PI Hob List + UINT64 FlattenedDeviceTree; // Pointer to Flattened Device tree +} EFI_RISCV_FIRMWARE_CONTEXT; + +// +// EDK2 OpenSBI firmware extension return status. +// +typedef struct { + UINTN Error; ///< SBI status code + UINTN Value; ///< Value returned +} SBI_RET; + +VOID +EFIAPI +SbiSetTimer ( + IN UINT64 Time + ); + +EFI_STATUS +EFIAPI +SbiSystemReset ( + IN UINTN ResetType, + IN UINTN ResetReason + ); + +/** + Get firmware context of the calling hart. + + @param[out] FirmwareContext The firmware context pointer. +**/ +VOID +EFIAPI +GetFirmwareContext ( + OUT EFI_RISCV_FIRMWARE_CONTEXT **FirmwareContext + ); + +/** + Set firmware context of the calling hart. + + @param[in] FirmwareContext The firmware context pointer. +**/ +VOID +EFIAPI +SetFirmwareContext ( + IN EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext + ); + +/** + Get pointer to OpenSBI Firmware Context + + Get the pointer of firmware context. + + @param FirmwareContextPtr Pointer to retrieve pointer to the + Firmware Context. +**/ +VOID +EFIAPI +GetFirmwareContextPointer ( + IN OUT EFI_RISCV_FIRMWARE_CONTEXT **FirmwareContextPtr + ); + +/** + Set pointer to OpenSBI Firmware Context + + Set the pointer of firmware context. + + @param FirmwareContextPtr Pointer to Firmware Context. +**/ +VOID +EFIAPI +SetFirmwareContextPointer ( + IN EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContextPtr + ); + +/** + Make ECALL in assembly + + Switch to M-mode + + @param[in,out] Arg0 + @param[in,out] Arg1 + @param[in] Arg2 + @param[in] Arg3 + @param[in] Arg4 + @param[in] Arg5 + @param[in] FID + @param[in] EXT +**/ +VOID +EFIAPI +RiscVSbiEcall ( + IN OUT UINTN *Arg0, + IN OUT UINTN *Arg1, + IN UINTN Arg2, + IN UINTN Arg3, + IN UINTN Arg4, + IN UINTN Arg5, + IN UINTN Fid, + IN UINTN Ext + ); + +#endif diff --git a/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c b/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c new file mode 100644 index 0000000000..2ba8f5ed36 --- /dev/null +++ b/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.c @@ -0,0 +1,231 @@ +/** @file + Instance of the SBI ecall library. + + It allows calling an SBI function via an ecall from S-Mode. + + Copyright (c) 2021-2022, Hewlett Packard Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include + +// +// Maximum arguments for SBI ecall +#define SBI_CALL_MAX_ARGS 6 + +/** + Call SBI call using ecall instruction. + + Asserts when NumArgs exceeds SBI_CALL_MAX_ARGS. + + @param[in] ExtId SBI extension ID. + @param[in] FuncId SBI function ID. + @param[in] NumArgs Number of arguments to pass to the ecall. + @param[in] ... Argument list for the ecall. + + @retval Returns SBI_RET structure with value and error code. + +**/ +STATIC +SBI_RET +EFIAPI +SbiCall ( + IN UINTN ExtId, + IN UINTN FuncId, + IN UINTN NumArgs, + ... + ) +{ + UINTN I; + SBI_RET Ret; + UINTN Args[SBI_CALL_MAX_ARGS]; + VA_LIST ArgList; + + VA_START (ArgList, NumArgs); + + if (NumArgs > SBI_CALL_MAX_ARGS) { + Ret.Error = SBI_ERR_INVALID_PARAM; + Ret.Value = -1; + return Ret; + } + + for (I = 0; I < SBI_CALL_MAX_ARGS; I++) { + if (I < NumArgs) { + Args[I] = VA_ARG (ArgList, UINTN); + } else { + // Default to 0 for all arguments that are not given + Args[I] = 0; + } + } + + VA_END (ArgList); + + // ECALL updates the a0 and a1 registers as return values. + RiscVSbiEcall ( + &Args[0], + &Args[1], + Args[2], + Args[3], + Args[4], + Args[5], + (UINTN)(FuncId), + (UINTN)(ExtId) + ); + + Ret.Error = Args[0]; + Ret.Value = Args[1]; + return Ret; +} + +/** + Translate SBI error code to EFI status. + + @param[in] SbiError SBI error code + @retval EFI_STATUS +**/ +STATIC +EFI_STATUS +EFIAPI +TranslateError ( + IN UINTN SbiError + ) +{ + switch (SbiError) { + case SBI_SUCCESS: + return EFI_SUCCESS; + case SBI_ERR_FAILED: + return EFI_DEVICE_ERROR; + break; + case SBI_ERR_NOT_SUPPORTED: + return EFI_UNSUPPORTED; + break; + case SBI_ERR_INVALID_PARAM: + return EFI_INVALID_PARAMETER; + break; + case SBI_ERR_DENIED: + return EFI_ACCESS_DENIED; + break; + case SBI_ERR_INVALID_ADDRESS: + return EFI_LOAD_ERROR; + break; + case SBI_ERR_ALREADY_AVAILABLE: + return EFI_ALREADY_STARTED; + break; + default: + // + // Reaches here only if SBI has defined a new error type + // + ASSERT (FALSE); + return EFI_UNSUPPORTED; + break; + } +} + +/** + Clear pending timer interrupt bit and set timer for next event after Time. + + To clear the timer without scheduling a timer event, set Time to a + practically infinite value or mask the timer interrupt by clearing sie.STIE. + + @param[in] Time The time offset to the next scheduled timer interrupt. +**/ +VOID +EFIAPI +SbiSetTimer ( + IN UINT64 Time + ) +{ + SbiCall (SBI_EXT_TIME, SBI_EXT_TIME_SET_TIMER, 1, Time); +} + +/** + Reset the system using SRST SBI extenion + + @param[in] ResetType The SRST System Reset Type. + @param[in] ResetReason The SRST System Reset Reason. +**/ +EFI_STATUS +EFIAPI +SbiSystemReset ( + IN UINTN ResetType, + IN UINTN ResetReason + ) +{ + SBI_RET Ret; + + Ret = SbiCall ( + SBI_EXT_SRST, + SBI_EXT_SRST_RESET, + 2, + ResetType, + ResetReason + ); + + return TranslateError (Ret.Error); +} + +/** + Get firmware context of the calling hart. + + @param[out] FirmwareContext The firmware context pointer. +**/ +VOID +EFIAPI +GetFirmwareContext ( + OUT EFI_RISCV_FIRMWARE_CONTEXT **FirmwareContext + ) +{ + *FirmwareContext = (EFI_RISCV_FIRMWARE_CONTEXT *)RiscVGetSupervisorScratch (); +} + +/** + Set firmware context of the calling hart. + + @param[in] FirmwareContext The firmware context pointer. +**/ +VOID +EFIAPI +SetFirmwareContext ( + IN EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext + ) +{ + RiscVSetSupervisorScratch ((UINT64)FirmwareContext); +} + +/** + Get pointer to OpenSBI Firmware Context + + Get the pointer of firmware context through OpenSBI FW Extension SBI. + + @param FirmwareContextPtr Pointer to retrieve pointer to the + Firmware Context. +**/ +VOID +EFIAPI +GetFirmwareContextPointer ( + IN OUT EFI_RISCV_FIRMWARE_CONTEXT **FirmwareContextPtr + ) +{ + GetFirmwareContext (FirmwareContextPtr); +} + +/** + Set the pointer to OpenSBI Firmware Context + + Set the pointer of firmware context through OpenSBI FW Extension SBI. + + @param FirmwareContextPtr Pointer to Firmware Context. +**/ +VOID +EFIAPI +SetFirmwareContextPointer ( + IN EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContextPtr + ) +{ + SetFirmwareContext (FirmwareContextPtr); +} diff --git a/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf b/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf new file mode 100644 index 0000000000..d6fd3f663a --- /dev/null +++ b/MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf @@ -0,0 +1,26 @@ +## @file +# RISC-V Library to call SBI ecalls +# +# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001b + BASE_NAME = BaseRiscVSbiLib + FILE_GUID = D742CF3D-E600-4009-8FB5-318073008508 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = RiscVSbiLib + +[Sources] + BaseRiscVSbiLib.c + RiscVSbiEcall.S + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib diff --git a/MdePkg/Library/BaseRiscVSbiLib/RiscVSbiEcall.S b/MdePkg/Library/BaseRiscVSbiLib/RiscVSbiEcall.S new file mode 100644 index 0000000000..8ba69f8512 --- /dev/null +++ b/MdePkg/Library/BaseRiscVSbiLib/RiscVSbiEcall.S @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// Make ECALL to SBI +// +// Copyright (c) 2023, Ventana Micro Systems Inc. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +//------------------------------------------------------------------------------ + +#include + +.data +.align 3 +.section .text + +// +// Make ECALL to SBI +// ecall updates the same a0 and a1 registers with +// return values. Hence, the C function which calls +// this should pass the address of Arg0 and Arg1. +// This routine saves the address and updates it +// with a0 and a1 once ecall returns. +// +// @param a0 : Pointer to Arg0 +// @param a1 : Pointer to Arg1 +// @param a2 : Arg2 +// @param a3 : Arg3 +// @param a4 : Arg4 +// @param a5 : Arg5 +// @param a6 : FunctionID +// @param a7 : ExtensionId +// +ASM_FUNC (RiscVSbiEcall) + mv t0, a0 + mv t1, a1 + ld a0, 0(a0) + ld a1, 0(a1) + ecall + sd a0, 0(t0) + sd a1, 0(t1) + ret diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index a7ad520419..80b6559053 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -316,6 +316,10 @@ ## @libraryclass Provides function to support TDX processing. TdxLib|Include/Library/TdxLib.h +[LibraryClasses.RISCV64] + ## @libraryclass Provides function to make ecalls to SBI + BaseRiscVSbiLib|Include/Library/BaseRiscVSbiLib.h + [Guids] # # GUID defined in UEFI2.1/UEFI2.0/EFI1.1 diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index 32a852dc46..0ac7618b46 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -190,4 +190,7 @@ MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicArmVirt.inf MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf +[Components.RISCV64] + MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf + [BuildOptions] From 49bec07b952715249c24a08e4258a785c3b72b47 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Fri, 27 Jan 2023 15:27:54 +0530 Subject: [PATCH 0616/1529] UefiCpuPkg: Add RISCV_EFI_BOOT_PROTOCOL related definitions REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 RISC-V UEFI based platforms need to support RISCV_EFI_BOOT_PROTOCOL. Add this protocol GUID definition and the header file required. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Daniel Schaefer Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Heinrich Schuchardt Reviewed-by: Andrei Warkentin Acked-by: Ray Ni --- .../Include/Protocol/RiscVBootProtocol.h | 34 +++++++++++++++++++ UefiCpuPkg/UefiCpuPkg.dec | 7 ++++ 2 files changed, 41 insertions(+) create mode 100644 UefiCpuPkg/Include/Protocol/RiscVBootProtocol.h diff --git a/UefiCpuPkg/Include/Protocol/RiscVBootProtocol.h b/UefiCpuPkg/Include/Protocol/RiscVBootProtocol.h new file mode 100644 index 0000000000..ed223b852d --- /dev/null +++ b/UefiCpuPkg/Include/Protocol/RiscVBootProtocol.h @@ -0,0 +1,34 @@ +/** @file + RISC-V Boot Protocol mandatory for RISC-V UEFI platforms. + + @par Revision Reference: + The protocol specification can be found at + https://github.com/riscv-non-isa/riscv-uefi + + Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef RISCV_BOOT_PROTOCOL_H_ +#define RISCV_BOOT_PROTOCOL_H_ + +typedef struct _RISCV_EFI_BOOT_PROTOCOL RISCV_EFI_BOOT_PROTOCOL; + +#define RISCV_EFI_BOOT_PROTOCOL_REVISION 0x00010000 +#define RISCV_EFI_BOOT_PROTOCOL_LATEST_VERSION \ + RISCV_EFI_BOOT_PROTOCOL_REVISION + +typedef +EFI_STATUS +(EFIAPI *EFI_GET_BOOT_HARTID)( + IN RISCV_EFI_BOOT_PROTOCOL *This, + OUT UINTN *BootHartId + ); + +typedef struct _RISCV_EFI_BOOT_PROTOCOL { + UINT64 Revision; + EFI_GET_BOOT_HARTID GetBootHartId; +} RISCV_EFI_BOOT_PROTOCOL; + +#endif diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index cff239d528..903ad52da9 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -86,6 +86,13 @@ ## Include/Protocol/SmMonitorInit.h gEfiSmMonitorInitProtocolGuid = { 0x228f344d, 0xb3de, 0x43bb, { 0xa4, 0xd7, 0xea, 0x20, 0xb, 0x1b, 0x14, 0x82 }} +[Protocols.RISCV64] + # + # Protocols defined for RISC-V systems + # + ## Include/Protocol/RiscVBootProtocol.h + gRiscVEfiBootProtocolGuid = { 0xccd15fec, 0x6f73, 0x4eec, { 0x83, 0x95, 0x3e, 0x69, 0xe4, 0xb9, 0x40, 0xbf }} + # # [Error.gUefiCpuPkgTokenSpaceGuid] # 0x80000001 | Invalid value provided. From 2dc444dab52dac63e9d2a0dec42c4e6d2d7e8942 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Thu, 15 Dec 2022 11:02:43 +0530 Subject: [PATCH 0617/1529] UefiCpuPkg: Add BaseRiscV64CpuExceptionHandlerLib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 Add Cpu Exception Handler library for RISC-V. This is copied from edk2-platforms/Silicon/RISC-V/ProcessorPkg/Library/RiscVExceptionLib Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Daniel Schaefer Cc: Abner Chang Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ray Ni --- .../BaseRiscV64CpuExceptionHandlerLib.inf | 42 ++++++ .../BaseRiscV64CpuExceptionHandlerLib.uni | 13 ++ .../CpuExceptionHandlerLib.c | 133 ++++++++++++++++++ .../CpuExceptionHandlerLib.h | 116 +++++++++++++++ .../SupervisorTrapHandler.S | 105 ++++++++++++++ UefiCpuPkg/UefiCpuPkg.dsc | 3 + 6 files changed, 412 insertions(+) create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.uni create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf new file mode 100644 index 0000000000..d804629436 --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf @@ -0,0 +1,42 @@ +## @file +# RISC-V CPU Exception Handler Library +# +# Copyright (c) 2022-2023, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = BaseRiscV64CpuExceptionHandlerLib + MODULE_UNI_FILE = BaseRiscV64CpuExceptionHandlerLib.uni + FILE_GUID = 6AB0D5FD-E615-45A3-9374-E284FB061FC9 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = CpuExceptionHandlerLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = RISCV64 +# + +[Sources] + SupervisorTrapHandler.S + CpuExceptionHandlerLib.c + CpuExceptionHandlerLib.h + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + SerialPortLib + PrintLib + SynchronizationLib + PeCoffGetEntryPointLib + MemoryAllocationLib + DebugLib diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.uni b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.uni new file mode 100644 index 0000000000..00cca22130 --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.uni @@ -0,0 +1,13 @@ +// /** @file +// +// Copyright (c) 2016 - 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "RISC-V CPU Exception Handler Librarys." + +#string STR_MODULE_DESCRIPTION #language en-US "RISC-V CPU Exception Handler Librarys." + diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c new file mode 100644 index 0000000000..f1ee7d236a --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c @@ -0,0 +1,133 @@ +/** @file + RISC-V Exception Handler library implementation. + + Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +#include "CpuExceptionHandlerLib.h" + +STATIC EFI_CPU_INTERRUPT_HANDLER mInterruptHandlers[2]; + +/** + Initializes all CPU exceptions entries and provides the default exception handlers. + + Caller should try to get an array of interrupt and/or exception vectors that are in use and need to + persist by EFI_VECTOR_HANDOFF_INFO defined in PI 1.3 specification. + If caller cannot get reserved vector list or it does not exists, set VectorInfo to NULL. + If VectorInfo is not NULL, the exception vectors will be initialized per vector attribute accordingly. + + @param[in] VectorInfo Pointer to reserved vector list. + + @retval EFI_SUCCESS CPU Exception Entries have been successfully initialized + with default exception handlers. + @retval EFI_INVALID_PARAMETER VectorInfo includes the invalid content if VectorInfo is not NULL. + @retval EFI_UNSUPPORTED This function is not supported. + +**/ +EFI_STATUS +EFIAPI +InitializeCpuExceptionHandlers ( + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL + ) +{ + RiscVSetSupervisorStvec ((UINT64)SupervisorModeTrap); + return EFI_SUCCESS; +} + +/** + Registers a function to be called from the processor interrupt handler. + + This function registers and enables the handler specified by InterruptHandler for a processor + interrupt or exception type specified by InterruptType. If InterruptHandler is NULL, then the + handler for the processor interrupt or exception type specified by InterruptType is uninstalled. + The installed handler is called once for each processor interrupt or exception. + NOTE: This function should be invoked after InitializeCpuExceptionHandlers() or + InitializeCpuInterruptHandlers() invoked, otherwise EFI_UNSUPPORTED returned. + + @param[in] InterruptType Defines which interrupt or exception to hook. + @param[in] InterruptHandler A pointer to a function of type EFI_CPU_INTERRUPT_HANDLER that is called + when a processor interrupt occurs. If this parameter is NULL, then the handler + will be uninstalled. + + @retval EFI_SUCCESS The handler for the processor interrupt was successfully installed or uninstalled. + @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler for InterruptType was + previously installed. + @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for InterruptType was not + previously installed. + @retval EFI_UNSUPPORTED The interrupt specified by InterruptType is not supported, + or this function is not supported. +**/ +EFI_STATUS +EFIAPI +RegisterCpuInterruptHandler ( + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + ) +{ + DEBUG ((DEBUG_INFO, "%a: Type:%x Handler: %x\n", __FUNCTION__, InterruptType, InterruptHandler)); + mInterruptHandlers[InterruptType] = InterruptHandler; + return EFI_SUCCESS; +} + +/** + Setup separate stacks for certain exception handlers. + If the input Buffer and BufferSize are both NULL, use global variable if possible. + + @param[in] Buffer Point to buffer used to separate exception stack. + @param[in, out] BufferSize On input, it indicates the byte size of Buffer. + If the size is not enough, the return status will + be EFI_BUFFER_TOO_SMALL, and output BufferSize + will be the size it needs. + + @retval EFI_SUCCESS The stacks are assigned successfully. + @retval EFI_UNSUPPORTED This function is not supported. + @retval EFI_BUFFER_TOO_SMALL This BufferSize is too small. +**/ +EFI_STATUS +EFIAPI +InitializeSeparateExceptionStacks ( + IN VOID *Buffer, + IN OUT UINTN *BufferSize + ) +{ + return EFI_SUCCESS; +} + +/** + Supervisor mode trap handler. + + @param[in] SmodeTrapReg Registers before trap occurred. + +**/ +VOID +RiscVSupervisorModeTrapHandler ( + SMODE_TRAP_REGISTERS *SmodeTrapReg + ) +{ + UINTN SCause; + EFI_SYSTEM_CONTEXT RiscVSystemContext; + + RiscVSystemContext.SystemContextRiscV64 = (EFI_SYSTEM_CONTEXT_RISCV64 *)SmodeTrapReg; + // + // Check scasue register. + // + SCause = (UINTN)RiscVGetSupervisorTrapCause (); + if ((SCause & (1UL << (sizeof (UINTN) * 8- 1))) != 0) { + // + // This is interrupt event. + // + SCause &= ~(1UL << (sizeof (UINTN) * 8- 1)); + if ((SCause == IRQ_S_TIMER) && (mInterruptHandlers[EXCEPT_RISCV_TIMER_INT] != NULL)) { + mInterruptHandlers[EXCEPT_RISCV_TIMER_INT](EXCEPT_RISCV_TIMER_INT, RiscVSystemContext); + } + } +} diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h new file mode 100644 index 0000000000..30f47e8755 --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h @@ -0,0 +1,116 @@ +/** @file + + RISC-V Exception Handler library definition file. + + Copyright (c) 2019-2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef RISCV_CPU_EXECPTION_HANDLER_LIB_H_ +#define RISCV_CPU_EXECPTION_HANDLER_LIB_H_ + +#include + +/** + Trap Handler for S-mode + +**/ +VOID +SupervisorModeTrap ( + VOID + ); + +// +// Index of SMode trap register +// +#define SMODE_TRAP_REGS_zero 0 +#define SMODE_TRAP_REGS_ra 1 +#define SMODE_TRAP_REGS_sp 2 +#define SMODE_TRAP_REGS_gp 3 +#define SMODE_TRAP_REGS_tp 4 +#define SMODE_TRAP_REGS_t0 5 +#define SMODE_TRAP_REGS_t1 6 +#define SMODE_TRAP_REGS_t2 7 +#define SMODE_TRAP_REGS_s0 8 +#define SMODE_TRAP_REGS_s1 9 +#define SMODE_TRAP_REGS_a0 10 +#define SMODE_TRAP_REGS_a1 11 +#define SMODE_TRAP_REGS_a2 12 +#define SMODE_TRAP_REGS_a3 13 +#define SMODE_TRAP_REGS_a4 14 +#define SMODE_TRAP_REGS_a5 15 +#define SMODE_TRAP_REGS_a6 16 +#define SMODE_TRAP_REGS_a7 17 +#define SMODE_TRAP_REGS_s2 18 +#define SMODE_TRAP_REGS_s3 19 +#define SMODE_TRAP_REGS_s4 20 +#define SMODE_TRAP_REGS_s5 21 +#define SMODE_TRAP_REGS_s6 22 +#define SMODE_TRAP_REGS_s7 23 +#define SMODE_TRAP_REGS_s8 24 +#define SMODE_TRAP_REGS_s9 25 +#define SMODE_TRAP_REGS_s10 26 +#define SMODE_TRAP_REGS_s11 27 +#define SMODE_TRAP_REGS_t3 28 +#define SMODE_TRAP_REGS_t4 29 +#define SMODE_TRAP_REGS_t5 30 +#define SMODE_TRAP_REGS_t6 31 +#define SMODE_TRAP_REGS_sepc 32 +#define SMODE_TRAP_REGS_sstatus 33 +#define SMODE_TRAP_REGS_sie 34 +#define SMODE_TRAP_REGS_last 35 + +#define SMODE_TRAP_REGS_OFFSET(x) ((SMODE_TRAP_REGS_##x) * __SIZEOF_POINTER__) +#define SMODE_TRAP_REGS_SIZE SMODE_TRAP_REGS_OFFSET(last) + +#pragma pack(1) +typedef struct { + // + // Below are follow the format of EFI_SYSTEM_CONTEXT + // + UINT64 zero; + UINT64 ra; + UINT64 sp; + UINT64 gp; + UINT64 tp; + UINT64 t0; + UINT64 t1; + UINT64 t2; + UINT64 s0; + UINT64 s1; + UINT64 a0; + UINT64 a1; + UINT64 a2; + UINT64 a3; + UINT64 a4; + UINT64 a5; + UINT64 a6; + UINT64 a7; + UINT64 s2; + UINT64 s3; + UINT64 s4; + UINT64 s5; + UINT64 s6; + UINT64 s7; + UINT64 s8; + UINT64 s9; + UINT64 s10; + UINT64 s11; + UINT64 t3; + UINT64 t4; + UINT64 t5; + UINT64 t6; + // + // Below are the additional information to + // EFI_SYSTEM_CONTEXT, private to supervisor mode trap + // and not public to EFI environment. + // + UINT64 sepc; + UINT64 sstatus; + UINT64 sie; +} SMODE_TRAP_REGISTERS; +#pragma pack() + +#endif diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S new file mode 100644 index 0000000000..649c4c5bec --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S @@ -0,0 +1,105 @@ +/** @file + RISC-V Processor supervisor mode trap handler + + Copyright (c) 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include "CpuExceptionHandlerLib.h" + + .align 3 + .section .entry, "ax", %progbits + .globl SupervisorModeTrap +SupervisorModeTrap: + addi sp, sp, -SMODE_TRAP_REGS_SIZE + + /* Save all general regisers except SP */ + sd t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) + + csrr t0, CSR_SSTATUS + and t0, t0, (SSTATUS_SIE | SSTATUS_SPIE) + sd t0, SMODE_TRAP_REGS_OFFSET(sstatus)(sp) + csrr t0, CSR_SEPC + sd t0, SMODE_TRAP_REGS_OFFSET(sepc)(sp) + csrr t0, CSR_SIE + sd t0, SMODE_TRAP_REGS_OFFSET(sie)(sp) + ld t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) + + sd ra, SMODE_TRAP_REGS_OFFSET(ra)(sp) + sd gp, SMODE_TRAP_REGS_OFFSET(gp)(sp) + sd tp, SMODE_TRAP_REGS_OFFSET(tp)(sp) + sd t1, SMODE_TRAP_REGS_OFFSET(t1)(sp) + sd t2, SMODE_TRAP_REGS_OFFSET(t2)(sp) + sd s0, SMODE_TRAP_REGS_OFFSET(s0)(sp) + sd s1, SMODE_TRAP_REGS_OFFSET(s1)(sp) + sd a0, SMODE_TRAP_REGS_OFFSET(a0)(sp) + sd a1, SMODE_TRAP_REGS_OFFSET(a1)(sp) + sd a2, SMODE_TRAP_REGS_OFFSET(a2)(sp) + sd a3, SMODE_TRAP_REGS_OFFSET(a3)(sp) + sd a4, SMODE_TRAP_REGS_OFFSET(a4)(sp) + sd a5, SMODE_TRAP_REGS_OFFSET(a5)(sp) + sd a6, SMODE_TRAP_REGS_OFFSET(a6)(sp) + sd a7, SMODE_TRAP_REGS_OFFSET(a7)(sp) + sd s2, SMODE_TRAP_REGS_OFFSET(s2)(sp) + sd s3, SMODE_TRAP_REGS_OFFSET(s3)(sp) + sd s4, SMODE_TRAP_REGS_OFFSET(s4)(sp) + sd s5, SMODE_TRAP_REGS_OFFSET(s5)(sp) + sd s6, SMODE_TRAP_REGS_OFFSET(s6)(sp) + sd s7, SMODE_TRAP_REGS_OFFSET(s7)(sp) + sd s8, SMODE_TRAP_REGS_OFFSET(s8)(sp) + sd s9, SMODE_TRAP_REGS_OFFSET(s9)(sp) + sd s10, SMODE_TRAP_REGS_OFFSET(s10)(sp) + sd s11, SMODE_TRAP_REGS_OFFSET(s11)(sp) + sd t3, SMODE_TRAP_REGS_OFFSET(t3)(sp) + sd t4, SMODE_TRAP_REGS_OFFSET(t4)(sp) + sd t5, SMODE_TRAP_REGS_OFFSET(t5)(sp) + sd t6, SMODE_TRAP_REGS_OFFSET(t6)(sp) + + /* Call to Supervisor mode trap handler in CpuExceptionHandlerLib.c */ + call RiscVSupervisorModeTrapHandler + + /* Restore all general regisers except SP */ + ld ra, SMODE_TRAP_REGS_OFFSET(ra)(sp) + ld gp, SMODE_TRAP_REGS_OFFSET(gp)(sp) + ld tp, SMODE_TRAP_REGS_OFFSET(tp)(sp) + ld t2, SMODE_TRAP_REGS_OFFSET(t2)(sp) + ld s0, SMODE_TRAP_REGS_OFFSET(s0)(sp) + ld s1, SMODE_TRAP_REGS_OFFSET(s1)(sp) + ld a0, SMODE_TRAP_REGS_OFFSET(a0)(sp) + ld a1, SMODE_TRAP_REGS_OFFSET(a1)(sp) + ld a2, SMODE_TRAP_REGS_OFFSET(a2)(sp) + ld a3, SMODE_TRAP_REGS_OFFSET(a3)(sp) + ld a4, SMODE_TRAP_REGS_OFFSET(a4)(sp) + ld a5, SMODE_TRAP_REGS_OFFSET(a5)(sp) + ld a6, SMODE_TRAP_REGS_OFFSET(a6)(sp) + ld a7, SMODE_TRAP_REGS_OFFSET(a7)(sp) + ld s2, SMODE_TRAP_REGS_OFFSET(s2)(sp) + ld s3, SMODE_TRAP_REGS_OFFSET(s3)(sp) + ld s4, SMODE_TRAP_REGS_OFFSET(s4)(sp) + ld s5, SMODE_TRAP_REGS_OFFSET(s5)(sp) + ld s6, SMODE_TRAP_REGS_OFFSET(s6)(sp) + ld s7, SMODE_TRAP_REGS_OFFSET(s7)(sp) + ld s8, SMODE_TRAP_REGS_OFFSET(s8)(sp) + ld s9, SMODE_TRAP_REGS_OFFSET(s9)(sp) + ld s10, SMODE_TRAP_REGS_OFFSET(s10)(sp) + ld s11, SMODE_TRAP_REGS_OFFSET(s11)(sp) + ld t3, SMODE_TRAP_REGS_OFFSET(t3)(sp) + ld t4, SMODE_TRAP_REGS_OFFSET(t4)(sp) + ld t5, SMODE_TRAP_REGS_OFFSET(t5)(sp) + ld t6, SMODE_TRAP_REGS_OFFSET(t6)(sp) + + ld t0, SMODE_TRAP_REGS_OFFSET(sepc)(sp) + csrw CSR_SEPC, t0 + ld t0, SMODE_TRAP_REGS_OFFSET(sie)(sp) + csrw CSR_SIE, t0 + csrr t0, CSR_SSTATUS + ld t1, SMODE_TRAP_REGS_OFFSET(sstatus)(sp) + or t0, t0, t1 + csrw CSR_SSTATUS, t0 + ld t1, SMODE_TRAP_REGS_OFFSET(t1)(sp) + ld t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) + addi sp, sp, SMODE_TRAP_REGS_SIZE + sret diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index f9a46089d2..35e66d93ef 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -195,5 +195,8 @@ [Components.X64] UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf +[Components.RISCV64] + UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf + [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 672ae0fe5a753f739f4436cc3904877db811ac76 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 5 Oct 2022 11:32:50 +0530 Subject: [PATCH 0618/1529] UefiCpuPkg: Add BaseRiscV64CpuTimerLib library REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 Add the RISC-V instance of the TimerLib. This is mostly copied from edk2-platforms/Silicon/RISC-V/ProcessorPkg/Library/RiscVTimerLib Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Daniel Schaefer Cc: Abner Chang Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ray Ni --- .../BaseRiscV64CpuTimerLib.inf | 33 +++ .../BaseRiscV64CpuTimerLib.uni | 14 ++ .../BaseRiscV64CpuTimerLib/CpuTimerLib.c | 199 ++++++++++++++++++ UefiCpuPkg/UefiCpuPkg.dsc | 1 + 4 files changed, 247 insertions(+) create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.uni create mode 100644 UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/CpuTimerLib.c diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf new file mode 100644 index 0000000000..3d5eaa4171 --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf @@ -0,0 +1,33 @@ +## @file +# RISC-V Base CPU Timer Library Instance +# +# Copyright (c) 2016 - 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = BaseRisV64CpuTimerLib + FILE_GUID = B635A600-EA24-4199-88E8-5761EEA96A51 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = TimerLib + MODULE_UNI_FILE = BaseRisV64CpuTimerLib.uni + +[Sources] + CpuTimerLib.c + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + PcdLib + DebugLib + +[Pcd] + gUefiCpuPkgTokenSpaceGuid.PcdCpuCoreCrystalClockFrequency ## CONSUMES diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.uni b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.uni new file mode 100644 index 0000000000..bb061f9a8f --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.uni @@ -0,0 +1,14 @@ +// /** @file +// Base CPU Timer Library for RISC-V +// +// Copyright (c) 2023, Ventana Micro Systems Inc. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "RISC-V CPU Timer Library" + +#string STR_MODULE_DESCRIPTION #language en-US "Provides basic timer support for RISC-V." + diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/CpuTimerLib.c b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/CpuTimerLib.c new file mode 100644 index 0000000000..9c8efc0f35 --- /dev/null +++ b/UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/CpuTimerLib.c @@ -0,0 +1,199 @@ +/** @file + RISC-V instance of Timer Library. + + Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +/** + Stalls the CPU for at least the given number of ticks. + + Stalls the CPU for at least the given number of ticks. It's invoked by + MicroSecondDelay() and NanoSecondDelay(). + + @param Delay A period of time to delay in ticks. + +**/ +VOID +InternalRiscVTimerDelay ( + IN UINT32 Delay + ) +{ + UINT32 Ticks; + UINT32 Times; + + Times = Delay >> (RISCV_TIMER_COMPARE_BITS - 2); + Delay &= ((1 << (RISCV_TIMER_COMPARE_BITS - 2)) - 1); + do { + // + // The target timer count is calculated here + // + Ticks = RiscVReadTimer () + Delay; + Delay = 1 << (RISCV_TIMER_COMPARE_BITS - 2); + while (((Ticks - RiscVReadTimer ()) & (1 << (RISCV_TIMER_COMPARE_BITS - 1))) == 0) { + CpuPause (); + } + } while (Times-- > 0); +} + +/** + 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 + ) +{ + InternalRiscVTimerDelay ( + (UINT32)DivU64x32 ( + MultU64x32 ( + MicroSeconds, + PcdGet64 (PcdCpuCoreCrystalClockFrequency) + ), + 1000000u + ) + ); + 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 + ) +{ + InternalRiscVTimerDelay ( + (UINT32)DivU64x32 ( + MultU64x32 ( + NanoSeconds, + PcdGet64 (PcdCpuCoreCrystalClockFrequency) + ), + 1000000000u + ) + ); + 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 (UINT64)RiscVReadTimer (); +} + +/**return + 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 = 0; + } + + if (EndValue != NULL) { + *EndValue = 32 - 1; + } + + return PcdGet64 (PcdCpuCoreCrystalClockFrequency); +} + +/** + 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 NanoSeconds; + UINT32 Remainder; + + // + // Ticks + // Time = --------- x 1,000,000,000 + // Frequency + // + NanoSeconds = MultU64x32 (DivU64x32Remainder (Ticks, PcdGet64 (PcdCpuCoreCrystalClockFrequency), &Remainder), 1000000000u); + + // + // Frequency < 0x100000000, so Remainder < 0x100000000, then (Remainder * 1,000,000,000) + // will not overflow 64-bit. + // + NanoSeconds += DivU64x32 (MultU64x32 ((UINT64)Remainder, 1000000000u), PcdGet64 (PcdCpuCoreCrystalClockFrequency)); + + return NanoSeconds; +} diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index 35e66d93ef..c511403842 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -197,6 +197,7 @@ [Components.RISCV64] UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf + UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From cbb8aba5bea69c8003aa75c36489c610143c2d4d Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Tue, 23 Aug 2022 22:22:20 +0530 Subject: [PATCH 0619/1529] UefiCpuPkg: Add CpuTimerDxeRiscV64 module REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 This DXE module initializes the timer interrupt handler and installs the Arch Timer protocol. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Daniel Schaefer Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ray Ni --- .../CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf | 51 +++ .../CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.uni | 14 + .../CpuTimerDxeRiscV64Extra.uni | 12 + UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c | 294 ++++++++++++++++++ UefiCpuPkg/CpuTimerDxeRiscV64/Timer.h | 177 +++++++++++ UefiCpuPkg/UefiCpuPkg.dsc | 1 + 6 files changed, 549 insertions(+) create mode 100644 UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf create mode 100644 UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.uni create mode 100644 UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64Extra.uni create mode 100644 UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c create mode 100644 UefiCpuPkg/CpuTimerDxeRiscV64/Timer.h diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf new file mode 100644 index 0000000000..c76bd96483 --- /dev/null +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf @@ -0,0 +1,51 @@ +## @file +# Timer Arch protocol module +# +# Copyright (c) 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001b + BASE_NAME = CpuTimerDxeRiscV64 + MODULE_UNI_FILE = CpuTimerDxeRiscV64.uni + FILE_GUID = 055DDAC6-9142-4013-BF20-FC2E5BC325C9 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = TimerDriverInitialize +# +# The following information is for reference only and not required by the build +# tools. +# +# VALID_ARCHITECTURES = RISCV64 +# +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + IoLib + CpuLib + UefiBootServicesTableLib + UefiDriverEntryPoint + +[LibraryClasses.RISCV64] + RiscVSbiLib + +[Sources.RISCV64] + Timer.h + Timer.c + +[Protocols] + gEfiCpuArchProtocolGuid ## CONSUMES + gEfiTimerArchProtocolGuid ## PRODUCES + +[Depex] + gEfiCpuArchProtocolGuid + +[UserExtensions.TianoCore."ExtraFiles"] + CpuTimerDxeRiscV64Extra.uni diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.uni b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.uni new file mode 100644 index 0000000000..76de1f3f35 --- /dev/null +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.uni @@ -0,0 +1,14 @@ +// /** @file +// +// Timer Arch protocol strings. +// +// Copyright (c) 2016, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Timer driver that provides Timer Arch protocol" + +#string STR_MODULE_DESCRIPTION #language en-US "Timer driver that provides Timer Arch protocol." diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64Extra.uni b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64Extra.uni new file mode 100644 index 0000000000..ceb93a7ce8 --- /dev/null +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64Extra.uni @@ -0,0 +1,12 @@ +// /** @file +// Timer Localized Strings and Content +// +// Copyright (c) 2016, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_PROPERTIES_MODULE_NAME +#language en-US +"Timer DXE Driver" diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c new file mode 100644 index 0000000000..db153f715e --- /dev/null +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c @@ -0,0 +1,294 @@ +/** @file + RISC-V Timer Architectural Protocol + + Copyright (c) 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include "Timer.h" + +// +// The handle onto which the Timer Architectural Protocol will be installed +// +STATIC EFI_HANDLE mTimerHandle = 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. +// +STATIC EFI_TIMER_NOTIFY mTimerNotifyFunction; + +// +// The current period of the timer interrupt +// +STATIC UINT64 mTimerPeriod = 0; + +/** + Timer Interrupt Handler. + + @param InterruptType The type of interrupt that occured + @param SystemContext A pointer to the system context when the interrupt occured +**/ +VOID +EFIAPI +TimerInterruptHandler ( + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + EFI_TPL OriginalTPL; + UINT64 RiscvTimer; + + OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); + if (mTimerNotifyFunction != NULL) { + mTimerNotifyFunction (mTimerPeriod); + } + + RiscVDisableTimerInterrupt (); // Disable SMode timer int + RiscVClearPendingTimerInterrupt (); + if (mTimerPeriod == 0) { + gBS->RestoreTPL (OriginalTPL); + RiscVDisableTimerInterrupt (); // Disable SMode timer int + return; + } + + RiscvTimer = RiscVReadTimer (); + SbiSetTimer (RiscvTimer += mTimerPeriod); + gBS->RestoreTPL (OriginalTPL); + RiscVEnableTimerInterrupt (); // enable SMode timer int +} + +/** + + 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 + ) +{ + DEBUG ((DEBUG_INFO, "TimerDriverRegisterHandler(0x%lx) called\n", NotifyFunction)); + 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 RiscvTimer; + + DEBUG ((DEBUG_INFO, "TimerDriverSetTimerPeriod(0x%lx)\n", TimerPeriod)); + + if (TimerPeriod == 0) { + mTimerPeriod = 0; + RiscVDisableTimerInterrupt (); // Disable SMode timer int + return EFI_SUCCESS; + } + + mTimerPeriod = TimerPeriod / 10; // convert unit from 100ns to 1us + RiscvTimer = RiscVReadTimer (); + SbiSetTimer (RiscvTimer + mTimerPeriod); + + mCpu->EnableInterrupt (mCpu); + RiscVEnableTimerInterrupt (); // enable SMode timer int + 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 + ) +{ + *TimerPeriod = mTimerPeriod; + return EFI_SUCCESS; +} + +/** + + 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_UNSUPPORTEDT The platform does not support the generation of soft timer interrupts. + +**/ +EFI_STATUS +EFIAPI +TimerDriverGenerateSoftInterrupt ( + IN EFI_TIMER_ARCH_PROTOCOL *This + ) +{ + return EFI_SUCCESS; +} + +/** + 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 occured attempting to initialize the driver. + +**/ +EFI_STATUS +EFIAPI +TimerDriverInitialize ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + + // + // 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); + + // + // Install interrupt handler for RISC-V Timer. + // + Status = mCpu->RegisterInterruptHandler (mCpu, EXCEPT_RISCV_TIMER_INT, TimerInterruptHandler); + ASSERT_EFI_ERROR (Status); + + // + // 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); + return Status; +} diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.h b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.h new file mode 100644 index 0000000000..586eb0cfad --- /dev/null +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.h @@ -0,0 +1,177 @@ +/** @file + RISC-V Timer Architectural Protocol definitions + + Copyright (c) 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef TIMER_H_ +#define TIMER_H_ + +#include + +#include +#include + +#include +#include +#include +#include + +// +// RISC-V use 100us timer. +// The default timer tick duration is set to 10 ms = 10 * 1000 * 10 100 ns units +// +#define DEFAULT_TIMER_TICK_DURATION 100000 + +extern VOID +RiscvSetTimerPeriod ( + UINT32 TimerPeriod + ); + +// +// Function Prototypes +// + +/** + 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 occured attempting to initialize the driver. + +**/ +EFI_STATUS +EFIAPI +TimerDriverInitialize ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +; + +/** + + 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_UNSUPPORTEDT The platform does not support the generation of soft timer interrupts. + +**/ +EFI_STATUS +EFIAPI +TimerDriverGenerateSoftInterrupt ( + IN EFI_TIMER_ARCH_PROTOCOL *This + ) +; + +#endif diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index c511403842..aba5ae9275 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -198,6 +198,7 @@ [Components.RISCV64] UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf + UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From f5c5dca29c6b597f01c514ab206761997aa33018 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Thu, 15 Dec 2022 11:13:44 +0530 Subject: [PATCH 0620/1529] UefiCpuPkg: Add CpuDxeRiscV64 module REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 This is copied from edk2-platforms/Silicon/RISC-V/ProcessorPkg/Universal/CpuDxe and added the RISCV_EFI_BOOT_PROTOCOL support. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Daniel Schaefer Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin --- UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c | 365 ++++++++++++++++++ UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h | 199 ++++++++++ UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf | 68 ++++ UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.uni | 13 + .../CpuDxeRiscV64/CpuDxeRiscV64Extra.uni | 14 + UefiCpuPkg/UefiCpuPkg.dsc | 1 + 6 files changed, 660 insertions(+) create mode 100644 UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c create mode 100644 UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h create mode 100644 UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf create mode 100644 UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.uni create mode 100644 UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64Extra.uni diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c new file mode 100644 index 0000000000..7551e06536 --- /dev/null +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c @@ -0,0 +1,365 @@ +/** @file + RISC-V CPU DXE driver. + + Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuDxe.h" + +// +// Global Variables +// +STATIC BOOLEAN mInterruptState = FALSE; +STATIC EFI_HANDLE mCpuHandle = NULL; +STATIC UINTN mBootHartId; +RISCV_EFI_BOOT_PROTOCOL gRiscvBootProtocol; + +/** + Get the boot hartid + + @param This Protocol instance structure + @param BootHartId Pointer to the Boot Hart ID variable + + @retval EFI_SUCCESS If BootHartId is returned + @retval EFI_INVALID_PARAMETER Either "BootHartId" is NULL or "This" is not + a valid RISCV_EFI_BOOT_PROTOCOL instance. + +**/ +EFI_STATUS +EFIAPI +RiscvGetBootHartId ( + IN RISCV_EFI_BOOT_PROTOCOL *This, + OUT UINTN *BootHartId + ) +{ + if ((This != &gRiscvBootProtocol) || (BootHartId == NULL)) { + return EFI_INVALID_PARAMETER; + } + + *BootHartId = mBootHartId; + return EFI_SUCCESS; +} + +RISCV_EFI_BOOT_PROTOCOL gRiscvBootProtocol = { + RISCV_EFI_BOOT_PROTOCOL_LATEST_VERSION, + RiscvGetBootHartId +}; + +EFI_CPU_ARCH_PROTOCOL gCpu = { + CpuFlushCpuDataCache, + CpuEnableInterrupt, + CpuDisableInterrupt, + CpuGetInterruptState, + CpuInit, + CpuRegisterInterruptHandler, + CpuGetTimerValue, + CpuSetMemoryAttributes, + 1, // NumberOfTimers + 4 // DmaBufferAlignment +}; + +// +// CPU Arch Protocol Functions +// + +/** + Flush CPU data cache. If the instruction cache is fully coherent + with all DMA operations then function can just return EFI_SUCCESS. + + @param This Protocol instance structure + @param Start Physical address to start flushing from. + @param Length Number of bytes to flush. Round up to chipset + granularity. + @param FlushType Specifies the type of flush operation to perform. + + @retval EFI_SUCCESS If cache was flushed + @retval EFI_UNSUPPORTED If flush type is not supported. + @retval EFI_DEVICE_ERROR If requested range could not be flushed. + +**/ +EFI_STATUS +EFIAPI +CpuFlushCpuDataCache ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS Start, + IN UINT64 Length, + IN EFI_CPU_FLUSH_TYPE FlushType + ) +{ + return EFI_SUCCESS; +} + +/** + Enables CPU interrupts. + + @param This Protocol instance structure + + @retval EFI_SUCCESS If interrupts were enabled in the CPU + @retval EFI_DEVICE_ERROR If interrupts could not be enabled on the CPU. + +**/ +EFI_STATUS +EFIAPI +CpuEnableInterrupt ( + IN EFI_CPU_ARCH_PROTOCOL *This + ) +{ + EnableInterrupts (); + mInterruptState = TRUE; + return EFI_SUCCESS; +} + +/** + Disables CPU interrupts. + + @param This Protocol instance structure + + @retval EFI_SUCCESS If interrupts were disabled in the CPU. + @retval EFI_DEVICE_ERROR If interrupts could not be disabled on the CPU. + +**/ +EFI_STATUS +EFIAPI +CpuDisableInterrupt ( + IN EFI_CPU_ARCH_PROTOCOL *This + ) +{ + DisableInterrupts (); + mInterruptState = FALSE; + return EFI_SUCCESS; +} + +/** + Return the state of interrupts. + + @param This Protocol instance structure + @param State Pointer to the CPU's current interrupt state + + @retval EFI_SUCCESS If interrupts were disabled in the CPU. + @retval EFI_INVALID_PARAMETER State is NULL. + +**/ +EFI_STATUS +EFIAPI +CpuGetInterruptState ( + IN EFI_CPU_ARCH_PROTOCOL *This, + OUT BOOLEAN *State + ) +{ + if (State == NULL) { + return EFI_INVALID_PARAMETER; + } + + *State = mInterruptState; + return EFI_SUCCESS; +} + +/** + Generates an INIT to the CPU. + + @param This Protocol instance structure + @param InitType Type of CPU INIT to perform + + @retval EFI_SUCCESS If CPU INIT occurred. This value should never be + seen. + @retval EFI_DEVICE_ERROR If CPU INIT failed. + @retval EFI_UNSUPPORTED Requested type of CPU INIT not supported. + +**/ +EFI_STATUS +EFIAPI +CpuInit ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_CPU_INIT_TYPE InitType + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Registers a function to be called from the CPU interrupt handler. + + @param This Protocol instance structure + @param InterruptType Defines which interrupt to hook. IA-32 + valid range is 0x00 through 0xFF + @param InterruptHandler A pointer to a function of type + EFI_CPU_INTERRUPT_HANDLER that is called + when a processor interrupt occurs. A null + pointer is an error condition. + + @retval EFI_SUCCESS If handler installed or uninstalled. + @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler + for InterruptType was previously installed. + @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for + InterruptType was not previously installed. + @retval EFI_UNSUPPORTED The interrupt specified by InterruptType + is not supported. + +**/ +EFI_STATUS +EFIAPI +CpuRegisterInterruptHandler ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + ) +{ + return RegisterCpuInterruptHandler (InterruptType, InterruptHandler); +} + +/** + Returns a timer value from one of the CPU's internal timers. There is no + inherent time interval between ticks but is a function of the CPU frequency. + + @param This - Protocol instance structure. + @param TimerIndex - Specifies which CPU timer is requested. + @param TimerValue - Pointer to the returned timer value. + @param TimerPeriod - A pointer to the amount of time that passes + in femtoseconds (10-15) for each increment + of TimerValue. If TimerValue does not + increment at a predictable rate, then 0 is + returned. The amount of time that has + passed between two calls to GetTimerValue() + can be calculated with the formula + (TimerValue2 - TimerValue1) * TimerPeriod. + This parameter is optional and may be NULL. + + @retval EFI_SUCCESS - If the CPU timer count was returned. + @retval EFI_UNSUPPORTED - If the CPU does not have any readable timers. + @retval EFI_DEVICE_ERROR - If an error occurred while reading the timer. + @retval EFI_INVALID_PARAMETER - TimerIndex is not valid or TimerValue is NULL. + +**/ +EFI_STATUS +EFIAPI +CpuGetTimerValue ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN UINT32 TimerIndex, + OUT UINT64 *TimerValue, + OUT UINT64 *TimerPeriod OPTIONAL + ) +{ + if (TimerValue == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (TimerIndex != 0) { + return EFI_INVALID_PARAMETER; + } + + *TimerValue = (UINT64)RiscVReadTimer (); + if (TimerPeriod != NULL) { + *TimerPeriod = DivU64x32 ( + 1000000000000000u, + PcdGet64 (PcdCpuCoreCrystalClockFrequency) + ); + } + + return EFI_SUCCESS; +} + +/** + Implementation of SetMemoryAttributes() service of CPU Architecture Protocol. + + This function modifies the attributes for the memory region specified by BaseAddress and + Length from their current attributes to the attributes specified by Attributes. + + @param This The EFI_CPU_ARCH_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of a memory region. + @param Length The size in bytes of the memory region. + @param Attributes The bit mask of attributes to set for the memory region. + + @retval EFI_SUCCESS The attributes were set for the memory region. + @retval EFI_ACCESS_DENIED The attributes for the memory resource range specified by + BaseAddress and Length cannot be modified. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes specified an illegal combination of attributes that + cannot be set together. + @retval EFI_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of + the memory resource range. + @retval EFI_UNSUPPORTED The processor does not support one or more bytes of the memory + resource range specified by BaseAddress and Length. + The bit mask of attributes is not support for the memory resource + range specified by BaseAddress and Length. + +**/ +EFI_STATUS +EFIAPI +CpuSetMemoryAttributes ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ) +{ + DEBUG ((DEBUG_INFO, "%a: Set memory attributes not supported yet\n", __FUNCTION__)); + return EFI_SUCCESS; +} + +/** + Initialize the state information for the CPU Architectural Protocol. + + @param ImageHandle Image handle this driver. + @param SystemTable Pointer to the System Table. + + @retval EFI_SUCCESS Thread can be successfully created + @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure + @retval EFI_DEVICE_ERROR Cannot create the thread + +**/ +EFI_STATUS +EFIAPI +InitializeCpu ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext; + + GetFirmwareContextPointer (&FirmwareContext); + ASSERT (FirmwareContext != NULL); + if (FirmwareContext == NULL) { + DEBUG ((DEBUG_ERROR, "Failed to get the pointer of EFI_RISCV_FIRMWARE_CONTEXT\n")); + return EFI_NOT_FOUND; + } + + DEBUG ((DEBUG_INFO, " %a: Firmware Context is at 0x%x.\n", __FUNCTION__, FirmwareContext)); + + mBootHartId = FirmwareContext->BootHartId; + DEBUG ((DEBUG_INFO, " %a: mBootHartId = 0x%x.\n", __FUNCTION__, mBootHartId)); + + InitializeCpuExceptionHandlers (NULL); + + // + // Make sure interrupts are disabled + // + DisableInterrupts (); + + // + // Install Boot protocol + // + Status = gBS->InstallProtocolInterface ( + &ImageHandle, + &gRiscVEfiBootProtocolGuid, + EFI_NATIVE_INTERFACE, + &gRiscvBootProtocol + ); + ASSERT_EFI_ERROR (Status); + + // + // Install CPU Architectural Protocol + // + Status = gBS->InstallMultipleProtocolInterfaces ( + &mCpuHandle, + &gEfiCpuArchProtocolGuid, + &gCpu, + NULL + ); + ASSERT_EFI_ERROR (Status); + return Status; +} diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h new file mode 100644 index 0000000000..49f4e11966 --- /dev/null +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.h @@ -0,0 +1,199 @@ +/** @file + RISC-V CPU DXE module header file. + + Copyright (c) 2016 - 2022, Hewlett Packard Enterprise Development LP. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef CPU_DXE_H_ +#define CPU_DXE_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + Flush CPU data cache. If the instruction cache is fully coherent + with all DMA operations then function can just return EFI_SUCCESS. + + @param This Protocol instance structure + @param Start Physical address to start flushing from. + @param Length Number of bytes to flush. Round up to chipset + granularity. + @param FlushType Specifies the type of flush operation to perform. + + @retval EFI_SUCCESS If cache was flushed + @retval EFI_UNSUPPORTED If flush type is not supported. + @retval EFI_DEVICE_ERROR If requested range could not be flushed. + +**/ +EFI_STATUS +EFIAPI +CpuFlushCpuDataCache ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS Start, + IN UINT64 Length, + IN EFI_CPU_FLUSH_TYPE FlushType + ); + +/** + Enables CPU interrupts. + + @param This Protocol instance structure + + @retval EFI_SUCCESS If interrupts were enabled in the CPU + @retval EFI_DEVICE_ERROR If interrupts could not be enabled on the CPU. + +**/ +EFI_STATUS +EFIAPI +CpuEnableInterrupt ( + IN EFI_CPU_ARCH_PROTOCOL *This + ); + +/** + Disables CPU interrupts. + + @param This Protocol instance structure + + @retval EFI_SUCCESS If interrupts were disabled in the CPU. + @retval EFI_DEVICE_ERROR If interrupts could not be disabled on the CPU. + +**/ +EFI_STATUS +EFIAPI +CpuDisableInterrupt ( + IN EFI_CPU_ARCH_PROTOCOL *This + ); + +/** + Return the state of interrupts. + + @param This Protocol instance structure + @param State Pointer to the CPU's current interrupt state + + @retval EFI_SUCCESS If interrupts were disabled in the CPU. + @retval EFI_INVALID_PARAMETER State is NULL. + +**/ +EFI_STATUS +EFIAPI +CpuGetInterruptState ( + IN EFI_CPU_ARCH_PROTOCOL *This, + OUT BOOLEAN *State + ); + +/** + Generates an INIT to the CPU. + + @param This Protocol instance structure + @param InitType Type of CPU INIT to perform + + @retval EFI_SUCCESS If CPU INIT occurred. This value should never be + seen. + @retval EFI_DEVICE_ERROR If CPU INIT failed. + @retval EFI_UNSUPPORTED Requested type of CPU INIT not supported. + +**/ +EFI_STATUS +EFIAPI +CpuInit ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_CPU_INIT_TYPE InitType + ); + +/** + Registers a function to be called from the CPU interrupt handler. + + @param This Protocol instance structure + @param InterruptType Defines which interrupt to hook. IA-32 + valid range is 0x00 through 0xFF + @param InterruptHandler A pointer to a function of type + EFI_CPU_INTERRUPT_HANDLER that is called + when a processor interrupt occurs. A null + pointer is an error condition. + + @retval EFI_SUCCESS If handler installed or uninstalled. + @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler + for InterruptType was previously installed. + @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for + InterruptType was not previously installed. + @retval EFI_UNSUPPORTED The interrupt specified by InterruptType + is not supported. + +**/ +EFI_STATUS +EFIAPI +CpuRegisterInterruptHandler ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + ); + +/** + Returns a timer value from one of the CPU's internal timers. There is no + inherent time interval between ticks but is a function of the CPU frequency. + + @param This - Protocol instance structure. + @param TimerIndex - Specifies which CPU timer is requested. + @param TimerValue - Pointer to the returned timer value. + @param TimerPeriod - A pointer to the amount of time that passes + in femtoseconds (10-15) for each increment + of TimerValue. If TimerValue does not + increment at a predictable rate, then 0 is + returned. The amount of time that has + passed between two calls to GetTimerValue() + can be calculated with the formula + (TimerValue2 - TimerValue1) * TimerPeriod. + This parameter is optional and may be NULL. + + @retval EFI_SUCCESS - If the CPU timer count was returned. + @retval EFI_UNSUPPORTED - If the CPU does not have any readable timers. + @retval EFI_DEVICE_ERROR - If an error occurred while reading the timer. + @retval EFI_INVALID_PARAMETER - TimerIndex is not valid or TimerValue is NULL. + +**/ +EFI_STATUS +EFIAPI +CpuGetTimerValue ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN UINT32 TimerIndex, + OUT UINT64 *TimerValue, + OUT UINT64 *TimerPeriod OPTIONAL + ); + +/** + Set memory cacheability attributes for given range of memeory. + + @param This Protocol instance structure + @param BaseAddress Specifies the start address of the + memory range + @param Length Specifies the length of the memory range + @param Attributes The memory cacheability for the memory range + + @retval EFI_SUCCESS If the cacheability of that memory range is + set successfully + @retval EFI_UNSUPPORTED If the desired operation cannot be done + @retval EFI_INVALID_PARAMETER The input parameter is not correct, + such as Length = 0 + +**/ +EFI_STATUS +EFIAPI +CpuSetMemoryAttributes ( + IN EFI_CPU_ARCH_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ); + +#endif diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf new file mode 100644 index 0000000000..e8fa25446a --- /dev/null +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf @@ -0,0 +1,68 @@ +## @file +# RISC-V CPU DXE module. +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = CpuDxeRiscV64 + MODULE_UNI_FILE = CpuDxeRiscV64.uni + FILE_GUID = BDEA19E2-778F-473C-BF82-5E38D6A27765 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = InitializeCpu + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + CpuLib + DebugLib + DxeServicesTableLib + MemoryAllocationLib + UefiBootServicesTableLib + UefiDriverEntryPoint + UefiLib + CpuExceptionHandlerLib + HobLib + ReportStatusCodeLib + TimerLib + PeCoffGetEntryPointLib + RiscVSbiLib + +[Sources] + CpuDxe.c + CpuDxe.h + +[Protocols] + gEfiCpuArchProtocolGuid ## PRODUCES + gRiscVEfiBootProtocolGuid ## PRODUCES + +[Guids] + gIdleLoopEventGuid ## CONSUMES ## Event + +[Ppis] + gEfiSecPlatformInformation2PpiGuid ## UNDEFINED # HOB + gEfiSecPlatformInformationPpiGuid ## UNDEFINED # HOB + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize ## CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuCoreCrystalClockFrequency ## CONSUMES + +[Depex] + TRUE + +[UserExtensions.TianoCore."ExtraFiles"] + CpuDxeRiscV64Extra.uni diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.uni b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.uni new file mode 100644 index 0000000000..460141a1aa --- /dev/null +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.uni @@ -0,0 +1,13 @@ +// /** @file +// +// Copyright (c) 2016 - 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Installs RISC-V CPU Architecture Protocol" + +#string STR_MODULE_DESCRIPTION #language en-US "RISC-V CPU driver installs CPU Architecture Protocol." + diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64Extra.uni b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64Extra.uni new file mode 100644 index 0000000000..6f819f068e --- /dev/null +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64Extra.uni @@ -0,0 +1,14 @@ +// /** @file +// CpuDxe Localized Strings and Content +// +// Copyright (c) 2016 - 2019, Hewlett Packard Enterprise Development LP. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_PROPERTIES_MODULE_NAME +#language en-US +"RISC-V Architectural DXE Driver" + + diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index aba5ae9275..a7318d3fe9 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -199,6 +199,7 @@ UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf + UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 6c6e1bf58a96aa68877f08b5acba8c761843abe8 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sun, 9 Oct 2022 18:21:29 +0530 Subject: [PATCH 0621/1529] UefiCpuPkg/UefiCpuPkg.ci.yaml: Ignore RISC-V file REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 RISC-V register names do not follow the EDK2 formatting. So, add it to ignore list for now. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Reviewed-by: Michael D Kinney Acked-by: Ray Ni --- UefiCpuPkg/UefiCpuPkg.ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/UefiCpuPkg/UefiCpuPkg.ci.yaml b/UefiCpuPkg/UefiCpuPkg.ci.yaml index a377366798..c2280aedf5 100644 --- a/UefiCpuPkg/UefiCpuPkg.ci.yaml +++ b/UefiCpuPkg/UefiCpuPkg.ci.yaml @@ -27,6 +27,7 @@ ], ## Both file path and directory path are accepted. "IgnoreFiles": [ + "Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h" ] }, "CompilerPlugin": { From 8d15fe76d3599dd2689e0931414c6df2949334d5 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 21 Sep 2022 06:36:37 +0530 Subject: [PATCH 0622/1529] ArmVirtPkg/PlatformHasAcpiDtDxe: Move to OvmfPkg REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 This module is required by other architectures like RISC-V. Hence, move this to OvmfPkg. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Ard Biesheuvel Reviewed-by: Andrei Warkentin --- ArmVirtPkg/ArmVirtPkg.dec | 9 --------- OvmfPkg/OvmfPkg.dec | 7 +++++++ .../PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c | 0 .../PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf | 3 +-- 4 files changed, 8 insertions(+), 11 deletions(-) rename {ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c (100%) rename {ArmVirtPkg => OvmfPkg}/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf (89%) diff --git a/ArmVirtPkg/ArmVirtPkg.dec b/ArmVirtPkg/ArmVirtPkg.dec index 89d21ec3a3..4645c91a83 100644 --- a/ArmVirtPkg/ArmVirtPkg.dec +++ b/ArmVirtPkg/ArmVirtPkg.dec @@ -34,8 +34,6 @@ gEarly16550UartBaseAddressGuid = { 0xea67ca3e, 0x1f54, 0x436b, { 0x97, 0x88, 0xd4, 0xeb, 0x29, 0xc3, 0x42, 0x67 } } gArmVirtSystemMemorySizeGuid = { 0x504eccb9, 0x1bf0, 0x4420, { 0x86, 0x5d, 0xdc, 0x66, 0x06, 0xd4, 0x13, 0xbf } } - gArmVirtVariableGuid = { 0x50bea1e5, 0xa2c5, 0x46e9, { 0x9b, 0x3a, 0x59, 0x59, 0x65, 0x16, 0xb0, 0x0a } } - [PcdsFeatureFlag] # # Feature Flag PCD that defines whether TPM2 support is enabled @@ -69,10 +67,3 @@ # Cloud Hypervisor has no other way to pass Rsdp address to the guest except use a PCD. # gArmVirtTokenSpaceGuid.PcdCloudHvAcpiRsdpBaseAddress|0x0|UINT64|0x00000005 - -[PcdsDynamic] - # - # Whether to force disable ACPI, regardless of the fw_cfg settings - # exposed by QEMU - # - gArmVirtTokenSpaceGuid.PcdForceNoAcpi|0x0|BOOLEAN|0x00000003 diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec index be30547474..749fbd3b6b 100644 --- a/OvmfPkg/OvmfPkg.dec +++ b/OvmfPkg/OvmfPkg.dec @@ -161,6 +161,7 @@ gVMMBootOrderGuid = {0x668f4529, 0x63d0, 0x4bb5, {0xb6, 0x5d, 0x6f, 0xbb, 0x9d, 0x36, 0xa4, 0x4a}} gUefiOvmfPkgTdxAcpiHobGuid = {0x6a0c5870, 0xd4ed, 0x44f4, {0xa1, 0x35, 0xdd, 0x23, 0x8b, 0x6f, 0x0c, 0x8d}} gEfiNonCcFvGuid = {0xae047c6d, 0xbce9, 0x426c, {0xae, 0x03, 0xa6, 0x8e, 0x3b, 0x8a, 0x04, 0x88}} + gOvmfVariableGuid = {0x50bea1e5, 0xa2c5, 0x46e9, {0x9b, 0x3a, 0x59, 0x59, 0x65, 0x16, 0xb0, 0x0a}} [Ppis] # PPI whose presence in the PPI database signals that the TPM base address @@ -467,6 +468,12 @@ # 2 - set by GOP Driver. gUefiOvmfPkgTokenSpaceGuid.PcdVideoResolutionSource|0|UINT8|0x64 + # + # Whether to force disable ACPI, regardless of the fw_cfg settings + # exposed by QEMU + # + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi|0x0|BOOLEAN|0x69 + [PcdsFeatureFlag] gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation|TRUE|BOOLEAN|0x1c gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderMmioTranslation|FALSE|BOOLEAN|0x1d diff --git a/ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c b/OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c similarity index 100% rename from ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c rename to OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.c diff --git a/ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf b/OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf similarity index 89% rename from ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf rename to OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf index e900aa9926..85873f73b2 100644 --- a/ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf +++ b/OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf @@ -19,7 +19,6 @@ PlatformHasAcpiDtDxe.c [Packages] - ArmVirtPkg/ArmVirtPkg.dec EmbeddedPkg/EmbeddedPkg.dec MdeModulePkg/MdeModulePkg.dec MdePkg/MdePkg.dec @@ -38,7 +37,7 @@ gEdkiiPlatformHasDeviceTreeGuid ## SOMETIMES_PRODUCES ## PROTOCOL [Pcd] - gArmVirtTokenSpaceGuid.PcdForceNoAcpi + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi [Depex] gEfiVariableArchProtocolGuid From 270693e38c6d874972502ca6f04aa8fca4923d8e Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 21 Sep 2022 06:38:18 +0530 Subject: [PATCH 0623/1529] ArmVirtPkg: Fix up the location of PlatformHasAcpiDtDxe REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 PlatformHasAcpiDtDxe is required by other architectures also. Hence, it is moved to OvmfPkg. So, update the consumers of this module with the new location. Cc: Ard Biesheuvel Cc: Leif Lindholm Cc: Sami Mujawar Cc: Gerd Hoffmann Signed-off-by: Sunil V L Reviewed-by: Andrei Warkentin Acked-by: Ard Biesheuvel --- ArmVirtPkg/ArmVirtCloudHv.dsc | 2 +- ArmVirtPkg/ArmVirtQemu.dsc | 4 ++-- ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc | 2 +- ArmVirtPkg/ArmVirtQemuKernel.dsc | 2 +- .../CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf | 2 +- ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ArmVirtPkg/ArmVirtCloudHv.dsc b/ArmVirtPkg/ArmVirtCloudHv.dsc index 7ca7a391d9..c975e139a2 100644 --- a/ArmVirtPkg/ArmVirtCloudHv.dsc +++ b/ArmVirtPkg/ArmVirtCloudHv.dsc @@ -198,7 +198,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 [PcdsDynamicHii] - gArmVirtTokenSpaceGuid.PcdForceNoAcpi|L"ForceNoAcpi"|gArmVirtVariableGuid|0x0|FALSE|NV,BS + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi|L"ForceNoAcpi"|gOvmfVariableGuid|0x0|FALSE|NV,BS ################################################################################ # diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 0f1c639548..72a0cacab4 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -305,7 +305,7 @@ !endif [PcdsDynamicHii] - gArmVirtTokenSpaceGuid.PcdForceNoAcpi|L"ForceNoAcpi"|gArmVirtVariableGuid|0x0|FALSE|NV,BS + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi|L"ForceNoAcpi"|gOvmfVariableGuid|0x0|FALSE|NV,BS !if $(TPM2_CONFIG_ENABLE) == TRUE gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS @@ -578,7 +578,7 @@ # # ACPI Support # - ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf + OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf [Components.AARCH64] MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf { diff --git a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc index e06ca74244..8a063bac04 100644 --- a/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc +++ b/ArmVirtPkg/ArmVirtQemuFvMain.fdf.inc @@ -141,7 +141,7 @@ READ_LOCK_STATUS = TRUE # # ACPI Support # - INF ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf + INF OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf !if $(ARCH) == AARCH64 INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf diff --git a/ArmVirtPkg/ArmVirtQemuKernel.dsc b/ArmVirtPkg/ArmVirtQemuKernel.dsc index 807c85d482..3cb9120e4e 100644 --- a/ArmVirtPkg/ArmVirtQemuKernel.dsc +++ b/ArmVirtPkg/ArmVirtQemuKernel.dsc @@ -461,7 +461,7 @@ # # ACPI Support # - ArmVirtPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf + OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf [Components.AARCH64] MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf { diff --git a/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf b/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf index 4af06b2a67..7cad40e11f 100644 --- a/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf +++ b/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf @@ -36,7 +36,7 @@ gEdkiiPlatformHasDeviceTreeGuid ## SOMETIMES_PRODUCES ## PROTOCOL [Pcd] - gArmVirtTokenSpaceGuid.PcdForceNoAcpi + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi [Depex] gEfiVariableArchProtocolGuid diff --git a/ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf b/ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf index 1cf25780f8..c5bf798c3b 100644 --- a/ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf +++ b/ArmVirtPkg/KvmtoolPlatformDxe/KvmtoolPlatformDxe.inf @@ -21,7 +21,7 @@ KvmtoolPlatformDxe.c [Packages] - ArmVirtPkg/ArmVirtPkg.dec + OvmfPkg/OvmfPkg.dec EmbeddedPkg/EmbeddedPkg.dec MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec @@ -37,7 +37,7 @@ gEdkiiPlatformHasDeviceTreeGuid ## SOMETIMES_PRODUCES ## PROTOCOL [Pcd] - gArmVirtTokenSpaceGuid.PcdForceNoAcpi + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi [Depex] TRUE From 8a3bbf68be34fdbd4f83b680da92fd3c900a2adb Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 20:52:02 +0530 Subject: [PATCH 0624/1529] OvmfPkg/RiscVVirt: Add PlatformBootManagerLib library RISC-V Qemu Virt platfform needs the PlatformBootManagerLib similar to the one in ArmVirtPlatform. Add the library in OvmfPkg/RiscVVirt leveraging the one from Arm. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ard Biesheuvel Acked-by: Jiewen Yao --- .../PlatformBootManagerLib/PlatformBm.c | 1078 +++++++++++++++++ .../PlatformBootManagerLib/PlatformBm.h | 45 + .../PlatformBootManagerLib.inf | 75 ++ .../PlatformBootManagerLib/QemuKernel.c | 77 ++ 4 files changed, 1275 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c create mode 100644 OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.h create mode 100644 OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf create mode 100644 OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c diff --git a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c new file mode 100644 index 0000000000..2559889638 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c @@ -0,0 +1,1078 @@ +/** @file + Implementation for PlatformBootManagerLib library class interfaces. + + Copyright (C) 2015-2016, Red Hat, Inc. + Copyright (c) 2014, ARM Ltd. All rights reserved.
+ Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "PlatformBm.h" + +#define DP_NODE_LEN(Type) { (UINT8)sizeof (Type), (UINT8)(sizeof (Type) >> 8) } + +#define VERSION_STRING_PREFIX L"RISC-V EDK2 firmware version " + +#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 () + +STATIC PLATFORM_SERIAL_CONSOLE mSerialConsole = { + // + // VENDOR_DEVICE_PATH SerialDxe + // + { + { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, DP_NODE_LEN (VENDOR_DEVICE_PATH) }, + EDKII_SERIAL_PORT_LIB_VENDOR_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) + } +}; + +#pragma pack (1) +typedef struct { + USB_CLASS_DEVICE_PATH Keyboard; + EFI_DEVICE_PATH_PROTOCOL End; +} PLATFORM_USB_KEYBOARD; +#pragma pack () + +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) + } +}; + +/** + 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 + ); + +/** + 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. +**/ +STATIC +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""; + + // + // 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. +**/ +STATIC +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 FILTER_FUNCTION checks if a handle corresponds to a Virtio RNG device at + the VIRTIO_DEVICE_PROTOCOL level. +**/ +STATIC +BOOLEAN +EFIAPI +IsVirtioRng ( + IN EFI_HANDLE Handle, + IN CONST CHAR16 *ReportText + ) +{ + EFI_STATUS Status; + VIRTIO_DEVICE_PROTOCOL *VirtIo; + + Status = gBS->HandleProtocol ( + Handle, + &gVirtioDeviceProtocolGuid, + (VOID **)&VirtIo + ); + if (EFI_ERROR (Status)) { + return FALSE; + } + + return (BOOLEAN)(VirtIo->SubSystemDeviceId == + VIRTIO_SUBSYSTEM_ENTROPY_SOURCE); +} + +/** + This FILTER_FUNCTION checks if a handle corresponds to a Virtio RNG device at + the EFI_PCI_IO_PROTOCOL level. +**/ +STATIC +BOOLEAN +EFIAPI +IsVirtioPciRng ( + IN EFI_HANDLE Handle, + IN CONST CHAR16 *ReportText + ) +{ + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 VendorId; + UINT16 DeviceId; + UINT8 RevisionId; + BOOLEAN Virtio10; + UINT16 SubsystemId; + + Status = gBS->HandleProtocol ( + Handle, + &gEfiPciIoProtocolGuid, + (VOID **)&PciIo + ); + if (EFI_ERROR (Status)) { + return FALSE; + } + + // + // Read and check VendorId. + // + Status = PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_VENDOR_ID_OFFSET, + 1, + &VendorId + ); + if (EFI_ERROR (Status)) { + goto PciError; + } + + if (VendorId != VIRTIO_VENDOR_ID) { + return FALSE; + } + + // + // Read DeviceId and RevisionId. + // + Status = PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_DEVICE_ID_OFFSET, + 1, + &DeviceId + ); + if (EFI_ERROR (Status)) { + goto PciError; + } + + Status = PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint8, + PCI_REVISION_ID_OFFSET, + 1, + &RevisionId + ); + if (EFI_ERROR (Status)) { + goto PciError; + } + + // + // From DeviceId and RevisionId, determine whether the device is a + // modern-only Virtio 1.0 device. In case of Virtio 1.0, DeviceId can + // immediately be restricted to VIRTIO_SUBSYSTEM_ENTROPY_SOURCE, and + // SubsystemId will only play a sanity-check role. Otherwise, DeviceId can + // only be sanity-checked, and SubsystemId will decide. + // + if ((DeviceId == 0x1040 + VIRTIO_SUBSYSTEM_ENTROPY_SOURCE) && + (RevisionId >= 0x01)) + { + Virtio10 = TRUE; + } else if ((DeviceId >= 0x1000) && (DeviceId <= 0x103F) && (RevisionId == 0x00)) { + Virtio10 = FALSE; + } else { + return FALSE; + } + + // + // Read and check SubsystemId as dictated by Virtio10. + // + Status = PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_SUBSYSTEM_ID_OFFSET, + 1, + &SubsystemId + ); + if (EFI_ERROR (Status)) { + goto PciError; + } + + if (Virtio10 && (SubsystemId >= 0x40)) { + return TRUE; + } + + if (!Virtio10 && (SubsystemId == VIRTIO_SUBSYSTEM_ENTROPY_SOURCE)) { + return TRUE; + } + + return FALSE; + +PciError: + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + return FALSE; +} + +/** + This CALLBACK_FUNCTION attempts to connect a handle non-recursively, asking + the matching driver to produce all first-level child handles. +**/ +STATIC +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. +**/ +STATIC +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 + )); +} + +STATIC +VOID +PlatformRegisterFvBootOption ( + EFI_GUID *FileGuid, + CHAR16 *Description, + 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. +**/ +STATIC +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) ? DEBUG_WARN : DEBUG_VERBOSE, + "%a: removing stale Boot#%04x %s: %r\n", + __FUNCTION__, + (UINT32)BootOptions[Index].OptionNumber, + DevicePathString == NULL ? L"" : DevicePathString, + Status + )); + if (DevicePathString != NULL) { + FreePool (DevicePathString); + } + + DEBUG_CODE_END (); + } + + EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); +} + +STATIC +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 + ) +{ + UINT16 FrontPageTimeout; + RETURN_STATUS PcdStatus; + EFI_STATUS Status; + + // + // Signal EndOfDxe PI Event + // + EfiEventGroupSignal (&gEfiEndOfDxeEventGroupGuid); + + // + // Disable the TPM 2 platform hierarchy + // + ConfigureTpmPlatformHierarchy (); + + // + // 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. + // + FrontPageTimeout = GetFrontPageTimeoutFromQemu (); + PcdStatus = PcdSet16S (PcdPlatformBootTimeOut, FrontPageTimeout); + ASSERT_RETURN_ERROR (PcdStatus); + // + // Reflect the PCD in the standard Timeout variable. + // + Status = gRT->SetVariable ( + EFI_TIME_OUT_VARIABLE_NAME, + &gEfiGlobalVariableGuid, + (EFI_VARIABLE_NON_VOLATILE | + EFI_VARIABLE_BOOTSERVICE_ACCESS | + EFI_VARIABLE_RUNTIME_ACCESS), + sizeof FrontPageTimeout, + &FrontPageTimeout + ); + DEBUG (( + EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, + "%a: SetVariable(%s, %u): %r\n", + __FUNCTION__, + EFI_TIME_OUT_VARIABLE_NAME, + FrontPageTimeout, + Status + )); + + // + // Register platform-specific boot options and keyboard shortcuts. + // + PlatformRegisterOptionsAndKeys (); + + // + // At this point, VIRTIO_DEVICE_PROTOCOL instances exist only for Virtio MMIO + // transports. Install EFI_RNG_PROTOCOL instances on Virtio MMIO RNG devices. + // + FilterAndProcess (&gVirtioDeviceProtocolGuid, IsVirtioRng, Connect); + + // + // Install both VIRTIO_DEVICE_PROTOCOL and (dependent) EFI_RNG_PROTOCOL + // instances on Virtio PCI RNG devices. + // + FilterAndProcess (&gEfiPciIoProtocolGuid, IsVirtioPciRng, Connect); +} + +/** + 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 scenario + > Signal console ready platform customized event + > Run diagnostics like memory testing + > Connect certain devices + > Dispatch additional option roms + > Special boot: e.g.: USB boot, enter UI +**/ +VOID +EFIAPI +PlatformBootManagerAfterConsole ( + VOID + ) +{ + RETURN_STATUS Status; + UINTN FirmwareVerLength; + + FirmwareVerLength = StrLen (PcdGetPtr (PcdFirmwareVersionString)); + // + // Show the splash screen. + // + BootLogoEnableLogo (); + + if (FirmwareVerLength > 0) { + Print ( + VERSION_STRING_PREFIX L"%s\n", + PcdGetPtr (PcdFirmwareVersionString) + ); + } + + Print (L"Press ESCAPE within 10 seconds for boot options "); + // + // Process QEMU's -kernel command line option. The kernel booted this way + // will receive ACPI tables: in PlatformBootManagerBeforeConsole(), we + // connected any and all PCI root bridges, and then signaled the ACPI + // platform driver. + // + TryRunningQemuKernel (); + + // + // Connect the purported boot devices. + // + Status = ConnectDevicesFromQemu (); + if (RETURN_ERROR (Status)) { + // + // Connect the rest of the devices. + // + EfiBootManagerConnectAll (); + } + + // + // 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 (); + + PlatformBmPrintScRegisterHandler (); +} + +/** + This function is called each second during the boot manager waits the + timeout. + + @param TimeoutRemain The remaining timeout. +**/ +VOID +EFIAPI +PlatformBootManagerWaitCallback ( + UINT16 TimeoutRemain + ) +{ + EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION Black; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION White; + UINT16 TimeoutInitial; + + TimeoutInitial = PcdGet16 (PcdPlatformBootTimeOut); + + // + // If PcdPlatformBootTimeOut is set to zero, then we consider + // that no progress update should be enacted. + // + if (TimeoutInitial == 0) { + return; + } + + Black.Raw = 0x00000000; + White.Raw = 0x00FFFFFF; + + BootLogoUpdateProgress ( + White.Pixel, + Black.Pixel, + L"Start boot option", + White.Pixel, + (TimeoutInitial - TimeoutRemain) * 100 / TimeoutInitial, + 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/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.h b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.h new file mode 100644 index 0000000000..70c52d9832 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.h @@ -0,0 +1,45 @@ +/** @file + Head file for BDS Platform specific code + + Copyright (C) 2015-2016, Red Hat, Inc. + Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _PLATFORM_BM_H_ +#define _PLATFORM_BM_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + 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/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf new file mode 100644 index 0000000000..9d66c8110c --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf @@ -0,0 +1,75 @@ +## @file +# Implementation for PlatformBootManagerLib library class interfaces for RISC-V. +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = DxeRiscV64PlatformBootManagerLib + FILE_GUID = 4FC87DC9-2666-49BB-9023-B5FAA1E9E732 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = PlatformBootManagerLib|DXE_DRIVER + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = RISCV64 +# + +[Sources] + PlatformBm.c + PlatformBm.h + QemuKernel.c + +[Packages] + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + SecurityPkg/SecurityPkg.dec + ShellPkg/ShellPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + BootLogoLib + DebugLib + DevicePathLib + MemoryAllocationLib + PcdLib + PlatformBmPrintScLib + QemuBootOrderLib + QemuLoadImageLib + ReportStatusCodeLib + TpmPlatformHierarchyLib + UefiBootManagerLib + UefiBootServicesTableLib + UefiLib + UefiRuntimeServicesTableLib + +[FixedPcd] + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultDataBits + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultParity + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultStopBits + +[Pcd] + gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString + +[Guids] + gEfiEndOfDxeEventGroupGuid + gEfiGlobalVariableGuid + gRootBridgesConnectedEventGroupGuid + gUefiShellFileGuid + gEfiTtyTermGuid + +[Protocols] + gEfiFirmwareVolume2ProtocolGuid + gEfiGraphicsOutputProtocolGuid + gEfiPciRootBridgeIoProtocolGuid + gVirtioDeviceProtocolGuid diff --git a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c new file mode 100644 index 0000000000..736628174f --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c @@ -0,0 +1,77 @@ +/** @file + Try to load an EFI-stubbed RISC-V Linux kernel from QEMU's fw_cfg. + + This implementation differs from OvmfPkg/Library/LoadLinuxLib. An EFI + stub in the subject kernel is a hard requirement here. + + Copyright (C) 2014-2016, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include + +#include "PlatformBm.h" + +// +// The entry point of the feature. +// + +/** + 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 + ) +{ + 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; +} From ef178366dad485639b93594452bb33fc3ac6e2da Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 20:56:15 +0530 Subject: [PATCH 0625/1529] OvmfPkg/RiscVVirt: Add PrePiHobListPointerLib library Add the PrePiHobListPointerLib required for RISC-V Qemu Virt machine since it follows PEIless design. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Jiewen Yao Acked-by: Ard Biesheuvel --- .../PrePiHobListPointer.c | 65 +++++++++++++++++++ .../PrePiHobListPointerLib.inf | 23 +++++++ 2 files changed, 88 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c create mode 100644 OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf diff --git a/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c new file mode 100644 index 0000000000..a58b7aae6b --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c @@ -0,0 +1,65 @@ +/** @file +* +* Copyright (c) 2021, Intel Corporation. All rights reserved.
+* SPDX-License-Identifier: BSD-2-Clause-Patent +* +**/ + +#include +#include +#include +#include +#include + +/** + Returns the pointer to the HOB list. + + This function returns the pointer to first HOB in the list. + + @return The pointer to the HOB list. + +**/ +VOID * +EFIAPI +PrePeiGetHobList ( + VOID + ) +{ + EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext; + + FirmwareContext = NULL; + GetFirmwareContextPointer (&FirmwareContext); + + if (FirmwareContext == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + return NULL; + } + + return (VOID *)FirmwareContext->PrePiHobList; +} + +/** + Updates the pointer to the HOB list. + + @param HobList Hob list pointer to store + +**/ +EFI_STATUS +EFIAPI +PrePeiSetHobList ( + IN VOID *HobList + ) +{ + EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext; + + FirmwareContext = NULL; + GetFirmwareContextPointer (&FirmwareContext); + + if (FirmwareContext == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + return EFI_NOT_READY; + } + + FirmwareContext->PrePiHobList = HobList; + return EFI_SUCCESS; +} diff --git a/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf new file mode 100644 index 0000000000..c539682e8d --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf @@ -0,0 +1,23 @@ +#/** @file +# +# Copyright (c) 2021, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#**/ + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = PrePiHobListPointerLib + FILE_GUID = E3FAFC60-758C-471B-A333-FE704A4C11B4 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = PrePiHobListPointerLib + +[Sources.RISCV64] + PrePiHobListPointer.c + +[Packages] + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + EmbeddedPkg/EmbeddedPkg.dec + UefiCpuPkg/UefiCpuPkg.dec From d62c9f7a4aef47d04019d6750379909ebe04ddf0 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 23:31:13 +0530 Subject: [PATCH 0626/1529] OvmfPkg/RiscVVirt: Add ResetSystemLib library RISC-V Qemu virt uses SBI calls to implement the reset. Add the base class library. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ard Biesheuvel Acked-by: Jiewen Yao --- .../ResetSystemLib/BaseResetSystemLib.inf | 38 ++++++ .../Library/ResetSystemLib/ResetSystemLib.c | 128 ++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf create mode 100644 OvmfPkg/RiscVVirt/Library/ResetSystemLib/ResetSystemLib.c diff --git a/OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf b/OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf new file mode 100644 index 0000000000..c3fa6bd99b --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf @@ -0,0 +1,38 @@ +## @file +# Base library instance for ResetSystem library class for RISC-V +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = BaseResetSystemLib + FILE_GUID = AB45A200-769D-4C10-B0D6-5E1FF5EEBF31 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = ResetSystemLib + +# +# The following information is for reference only and not required by the build +# tools. +# +# VALID_ARCHITECTURES = RISCV64 +# + +[Sources] + ResetSystemLib.c + +[Packages] + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + IoLib + TimerLib + RiscVSbiLib diff --git a/OvmfPkg/RiscVVirt/Library/ResetSystemLib/ResetSystemLib.c b/OvmfPkg/RiscVVirt/Library/ResetSystemLib/ResetSystemLib.c new file mode 100644 index 0000000000..14f7653aa8 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/ResetSystemLib/ResetSystemLib.c @@ -0,0 +1,128 @@ +/** @file + Reset System Library functions for RISC-V + + Copyright (c) 2021, Hewlett Packard Development LP. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + 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 + ) +{ + // Warm Reset via SBI ecall + SbiSystemReset (SBI_SRST_RESET_TYPE_COLD_REBOOT, SBI_SRST_RESET_REASON_NONE); +} + +/** + 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 + ) +{ + // Warm Reset via SBI ecall + SbiSystemReset (SBI_SRST_RESET_TYPE_WARM_REBOOT, SBI_SRST_RESET_REASON_NONE); +} + +/** + 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 shutdown reset. +**/ +VOID +EFIAPI +ResetShutdown ( + VOID + ) +{ + // Shut down via SBI ecall + SbiSystemReset (SBI_SRST_RESET_TYPE_SHUTDOWN, SBI_SRST_RESET_REASON_NONE); +} + +/** + 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 + ) +{ + // + // Can map to OpenSBI vendor or platform specific reset type. + // + return; +} + +/** + The ResetSystem function resets the entire platform. + + @param[in] ResetType The type of reset to perform. + @param[in] ResetStatus The status code for the reset. + @param[in] DataSize The size, in bytes, of ResetData. + @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or EfiResetShutdown + the data buffer starts with a Null-terminated string, optionally + followed by additional binary data. The string is a description + that the caller may use to further indicate the reason for the + system reset. +**/ +VOID +EFIAPI +ResetSystem ( + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL + ) +{ + switch (ResetType) { + case EfiResetWarm: + ResetWarm (); + break; + + case EfiResetCold: + ResetCold (); + break; + + case EfiResetShutdown: + ResetShutdown (); + return; + + case EfiResetPlatformSpecific: + ResetPlatformSpecific (DataSize, ResetData); + return; + + default: + return; + } +} From 50f473aed71f27f0baac0a7b75d151ed475f0b43 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 20:59:36 +0530 Subject: [PATCH 0627/1529] OvmfPkg/RiscVVirt: Add VirtNorFlashPlatformLib library Qemu NOR flash driver needs this library. Add this library for RISC-V leveraged from SbsaQemu. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Jiewen Yao Acked-by: Ard Biesheuvel --- .../VirtNorFlashStaticLib.c | 40 +++++++++++++++++++ .../VirtNorFlashStaticLib.inf | 30 ++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c create mode 100644 OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf diff --git a/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c b/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c new file mode 100644 index 0000000000..fdc2ccb629 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.c @@ -0,0 +1,40 @@ +/** @file + + Copyright (c) 2019, Linaro Ltd. All rights reserved + + SPDX-License-Identifier: BSD-2-Clause-Patent + + **/ + +#include +#include +#include + +#define QEMU_NOR_BLOCK_SIZE SIZE_256KB + +EFI_STATUS +VirtNorFlashPlatformInitialization ( + VOID + ) +{ + return EFI_SUCCESS; +} + +VIRT_NOR_FLASH_DESCRIPTION mNorFlashDevice = +{ + FixedPcdGet32 (PcdOvmfFdBaseAddress), + FixedPcdGet64 (PcdFlashNvStorageVariableBase), + FixedPcdGet32 (PcdOvmfFirmwareFdSize), + QEMU_NOR_BLOCK_SIZE +}; + +EFI_STATUS +VirtNorFlashPlatformGetDevices ( + OUT VIRT_NOR_FLASH_DESCRIPTION **NorFlashDescriptions, + OUT UINT32 *Count + ) +{ + *NorFlashDescriptions = &mNorFlashDevice; + *Count = 1; + return EFI_SUCCESS; +} diff --git a/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf b/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf new file mode 100644 index 0000000000..4e87bd4373 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf @@ -0,0 +1,30 @@ +#/** @file +# +# Component description file for VirtNorFlashStaticLib module +# +# Copyright (c) 2014, Linaro Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +#**/ + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = VirtNorFlashStaticLib + FILE_GUID = 064742F1-E531-4D7D-A154-22315889CC23 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = VirtNorFlashPlatformLib + +[Sources.common] + VirtNorFlashStaticLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + OvmfPkg/OvmfPkg.dec + +[Pcd] + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase From 352a23de8cd78b9e4ff178ef9ac0e7c67bf309d5 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 21:01:04 +0530 Subject: [PATCH 0628/1529] OvmfPkg/RiscVVirt: Add PciCpuIo2Dxe module Add PciCpuIo2Dxe driver to implement EFI_CPU_IO2_PROTOCOL to add the translation for IO access. This is copied from ArmPciCpuIo2Dxe driver. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ard Biesheuvel Acked-by: Jiewen Yao --- OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.c | 557 ++++++++++++++++++ .../RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf | 48 ++ 2 files changed, 605 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.c create mode 100644 OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf diff --git a/OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.c b/OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.c new file mode 100644 index 0000000000..f3bf07e631 --- /dev/null +++ b/OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.c @@ -0,0 +1,557 @@ +/** @file + Produces the CPU I/O 2 Protocol. + +Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.
+Copyright (c) 2016, Linaro Ltd. All rights reserved.
+Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +#include + +#include +#include +#include +#include +#include + +#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. + +**/ +STATIC +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. + +**/ +STATIC +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. + +**/ +STATIC +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. + +**/ +STATIC +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. + +**/ +STATIC +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/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf b/OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf new file mode 100644 index 0000000000..4f78cfa406 --- /dev/null +++ b/OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf @@ -0,0 +1,48 @@ +## @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.
+# Copyright (c) 2016, Linaro Ltd. All rights reserved.
+# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = PciCpuIo2Dxe + FILE_GUID = 9BD3C765-2579-4CF0-9349-D77205565030 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = PciCpuIo2Initialize + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = RISCV64 +# + +[Sources] + PciCpuIo2Dxe.c + +[Packages] + OvmfPkg/OvmfPkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + BaseLib + DebugLib + IoLib + PcdLib + UefiBootServicesTableLib + +[Pcd] + gEfiMdePkgTokenSpaceGuid.PcdPciIoTranslation + +[Protocols] + gEfiCpuIo2ProtocolGuid ## PRODUCES + +[Depex] + TRUE From 10c713e8b2aba36b77af2625584391a36690aed2 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 21:02:23 +0530 Subject: [PATCH 0629/1529] OvmfPkg/RiscVVirt: Add SEC module Add the SEC module for RISC-V Qemu virt machine support. It uses the PEI less design. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Jiewen Yao Acked-by: Ard Biesheuvel --- OvmfPkg/RiscVVirt/Sec/Cpu.c | 33 ++++ OvmfPkg/RiscVVirt/Sec/Memory.c | 263 ++++++++++++++++++++++++++++++ OvmfPkg/RiscVVirt/Sec/Platform.c | 84 ++++++++++ OvmfPkg/RiscVVirt/Sec/SecEntry.S | 21 +++ OvmfPkg/RiscVVirt/Sec/SecMain.c | 104 ++++++++++++ OvmfPkg/RiscVVirt/Sec/SecMain.h | 102 ++++++++++++ OvmfPkg/RiscVVirt/Sec/SecMain.inf | 66 ++++++++ 7 files changed, 673 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/Sec/Cpu.c create mode 100644 OvmfPkg/RiscVVirt/Sec/Memory.c create mode 100644 OvmfPkg/RiscVVirt/Sec/Platform.c create mode 100644 OvmfPkg/RiscVVirt/Sec/SecEntry.S create mode 100644 OvmfPkg/RiscVVirt/Sec/SecMain.c create mode 100644 OvmfPkg/RiscVVirt/Sec/SecMain.h create mode 100644 OvmfPkg/RiscVVirt/Sec/SecMain.inf diff --git a/OvmfPkg/RiscVVirt/Sec/Cpu.c b/OvmfPkg/RiscVVirt/Sec/Cpu.c new file mode 100644 index 0000000000..2c16df697e --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/Cpu.c @@ -0,0 +1,33 @@ +/** @file +The library call to pass the device tree to DXE via HOB. + +Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +// +//// The package level header files this module uses +//// +#include + +#include +#include + +/** + Cpu Peim initialization. + +**/ +EFI_STATUS +CpuPeimInitialization ( + VOID + ) +{ + // + // for MMU type >= sv39 + // + BuildCpuHob (56, 32); + + return EFI_SUCCESS; +} diff --git a/OvmfPkg/RiscVVirt/Sec/Memory.c b/OvmfPkg/RiscVVirt/Sec/Memory.c new file mode 100644 index 0000000000..70935b07b5 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/Memory.c @@ -0,0 +1,263 @@ +/** @file + Memory Detection for Virtual Machines. + + Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+ Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +Module Name: + + MemDetect.c + +**/ + +// +// The package level header files this module uses +// +#include + +// +// The Library classes this module consumes +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +VOID +BuildMemoryTypeInformationHob ( + VOID + ); + +/** + Build reserved memory range resource HOB. + + @param MemoryBase Reserved memory range base address. + @param MemorySize Reserved memory range size. + +**/ +STATIC +VOID +AddReservedMemoryBaseSizeHob ( + EFI_PHYSICAL_ADDRESS MemoryBase, + UINT64 MemorySize + ) +{ + BuildResourceDescriptorHob ( + EFI_RESOURCE_MEMORY_RESERVED, + EFI_RESOURCE_ATTRIBUTE_PRESENT | + EFI_RESOURCE_ATTRIBUTE_INITIALIZED | + EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | + EFI_RESOURCE_ATTRIBUTE_TESTED, + MemoryBase, + MemorySize + ); +} + +/** + Create memory range resource HOB using the memory base + address and size. + + @param MemoryBase Memory range base address. + @param MemorySize Memory range size. + +**/ +STATIC +VOID +AddMemoryBaseSizeHob ( + EFI_PHYSICAL_ADDRESS MemoryBase, + UINT64 MemorySize + ) +{ + BuildResourceDescriptorHob ( + EFI_RESOURCE_SYSTEM_MEMORY, + EFI_RESOURCE_ATTRIBUTE_PRESENT | + EFI_RESOURCE_ATTRIBUTE_INITIALIZED | + EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE | + EFI_RESOURCE_ATTRIBUTE_TESTED, + MemoryBase, + MemorySize + ); +} + +/** + Create memory range resource HOB using memory base + address and top address of the memory range. + + @param MemoryBase Memory range base address. + @param MemoryLimit Memory range size. + +**/ +STATIC +VOID +AddMemoryRangeHob ( + EFI_PHYSICAL_ADDRESS MemoryBase, + EFI_PHYSICAL_ADDRESS MemoryLimit + ) +{ + AddMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase)); +} + +/** + Configure MMU +**/ +STATIC +VOID +InitMmu ( + ) +{ + // + // Set supervisor translation mode to Bare mode + // + RiscVSetSupervisorAddressTranslationRegister ((UINT64)SATP_MODE_OFF << 60); + DEBUG ((DEBUG_INFO, "%a: Set Supervisor address mode to bare-metal mode.\n", __FUNCTION__)); +} + +/** + Publish system RAM and reserve memory regions. + +**/ +STATIC +VOID +InitializeRamRegions ( + EFI_PHYSICAL_ADDRESS SystemMemoryBase, + UINT64 SystemMemorySize, + EFI_PHYSICAL_ADDRESS MmodeResvBase, + UINT64 MmodeResvSize + ) +{ + /* + * M-mode FW can be loaded anywhere in memory but should not overlap + * with the EDK2. This can happen if some other boot code loads the + * M-mode firmware. + * + * The M-mode firmware memory should be marked as reserved memory + * so that OS doesn't use it. + */ + DEBUG (( + DEBUG_INFO, + "%a: M-mode FW Memory Start:0x%lx End:0x%lx\n", + __FUNCTION__, + MmodeResvBase, + MmodeResvBase + MmodeResvSize + )); + AddReservedMemoryBaseSizeHob (MmodeResvBase, MmodeResvSize); + + if (MmodeResvBase > SystemMemoryBase) { + AddMemoryRangeHob (SystemMemoryBase, MmodeResvBase); + } + + AddMemoryRangeHob ( + MmodeResvBase + MmodeResvSize, + SystemMemoryBase + SystemMemorySize + ); +} + +/** + Initialize memory hob based on the DTB information. + + @return EFI_SUCCESS The memory hob added successfully. + +**/ +EFI_STATUS +MemoryPeimInitialization ( + VOID + ) +{ + EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext; + CONST UINT64 *RegProp; + CONST CHAR8 *Type; + UINT64 CurBase, CurSize; + INT32 Node, Prev; + INT32 Len; + VOID *FdtPointer; + EFI_PHYSICAL_ADDRESS MmodeResvBase; + UINT64 MmodeResvSize; + + FirmwareContext = NULL; + GetFirmwareContextPointer (&FirmwareContext); + + if (FirmwareContext == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + FdtPointer = (VOID *)FirmwareContext->FlattenedDeviceTree; + if (FdtPointer == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + /* try to locate the reserved memory opensbi node */ + Node = fdt_path_offset (FdtPointer, "/reserved-memory/mmode_resv0"); + if (Node >= 0) { + RegProp = fdt_getprop (FdtPointer, Node, "reg", &Len); + if ((RegProp != 0) && (Len == (2 * sizeof (UINT64)))) { + MmodeResvBase = fdt64_to_cpu (ReadUnaligned64 (RegProp)); + MmodeResvSize = fdt64_to_cpu (ReadUnaligned64 (RegProp + 1)); + } + } + + // Look for the lowest memory node + for (Prev = 0; ; Prev = Node) { + Node = fdt_next_node (FdtPointer, Prev, NULL); + if (Node < 0) { + break; + } + + // Check for memory node + Type = fdt_getprop (FdtPointer, Node, "device_type", &Len); + if (Type && (AsciiStrnCmp (Type, "memory", 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 (FdtPointer, Node, "reg", &Len); + if ((RegProp != 0) && (Len == (2 * sizeof (UINT64)))) { + CurBase = fdt64_to_cpu (ReadUnaligned64 (RegProp)); + CurSize = fdt64_to_cpu (ReadUnaligned64 (RegProp + 1)); + + DEBUG (( + DEBUG_INFO, + "%a: System RAM @ 0x%lx - 0x%lx\n", + __FUNCTION__, + CurBase, + CurBase + CurSize - 1 + )); + + if ((MmodeResvBase >= CurBase) && ((MmodeResvBase + MmodeResvSize) <= (CurBase + CurSize))) { + InitializeRamRegions ( + CurBase, + CurSize, + MmodeResvBase, + MmodeResvSize + ); + } else { + AddMemoryBaseSizeHob (CurBase, CurSize); + } + } else { + DEBUG (( + DEBUG_ERROR, + "%a: Failed to parse FDT memory node\n", + __FUNCTION__ + )); + } + } + } + + InitMmu (); + + BuildMemoryTypeInformationHob (); + + return EFI_SUCCESS; +} diff --git a/OvmfPkg/RiscVVirt/Sec/Platform.c b/OvmfPkg/RiscVVirt/Sec/Platform.c new file mode 100644 index 0000000000..e8fd126cf8 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/Platform.c @@ -0,0 +1,84 @@ +/** @file +The library call to pass the device tree to DXE via HOB. + +Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +// +//// The package level header files this module uses +//// +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/** + @retval EFI_SUCCESS The address of FDT is passed in HOB. + EFI_UNSUPPORTED Can't locate FDT. +**/ +EFI_STATUS +EFIAPI +PlatformPeimInitialization ( + VOID + ) +{ + EFI_RISCV_FIRMWARE_CONTEXT *FirmwareContext; + VOID *FdtPointer; + VOID *Base; + VOID *NewBase; + UINTN FdtSize; + UINTN FdtPages; + UINT64 *FdtHobData; + + FirmwareContext = NULL; + GetFirmwareContextPointer (&FirmwareContext); + + if (FirmwareContext == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + FdtPointer = (VOID *)FirmwareContext->FlattenedDeviceTree; + if (FdtPointer == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + DEBUG ((DEBUG_INFO, "%a: Build FDT HOB - FDT at address: 0x%x \n", __FUNCTION__, FdtPointer)); + Base = FdtPointer; + if (fdt_check_header (Base) != 0) { + DEBUG ((DEBUG_ERROR, "%a: Corrupted DTB\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + FdtSize = fdt_totalsize (Base); + FdtPages = EFI_SIZE_TO_PAGES (FdtSize); + NewBase = AllocatePages (FdtPages); + if (NewBase == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Could not allocate memory for DTB\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + fdt_open_into (Base, NewBase, EFI_PAGES_TO_SIZE (FdtPages)); + + FdtHobData = BuildGuidHob (&gFdtHobGuid, sizeof *FdtHobData); + if (FdtHobData == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Could not build FDT Hob\n", __FUNCTION__)); + return EFI_UNSUPPORTED; + } + + *FdtHobData = (UINTN)NewBase; + + BuildFvHob (PcdGet32 (PcdOvmfDxeMemFvBase), PcdGet32 (PcdOvmfDxeMemFvSize)); + + return EFI_SUCCESS; +} diff --git a/OvmfPkg/RiscVVirt/Sec/SecEntry.S b/OvmfPkg/RiscVVirt/Sec/SecEntry.S new file mode 100644 index 0000000000..e919a3cb0e --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/SecEntry.S @@ -0,0 +1,21 @@ +/* + Copyright (c) 2022 Ventana Micro Systems Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent + + */ + +#include "SecMain.h" + +.text +.align 3 + +ASM_FUNC (_ModuleEntryPoint) + /* Use Temp memory as the stack for calling to C code */ + li a4, FixedPcdGet32 (PcdOvmfSecPeiTempRamBase) + li a5, FixedPcdGet32 (PcdOvmfSecPeiTempRamSize) + + /* Use Temp memory as the stack for calling to C code */ + add sp, a4, a5 + + call SecStartup diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.c b/OvmfPkg/RiscVVirt/Sec/SecMain.c new file mode 100644 index 0000000000..054e49ef0c --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.c @@ -0,0 +1,104 @@ +/** @file + RISC-V SEC phase module for Qemu Virt. + + Copyright (c) 2008 - 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "SecMain.h" + +STATIC +EFI_STATUS +EFIAPI +SecInitializePlatform ( + VOID + ) +{ + EFI_STATUS Status; + + MemoryPeimInitialization (); + + CpuPeimInitialization (); + + // Set the Boot Mode + SetBootMode (BOOT_WITH_FULL_CONFIGURATION); + + Status = PlatformPeimInitialization (); + ASSERT_EFI_ERROR (Status); + + return EFI_SUCCESS; +} + +/** + + Entry point to the C language phase of SEC. After the SEC assembly + code has initialized some temporary memory and set up the stack, + the control is transferred to this function. + + + @param[in] BootHartId Hardware thread ID of boot hart. + @param[in] DeviceTreeAddress Pointer to Device Tree (DTB) +**/ +VOID +NORETURN +EFIAPI +SecStartup ( + IN UINTN BootHartId, + IN VOID *DeviceTreeAddress + ) +{ + EFI_HOB_HANDOFF_INFO_TABLE *HobList; + EFI_RISCV_FIRMWARE_CONTEXT FirmwareContext; + EFI_STATUS Status; + UINT64 UefiMemoryBase; + UINT64 StackBase; + + // + // Report Status Code to indicate entering SEC core + // + DEBUG (( + DEBUG_INFO, + "%a() BootHartId: 0x%x, DeviceTreeAddress=0x%x\n", + __FUNCTION__, + BootHartId, + DeviceTreeAddress + )); + + FirmwareContext.BootHartId = BootHartId; + FirmwareContext.FlattenedDeviceTree = (UINT64)DeviceTreeAddress; + SetFirmwareContextPointer (&FirmwareContext); + + StackBase = (UINT64)FixedPcdGet32 (PcdOvmfSecPeiTempRamBase); + UefiMemoryBase = StackBase + FixedPcdGet32 (PcdOvmfSecPeiTempRamSize) - SIZE_32MB; + + // Declare the PI/UEFI memory region + HobList = HobConstructor ( + (VOID *)UefiMemoryBase, + SIZE_32MB, + (VOID *)UefiMemoryBase, + (VOID *)StackBase // The top of the UEFI Memory is reserved for the stacks + ); + PrePeiSetHobList (HobList); + + SecInitializePlatform (); + + // + // Process all libraries constructor function linked to SecMain. + // + ProcessLibraryConstructorList (); + + // Assume the FV that contains the SEC (our code) also contains a compressed FV. + Status = DecompressFirstFv (); + ASSERT_EFI_ERROR (Status); + + // Load the DXE Core and transfer control to it + Status = LoadDxeCoreFromFv (NULL, 0); + ASSERT_EFI_ERROR (Status); + // + // Should not come here. + // + UNREACHABLE (); +} diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.h b/OvmfPkg/RiscVVirt/Sec/SecMain.h new file mode 100644 index 0000000000..83a8058efe --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.h @@ -0,0 +1,102 @@ +/** @file + Master header file for SecCore. + + Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef SEC_MAIN_H_ +#define SEC_MAIN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + Entry point to the C language phase of SEC. After the SEC assembly + code has initialized some temporary memory and set up the stack, + the control is transferred to this function. + + @param SizeOfRam Size of the temporary memory available for use. + @param TempRamBase Base address of temporary ram + @param BootFirmwareVolume Base address of the Boot Firmware Volume. +**/ +VOID +NORETURN +EFIAPI +SecStartup ( + IN UINTN BootHartId, + IN VOID *DeviceTreeAddress + ); + +/** + Auto-generated function that calls the library constructors for all of the module's + dependent libraries. This function must be called by the SEC Core once a stack has + been established. + +**/ +VOID +EFIAPI +ProcessLibraryConstructorList ( + VOID + ); + +/** + Perform Platform PEIM initialization. + + @return EFI_SUCCESS The platform initialized successfully. + @retval Others - As the error code indicates + +**/ +EFI_STATUS +EFIAPI +PlatformPeimInitialization ( + VOID + ); + +/** + Perform Memory PEIM initialization. + + @return EFI_SUCCESS The platform initialized successfully. + @retval Others - As the error code indicates + +**/ +EFI_STATUS +EFIAPI +MemoryPeimInitialization ( + VOID + ); + +/** + Perform CPU PEIM initialization. + + @return EFI_SUCCESS The platform initialized successfully. + @retval Others - As the error code indicates + +**/ +EFI_STATUS +EFIAPI +CpuPeimInitialization ( + VOID + ); + +#endif diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.inf b/OvmfPkg/RiscVVirt/Sec/SecMain.inf new file mode 100644 index 0000000000..aed35d3af5 --- /dev/null +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.inf @@ -0,0 +1,66 @@ +## @file +# SEC Driver for RISC-V +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SecMainRiscV64 + FILE_GUID = 16740C0A-AA84-4F62-A06D-AE328057AE07 + MODULE_TYPE = SEC + VERSION_STRING = 1.0 + ENTRY_POINT = SecMain + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = RISCV64 +# + +[Sources] + SecEntry.S + SecMain.c + SecMain.h + Cpu.c + Memory.c + Platform.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + OvmfPkg/OvmfPkg.dec + EmbeddedPkg/EmbeddedPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + PcdLib + IoLib + PeCoffLib + LzmaDecompressLib + RiscVSbiLib + PrePiLib + FdtLib + MemoryAllocationLib + HobLib + +[Ppis] + gEfiTemporaryRamSupportPpiGuid # PPI ALWAYS_PRODUCED + gEfiTemporaryRamDonePpiGuid ## PRODUCES + +[Pcd] + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress + +[Guids] + gFdtHobGuid From b5af0f523f87471d32800b20a62f9fcc0452620d Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 21:03:59 +0530 Subject: [PATCH 0630/1529] OvmfPkg/RiscVVirt: Add build files for Qemu Virt platform REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 Add infrastructure files to build edk2 for RISC-V qemu virt machine. - It follows PEI less design. - EDK2 for qemu virt is booted in S-mode as a payload for M-mode FW - Leveraged from ArmVirtQemu Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Abner Chang Reviewed-by: Andrei Warkentin Acked-by: Ard Biesheuvel Acked-by: Jiewen Yao --- OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc | 336 +++++++++++++++++++ OvmfPkg/RiscVVirt/RiscVVirt.fdf.inc | 41 +++ OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc | 504 ++++++++++++++++++++++++++++ OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf | 306 +++++++++++++++++ OvmfPkg/RiscVVirt/VarStore.fdf.inc | 79 +++++ 5 files changed, 1266 insertions(+) create mode 100644 OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc create mode 100644 OvmfPkg/RiscVVirt/RiscVVirt.fdf.inc create mode 100644 OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc create mode 100644 OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf create mode 100644 OvmfPkg/RiscVVirt/VarStore.fdf.inc diff --git a/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc new file mode 100644 index 0000000000..731f54f73f --- /dev/null +++ b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc @@ -0,0 +1,336 @@ +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved. +# Copyright (c) 2011 - 2022, ARM Limited. All rights reserved. +# Copyright (c) 2014, Linaro Limited. All rights reserved. +# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# + +[Defines] + DEFINE DEBUG_PRINT_ERROR_LEVEL = 0x80000047 + +[LibraryClasses.common] +!ifdef $(SOURCE_DEBUG_ENABLE) + PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf + DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf +!else + PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf + DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf +!endif +!if $(DEBUG_ON_SERIAL_PORT) == TRUE + DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf +!else + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf +!endif + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf + PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf + UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf + CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf + CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf + UefiLib|MdePkg/Library/UefiLib/UefiLib.inf + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf + DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf + ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf + ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf + FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf + PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf + UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf + OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf + OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + + # + # Ramdisk Requirements + # + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + + # Allow dynamic PCDs + # + + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + + # Networking Requirements +!include NetworkPkg/NetworkLibs.dsc.inc +!if $(NETWORK_TLS_ENABLE) == TRUE + TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf +!endif + + + # Add support for GCC stack protector + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf + + # RISC-V Architectural Libraries + CpuExceptionHandlerLib|UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/BaseRiscV64CpuExceptionHandlerLib.inf + RiscVSbiLib|MdePkg/Library/BaseRiscVSbiLib/BaseRiscVSbiLib.inf + PlatformBootManagerLib|OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf + ResetSystemLib|OvmfPkg/RiscVVirt/Library/ResetSystemLib/BaseResetSystemLib.inf + + RealTimeClockLib|EmbeddedPkg/Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf + TimeBaseLib|EmbeddedPkg/Library/TimeBaseLib/TimeBaseLib.inf + SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf + + DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + DebugAgentTimerLib|EmbeddedPkg/Library/DebugAgentTimerLibNull/DebugAgentTimerLibNull.inf + + # Flattened Device Tree (FDT) access library + FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf + + # PCI Libraries + PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf + PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf + PciCapLib|OvmfPkg/Library/BasePciCapLib/BasePciCapLib.inf + PciCapPciSegmentLib|OvmfPkg/Library/BasePciCapPciSegmentLib/BasePciCapPciSegmentLib.inf + PciCapPciIoLib|OvmfPkg/Library/UefiPciCapPciIoLib/UefiPciCapPciIoLib.inf + DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf + + # USB Libraries + UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf + + # + # CryptoPkg libraries needed by multiple firmware features + # + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf +!if $(NETWORK_TLS_ENABLE) == TRUE + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf +!else + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +!endif + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf + RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf + + # + # Secure Boot dependencies + # +!if $(SECURE_BOOT_ENABLE) == TRUE + AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + SecureBootVariableProvisionLib|SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.inf + PlatformPKProtectionLib|SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.inf + + # re-use the UserPhysicalPresent() dummy implementation from the ovmf tree + PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf +!else + AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf +!endif + VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf + VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf + VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf + UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf + ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf + PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + +[LibraryClasses.common.SEC] + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf + ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf + PlatformSecLib|UefiCpuPkg/Library/PlatformSecLibNull/PlatformSecLibNull.inf + HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf + PrePiHobListPointerLib|OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf + MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf + +[LibraryClasses.common.DXE_CORE] + PerformanceLib|MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.inf + HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf + MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf + DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf + +[LibraryClasses.common.DXE_DRIVER] + SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + +[LibraryClasses.common.UEFI_APPLICATION] + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + +[LibraryClasses.common.UEFI_DRIVER] + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + +[LibraryClasses.common.DXE_RUNTIME_DRIVER] + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf +!if $(DEBUG_ON_SERIAL_PORT) == TRUE + DebugLib|MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf +!endif + VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLibRuntimeDxe.inf + +!if $(SECURE_BOOT_ENABLE) == TRUE + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +!endif + +################################################################################ +# +# Pcd Section - list of all EDK II PCD Entries defined by this Platform +# +################################################################################ + +[PcdsFeatureFlag.common] + gEfiMdeModulePkgTokenSpaceGuid.PcdHiiOsRuntimeSupport|FALSE + + gEmbeddedTokenSpaceGuid.PcdPrePiProduceMemoryTypeInformationHob|TRUE + +[PcdsFeatureFlag] + # + # Activate AcpiSdtProtocol + # + gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE + +[PcdsFixedAtBuild.common] + gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000 + gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000 + gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|0 + gEfiMdePkgTokenSpaceGuid.PcdSpinLockTimeout|10000000 + gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|320 + + # DEBUG_ASSERT_ENABLED 0x01 + # DEBUG_PRINT_ENABLED 0x02 + # DEBUG_CODE_ENABLED 0x04 + # CLEAR_MEMORY_ENABLED 0x08 + # ASSERT_BREAKPOINT_ENABLED 0x10 + # ASSERT_DEADLOOP_ENABLED 0x20 +!if $(DEBUG_ON_SERIAL_PORT) != TRUE + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x21 +!else + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2f +!endif + + # DEBUG_INIT 0x00000001 // Initialization + # DEBUG_WARN 0x00000002 // Warnings + # DEBUG_LOAD 0x00000004 // Load events + # DEBUG_FS 0x00000008 // EFI File system + # DEBUG_POOL 0x00000010 // Alloc & Free (pool) + # DEBUG_PAGE 0x00000020 // Alloc & Free (page) + # DEBUG_INFO 0x00000040 // Informational debug messages + # DEBUG_DISPATCH 0x00000080 // PEI/DXE/SMM Dispatchers + # DEBUG_VARIABLE 0x00000100 // Variable + # DEBUG_BM 0x00000400 // Boot Manager + # DEBUG_BLKIO 0x00001000 // BlkIo Driver + # DEBUG_NET 0x00004000 // SNP Driver + # DEBUG_UNDI 0x00010000 // UNDI Driver + # DEBUG_LOADFILE 0x00020000 // LoadFile + # DEBUG_EVENT 0x00080000 // Event messages + # DEBUG_GCD 0x00100000 // Global Coherency Database changes + # DEBUG_CACHE 0x00200000 // Memory range cachability changes + # DEBUG_VERBOSE 0x00400000 // Detailed debug messages that may + # // significantly impact boot performance + # DEBUG_ERROR 0x80000000 // Error +!if $(DEBUG_ON_SERIAL_PORT) == TRUE + gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|$(DEBUG_PRINT_ERROR_LEVEL) +!endif + + # + # Optional feature to help prevent EFI memory map fragments + # Turned on and off via: PcdPrePiProduceMemoryTypeInformationHob + # Values are in EFI Pages (4K). DXE Core will make sure that + # at least this much of each type of memory can be allocated + # from a single memory range. This way you only end up with + # maximum of two fragments for each type in the memory map + # (the memory used, and the free memory that was prereserved + # but not used). + # + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0 +!if $(SECURE_BOOT_ENABLE) == TRUE + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|600 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|400 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|1500 +!else + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|300 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|150 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesCode|1000 +!endif + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiBootServicesData|6000 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|20 + gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0 + + # + # Enable strict image permissions for all images. (This applies + # only to images that were built with >= 4 KB section alignment.) + # + gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x3 + + # + # Enable NX memory protection for all non-code regions, including OEM and OS + # reserved ones, with the exception of LoaderData regions, of which OS loaders + # (i.e., GRUB) may assume that its contents are executable. + # + gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5 + +[Components.common] + # + # Ramdisk support + # + MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf + + ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf { + + gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE + } + ShellPkg/DynamicCommand/HttpDynamicCommand/HttpDynamicCommand.inf { + + gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE + } + OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf { + + gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE + } + ShellPkg/Application/Shell/Shell.inf { + + ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf + NULL|ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.inf + NULL|ShellPkg/Library/UefiShellLevel1CommandsLib/UefiShellLevel1CommandsLib.inf + NULL|ShellPkg/Library/UefiShellLevel3CommandsLib/UefiShellLevel3CommandsLib.inf + NULL|ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.inf + NULL|ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf +!if $(ACPIVIEW_ENABLE) == TRUE + NULL|ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf +!endif + NULL|ShellPkg/Library/UefiShellInstall1CommandsLib/UefiShellInstall1CommandsLib.inf + NULL|ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.inf +!if $(NETWORK_IP6_ENABLE) == TRUE + NULL|ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.inf +!endif + HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + BcfgCommandLib|ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.inf + + + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xFF + gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE + gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000 + } + + # + # ACPI Support + # + MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf { + + NULL|EmbeddedPkg/Library/PlatformHasAcpiLib/PlatformHasAcpiLib.inf + } diff --git a/OvmfPkg/RiscVVirt/RiscVVirt.fdf.inc b/OvmfPkg/RiscVVirt/RiscVVirt.fdf.inc new file mode 100644 index 0000000000..b0a1c3293f --- /dev/null +++ b/OvmfPkg/RiscVVirt/RiscVVirt.fdf.inc @@ -0,0 +1,41 @@ +## @file +# Definitions of Flash definition file on RiscVVirt RISC-V platform +# +# Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## +[Defines] +DEFINE BLOCK_SIZE = 0x1000 + +DEFINE PFLASH1_BASE = 0x22000000 + +DEFINE FW_BASE_ADDRESS = $(PFLASH1_BASE) +DEFINE FW_SIZE = 0x00800000 +DEFINE FW_BLOCKS = 0x800 + +DEFINE CODE_BASE_ADDRESS = $(FW_BASE_ADDRESS) +DEFINE CODE_SIZE = 0x00740000 +DEFINE CODE_BLOCKS = 0x740 + +DEFINE VARS_SIZE = 0x000C0000 +DEFINE VARS_BLOCK_SIZE = 0x40000 +DEFINE VARS_BLOCKS = 0x3 + +# +# EFI Variable memory region. +# The total size of EFI Variable FD must include +# all of sub regions of EFI Variable +# +DEFINE VARS_OFFSET = $(CODE_SIZE) +DEFINE VARS_LIVE_SIZE = 0x00040000 +DEFINE VARS_FTW_WORKING_OFFSET = $(VARS_OFFSET) + $(VARS_LIVE_SIZE) +DEFINE VARS_FTW_WORKING_SIZE = 0x00040000 +DEFINE VARS_FTW_SPARE_OFFSET = $(VARS_FTW_WORKING_OFFSET) + $(VARS_FTW_WORKING_SIZE) +DEFINE VARS_FTW_SPARE_SIZE = 0x00040000 + +SET gUefiCpuPkgTokenSpaceGuid.PcdCpuCoreCrystalClockFrequency = 10000000 +SET gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase = 0x83FF0000 +SET gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize = 0x00010000 diff --git a/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc new file mode 100644 index 0000000000..054d511138 --- /dev/null +++ b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc @@ -0,0 +1,504 @@ +## @file +# RISC-V EFI on RiscVVirtQem platform +# +# Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +################################################################################ +# +# Defines Section - statements that will be processed to create a Makefile. +# +################################################################################ +[Defines] + PLATFORM_NAME = RiscVVirtQemu + PLATFORM_GUID = 39DADB39-1B21-4867-838E-830B6149B9E0 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x0001001c + OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME) + SUPPORTED_ARCHITECTURES = RISCV64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT + FLASH_DEFINITION = OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf + + # + # Enable below options may cause build error or may not work on + # the initial version of RISC-V package + # Defines for default states. These can be changed on the command line. + # -D FLAG=VALUE + # + DEFINE TTY_TERMINAL = FALSE + DEFINE SECURE_BOOT_ENABLE = FALSE + DEFINE TPM2_ENABLE = FALSE + DEFINE TPM2_CONFIG_ENABLE = FALSE + DEFINE DEBUG_ON_SERIAL_PORT = TRUE + + # + # Network definition + # + DEFINE NETWORK_IP6_ENABLE = FALSE + DEFINE NETWORK_HTTP_BOOT_ENABLE = FALSE + DEFINE NETWORK_SNP_ENABLE = FALSE + DEFINE NETWORK_TLS_ENABLE = FALSE + DEFINE NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE + DEFINE NETWORK_ISCSI_ENABLE = FALSE + +!if $(NETWORK_SNP_ENABLE) == TRUE + !error "NETWORK_SNP_ENABLE is IA32/X64/EBC only" +!endif + + +!include MdePkg/MdeLibs.dsc.inc + +[BuildOptions] + GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG +!ifdef $(SOURCE_DEBUG_ENABLE) + GCC:*_*_RISCV64_GENFW_FLAGS = --keepexceptiontable +!endif + +[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] + GCC: *_*_*_DLINK_FLAGS = -z common-page-size=0x1000 + MSFT: *_*_*_DLINK_FLAGS = /ALIGN:4096 + +################################################################################ +# +# Library Class section - list of all Library Classes needed by this Platform. +# +################################################################################ + +!include NetworkPkg/NetworkDefines.dsc.inc + +!include OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc + +!include MdePkg/MdeLibs.dsc.inc + +[LibraryClasses.common] + # Virtio Support + VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf + VirtioMmioDeviceLib|OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceLib.inf + QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibMmio.inf + QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/BaseQemuFwCfgS3LibNull.inf + QemuFwCfgSimpleParserLib|OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParserLib.inf + QemuLoadImageLib|OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.inf + + TimerLib|UefiCpuPkg/Library/BaseRiscV64CpuTimerLib/BaseRiscV64CpuTimerLib.inf + VirtNorFlashPlatformLib|OvmfPkg/RiscVVirt/Library/VirtNorFlashPlatformLib/VirtNorFlashStaticLib.inf + + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf + PlatformBootManagerLib|OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf + PlatformBmPrintScLib|OvmfPkg/Library/PlatformBmPrintScLib/PlatformBmPrintScLib.inf + CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf + FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf + QemuBootOrderLib|OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + PciPcdProducerLib|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf + PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf + PciHostBridgeLib|OvmfPkg/Fdt/FdtPciHostBridgeLib/FdtPciHostBridgeLib.inf + PciHostBridgeUtilityLib|OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.inf + PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf + PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf + +!if $(TPM2_ENABLE) == TRUE + Tpm2CommandLib|SecurityPkg/Library/Tpm2CommandLib/Tpm2CommandLib.inf + Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibQemu/DxeTcg2PhysicalPresenceLib.inf + TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf + TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf +!else + TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf + TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLibNull/PeiDxeTpmPlatformHierarchyLib.inf +!endif + +[LibraryClasses.common.DXE_DRIVER] + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + +!if $(TPM2_ENABLE) == TRUE + Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf +!endif + +[LibraryClasses.common.UEFI_DRIVER] + UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf + PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + +#!include NetworkPkg/NetworkBuildOptions.dsc.inc + +################################################################################ +# +# Pcd Section - list of all EDK II PCD Entries defined by this Platform. +# +################################################################################ +[PcdsFeatureFlag.common] + gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation|TRUE + gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderMmioTranslation|TRUE + + ## If TRUE, Graphics Output Protocol will be installed on virtual handle created by ConsplitterDxe. + # It could be set FALSE to save size. + gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE + + gEfiMdeModulePkgTokenSpaceGuid.PcdTurnOffUsbLegacySupport|TRUE + +[PcdsFixedAtBuild.common] + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800 +!if $(NETWORK_TLS_ENABLE) == TRUE + # + # The cumulative and individual VOLATILE variable size limits should be set + # high enough for accommodating several and/or large CA certificates. + # + gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x80000 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVolatileVariableSize|0x40000 +!endif + + gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString|L"2.7" + + # Serial Port + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseMmio|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0x10000000 + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate|9600 + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseHardwareFlowControl|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialClockRate|3686400 + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterStride|1 + + # + # Network Pcds + # +!include NetworkPkg/NetworkPcds.dsc.inc + + gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 } + + + # + # Enable the non-executable DXE stack. (This gets set up by DxeIpl) + # + gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|TRUE + +!if $(SECURE_BOOT_ENABLE) == TRUE + # override the default values from SecurityPkg to ensure images from all sources are verified in secure boot + gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x04 + gEfiSecurityPkgTokenSpaceGuid.PcdFixedMediaImageVerificationPolicy|0x04 + gEfiSecurityPkgTokenSpaceGuid.PcdRemovableMediaImageVerificationPolicy|0x04 +!endif + + gEfiShellPkgTokenSpaceGuid.PcdShellFileOperationSize|0x20000 + gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x02 + gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 + + gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosEntryPointProvideMethod|0x2 + +[PcdsDynamicDefault.common] + gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|3 + + ## If TRUE, OvmfPkg/AcpiPlatformDxe will not wait for PCI + # enumeration to complete before installing ACPI tables. + gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|TRUE + + # set PcdPciExpressBaseAddress to MAX_UINT64, which signifies that this + # PCD and PcdPciDisableBusEnumeration above have not been assigned yet + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xFFFFFFFFFFFFFFFF + + gEfiMdePkgTokenSpaceGuid.PcdPciIoTranslation|0x0 + + # + # Set video resolution for boot options and for text setup. + # PlatformDxe can set the former at runtime. + # + gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution|1280 + gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution|800 + gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution|640 + gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution|480 + gEfiMdeModulePkgTokenSpaceGuid.PcdConOutRow|0 + gEfiMdeModulePkgTokenSpaceGuid.PcdConOutColumn|0 + + # + # SMBIOS entry point version + # + gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0300 + gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0 + gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE + + gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0 + + # + # IPv4 and IPv6 PXE Boot support. + # + gEfiNetworkPkgTokenSpaceGuid.PcdIPv4PXESupport|0x01 + gEfiNetworkPkgTokenSpaceGuid.PcdIPv6PXESupport|0x01 + + # + # TPM2 support + # +!if $(TPM2_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 + gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} + gEfiSecurityPkgTokenSpaceGuid.PcdTpm2HashMask|0 +!else +[PcdsPatchableInModule] + # make this PCD patchable instead of dynamic when TPM support is not enabled + # this permits setting the PCD in unreachable code without pulling in dynamic PCD support + gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress|0x0 +!endif + +[PcdsDynamicHii] + gUefiOvmfPkgTokenSpaceGuid.PcdForceNoAcpi|L"ForceNoAcpi"|gOvmfVariableGuid|0x0|FALSE|NV,BS + +!if $(TPM2_CONFIG_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS + gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS +!endif + + gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|L"Timeout"|gEfiGlobalVariableGuid|0x0|5 + +[LibraryClasses.common.PEI_CORE, LibraryClasses.common.PEIM] +!if $(TPM2_ENABLE) == TRUE + PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf +!else + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf +!endif + +################################################################################ +# +# Components Section - list of all EDK II Modules needed by this Platform. +# +################################################################################ +[Components] + + # + # SEC Phase modules + # + OvmfPkg/RiscVVirt/Sec/SecMain.inf { + + ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf + LzmaDecompressLib|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf + PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf + HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf + PrePiHobListPointerLib|OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointerLib.inf + MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf + } + + # + # DXE + # + MdeModulePkg/Core/Dxe/DxeMain.inf { + + NULL|MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + } + + MdeModulePkg/Universal/PCD/Dxe/Pcd.inf { + + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + } + + # + # Architectural Protocols + # + UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf + MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf { + + NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf + # don't use unaligned CopyMem () on the UEFI varstore NOR flash region + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + } + +!if $(SECURE_BOOT_ENABLE) == TRUE + MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf { + + NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf +!if $(TPM2_ENABLE) == TRUE + NULL|SecurityPkg/Library/DxeTpm2MeasureBootLib/DxeTpm2MeasureBootLib.inf +!endif + } + SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf + OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.inf +!else + MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf +!endif + MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf + MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf + MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf + EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf + EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf + + MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf + MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf + MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf + MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf + MdeModulePkg/Universal/SerialDxe/SerialDxe.inf + + MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf + + UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf + OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf + MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf + + # + # Status Code Routing + # + MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf + MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf + + # + # Platform Driver + # + OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.inf + EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.inf { + + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + } + OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf + OvmfPkg/VirtioBlkDxe/VirtioBlk.inf + OvmfPkg/VirtioScsiDxe/VirtioScsi.inf + OvmfPkg/VirtioNetDxe/VirtioNet.inf + OvmfPkg/VirtioRngDxe/VirtioRng.inf + + # + # FAT filesystem + GPT/MBR partitioning + UDF filesystem + virtio-fs + # + MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf + MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf + MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf + FatPkg/EnhancedFatDxe/Fat.inf + MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf + OvmfPkg/VirtioFsDxe/VirtioFsDxe.inf + + # + # Bds + # + MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf { + + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + } + MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf + MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf + MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf + MdeModulePkg/Universal/BdsDxe/BdsDxe.inf + MdeModulePkg/Logo/LogoDxe.inf + MdeModulePkg/Application/UiApp/UiApp.inf { + + NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf + NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf + NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf + } + OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf { + + NULL|OvmfPkg/Library/BlobVerifierLibNull/BlobVerifierLibNull.inf + } + + # + # Networking stack + # +!include NetworkPkg/NetworkComponents.dsc.inc + + NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf { + + NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf + } + +!if $(NETWORK_TLS_ENABLE) == TRUE + NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf { + + NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf + } +!endif + + # + # SCSI Bus and Disk Driver + # + MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf + MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf + + # + # NVME Driver + # + MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf + + # + # SMBIOS Support + # + MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf { + + NULL|OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.inf + } + OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf + + # + # PCI support + # + OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf { + + NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf + } + MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf + MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf { + + NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf + } + OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf + OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf + OvmfPkg/Virtio10Dxe/Virtio10.inf + + # + # Video support + # + OvmfPkg/QemuRamfbDxe/QemuRamfbDxe.inf + OvmfPkg/VirtioGpuDxe/VirtioGpu.inf + OvmfPkg/PlatformDxe/Platform.inf + + # + # USB Support + # + MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf + MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf + MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf + MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf + MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf + MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf + + # + # TPM2 support + # +!if $(TPM2_ENABLE) == TRUE + SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf { + + HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterDxe.inf + Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibRouter/Tpm2DeviceLibRouterDxe.inf + NULL|SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2InstanceLibDTpm.inf + NULL|SecurityPkg/Library/HashInstanceLibSha1/HashInstanceLibSha1.inf + NULL|SecurityPkg/Library/HashInstanceLibSha256/HashInstanceLibSha256.inf + NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf + NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf + NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf + } +!if $(TPM2_CONFIG_ENABLE) == TRUE + SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf +!endif +!endif + + # + # ACPI Support + # + OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf + MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf + OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf { + + NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf + } diff --git a/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf b/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf new file mode 100644 index 0000000000..6072c37af0 --- /dev/null +++ b/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf @@ -0,0 +1,306 @@ +# @file +# Flash definition file on RiscVVirt RISC-V platform +# +# Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# Platform definitions +# + +!include RiscVVirt.fdf.inc + +################################################################################ +[FD.RISCV_VIRT] +BaseAddress = $(FW_BASE_ADDRESS)|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress +Size = $(FW_SIZE)|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFirmwareFdSize +ErasePolarity = 1 +BlockSize = $(BLOCK_SIZE) +NumBlocks = $(FW_BLOCKS) + +0x00000000|$(CODE_SIZE) +gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize +FV = FVMAIN_COMPACT + +!include VarStore.fdf.inc +################################################################################ + +[FV.DXEFV] +BlockSize = 0x10000 +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE + +# +# DXE Phase modules +# +INF MdeModulePkg/Core/Dxe/DxeMain.inf +INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf +INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf +INF OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.inf +INF EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.inf +INF OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf + +# +# PI DXE Drivers producing Architectural Protocols (EFI Services) +# +INF UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf +INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf +INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf +INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf +INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf +INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf +!if $(SECURE_BOOT_ENABLE) == TRUE + INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf +!endif +INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf +INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf +INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf +INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf +INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf + +# +# Multiple Console IO support +# +INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf +INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf +INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf +INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf +INF MdeModulePkg/Universal/SerialDxe/SerialDxe.inf + +# RISC-V Core Drivers +INF UefiCpuPkg/CpuTimerDxeRiscV64/CpuTimerDxeRiscV64.inf +INF OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.inf +INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf + +# +# FAT filesystem + GPT/MBR partitioning + UDF filesystem + virtio-fs +# +INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf +INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf +INF FatPkg/EnhancedFatDxe/Fat.inf +INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf +INF MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf +INF OvmfPkg/VirtioFsDxe/VirtioFsDxe.inf + +# +# Status Code Routing +# +INF MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf +INF MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf + +# +# Platform Driver +# +INF OvmfPkg/VirtioBlkDxe/VirtioBlk.inf +INF OvmfPkg/VirtioNetDxe/VirtioNet.inf +INF OvmfPkg/VirtioScsiDxe/VirtioScsi.inf +INF OvmfPkg/VirtioRngDxe/VirtioRng.inf + +INF ShellPkg/Application/Shell/Shell.inf +INF ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf +INF ShellPkg/DynamicCommand/HttpDynamicCommand/HttpDynamicCommand.inf +INF OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf + +# +# Bds +# +INF MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf +INF MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf +INF MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf +INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf +INF MdeModulePkg/Application/UiApp/UiApp.inf +INF OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf + +# +# Networking stack +# +!include NetworkPkg/Network.fdf.inc + +# +# SCSI Bus and Disk Driver +# +INF MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf +INF MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf + +# +# NVME Driver +# +INF MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf + +# +# SMBIOS Support +# +INF MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf +INF OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf + +# +# ACPI Support +# +INF OvmfPkg/PlatformHasAcpiDtDxe/PlatformHasAcpiDtDxe.inf +INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf +INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf +INF OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf + +# +# PCI support +# +INF OvmfPkg/RiscVVirt/PciCpuIo2Dxe/PciCpuIo2Dxe.inf +INF MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf +INF MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf +INF OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf +INF OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf +INF OvmfPkg/Virtio10Dxe/Virtio10.inf + +# +# Video support +# +INF OvmfPkg/QemuRamfbDxe/QemuRamfbDxe.inf +INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf +INF OvmfPkg/PlatformDxe/Platform.inf + +# +# Usb Support +# +INF MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf +INF MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf +INF MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf +INF MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf +INF MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf +INF MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf + +# +# TianoCore logo (splash screen) +# +INF MdeModulePkg/Logo/LogoDxe.inf + +# +# Ramdisk support +# +INF MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf + +#INF MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf + +################################################################################ + +[FV.FVMAIN_COMPACT] +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE +FvNameGuid = 27A72E80-3118-4c0c-8673-AA5B4EFA9613 + +INF OvmfPkg/RiscVVirt/Sec/SecMain.inf + +FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { + SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE { + SECTION FV_IMAGE = DXEFV + } + } + +[Rule.Common.SEC] + FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED { + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING ="$(MODULE_NAME)" Optional + VERSION STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.PEI_CORE] + FILE PEI_CORE = $(NAMED_GUID) { + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING ="$(MODULE_NAME)" Optional + VERSION STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.PEIM] + FILE PEIM = $(NAMED_GUID) { + PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.DXE_CORE] + FILE DXE_CORE = $(NAMED_GUID) { + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.DXE_DRIVER] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.DXE_RUNTIME_DRIVER] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 Align = 4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.UEFI_DRIVER] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.UEFI_DRIVER.BINARY] + FILE DRIVER = $(NAMED_GUID) { + DXE_DEPEX DXE_DEPEX Optional |.depex + PE32 PE32 Align=4K |.efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.UEFI_APPLICATION] + FILE APPLICATION = $(NAMED_GUID) { + PE32 PE32 Align=4K $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.UEFI_APPLICATION.BINARY] + FILE APPLICATION = $(NAMED_GUID) { + PE32 PE32 Align=4K |.efi + UI STRING="$(MODULE_NAME)" Optional + VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) + } + +[Rule.Common.USER_DEFINED.ACPITABLE] + FILE FREEFORM = $(NAMED_GUID) { + RAW ACPI |.acpi + RAW ASL |.aml + } diff --git a/OvmfPkg/RiscVVirt/VarStore.fdf.inc b/OvmfPkg/RiscVVirt/VarStore.fdf.inc new file mode 100644 index 0000000000..30b170d779 --- /dev/null +++ b/OvmfPkg/RiscVVirt/VarStore.fdf.inc @@ -0,0 +1,79 @@ +## @file +# FDF include file with Layout Regions that define an empty variable store. +# +# Copyright (c) 2022, Ventana Micro Systems Inc. All rights reserved.
+# Copyright (c) 2021, Hewlett Packard Enterprise Development LP. All rights reserved.
+# Copyright (C) 2014, Red Hat, Inc. +# Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +$(VARS_OFFSET)|$(VARS_LIVE_SIZE) +gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize +# +# NV_VARIABLE_STORE +# +DATA = { + ## This is the EFI_FIRMWARE_VOLUME_HEADER + # ZeroVector [] + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + # FileSystemGuid: gEfiSystemNvDataFvGuid = + # { 0xFFF12B8D, 0x7696, 0x4C8B, + # { 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50 }} + 0x8D, 0x2B, 0xF1, 0xFF, 0x96, 0x76, 0x8B, 0x4C, + 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50, + # FvLength: 0x20000 + 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + # Signature "_FVH" # Attributes + 0x5f, 0x46, 0x56, 0x48, 0xff, 0xfe, 0x04, 0x00, + # HeaderLength # CheckSum # ExtHeaderOffset #Reserved #Revision + 0x48, 0x00, 0x39, 0xF1, 0x00, 0x00, 0x00, 0x02, + # Blockmap[0]: 0x20 Blocks * 0x1000 Bytes / Block + 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, + # Blockmap[1]: End + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ## This is the VARIABLE_STORE_HEADER +!if $(SECURE_BOOT_ENABLE) == TRUE + # Signature: gEfiAuthenticatedVariableGuid = + # { 0xaaf32c78, 0x947b, 0x439a, + # { 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92 }} + 0x78, 0x2c, 0xf3, 0xaa, 0x7b, 0x94, 0x9a, 0x43, + 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92, +!else + # Signature: gEfiVariableGuid = + # { 0xddcf3616, 0x3275, 0x4164, + # { 0x98, 0xb6, 0xfe, 0x85, 0x70, 0x7f, 0xfe, 0x7d }} + 0x16, 0x36, 0xcf, 0xdd, 0x75, 0x32, 0x64, 0x41, + 0x98, 0xb6, 0xfe, 0x85, 0x70, 0x7f, 0xfe, 0x7d, +!endif + # Size: 0x40000 (gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize) - + # 0x48 (size of EFI_FIRMWARE_VOLUME_HEADER) = 0x3FFB8 + # This can speed up the Variable Dispatch a bit. + 0xB8, 0xFF, 0x03, 0x00, + # FORMATTED: 0x5A #HEALTHY: 0xFE #Reserved: UINT16 #Reserved1: UINT32 + 0x5A, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +} + +$(VARS_FTW_WORKING_OFFSET)|$(VARS_FTW_WORKING_SIZE) +gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize +# +#NV_FTW_WROK +# +DATA = { + # EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER->Signature = gEdkiiWorkingBlockSignatureGuid = + # { 0x9e58292b, 0x7c68, 0x497d, { 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95 }} + 0x2b, 0x29, 0x58, 0x9e, 0x68, 0x7c, 0x7d, 0x49, + 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95, + # Crc:UINT32 #WorkingBlockValid:1, WorkingBlockInvalid:1, Reserved + 0x2c, 0xaf, 0x2c, 0x64, 0xFE, 0xFF, 0xFF, 0xFF, + # WriteQueueSize: UINT64 + 0xE0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +} + +$(VARS_FTW_SPARE_OFFSET)|$(VARS_FTW_SPARE_SIZE) +gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize +# +#NV_FTW_SPARE From 436a0b58191a3a8b585ef73f47d7e278441bd70b Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 28 Jan 2023 23:40:51 +0530 Subject: [PATCH 0631/1529] Maintainers.txt: Add entry for OvmfPkg/RiscVVirt REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4076 RiscVVirt is created to support EDK2 for RISC-V qemu virt machine platform. Add maintainer entries. Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Signed-off-by: Sunil V L Reviewed-by: Andrei Warkentin Reviewed-by: Jiewen Yao Reviewed-by: Michael D Kinney Acked-by: Ard Biesheuvel --- Maintainers.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Maintainers.txt b/Maintainers.txt index 4aa7973d51..d22224607a 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -544,6 +544,11 @@ F: OvmfPkg/XenResetVector/ R: Anthony Perard [tperard] R: Julien Grall [jgrall] +OvmfPkg: RISC-V Qemu Virt Platform +F: OvmfPkg/RiscVVirt +R: Sunil V L [vlsunil] +R: Andrei Warkentin [andreiw] + PcAtChipsetPkg F: PcAtChipsetPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/PcAtChipsetPkg From a433ecf0ecc139e87ec51b0fba4323a68b478108 Mon Sep 17 00:00:00 2001 From: Joey Vagedes Date: Thu, 16 Feb 2023 05:54:16 +0000 Subject: [PATCH 0632/1529] BaseTools: Update WindowsVsToolChain plugin This patch updates edk2-pytool-library dependency to v0.14.0, which has an interface change to FindWithVsWhere. The BaseTools plugin uses this function, so it is being updated to account for the interface change. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Michael D Kinney Signed-off-by: Joey Vagedes Acked-by: Michael Kubacki Reviewed-by: Liming Gao --- .../WindowsVsToolChain/WindowsVsToolChain.py | 16 ++++++++++++---- pip-requirements.txt | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py index 0fba2c1b53..615b5ed6d1 100644 --- a/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py +++ b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py @@ -177,15 +177,23 @@ def do_pre_build(self, thebuilder): def _get_vs_install_path(self, vs_version, varname): # check if already specified - path = shell_environment.GetEnvironment().get_shell_var(varname) + path = None + if varname is not None: + path = shell_environment.GetEnvironment().get_shell_var(varname) + if(path is None): # Not specified...find latest - (rc, path) = FindWithVsWhere(vs_version=vs_version) - if rc == 0 and path is not None and os.path.exists(path): + try: + path = FindWithVsWhere(vs_version=vs_version) + except (EnvironmentError, ValueError, RuntimeError) as e: + self.Logger.error(str(e)) + return None + + if path is not None and os.path.exists(path): self.Logger.debug("Found VS instance for %s", vs_version) else: self.Logger.error( - "Failed to find VS instance with VsWhere (%d)" % rc) + f"VsWhere successfully executed, but could not find VS instance for {vs_version}.") return path def _get_vc_version(self, path, varname): diff --git a/pip-requirements.txt b/pip-requirements.txt index 4ffcadddd8..3c3bf921dd 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -12,8 +12,8 @@ # https://www.python.org/dev/peps/pep-0440/#version-specifiers ## -edk2-pytool-library==0.12.1 -edk2-pytool-extensions~=0.20.0 +edk2-pytool-library==0.14.0 +edk2-pytool-extensions~=0.21.8 edk2-basetools==0.1.39 antlr4-python3-runtime==4.7.1 lcov-cobertura==2.0.2 From f7de5c4bea9ebd51c35baf285619a91d8d744ad8 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 22 Feb 2023 10:37:10 +0800 Subject: [PATCH 0633/1529] BaseTools/tools_def.template: Update -march parameter for RISC-V Replace rv64imafdc with rv64gc so that it works for gcc 12. "g" means imafd in gcc < 12 and imafd_zifencei_zicsr in gcc >= 12. So, replacing rv64imafdc with rv64gc will work for both gcc <12 and gcc >=12. Cc: Bob Feng Cc: Liming Gao Cc: Yuwei Chen Cc: Andrei Warkentin Cc: Heinrich Schuchardt Signed-off-by: Sunil V L Tested-by: Gerd Hoffmann Tested-by: Heinrich Schuchardt Reviewed-by: Liming Gao --- BaseTools/Conf/tools_def.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index f77e936c04..471eb67c0c 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -1965,7 +1965,7 @@ DEFINE GCC5_RISCV_ALL_CC_FLAGS_WARNING_DISABLE = -Wno-tautological-compare -W DEFINE GCC5_RISCV_OPENSBI_TYPES = -DOPENSBI_EXTERNAL_SBI_TYPES=OpensbiTypes.h -DEFINE GCC5_RISCV64_ARCH = rv64imafdc +DEFINE GCC5_RISCV64_ARCH = rv64gc DEFINE GCC5_RISCV32_RISCV64_ASLDLINK_FLAGS = DEF(GCC5_RISCV_ALL_DLINK_COMMON) -Wl,--entry,ReferenceAcpiTable -u ReferenceAcpiTable DEFINE GCC5_RISCV64_CC_FLAGS = DEF(GCC5_RISCV_ALL_CC_FLAGS) DEF(GCC5_RISCV_ALL_CC_FLAGS_WARNING_DISABLE) DEF(GCC5_RISCV_OPENSBI_TYPES) -march=DEF(GCC5_RISCV64_ARCH) -fno-builtin -fno-builtin-memcpy -fno-stack-protector -Wno-address -fno-asynchronous-unwind-tables -Wno-unused-but-set-variable -fpack-struct=8 -mcmodel=medany -mabi=lp64 -mno-relax DEFINE GCC5_RISCV64_DLINK_FLAGS = DEF(GCC5_RISCV_ALL_DLINK_FLAGS) -Wl,-melf64lriscv,--oformat=elf64-littleriscv,--no-relax From f325bcc8bff0ec9eb1c55a54b5700353ebbda5fc Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 22 Feb 2023 10:36:59 +0800 Subject: [PATCH 0634/1529] OvmfPkg/RiscVVirt: Fix SCT memory allocation test case failure Fix the UEFI memory range calculation by including the correct stack memory range. Without this fix, SCT hangs in MemoryAllocation test cases which call AllocateAddress(). Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: Andrei Warkentin Reported-by: Heinrich Schuchardt Signed-off-by: Sunil V L Reviewed-by: Andrei Warkentin --- OvmfPkg/RiscVVirt/Sec/SecMain.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.c b/OvmfPkg/RiscVVirt/Sec/SecMain.c index 054e49ef0c..73b9b21a67 100644 --- a/OvmfPkg/RiscVVirt/Sec/SecMain.c +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.c @@ -71,8 +71,9 @@ SecStartup ( FirmwareContext.FlattenedDeviceTree = (UINT64)DeviceTreeAddress; SetFirmwareContextPointer (&FirmwareContext); - StackBase = (UINT64)FixedPcdGet32 (PcdOvmfSecPeiTempRamBase); - UefiMemoryBase = StackBase + FixedPcdGet32 (PcdOvmfSecPeiTempRamSize) - SIZE_32MB; + StackBase = (UINT64)FixedPcdGet32 (PcdOvmfSecPeiTempRamBase) + + FixedPcdGet32 (PcdOvmfSecPeiTempRamSize); + UefiMemoryBase = StackBase - SIZE_32MB; // Declare the PI/UEFI memory region HobList = HobConstructor ( From 7441e30c6b09f5f653ce2145770c19d724de9e59 Mon Sep 17 00:00:00 2001 From: MarsX Lin Date: Tue, 3 Jan 2023 14:55:20 +0800 Subject: [PATCH 0635/1529] UefiPayloadPkg: remove the change that get platform specific logic REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4241 Since UefiPayloadPkg had supported multiple firmware volume, remove the platform specific logic via protocol Cc: Ray Ni Cc: Sean Rhodes Cc: Gua Guo Reviewed-by: James Lu Reviewed-by: Guo Dong Signed-off-by: MarsX Lin --- .../Protocol/PlatformBootManagerOverride.h | 84 ------------------- .../PlatformBootManager.c | 27 ------ .../PlatformBootManagerLib.inf | 1 - UefiPayloadPkg/UefiPayloadPkg.dec | 2 - 4 files changed, 114 deletions(-) delete mode 100644 UefiPayloadPkg/Include/Protocol/PlatformBootManagerOverride.h diff --git a/UefiPayloadPkg/Include/Protocol/PlatformBootManagerOverride.h b/UefiPayloadPkg/Include/Protocol/PlatformBootManagerOverride.h deleted file mode 100644 index 878ddc044b..0000000000 --- a/UefiPayloadPkg/Include/Protocol/PlatformBootManagerOverride.h +++ /dev/null @@ -1,84 +0,0 @@ -/** @file - This file defines the Univeral Payload Platform BootManager Protocol. - - Copyright (c) 2021, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent -**/ - -#ifndef __PLATFORM_BOOT_MANAGER_OVERRIDE_H__ -#define __PLATFORM_BOOT_MANAGER_OVERRIDE_H__ - -/** - Do the platform specific action before the console is connected. - - Such as: - Update console variable; - Register new Driver#### or Boot####; - Signal ReadyToLock event. - - This function will override the default behavior in PlatformBootManagerLib -**/ -typedef -VOID -(EFIAPI *UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_BEFORE_CONSOLE)( - VOID - ); - -/** - Do the platform specific action after the console is connected. - - Such as: - Dynamically switch output mode; - Signal console ready platform customized event; - Run diagnostics like memory testing; - Connect certain devices; - Dispatch aditional option roms. - - This function will override the default behavior in PlatformBootManagerLib -**/ -typedef -VOID -(EFIAPI *UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_AFTER_CONSOLE)( - VOID - ); - -/** - This function is called each second during the boot manager waits the timeout. - This function will override the default behavior in PlatformBootManagerLib - - @param TimeoutRemain The remaining timeout. -**/ -typedef -VOID -(EFIAPI *UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_WAIT_CALLBACK)( - UINT16 TimeoutRemain - ); - -/** - 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. - This function will override the default behavior in PlatformBootManagerLib -**/ -typedef -VOID -(EFIAPI *UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_UNABLE_TO_BOOT)( - VOID - ); - -/// -/// Provides an interface to override the default behavior in PlatformBootManagerLib, -/// so platform can provide its own platform specific logic through this protocol -/// -typedef struct { - UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_BEFORE_CONSOLE BeforeConsole; - UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_AFTER_CONSOLE AfterConsole; - UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_WAIT_CALLBACK WaitCallback; - UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_UNABLE_TO_BOOT UnableToBoot; -} UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_PROTOCOL; - -extern GUID gUniversalPayloadPlatformBootManagerOverrideProtocolGuid; - -#endif diff --git a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManager.c b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManager.c index a92a260a6e..62637ae6aa 100644 --- a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManager.c +++ b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManager.c @@ -9,12 +9,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PlatformBootManager.h" #include "PlatformConsole.h" -#include #include #include -UNIVERSAL_PAYLOAD_PLATFORM_BOOT_MANAGER_OVERRIDE_PROTOCOL *mUniversalPayloadPlatformBootManagerOverrideInstance = NULL; - /** Signal EndOfDxe event and install SMM Ready to lock protocol. @@ -167,17 +164,6 @@ PlatformBootManagerBeforeConsole ( EFI_INPUT_KEY CustomKey; EFI_INPUT_KEY Down; EFI_BOOT_MANAGER_LOAD_OPTION BootOption; - EFI_STATUS Status; - - Status = gBS->LocateProtocol (&gUniversalPayloadPlatformBootManagerOverrideProtocolGuid, NULL, (VOID **)&mUniversalPayloadPlatformBootManagerOverrideInstance); - if (EFI_ERROR (Status)) { - mUniversalPayloadPlatformBootManagerOverrideInstance = NULL; - } - - if (mUniversalPayloadPlatformBootManagerOverrideInstance != NULL) { - mUniversalPayloadPlatformBootManagerOverrideInstance->BeforeConsole (); - return; - } // // Register ENTER as CONTINUE key @@ -246,11 +232,6 @@ PlatformBootManagerAfterConsole ( EDKII_PLATFORM_LOGO_PROTOCOL *PlatformLogo; EFI_STATUS Status; - if (mUniversalPayloadPlatformBootManagerOverrideInstance != NULL) { - mUniversalPayloadPlatformBootManagerOverrideInstance->AfterConsole (); - return; - } - Black.Blue = Black.Green = Black.Red = Black.Reserved = 0; White.Blue = White.Green = White.Red = White.Reserved = 0xFF; @@ -297,10 +278,6 @@ PlatformBootManagerWaitCallback ( UINT16 TimeoutRemain ) { - if (mUniversalPayloadPlatformBootManagerOverrideInstance != NULL) { - mUniversalPayloadPlatformBootManagerOverrideInstance->WaitCallback (TimeoutRemain); - } - return; } @@ -317,10 +294,6 @@ PlatformBootManagerUnableToBoot ( VOID ) { - if (mUniversalPayloadPlatformBootManagerOverrideInstance != NULL) { - mUniversalPayloadPlatformBootManagerOverrideInstance->UnableToBoot (); - } - return; } diff --git a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf index 7ec93420f2..f9626175e2 100644 --- a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf +++ b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf @@ -60,7 +60,6 @@ gEfiBootLogoProtocolGuid ## CONSUMES gEfiDxeSmmReadyToLockProtocolGuid gEfiSmmAccess2ProtocolGuid - gUniversalPayloadPlatformBootManagerOverrideProtocolGuid gEfiSerialIoProtocolGuid gEfiPciRootBridgeIoProtocolGuid diff --git a/UefiPayloadPkg/UefiPayloadPkg.dec b/UefiPayloadPkg/UefiPayloadPkg.dec index 1ccfc32548..7d61d6eeae 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dec +++ b/UefiPayloadPkg/UefiPayloadPkg.dec @@ -52,8 +52,6 @@ # gPlatformGOPPolicyGuid = { 0xec2e931b, 0x3281, 0x48a5, { 0x81, 0x07, 0xdf, 0x8a, 0x8b, 0xed, 0x3c, 0x5d } } - gUniversalPayloadPlatformBootManagerOverrideProtocolGuid = { 0xdb3fc2df, 0x7376, 0x4a8d, { 0x82, 0xab, 0x91, 0x54, 0xa1, 0x36, 0xa6, 0x5a } } - ################################################################################ # # PCD Declarations section - list of all PCDs Declared by this Package From 51973ed93e8cde91abff28e99743e981090eb203 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 25 Feb 2023 13:32:00 +0800 Subject: [PATCH 0636/1529] OvmfPkg/RiscVVirt: Add Stack HOB REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4350 Currently, stack HOB is not created for the stack memory. This causes stack memory to be treated as free memory and any memory allocation which happens at this address causes random memory corruption. Fix this by creating the stack HOB which marks the memory as BS data. Cc: Liming Gao Cc: Andrei Warkentin Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Reported-by: Andrei Warkentin Tested-by: Andrei Warkentin Reviewed-by: Andrei Warkentin --- OvmfPkg/RiscVVirt/Sec/SecMain.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.c b/OvmfPkg/RiscVVirt/Sec/SecMain.c index 73b9b21a67..adf73f2eb6 100644 --- a/OvmfPkg/RiscVVirt/Sec/SecMain.c +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.c @@ -55,6 +55,7 @@ SecStartup ( EFI_STATUS Status; UINT64 UefiMemoryBase; UINT64 StackBase; + UINT32 StackSize; // // Report Status Code to indicate entering SEC core @@ -71,9 +72,9 @@ SecStartup ( FirmwareContext.FlattenedDeviceTree = (UINT64)DeviceTreeAddress; SetFirmwareContextPointer (&FirmwareContext); - StackBase = (UINT64)FixedPcdGet32 (PcdOvmfSecPeiTempRamBase) + - FixedPcdGet32 (PcdOvmfSecPeiTempRamSize); - UefiMemoryBase = StackBase - SIZE_32MB; + StackBase = (UINT64)FixedPcdGet32 (PcdOvmfSecPeiTempRamBase); + StackSize = FixedPcdGet32 (PcdOvmfSecPeiTempRamSize); + UefiMemoryBase = StackBase + StackSize - SIZE_32MB; // Declare the PI/UEFI memory region HobList = HobConstructor ( @@ -86,6 +87,8 @@ SecStartup ( SecInitializePlatform (); + BuildStackHob (StackBase, StackSize); + // // Process all libraries constructor function linked to SecMain. // From be2d2a6c71e4a78d086b5d08cafee0b5ee327d3c Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Fri, 2 Dec 2022 05:49:35 +0800 Subject: [PATCH 0637/1529] ShellPkg: Improve "ping" output by adding equals sign after time The output of the "ping" command shows the time without a space between the label and the value. e.g.: 20 bytes from 192.168.0.1 : icmp_seq=1 ttl=1 time1~2ms Improve the readability and consistency by adding an equals sign for the time value: 20 bytes from 192.168.0.1 : icmp_seq=1 ttl=1 time=1~2ms Signed-off-by: Rebecca Cran Reviewed-by: Zhichao Gao --- .../UefiShellNetwork1CommandsLib.uni | 2 +- .../UefiShellNetwork2CommandsLib.uni | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.uni b/ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.uni index 73cf96d9e6..37fd4a1192 100644 --- a/ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.uni +++ b/ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.uni @@ -52,7 +52,7 @@ #string STR_PING_NOROUTE_FOUND #language en-US "There is no route to the destination '%B%s%N' from the source '%B%s%N' was found.\r\n" #string STR_PING_START #language en-US "Ping %s %d data bytes.\r\n" #string STR_PING_TIMEOUT #language en-US "Echo request sequence %d timeout.\r\n" -#string STR_PING_REPLY_INFO #language en-US "%d bytes from %s : icmp_seq=%d ttl=%d time%d~%dms\r\n" +#string STR_PING_REPLY_INFO #language en-US "%d bytes from %s : icmp_seq=%d ttl=%d time=%d~%dms\r\n" #string STR_PING_STAT #language en-US "\n%d packets transmitted, %d received, %d%% packet loss, time %dms\r\n" #string STR_PING_RTT #language en-US "\nRtt(round trip time) min=%d~%dms max=%d~%dms avg=%d~%dms\r\n" diff --git a/ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.uni b/ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.uni index 30913ae5b5..cb9d39a33f 100644 --- a/ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.uni +++ b/ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.uni @@ -33,7 +33,7 @@ #string STR_PING6_NOSOURCE_INDOMAIN #language en-US "No sources in %s's multicast domain.\r\n" #string STR_PING6_START #language en-US "Ping %s %d data bytes\r\n" #string STR_PING6_TIMEOUT #language en-US "Echo request sequence %d timeout.\r\n" -#string STR_PING6_REPLY_INFO #language en-US "%d bytes from %s : icmp_seq=%d ttl=%d time%d~%dms\r\n" +#string STR_PING6_REPLY_INFO #language en-US "%d bytes from %s : icmp_seq=%d ttl=%d time=%d~%dms\r\n" #string STR_PING6_STAT #language en-US "\n%d packets transmitted, %d received, %d%% packet loss, time %dms\r\n" #string STR_PING6_RTT #language en-US "\nRtt(round trip time) min=%d~%dms max=%d~%dms avg=%d~%dms\r\n" From 31f8b0dc3a37002719618c02e66e1476e19a07b9 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Wed, 1 Mar 2023 16:44:57 +0800 Subject: [PATCH 0638/1529] RedfishPkg/RedfishDebugLib: provide Redfish debug Introduce RedfishDebugLib to RedfishPkg. This library provides several debugging functions for Redfish application. Redfish drivers rely on Rest Ex protocol to communicate with BMC and the communication data may be big and complicated. Use RedfishDebugLib in RedfishRestExDxe to simplify debugging process. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang --- RedfishPkg/Include/Library/RedfishDebugLib.h | 90 +++++++ .../Library/RedfishDebugLib/RedfishDebugLib.c | 229 ++++++++++++++++++ .../RedfishDebugLib/RedfishDebugLib.inf | 39 +++ RedfishPkg/RedfishLibs.dsc.inc | 2 + RedfishPkg/RedfishPkg.dec | 5 + RedfishPkg/RedfishPkg.dsc | 1 + .../RedfishRestExDxe/RedfishRestExDxe.inf | 2 + .../RedfishRestExDxe/RedfishRestExInternal.h | 2 + .../RedfishRestExDxe/RedfishRestExProtocol.c | 32 +-- 9 files changed, 387 insertions(+), 15 deletions(-) create mode 100644 RedfishPkg/Include/Library/RedfishDebugLib.h create mode 100644 RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c create mode 100644 RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf diff --git a/RedfishPkg/Include/Library/RedfishDebugLib.h b/RedfishPkg/Include/Library/RedfishDebugLib.h new file mode 100644 index 0000000000..21f01353ed --- /dev/null +++ b/RedfishPkg/Include/Library/RedfishDebugLib.h @@ -0,0 +1,90 @@ +/** @file + This file defines the Redfish debug library interface. + + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef REDFISH_DEBUG_LIB_H_ +#define REDFISH_DEBUG_LIB_H_ + +#include +#include +#include + +#define DEBUG_REDFISH_NETWORK DEBUG_INFO ///< Debug error level for Redfish networking function + +/** + + This function dump the Json string in given error level. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] JsonValue Json value to dump. + + @retval EFI_SUCCESS Json string is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpJsonValue ( + IN UINTN ErrorLevel, + IN EDKII_JSON_VALUE JsonValue + ); + +/** + + This function dump the status code, header and body in given + Redfish payload. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] Payload Redfish payload to dump + + @retval EFI_SUCCESS Redfish payload is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpRedfishPayload ( + IN UINTN ErrorLevel, + IN REDFISH_PAYLOAD Payload + ); + +/** + + This function dump the status code, header and body in given + Redfish response. + + @param[in] Message Message string + @param[in] ErrorLevel DEBUG macro error level + @param[in] Response Redfish response to dump + + @retval EFI_SUCCESS Redfish response is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpRedfishResponse ( + IN CONST CHAR8 *Message, + IN UINTN ErrorLevel, + IN REDFISH_RESPONSE *Response + ); + +/** + + This function dump the HTTP status code. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] HttpStatusCode HTTP status code + + @retval EFI_SUCCESS HTTP status code is printed + +**/ +EFI_STATUS +DumpHttpStatusCode ( + IN UINTN ErrorLevel, + IN EFI_HTTP_STATUS_CODE HttpStatusCode + ); + +#endif diff --git a/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c new file mode 100644 index 0000000000..6f1d9de25e --- /dev/null +++ b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.c @@ -0,0 +1,229 @@ +/** @file + Redfish debug library to debug Redfish application. + + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +#include +#include +#include +#include +#include + +#ifndef IS_EMPTY_STRING +#define IS_EMPTY_STRING(a) ((a) == NULL || (a)[0] == '\0') +#endif + +#define REDFISH_JSON_STRING_LENGTH 200 +#define REDFISH_JSON_OUTPUT_FORMAT (EDKII_JSON_COMPACT | EDKII_JSON_INDENT(2)) + +/** + + This function dump the Json string in given error level. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] JsonValue Json value to dump. + + @retval EFI_SUCCESS Json string is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpJsonValue ( + IN UINTN ErrorLevel, + IN EDKII_JSON_VALUE JsonValue + ) +{ + CHAR8 *String; + CHAR8 *Runner; + CHAR8 Buffer[REDFISH_JSON_STRING_LENGTH + 1]; + UINTN StrLen; + UINTN Count; + UINTN Index; + + if (JsonValue == NULL) { + return EFI_INVALID_PARAMETER; + } + + String = JsonDumpString (JsonValue, REDFISH_JSON_OUTPUT_FORMAT); + if (String == NULL) { + return EFI_UNSUPPORTED; + } + + StrLen = AsciiStrLen (String); + if (StrLen == 0) { + return EFI_UNSUPPORTED; + } + + Count = StrLen / REDFISH_JSON_STRING_LENGTH; + Runner = String; + for (Index = 0; Index < Count; Index++) { + AsciiStrnCpyS (Buffer, (REDFISH_JSON_STRING_LENGTH + 1), Runner, REDFISH_JSON_STRING_LENGTH); + Buffer[REDFISH_JSON_STRING_LENGTH] = '\0'; + DEBUG ((ErrorLevel, "%a", Buffer)); + Runner += REDFISH_JSON_STRING_LENGTH; + } + + Count = StrLen % REDFISH_JSON_STRING_LENGTH; + if (Count > 0) { + DEBUG ((ErrorLevel, "%a", Runner)); + } + + DEBUG ((ErrorLevel, "\n")); + + FreePool (String); + return EFI_SUCCESS; +} + +/** + + This function dump the status code, header and body in given + Redfish payload. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] Payload Redfish payload to dump + + @retval EFI_SUCCESS Redfish payload is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpRedfishPayload ( + IN UINTN ErrorLevel, + IN REDFISH_PAYLOAD Payload + ) +{ + EDKII_JSON_VALUE JsonValue; + + if (Payload == NULL) { + return EFI_INVALID_PARAMETER; + } + + JsonValue = RedfishJsonInPayload (Payload); + if (JsonValue != NULL) { + DEBUG ((ErrorLevel, "Payload:\n")); + DumpJsonValue (ErrorLevel, JsonValue); + } + + return EFI_SUCCESS; +} + +/** + + This function dump the HTTP status code. + + @param[in] ErrorLevel DEBUG macro error level + @param[in] HttpStatusCode HTTP status code + + @retval EFI_SUCCESS HTTP status code is printed + +**/ +EFI_STATUS +DumpHttpStatusCode ( + IN UINTN ErrorLevel, + IN EFI_HTTP_STATUS_CODE HttpStatusCode + ) +{ + switch (HttpStatusCode) { + case HTTP_STATUS_100_CONTINUE: + DEBUG ((ErrorLevel, "Status code: 100 CONTINUE\n")); + break; + case HTTP_STATUS_200_OK: + DEBUG ((ErrorLevel, "Status code: 200 OK\n")); + break; + case HTTP_STATUS_201_CREATED: + DEBUG ((ErrorLevel, "Status code: 201 CREATED\n")); + break; + case HTTP_STATUS_202_ACCEPTED: + DEBUG ((ErrorLevel, "Status code: 202 ACCEPTED\n")); + break; + case HTTP_STATUS_304_NOT_MODIFIED: + DEBUG ((ErrorLevel, "Status code: 304 NOT MODIFIED\n")); + break; + case HTTP_STATUS_400_BAD_REQUEST: + DEBUG ((ErrorLevel, "Status code: 400 BAD REQUEST\n")); + break; + case HTTP_STATUS_401_UNAUTHORIZED: + DEBUG ((ErrorLevel, "Status code: 401 UNAUTHORIZED\n")); + break; + case HTTP_STATUS_403_FORBIDDEN: + DEBUG ((ErrorLevel, "Status code: 403 FORBIDDEN\n")); + break; + case HTTP_STATUS_404_NOT_FOUND: + DEBUG ((ErrorLevel, "Status code: 404 NOT FOUND\n")); + break; + case HTTP_STATUS_405_METHOD_NOT_ALLOWED: + DEBUG ((ErrorLevel, "Status code: 405 METHOD NOT ALLOWED\n")); + break; + case HTTP_STATUS_500_INTERNAL_SERVER_ERROR: + DEBUG ((ErrorLevel, "Status code: 500 INTERNAL SERVER ERROR\n")); + break; + default: + DEBUG ((ErrorLevel, "Status code: 0x%x\n", HttpStatusCode)); + break; + } + + return EFI_SUCCESS; +} + +/** + + This function dump the status code, header and body in given + Redfish response. + + @param[in] Message Message string + @param[in] ErrorLevel DEBUG macro error level + @param[in] Response Redfish response to dump + + @retval EFI_SUCCESS Redfish response is printed. + @retval Others Errors occur. + +**/ +EFI_STATUS +DumpRedfishResponse ( + IN CONST CHAR8 *Message, + IN UINTN ErrorLevel, + IN REDFISH_RESPONSE *Response + ) +{ + UINTN Index; + + if (Response == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (!IS_EMPTY_STRING (Message)) { + DEBUG ((ErrorLevel, "%a\n", Message)); + } + + // + // status code + // + if (Response->StatusCode != NULL) { + DumpHttpStatusCode (ErrorLevel, *(Response->StatusCode)); + } + + // + // header + // + if (Response->HeaderCount > 0) { + DEBUG ((ErrorLevel, "Header: %d\n", Response->HeaderCount)); + for (Index = 0; Index < Response->HeaderCount; Index++) { + DEBUG ((ErrorLevel, " %a: %a\n", Response->Headers[Index].FieldName, Response->Headers[Index].FieldValue)); + } + } + + // + // Body + // + if (Response->Payload != NULL) { + DumpRedfishPayload (ErrorLevel, Response->Payload); + } + + return EFI_SUCCESS; +} diff --git a/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf new file mode 100644 index 0000000000..048d27c6dc --- /dev/null +++ b/RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf @@ -0,0 +1,39 @@ +## @file +# INF file for Redfish debug library. +# +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = RedfishDebugLib + FILE_GUID = 7F64C79F-ABD0-4446-86B5-2C1AE36168AD + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = RedfishDebugLib| DXE_DRIVER UEFI_DRIVER + +# +# VALID_ARCHITECTURES = IA32 X64 EBC +# + +[Sources] + RedfishDebugLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + RedfishPkg/RedfishPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + JsonLib + MemoryAllocationLib + RedfishLib + UefiLib + +[Depex] + TRUE diff --git a/RedfishPkg/RedfishLibs.dsc.inc b/RedfishPkg/RedfishLibs.dsc.inc index 56950b711f..84f52d4b27 100644 --- a/RedfishPkg/RedfishLibs.dsc.inc +++ b/RedfishPkg/RedfishLibs.dsc.inc @@ -6,6 +6,7 @@ # of EDKII network library classes. # # (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -17,5 +18,6 @@ RedfishCrtLib|RedfishPkg/PrivateLibrary/RedfishCrtLib/RedfishCrtLib.inf JsonLib|RedfishPkg/Library/JsonLib/JsonLib.inf RedfishLib|RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf + RedfishDebugLib|RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf !endif diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index 130e7ec260..53e52c2b00 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -4,6 +4,7 @@ # Copyright (c) 2019, Intel Corporation. All rights reserved.
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP
# Copyright (c) 2023, American Megatrends International LLC. +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -55,6 +56,10 @@ # RedfishContentCodingLib|Include/Library/RedfishContentCodingLib.h + ## @libraryclass Redfish Debug Library + # Library provides Redfish debug functions. + RedfishDebugLib|Include/Library/RedfishDebugLib.h + [LibraryClasses.Common.Private] ## @libraryclass Provides the private C runtime library functions. # CRT library is currently used by edk2 JsonLib (open source diff --git a/RedfishPkg/RedfishPkg.dsc b/RedfishPkg/RedfishPkg.dsc index 16139146ff..cf25b63cc2 100644 --- a/RedfishPkg/RedfishPkg.dsc +++ b/RedfishPkg/RedfishPkg.dsc @@ -58,5 +58,6 @@ RedfishPkg/PrivateLibrary/RedfishCrtLib/RedfishCrtLib.inf RedfishPkg/Library/JsonLib/JsonLib.inf RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf + RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf !include RedfishPkg/Redfish.dsc.inc diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf b/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf index 2f7a2188e8..64e6343bfb 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExDxe.inf @@ -4,6 +4,7 @@ # Copyright (c) 2019, Intel Corporation. All rights reserved.
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
# Copyright (c) 2023, American Megatrends International LLC. +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -44,6 +45,7 @@ PrintLib MemoryAllocationLib NetLib + RedfishDebugLib UefiLib UefiBootServicesTableLib UefiDriverEntryPoint diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExInternal.h b/RedfishPkg/RedfishRestExDxe/RedfishRestExInternal.h index a687c4ddb1..bca679e2cc 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExInternal.h +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExInternal.h @@ -3,6 +3,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -21,6 +22,7 @@ #include #include #include +#include #include #include #include diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c index 1c3deab09a..3722e1f795 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExProtocol.c @@ -4,6 +4,7 @@ Copyright (c) 2019, Intel Corporation. All rights reserved.
(C) Copyright 2020 Hewlett Packard Enterprise Development LP
Copyright (c) 2023, American Megatrends International LLC. + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -90,12 +91,12 @@ RedfishRestExSendReceive ( MediaPresent = TRUE; NetLibDetectMedia (Instance->Service->ControllerHandle, &MediaPresent); if (!MediaPresent) { - DEBUG ((DEBUG_INFO, "RedfishRestExSendReceive(): No MediaPresent.\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "RedfishRestExSendReceive(): No MediaPresent.\n")); return EFI_NO_MEDIA; } - DEBUG ((DEBUG_INFO, "\nRedfishRestExSendReceive():\n")); - DEBUG ((DEBUG_INFO, "*** Perform HTTP Request Method - %d, URL: %s\n", RequestMessage->Data.Request->Method, RequestMessage->Data.Request->Url)); + DEBUG ((DEBUG_REDFISH_NETWORK, "\nRedfishRestExSendReceive():\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "*** Perform HTTP Request Method - %d, URL: %s\n", RequestMessage->Data.Request->Method, RequestMessage->Data.Request->Url)); if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode)) { // @@ -215,7 +216,7 @@ ReSendRequest:; goto ON_EXIT; } - DEBUG ((DEBUG_INFO, "Receiving HTTP response and headers...\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "Receiving HTTP response and headers...\n")); Status = RedfishCheckHttpReceiveStatus ( Instance, HttpIoRecvResponse ( @@ -239,12 +240,12 @@ ReSendRequest:; RequestMessage->HeaderCount--; // Minus one header count for "Expect". } - DEBUG ((DEBUG_INFO, "HTTP Response StatusCode - %d:", ResponseData->Response.StatusCode)); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP Response StatusCode - %d:", ResponseData->Response.StatusCode)); if (ResponseData->Response.StatusCode == HTTP_STATUS_200_OK) { - DEBUG ((DEBUG_INFO, "HTTP_STATUS_200_OK\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_200_OK\n")); if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { - DEBUG ((DEBUG_INFO, "This is chunk transfer, start to send all chunks - %d.", ResponseData->Response.StatusCode)); + DEBUG ((DEBUG_REDFISH_NETWORK, "This is chunk transfer, start to send all chunks - %d.", ResponseData->Response.StatusCode)); SendChunkProcess++; goto ReSendRequest; } @@ -261,7 +262,7 @@ ReSendRequest:; } else if (ResponseData->Response.StatusCode == HTTP_STATUS_202_ACCEPTED) { DEBUG ((DEBUG_INFO, "HTTP_STATUS_202_ACCEPTED\n")); } else if (ResponseData->Response.StatusCode == HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE) { - DEBUG ((DEBUG_INFO, "HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE\n")); Status = EFI_BAD_BUFFER_SIZE; goto ON_EXIT; @@ -271,25 +272,25 @@ ReSendRequest:; Status = EFI_ACCESS_DENIED; goto ON_EXIT; } else if (ResponseData->Response.StatusCode == HTTP_STATUS_400_BAD_REQUEST) { - DEBUG ((DEBUG_INFO, "HTTP_STATUS_400_BAD_REQUEST\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_400_BAD_REQUEST\n")); if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { - DEBUG ((DEBUG_INFO, "Bad request may caused by zero length chunk. Try to send all chunks...\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "Bad request may caused by zero length chunk. Try to send all chunks...\n")); SendChunkProcess++; goto ReSendRequest; } } else if (ResponseData->Response.StatusCode == HTTP_STATUS_100_CONTINUE) { - DEBUG ((DEBUG_INFO, "HTTP_STATUS_100_CONTINUE\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_100_CONTINUE\n")); if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendChunkProcess == HttpIoSendChunkHeaderZeroContent)) { // // We get HTTP_STATUS_100_CONTINUE to send the body using chunk transfer. // - DEBUG ((DEBUG_INFO, "HTTP_STATUS_100_CONTINUE for chunk transfer...\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_100_CONTINUE for chunk transfer...\n")); SendChunkProcess++; goto ReSendRequest; } if (FixedPcdGetBool (PcdRedfishRestExChunkRequestMode) && (SendNonChunkProcess == HttpIoSendNonChunkHeaderZeroContent)) { - DEBUG ((DEBUG_INFO, "HTTP_STATUS_100_CONTINUE for non chunk transfer...\n")); + DEBUG ((DEBUG_REDFISH_NETWORK, "HTTP_STATUS_100_CONTINUE for non chunk transfer...\n")); SendNonChunkProcess++; goto ReSendRequest; } @@ -313,6 +314,7 @@ ReSendRequest:; } } else { DEBUG ((DEBUG_ERROR, "This HTTP Status is not handled!\n")); + DumpHttpStatusCode (DEBUG_REDFISH_NETWORK, ResponseData->Response.StatusCode); Status = EFI_UNSUPPORTED; goto ON_EXIT; } @@ -426,10 +428,10 @@ ReSendRequest:; TotalReceivedSize += ResponseData->BodyLength; } - DEBUG ((DEBUG_INFO, "Total of length of Response :%d\n", TotalReceivedSize)); + DEBUG ((DEBUG_REDFISH_NETWORK, "Total of length of Response :%d\n", TotalReceivedSize)); } - DEBUG ((DEBUG_INFO, "RedfishRestExSendReceive()- EFI_STATUS: %r\n", Status)); + DEBUG ((DEBUG_REDFISH_NETWORK, "RedfishRestExSendReceive()- EFI_STATUS: %r\n", Status)); ON_EXIT: From 591dd320384b6711b1feccb96a1dfba24db42a4d Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:28 +0800 Subject: [PATCH 0639/1529] UefiCpuPkg/PiSmmCpuDxeSmm: Fix invalid InitializeMpSyncData call REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4338 No need call InitializeMpSyncData during normal boot SMI init, because mSmmMpSyncData is NULL at that time. mSmmMpSyncData is allocated in InitializeMpServiceData, which is invoked after normal boot SMI init (SmmRelocateBases). Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Cc: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Acked-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 655175a2c6..2ac655d032 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -1,7 +1,7 @@ /** @file Agent Module to load other modules to deploy SMM Entry Vector for X86 CPU. -Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -371,9 +371,7 @@ SmmInitHandler ( // Check XD and BTS features on each processor on normal boot // CheckFeatureSupported (); - } - - if (mIsBsp) { + } else if (mIsBsp) { // // BSP rebase is already done above. // Initialize private data during S3 resume From 90e5b90019388cb18f124b08293d40c0b61389e0 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:29 +0800 Subject: [PATCH 0640/1529] UefiCpuPkg/PiSmmCpuDxeSmm: Replace mIsBsp by mBspApicId check This patch is to replace mIsBsp by mBspApicId check. mIsBsp becomes the local variable (IsBsp), then it can be checked dynamically in the function. Instead, we define the mBspApicId, which is to record the BSP ApicId used for compare in SmmInitHandler. With this change, SmmInitHandler can be run in parallel during SMM init. Note: This patch is the per-prepared work by refining the SmmInitHandler, then, we can do the next step to combine 2 SMIs (gcSmmInitTemplate & gcSmiHandlerTemplate) into one (gcSmiHandlerTemplate), the new SMI handler will call the SmmInitHandler in parallel to do the init. Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Cc: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Reviewed-by: Ray Ni Reviewed-by: Gerd Hoffmann --- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 23 +++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 2ac655d032..6e795d1756 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -59,7 +59,6 @@ SMM_CPU_PRIVATE_DATA *gSmmCpuPrivate = &mSmmCpuPrivateData; // SMM Relocation variables // volatile BOOLEAN *mRebased; -volatile BOOLEAN mIsBsp; /// /// Handle for the SMM CPU Protocol @@ -85,6 +84,8 @@ EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL mSmmMemoryAttribute = { EFI_CPU_INTERRUPT_HANDLER mExternalVectorTable[EXCEPTION_VECTOR_NUMBER]; +UINT32 mBspApicId = 0; + // // SMM stack information // @@ -343,8 +344,9 @@ SmmInitHandler ( VOID ) { - UINT32 ApicId; - UINTN Index; + UINT32 ApicId; + UINTN Index; + BOOLEAN IsBsp; // // Update SMM IDT entries' code segment and load IDT @@ -352,6 +354,8 @@ SmmInitHandler ( AsmWriteIdtr (&gcSmiIdtr); ApicId = GetApicId (); + IsBsp = (BOOLEAN)(mBspApicId == ApicId); + ASSERT (mNumberOfCpus <= mMaxNumberOfCpus); for (Index = 0; Index < mNumberOfCpus; Index++) { @@ -361,7 +365,7 @@ SmmInitHandler ( // SmmCpuFeaturesInitializeProcessor ( Index, - mIsBsp, + IsBsp, gSmmCpuPrivate->ProcessorInfo, &mCpuHotPlugData ); @@ -371,7 +375,7 @@ SmmInitHandler ( // Check XD and BTS features on each processor on normal boot // CheckFeatureSupported (); - } else if (mIsBsp) { + } else if (IsBsp) { // // BSP rebase is already done above. // Initialize private data during S3 resume @@ -407,7 +411,6 @@ SmmRelocateBases ( SMRAM_SAVE_STATE_MAP BakBuf2; SMRAM_SAVE_STATE_MAP *CpuStatePtr; UINT8 *U8Ptr; - UINT32 ApicId; UINTN Index; UINTN BspIndex; @@ -448,17 +451,16 @@ SmmRelocateBases ( // // Retrieve the local APIC ID of current processor // - ApicId = GetApicId (); + mBspApicId = GetApicId (); // // Relocate SM bases for all APs // This is APs' 1st SMI - rebase will be done here, and APs' default SMI handler will be overridden by gcSmmInitTemplate // - mIsBsp = FALSE; BspIndex = (UINTN)-1; for (Index = 0; Index < mNumberOfCpus; Index++) { mRebased[Index] = FALSE; - if (ApicId != (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) { + if (mBspApicId != (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) { SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId); // // Wait for this AP to finish its 1st SMI @@ -477,8 +479,7 @@ SmmRelocateBases ( // Relocate BSP's SMM base // ASSERT (BspIndex != (UINTN)-1); - mIsBsp = TRUE; - SendSmiIpi (ApicId); + SendSmiIpi (mBspApicId); // // Wait for the BSP to finish its 1st SMI // From 427700e7b9f1d8a7255aaebee7356e06e395bc75 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:30 +0800 Subject: [PATCH 0641/1529] UefiCpuPkg/SmmBaseHob.h: Add SMM Base HOB Data REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4337 The default SMBASE for the x86 processor is 0x30000. When SMI happens, processor runs the SMI handler at SMBASE+0x8000. Also, the SMM save state area is within SMBASE+0x10000. One of the SMM initialization from processor perspective is to relocate and program the new SMBASE (in TSEG range) for each processor. When the SMBASE relocation happens in a PEI module, the PEI module shall produce the SMM_BASE_HOB in HOB database which tells the PiSmmCpuDxeSmm driver (runs at a later phase) about the new SMBASE for each processor. PiSmmCpuDxeSmm driver installs the SMI handler at the SMM_BASE_HOB.SmBase[Index]+0x8000 for processor Index. When the HOB doesn't exist, PiSmmCpuDxeSmm driver shall relocate and program the new SMBASE itself. This patch adds the SMM Base HOB for any PEI module to do the SmBase relocation ahead of PiSmmCpuDxeSmm driver and store the relocated SmBase address in array for each processor. Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Cc: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Acked-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Include/Guid/SmmBaseHob.h | 75 ++++++++++++++++++++++++++++ UefiCpuPkg/UefiCpuPkg.dec | 5 +- 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 UefiCpuPkg/Include/Guid/SmmBaseHob.h diff --git a/UefiCpuPkg/Include/Guid/SmmBaseHob.h b/UefiCpuPkg/Include/Guid/SmmBaseHob.h new file mode 100644 index 0000000000..115e749348 --- /dev/null +++ b/UefiCpuPkg/Include/Guid/SmmBaseHob.h @@ -0,0 +1,75 @@ +/** @file + The Smm Base HOB is used to store the information of: + * The relocated SmBase address in array for each processor. + + The default Smbase for the x86 processor is 0x30000. When SMI happens, processor + runs the SMI handler at Smbase+0x8000. Also, the SMM save state area is within + Smbase+0x10000. Since it's the start address to store the processor save state + and code for the SMI entry point, those info are tiled within an SMRAM allocated + or reserved buffer. This tile size shall be enough to cover 3 parts: + 1. Processor SMRAM Save State Map starts at Smbase + 0xfc00 + 2. Extra processor specific context start starts at Smbase + 0xfb00 + 3. SMI entry point starts at Smbase + 0x8000. + Besides, This size should be rounded up to nearest power of 2. The Smm Base HOB + producer should be responsible for reserving enough size. + + One of the SMM initialization from processor perspective is to relocate and program + the new Smbase (in TSEG range) for each processor thread. When the Smbase relocation + happens in a PEI module, the PEI module shall produce the SMM_BASE_HOB in HOB database + which tells the PiSmmCpuDxeSmm driver (which runs at a later phase) about the new + Smbase for each processor. PiSmmCpuDxeSmm driver installs the SMI handler at the + SMM_BASE_HOB.Smbase[Index]+0x8000 for processor index. When the HOB doesn't exist, + PiSmmCpuDxeSmm driver shall relocate and program the new Smbase itself. + + Note: + 1. Smbase relocation process needs to program the vender specific hardware + interface to set Smbase, it might be in the thread scope. It's doable to + program the hardware interface using DXE MP service protocol in PiSmmCpuDxeSmm + entry point. But, considering the standalone MM environment where the CpuMm + driver runs in a isolated environment and it cannot invoke any DXE or PEI MP + service, we recommend to put the hardware interface programming in a separate + PEI module instead of in the PiSmmCpuDxeSmm driver. + + 2. There is the hard requirement that SMI Entry Size <= 0x1000, data Size <= + 0x1000 in PiSmmCpuDxeSmm. So, this require the allocated or reserved buffer in + SMRAM should be >= 0x2000. + + Copyright (c) 2023, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef SMM_BASE_HOB_H_ +#define SMM_BASE_HOB_H_ + +#define SMM_BASE_HOB_DATA_GUID \ + { \ + 0xc2217ba7, 0x03bb, 0x4f63, {0xa6, 0x47, 0x7c, 0x25, 0xc5, 0xfc, 0x9d, 0x73} \ + } + +#pragma pack(1) +typedef struct { + /// + /// ProcessorIndex tells which processor range this specific HOB instance described. + /// If ProcessorIndex is set to 0, it indicats the HOB describes the processor from + /// 0 to NumberOfProcessors - 1. The HOB list may contains multiple this HOB + /// instances. Each HOB instances describe the information for processor from + /// ProcessorIndex to ProcessorIndex + NumberOfProcessors - 1. The instance order in + /// the HOB list is random so consumer can not assume the ProcessorIndex of first + /// instance is 0. + /// + UINT32 ProcessorIndex; + /// + /// Describes the Number of all max supported processors. + /// + UINT32 NumberOfProcessors; + /// + /// Pointer to SmBase address for each processor. + /// + UINT64 SmBase[]; +} SMM_BASE_HOB_DATA; +#pragma pack() + +extern EFI_GUID gSmmBaseHobGuid; + +#endif diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 903ad52da9..2115aa4387 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -1,7 +1,7 @@ ## @file UefiCpuPkg.dec # This Package provides UEFI compatible CPU modules and libraries. # -# Copyright (c) 2007 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2023, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -78,6 +78,9 @@ ## Include/Guid/MicrocodePatchHob.h gEdkiiMicrocodePatchHobGuid = { 0xd178f11d, 0x8716, 0x418e, { 0xa1, 0x31, 0x96, 0x7d, 0x2a, 0xc4, 0x28, 0x43 }} + ## Include/Guid/SmmBaseHob.h + gSmmBaseHobGuid = { 0xc2217ba7, 0x03bb, 0x4f63, {0xa6, 0x47, 0x7c, 0x25, 0xc5, 0xfc, 0x9d, 0x73 }} + [Protocols] ## Include/Protocol/SmmCpuService.h gEfiSmmCpuServiceProtocolGuid = { 0x1d202cab, 0xc8ab, 0x4d5c, { 0x94, 0xf7, 0x3c, 0xfc, 0xc0, 0xd3, 0xd3, 0x35 }} From ce0e7d465283206d6d49b0b394a7204b01832707 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:31 +0800 Subject: [PATCH 0642/1529] UefiCpuPkg/PiSmmCpuDxeSmm: Consume SMM Base Hob for SmBase info REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4337 Existing SMBASE Relocation is in the PiSmmCpuDxeSmm driver, which will relocate the SMBASE of each processor by setting the SMBASE field in the saved state map (at offset 7EF8h) to a new value. The RSM instruction reloads the internal SMBASE register with the value in SMBASE field when each time it exits SMM. All subsequent SMI requests will use the new SMBASE to find the starting address for the SMI handler (at SMBASE + 8000h). Due to the default SMBASE for all x86 processors is 0x30000, the APs' 1st SMI for rebase has to be executed one by one to avoid the processors over-writing each other's SMM Save State Area (see existing SmmRelocateBases() function), which means the next AP has to wait for the previous AP to finish its 1st SMI, then it can call into its 1st SMI for rebase via Smi Ipi command, thus leading the existing SMBASE Relocation has to be running in series. Besides, it needs very complex code to handle the AP exit semaphore (mRebased[Index]), which will hook return address of SMM Save State so that semaphore code can be executed immediately after AP exits SMM for SMBASE relocation (see existing SemaphoreHook() function). With SMM Base Hob support, PiSmmCpuDxeSmm does not need the RSM instruction to do the SMBASE Relocation. SMBASE Register for each processors have already been programmed and all SMBASE address have recorded in SMM Base Hob. So the same default SMBASE Address (0x30000) will not be used, thus the processors over-writing each other's SMM Save State Area will not happen in PiSmmCpuDxeSmm driver. This way makes the first SMI init can be executed in parallel and save boot time on multi-core system. Besides, Semaphore Hook code logic is also not required, which will greatly simplify the SMBASE Relocation flow. Mainly changes as below: * Assume the biggest possibility of tile size is 8k. * Combine 2 SMIs (gcSmmInitTemplate & gcSmiHandlerTemplate) into one (gcSmiHandlerTemplate), the new SMI handler needs to run to 2 paths: one to SmmCpuFeaturesInitializeProcessor(), the other to SMM Core Entry Point. * Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) for first SMI init before normal SMI sources happen. * Call SmmCpuFeaturesInitializeProcessor() in parallel. Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Acked-by: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c | 31 +++- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 25 ++- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 166 +++++++++++++++---- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 26 ++- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 3 +- 5 files changed, 214 insertions(+), 37 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c index fb4a44eab6..d408b3f9f7 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c @@ -1,7 +1,7 @@ /** @file Code for Processor S3 restoration -Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -824,9 +824,34 @@ SmmRestoreCpu ( } // - // Restore SMBASE for BSP and all APs + // Make sure the gSmmBaseHobGuid existence status is the same between normal and S3 boot. // - SmmRelocateBases (); + ASSERT (mSmmRelocated == (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL)); + if (mSmmRelocated != (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL)) { + DEBUG (( + DEBUG_ERROR, + "gSmmBaseHobGuid %a produced in normal boot but %a in S3 boot!", + mSmmRelocated ? "is" : "is not", + mSmmRelocated ? "is not" : "is" + )); + CpuDeadLoop (); + } + + // + // Check whether Smm Relocation is done or not. + // If not, will do the SmmBases Relocation here!!! + // + if (!mSmmRelocated) { + // + // Restore SMBASE for BSP and all APs + // + SmmRelocateBases (); + } else { + // + // Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) to execute first SMI init. + // + ExecuteFirstSmiInit (); + } // // Skip initialization if mAcpiCpuData is not valid diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index a0967eb69c..baf827cf9d 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -1,7 +1,7 @@ /** @file SMM MP service implementation -Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -1723,6 +1723,10 @@ SmiRendezvous ( ASSERT (CpuIndex < mMaxNumberOfCpus); + if (mSmmRelocated) { + ASSERT (mSmmInitialized != NULL); + } + // // Save Cr2 because Page Fault exception in SMM may override its value, // when using on-demand paging for above 4G memory. @@ -1730,6 +1734,25 @@ SmiRendezvous ( Cr2 = 0; SaveCr2 (&Cr2); + if (mSmmRelocated && !mSmmInitialized[CpuIndex]) { + // + // Perform SmmInitHandler for CpuIndex + // + SmmInitHandler (); + + // + // Restore Cr2 + // + RestoreCr2 (Cr2); + + // + // Mark the first SMI init for CpuIndex has been done so as to avoid the reentry. + // + mSmmInitialized[CpuIndex] = TRUE; + + return; + } + // // Call the user register Startup function first. // diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 6e795d1756..d2d0950f3b 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -84,6 +84,8 @@ EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL mSmmMemoryAttribute = { EFI_CPU_INTERRUPT_HANDLER mExternalVectorTable[EXCEPTION_VECTOR_NUMBER]; +BOOLEAN mSmmRelocated = FALSE; +volatile BOOLEAN *mSmmInitialized = NULL; UINT32 mBspApicId = 0; // @@ -383,10 +385,12 @@ SmmInitHandler ( InitializeMpSyncData (); } - // - // Hook return after RSM to set SMM re-based flag - // - SemaphoreHook (Index, &mRebased[Index]); + if (!mSmmRelocated) { + // + // Hook return after RSM to set SMM re-based flag + // + SemaphoreHook (Index, &mRebased[Index]); + } return; } @@ -395,6 +399,51 @@ SmmInitHandler ( ASSERT (FALSE); } +/** + Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) to execute first SMI init. + +**/ +VOID +ExecuteFirstSmiInit ( + VOID + ) +{ + UINTN Index; + + if (mSmmInitialized == NULL) { + mSmmInitialized = (BOOLEAN *)AllocatePool (sizeof (BOOLEAN) * mMaxNumberOfCpus); + } + + ASSERT (mSmmInitialized != NULL); + if (mSmmInitialized == NULL) { + return; + } + + // + // Reset the mSmmInitialized to false. + // + ZeroMem ((VOID *)mSmmInitialized, sizeof (BOOLEAN) * mMaxNumberOfCpus); + + // + // Get the BSP ApicId. + // + mBspApicId = GetApicId (); + + // + // Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) for SMM init + // + SendSmiIpi (mBspApicId); + SendSmiIpiAllExcludingSelf (); + + // + // Wait for all processors to finish its 1st SMI + // + for (Index = 0; Index < mNumberOfCpus; Index++) { + while (!(BOOLEAN)mSmmInitialized[Index]) { + } + } +} + /** Relocate SmmBases for each processor. @@ -562,6 +611,11 @@ PiCpuSmmEntry ( UINTN FamilyId; UINTN ModelId; UINT32 Cr3; + EFI_HOB_GUID_TYPE *GuidHob; + SMM_BASE_HOB_DATA *SmmBaseHobData; + + GuidHob = NULL; + SmmBaseHobData = NULL; // // Initialize address fixup @@ -790,26 +844,54 @@ PiCpuSmmEntry ( ASSERT (TileSize <= (SMRAM_SAVE_STATE_MAP_OFFSET + sizeof (SMRAM_SAVE_STATE_MAP) - SMM_HANDLER_OFFSET)); // - // Allocate buffer for all of the tiles. - // - // Intel(R) 64 and IA-32 Architectures Software Developer's Manual - // Volume 3C, Section 34.11 SMBASE Relocation - // For Pentium and Intel486 processors, the SMBASE values must be - // aligned on a 32-KByte boundary or the processor will enter shutdown - // state during the execution of a RSM instruction. - // - // Intel486 processors: FamilyId is 4 - // Pentium processors : FamilyId is 5 + // Retrive the allocated SmmBase from gSmmBaseHobGuid. If found, + // means the SmBase relocation has been done. // - BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)); - if ((FamilyId == 4) || (FamilyId == 5)) { - Buffer = AllocateAlignedCodePages (BufferPages, SIZE_32KB); + GuidHob = GetFirstGuidHob (&gSmmBaseHobGuid); + if (GuidHob != NULL) { + // + // Check whether the Required TileSize is enough. + // + if (TileSize > SIZE_8KB) { + DEBUG ((DEBUG_ERROR, "The Range of Smbase in SMRAM is not enough -- Required TileSize = 0x%08x, Actual TileSize = 0x%08x\n", TileSize, SIZE_8KB)); + CpuDeadLoop (); + return RETURN_BUFFER_TOO_SMALL; + } + + SmmBaseHobData = GET_GUID_HOB_DATA (GuidHob); + + // + // Assume single instance of HOB produced, expect the HOB.NumberOfProcessors equals to the mMaxNumberOfCpus. + // + ASSERT (SmmBaseHobData->NumberOfProcessors == (UINT32)mMaxNumberOfCpus && SmmBaseHobData->ProcessorIndex == 0); + mSmmRelocated = TRUE; } else { - Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); - } + // + // When the HOB doesn't exist, allocate new SMBASE itself. + // + DEBUG ((DEBUG_INFO, "PiCpuSmmEntry: gSmmBaseHobGuid not found!\n")); + // + // Allocate buffer for all of the tiles. + // + // Intel(R) 64 and IA-32 Architectures Software Developer's Manual + // Volume 3C, Section 34.11 SMBASE Relocation + // For Pentium and Intel486 processors, the SMBASE values must be + // aligned on a 32-KByte boundary or the processor will enter shutdown + // state during the execution of a RSM instruction. + // + // Intel486 processors: FamilyId is 4 + // Pentium processors : FamilyId is 5 + // + BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)); + if ((FamilyId == 4) || (FamilyId == 5)) { + Buffer = AllocateAlignedCodePages (BufferPages, SIZE_32KB); + } else { + Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); + } - ASSERT (Buffer != NULL); - DEBUG ((DEBUG_INFO, "SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE (BufferPages))); + ASSERT (Buffer != NULL); + DEBUG ((DEBUG_INFO, "New Allcoated SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE (BufferPages))); + } // // Allocate buffer for pointers to array in SMM_CPU_PRIVATE_DATA. @@ -844,7 +926,8 @@ PiCpuSmmEntry ( // size for each CPU in the platform // for (Index = 0; Index < mMaxNumberOfCpus; Index++) { - mCpuHotPlugData.SmBase[Index] = (UINTN)Buffer + Index * TileSize - SMM_HANDLER_OFFSET; + mCpuHotPlugData.SmBase[Index] = mSmmRelocated ? (UINTN)SmmBaseHobData->SmBase[Index] : (UINTN)Buffer + Index * TileSize - SMM_HANDLER_OFFSET; + gSmmCpuPrivate->CpuSaveStateSize[Index] = sizeof (SMRAM_SAVE_STATE_MAP); gSmmCpuPrivate->CpuSaveState[Index] = (VOID *)(mCpuHotPlugData.SmBase[Index] + SMRAM_SAVE_STATE_MAP_OFFSET); gSmmCpuPrivate->Operation[Index] = SmmCpuNone; @@ -957,17 +1040,23 @@ PiCpuSmmEntry ( InitializeSmmIdt (); // - // Relocate SMM Base addresses to the ones allocated from SMRAM + // Check whether Smm Relocation is done or not. + // If not, will do the SmmBases Relocation here!!! // - mRebased = (BOOLEAN *)AllocateZeroPool (sizeof (BOOLEAN) * mMaxNumberOfCpus); - ASSERT (mRebased != NULL); - SmmRelocateBases (); + if (!mSmmRelocated) { + // + // Relocate SMM Base addresses to the ones allocated from SMRAM + // + mRebased = (BOOLEAN *)AllocateZeroPool (sizeof (BOOLEAN) * mMaxNumberOfCpus); + ASSERT (mRebased != NULL); + SmmRelocateBases (); - // - // Call hook for BSP to perform extra actions in normal mode after all - // SMM base addresses have been relocated on all CPUs - // - SmmCpuFeaturesSmmRelocationComplete (); + // + // Call hook for BSP to perform extra actions in normal mode after all + // SMM base addresses have been relocated on all CPUs + // + SmmCpuFeaturesSmmRelocationComplete (); + } DEBUG ((DEBUG_INFO, "mXdSupported - 0x%x\n", mXdSupported)); @@ -998,6 +1087,21 @@ PiCpuSmmEntry ( } } + // + // For relocated SMBASE, some MSRs & CSRs are still required to be configured in SMM Mode for SMM Initialization. + // Those MSRs & CSRs must be configured before normal SMI sources happen. + // So, here is to issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) to execute first SMI init. + // + if (mSmmRelocated) { + ExecuteFirstSmiInit (); + + // + // Call hook for BSP to perform extra actions in normal mode after all + // SMM base addresses have been relocated on all CPUs + // + SmmCpuFeaturesSmmRelocationComplete (); + } + // // Fill in SMM Reserved Regions // diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 5f0a38e400..c3731f174b 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -1,7 +1,7 @@ /** @file Agent Module to load other modules to deploy SMM Entry Vector for X86 CPU. -Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -25,6 +25,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include @@ -348,6 +349,25 @@ SmmWriteSaveState ( IN CONST VOID *Buffer ); +/** + C function for SMI handler. To change all processor's SMMBase Register. + +**/ +VOID +EFIAPI +SmmInitHandler ( + VOID + ); + +/** + Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) to execute first SMI init. + +**/ +VOID +ExecuteFirstSmiInit ( + VOID + ); + /** Read a CPU Save State register on the target processor. @@ -402,6 +422,10 @@ WriteSaveStateRegister ( IN CONST VOID *Buffer ); +extern BOOLEAN mSmmRelocated; +extern volatile BOOLEAN *mSmmInitialized; +extern UINT32 mBspApicId; + extern CONST UINT8 gcSmmInitTemplate[]; extern CONST UINT16 gcSmmInitSize; X86_ASSEMBLY_PATCH_LABEL gPatchSmmCr0; diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index b4b327f60c..9bfa8c1a76 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -4,7 +4,7 @@ # This SMM driver performs SMM initialization, deploy SMM Entry Vector, # provides CPU specific services in SMM. # -# Copyright (c) 2009 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
# Copyright (c) 2017, AMD Incorporated. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -114,6 +114,7 @@ gEfiAcpiVariableGuid ## SOMETIMES_CONSUMES ## HOB # it is used for S3 boot. gEdkiiPiSmmMemoryAttributesTableGuid ## CONSUMES ## SystemTable gEfiMemoryAttributesTableGuid ## CONSUMES ## SystemTable + gSmmBaseHobGuid ## CONSUMES [FeaturePcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmDebug ## CONSUMES From b87d01cb07aaa05f0035bbd81173a3f355438c83 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:32 +0800 Subject: [PATCH 0643/1529] UefiCpuPkg/SmmCpuFeaturesLib: Skip SMBASE configuration REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4337 This patch is to avoid configure SMBASE if SmBase relocation has been done. If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded in the SmBase array. No need to do the relocation in SmmCpuFeaturesInitializeProcessor(). Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Acked-by: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Reviewed-by: Ray Ni --- .../SmmCpuFeaturesLib/CpuFeaturesLib.h | 2 ++ .../IntelSmmCpuFeaturesLib.c | 25 ++++++++++++++++--- .../SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 6 ++++- .../SmmCpuFeaturesLibStm.inf | 3 ++- UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c | 3 +-- .../StandaloneMmCpuFeaturesLib.inf | 6 ++++- 6 files changed, 36 insertions(+), 9 deletions(-) diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h index fd3e902547..c2e4fbe96b 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/CpuFeaturesLib.h @@ -9,11 +9,13 @@ #ifndef CPU_FEATURES_LIB_H_ #define CPU_FEATURES_LIB_H_ +#include #include #include #include #include #include +#include /** Performs library initialization. diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c index d5eaaa7a99..1a2c706fa1 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/IntelSmmCpuFeaturesLib.c @@ -1,7 +1,7 @@ /** @file Implementation shared across all library instances. -Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2010 - 2023, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -38,6 +38,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent UINT32 mSmrrPhysBaseMsr = SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE; UINT32 mSmrrPhysMaskMsr = SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK; +// +// Indicate SmBase for each Processors has been relocated or not. If TRUE, +// means no need to do the relocation in SmmCpuFeaturesInitializeProcessor(). +// +BOOLEAN mSmmCpuFeaturesSmmRelocated; + // // Set default value to assume MTRRs need to be configured on each SMI // @@ -144,6 +150,12 @@ CpuFeaturesLibInitialization ( // mSmrrEnabled = (BOOLEAN *)AllocatePool (sizeof (BOOLEAN) * GetCpuMaxLogicalProcessorNumber ()); ASSERT (mSmrrEnabled != NULL); + + // + // If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded + // in the SmBase array. + // + mSmmCpuFeaturesSmmRelocated = (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL); } /** @@ -187,10 +199,15 @@ SmmCpuFeaturesInitializeProcessor ( UINTN ModelId; // - // Configure SMBASE. + // No need to configure SMBASE if SmBase relocation has been done. // - CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET); - CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex]; + if (!mSmmCpuFeaturesSmmRelocated) { + // + // Configure SMBASE. + // + CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET); + CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex]; + } // // Intel(R) 64 and IA-32 Architectures Software Developer's Manual diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf index 9ac7dde78f..46ae2bf85e 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf @@ -1,7 +1,7 @@ ## @file # The CPU specific programming for PiSmmCpuDxeSmm module. # -# Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -33,6 +33,10 @@ PcdLib MemoryAllocationLib DebugLib + HobLib + +[Guids] + gSmmBaseHobGuid ## CONSUMES [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf index 86d367e0a0..51322ff189 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibStm.inf @@ -2,7 +2,7 @@ # The CPU specific programming for PiSmmCpuDxeSmm module when STM support # is included. # -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -64,6 +64,7 @@ gMsegSmramGuid ## SOMETIMES_CONSUMES ## HOB gEfiAcpi20TableGuid ## SOMETIMES_CONSUMES ## SystemTable gEfiAcpi10TableGuid ## SOMETIMES_CONSUMES ## SystemTable + gSmmBaseHobGuid ## CONSUMES [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c index 3cf162ada0..6cb1c515c0 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmStm.c @@ -1,14 +1,13 @@ /** @file SMM STM support functions - Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include #include -#include #include #include #include diff --git a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf index b1f60a5505..c836939d33 100644 --- a/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf +++ b/UefiCpuPkg/Library/SmmCpuFeaturesLib/StandaloneMmCpuFeaturesLib.inf @@ -1,7 +1,7 @@ ## @file # Standalone MM CPU specific programming. # -# Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -34,6 +34,10 @@ DebugLib MemoryAllocationLib PcdLib + HobLib + +[Guids] + gSmmBaseHobGuid ## CONSUMES [FixedPcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber ## SOMETIMES_CONSUMES From 4f536bfcfd139bee91a991ccedae57125e107afd Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Thu, 16 Feb 2023 14:16:33 +0800 Subject: [PATCH 0644/1529] OvmfPkg/SmmCpuFeaturesLib: Check SmBase relocation supported or not REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4337 This patch is to check SmBase relocation supported or not. If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded in the SmBase array. ASSERT it's not supported in OVMF. Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Cc: Gerd Hoffmann Cc: Rahul Kumar Signed-off-by: Jiaxin Wu Reviewed-by: Gerd Hoffmann Reviewed-by: Ray Ni --- OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c | 10 +++++++++- .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c index 6693666d04..a1dd10c9f2 100644 --- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c +++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c @@ -1,7 +1,7 @@ /** @file The CPU specific programming for PiSmmCpuDxeSmm module. - Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.
+ Copyright (c) 2010 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -17,10 +17,12 @@ #include #include #include +#include #include #include #include #include +#include // // EFER register LMA bit @@ -43,6 +45,12 @@ SmmCpuFeaturesLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { + // + // If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded + // in the SmBase array. ASSERT it's not supported in OVMF. + // + ASSERT (GetFirstGuidHob (&gSmmBaseHobGuid) == NULL); + // // No need to program SMRRs on our virtual platform. // diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf index 8a426a4c10..2697a90525 100644 --- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf +++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf @@ -1,7 +1,7 @@ ## @file # The CPU specific programming for PiSmmCpuDxeSmm module. # -# Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -35,6 +35,10 @@ SafeIntLib SmmServicesTableLib UefiBootServicesTableLib + HobLib + +[Guids] + gSmmBaseHobGuid ## CONSUMES [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber From aa15350031d85b6d57e40bf3243b11ddc0918f39 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Fri, 24 Feb 2023 08:18:01 +0800 Subject: [PATCH 0645/1529] MdeModulePkg: Improve formatting of DEBUG messages in UsbBusDxe Improve the formatting of DEBUG messages in UsbBusDxe by adding a hyphen to separate the EFI_STATUS code. Signed-off-by: Rebecca Cran Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c | 12 ++++++------ MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c | 6 +++--- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c | 2 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c index 6a3ac63c3a..c25f3cc2f2 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c @@ -838,7 +838,7 @@ UsbIoPortReset ( if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, - "UsbIoPortReset: failed to reset hub port %d@hub %d, %r \n", + "UsbIoPortReset: failed to reset hub port %d@hub %d - %r\n", Dev->ParentPort, Dev->ParentAddr, Status @@ -945,7 +945,7 @@ UsbBusBuildProtocol ( ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to open device path %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to open device path - %r\n", Status)); FreePool (UsbBus); return Status; @@ -978,7 +978,7 @@ UsbBusBuildProtocol ( ); if (EFI_ERROR (Status) && EFI_ERROR (Status2)) { - DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to open USB_HC/USB2_HC %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to open USB_HC/USB2_HC - %r\n", Status)); Status = EFI_DEVICE_ERROR; goto CLOSE_HC; @@ -1006,7 +1006,7 @@ UsbBusBuildProtocol ( ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to install bus protocol %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to install bus protocol - %r\n", Status)); goto CLOSE_HC; } @@ -1054,7 +1054,7 @@ UsbBusBuildProtocol ( Status = mUsbRootHubApi.Init (RootIf); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to init root hub %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to init root hub - %r\n", Status)); goto FREE_ROOTHUB; } @@ -1102,7 +1102,7 @@ UsbBusBuildProtocol ( ); FreePool (UsbBus); - DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to start bus driver %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to start bus driver - %r\n", Status)); return Status; } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c index a620a67074..8b078e7e49 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c @@ -761,7 +761,7 @@ UsbGetOneConfig ( if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, - "UsbGetOneConfig: failed to get descript length(%d) %r\n", + "UsbGetOneConfig: failed to get descript length(%d) - %r\n", Desc.TotalLength, Status )); @@ -787,7 +787,7 @@ UsbGetOneConfig ( Status = UsbCtrlGetDesc (UsbDev, USB_DESC_TYPE_CONFIG, Index, 0, Buf, Desc.TotalLength); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbGetOneConfig: failed to get full descript %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbGetOneConfig: failed to get full descript - %r\n", Status)); FreePool (Buf); return NULL; @@ -891,7 +891,7 @@ UsbBuildDescTable ( Status = UsbBuildLangTable (UsbDev); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "UsbBuildDescTable: get language ID table %r\n", Status)); + DEBUG ((DEBUG_INFO, "UsbBuildDescTable: get language ID table - %r\n", Status)); } return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c index aed34596f4..b3a40639f2 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c @@ -440,7 +440,7 @@ UsbSelectConfig ( if (EFI_ERROR (Status)) { DEBUG (( DEBUG_WARN, - "UsbSelectConfig: failed to connect driver %r, ignored\n", + "UsbSelectConfig: failed to connect driver - %r, ignored\n", Status )); } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c index 0497a73f44..1a473d0998 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c @@ -609,7 +609,7 @@ UsbHubInit ( Status = UsbHubReadDesc (HubDev, HubDesc); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbHubInit: failed to read HUB descriptor %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbHubInit: failed to read HUB descriptor - %r\n", Status)); return Status; } From f1dfa38339b68bbe4152d59e6b56ee8f34f33ef1 Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:47 +0800 Subject: [PATCH 0646/1529] UefiCpuPkg: Check AP_SAFE_STACK_SIZE during build time. Check if AP_SAFE_STACK_SIZE is aligned with CPU_STACK_ALIGNMENT during build time. No functional or structural changes. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/MpLib.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index f5086e497e..a73a89d2a5 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -1,7 +1,7 @@ /** @file Common header file for MP Initialize Library. - Copyright (c) 2016 - 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2020, AMD Inc. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -311,6 +311,7 @@ typedef struct { #define AP_SAFE_STACK_SIZE 128 #define AP_RESET_STACK_SIZE AP_SAFE_STACK_SIZE +STATIC_ASSERT ((AP_SAFE_STACK_SIZE & (CPU_STACK_ALIGNMENT - 1)) == 0, "AP_SAFE_STACK_SIZE is not aligned with CPU_STACK_ALIGNMENT"); #pragma pack(1) From e797e23a574ccd2c46e5ad2707f46be8b8a21dcd Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:48 +0800 Subject: [PATCH 0647/1529] UefiCpuPkg: Split the path in RelocateApLoop into two. Add the union RELOCATE_AP_LOOP_ENTRY, split the path in RelocateApLoop into two: 1. 64-bit AMD processors with SEV-ES 2. Intel processors (32-bit or 64-bit), 32-bit AMD processors, or 64-bit AMD processors without SEV-ES. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 70 +++++++++++++++---------- UefiCpuPkg/Library/MpInitLib/MpLib.h | 6 +++ 2 files changed, 48 insertions(+), 28 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index a84e9e33ba..e9ac858f4f 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -1,7 +1,7 @@ /** @file MP initialize support functions for DXE phase. - Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -20,14 +20,14 @@ #define AP_SAFE_STACK_SIZE 128 -CPU_MP_DATA *mCpuMpData = NULL; -EFI_EVENT mCheckAllApsEvent = NULL; -EFI_EVENT mMpInitExitBootServicesEvent = NULL; -EFI_EVENT mLegacyBootEvent = NULL; -volatile BOOLEAN mStopCheckAllApsStatus = TRUE; -VOID *mReservedApLoopFunc = NULL; -UINTN mReservedTopOfApStack; -volatile UINT32 mNumberToFinish = 0; +CPU_MP_DATA *mCpuMpData = NULL; +EFI_EVENT mCheckAllApsEvent = NULL; +EFI_EVENT mMpInitExitBootServicesEvent = NULL; +EFI_EVENT mLegacyBootEvent = NULL; +volatile BOOLEAN mStopCheckAllApsStatus = TRUE; +RELOCATE_AP_LOOP_ENTRY mReservedApLoop; +UINTN mReservedTopOfApStack; +volatile UINT32 mNumberToFinish = 0; // // Begin wakeup buffer allocation below 0x88000 @@ -378,32 +378,46 @@ RelocateApLoop ( IN OUT VOID *Buffer ) { - CPU_MP_DATA *CpuMpData; - BOOLEAN MwaitSupport; - ASM_RELOCATE_AP_LOOP AsmRelocateApLoopFunc; - UINTN ProcessorNumber; - UINTN StackStart; + CPU_MP_DATA *CpuMpData; + BOOLEAN MwaitSupport; + UINTN ProcessorNumber; + UINTN StackStart; MpInitLibWhoAmI (&ProcessorNumber); CpuMpData = GetCpuMpData (); MwaitSupport = IsMwaitSupport (); if (CpuMpData->UseSevEsAPMethod) { + // + // 64-bit AMD processors with SEV-ES + // StackStart = CpuMpData->SevEsAPResetStackStart; + mReservedApLoop.AmdSevEntry ( + MwaitSupport, + CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, + StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, + (UINTN)&mNumberToFinish, + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer + ); } else { + // + // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or 64-bit AMD processors without SEV-ES + // StackStart = mReservedTopOfApStack; + mReservedApLoop.GenericEntry ( + MwaitSupport, + CpuMpData->ApTargetCState, + CpuMpData->PmCodeSegment, + StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, + (UINTN)&mNumberToFinish, + CpuMpData->Pm16CodeSegment, + CpuMpData->SevEsAPBuffer, + CpuMpData->WakeupBuffer + ); } - AsmRelocateApLoopFunc = (ASM_RELOCATE_AP_LOOP)(UINTN)mReservedApLoopFunc; - AsmRelocateApLoopFunc ( - MwaitSupport, - CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, - StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, - (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer - ); // // It should never reach here // @@ -547,8 +561,8 @@ InitMpGlobalData ( ); ASSERT_EFI_ERROR (Status); - mReservedApLoopFunc = (VOID *)(UINTN)Address; - ASSERT (mReservedApLoopFunc != NULL); + mReservedApLoop.Data = (VOID *)(UINTN)Address; + ASSERT (mReservedApLoop.Data != NULL); // // Make sure that the buffer memory is executable if NX protection is enabled @@ -583,7 +597,7 @@ InitMpGlobalData ( mReservedTopOfApStack = (UINTN)Address + ApSafeBufferSize; ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); CopyMem ( - mReservedApLoopFunc, + mReservedApLoop.Data, CpuMpData->AddressMap.RelocateApLoopFuncAddress, CpuMpData->AddressMap.RelocateApLoopFuncSize ); diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index a73a89d2a5..81a95733fc 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -402,6 +402,12 @@ AsmExchangeRole ( IN CPU_EXCHANGE_ROLE_INFO *OthersInfo ); +typedef union { + VOID *Data; + ASM_RELOCATE_AP_LOOP AmdSevEntry; // 64-bit AMD Sev processors + ASM_RELOCATE_AP_LOOP GenericEntry; // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or AMD non-Sev processors +} RELOCATE_AP_LOOP_ENTRY; + /** Get the pointer to CPU MP Data structure. From 6cb969b4c29f763f2e72e667f3cbff09c847b98e Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:49 +0800 Subject: [PATCH 0648/1529] UefiCpuPkg: Allocate contiguous memory for stacks and APs loop. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 40 +++++++++++-------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index e9ac858f4f..224215878c 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -480,11 +480,12 @@ InitMpGlobalData ( { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS Address; - UINTN ApSafeBufferSize; UINTN Index; EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; UINTN StackBase; CPU_INFO_IN_HOB *CpuInfoInHob; + UINTN StackPages; + UINTN FuncPages; SaveCpuMpData (CpuMpData); @@ -547,16 +548,23 @@ InitMpGlobalData ( // Allocating it in advance since memory services are not available in // Exit Boot Services callback function. // - ApSafeBufferSize = EFI_PAGES_TO_SIZE ( - EFI_SIZE_TO_PAGES ( - CpuMpData->AddressMap.RelocateApLoopFuncSize - ) - ); + // +------------+ (TopOfApStack) + // | Stack * N | + // +------------+ (stack base, 4k aligned) + // | Padding | + // +------------+ + // | Ap Loop | + // +------------+ ((low address, 4k-aligned) + // + + StackPages = EFI_SIZE_TO_PAGES (CpuMpData->CpuCount * AP_SAFE_STACK_SIZE); + FuncPages = EFI_SIZE_TO_PAGES (CpuMpData->AddressMap.RelocateApLoopFuncSize); + Address = BASE_4GB - 1; Status = gBS->AllocatePages ( AllocateMaxAddress, EfiReservedMemoryType, - EFI_SIZE_TO_PAGES (ApSafeBufferSize), + StackPages + FuncPages, &Address ); ASSERT_EFI_ERROR (Status); @@ -575,26 +583,12 @@ InitMpGlobalData ( if (!EFI_ERROR (Status)) { gDS->SetMemorySpaceAttributes ( Address, - ApSafeBufferSize, + EFI_PAGES_TO_SIZE (FuncPages), MemDesc.Attributes & (~EFI_MEMORY_XP) ); } - ApSafeBufferSize = EFI_PAGES_TO_SIZE ( - EFI_SIZE_TO_PAGES ( - CpuMpData->CpuCount * AP_SAFE_STACK_SIZE - ) - ); - Address = BASE_4GB - 1; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - EFI_SIZE_TO_PAGES (ApSafeBufferSize), - &Address - ); - ASSERT_EFI_ERROR (Status); - - mReservedTopOfApStack = (UINTN)Address + ApSafeBufferSize; + mReservedTopOfApStack = (UINTN)Address + EFI_PAGES_TO_SIZE (StackPages+FuncPages); ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); CopyMem ( mReservedApLoop.Data, From 5d5c7b9bdb6d56e16a9d8fa871fd98162236432c Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Wed, 1 Mar 2023 14:09:50 +0800 Subject: [PATCH 0649/1529] OvmfPkg: Add CpuPageTableLib required by MpInitLib. Add CpuPageTableLib required by MpInitLib in OvmfPkg. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- OvmfPkg/AmdSev/AmdSevX64.dsc | 3 ++- OvmfPkg/CloudHv/CloudHvX64.dsc | 3 ++- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 4 +++- OvmfPkg/Microvm/MicrovmX64.dsc | 3 ++- OvmfPkg/OvmfPkgIa32X64.dsc | 3 ++- OvmfPkg/OvmfPkgX64.dsc | 4 +++- OvmfPkg/OvmfXen.dsc | 3 ++- 7 files changed, 16 insertions(+), 7 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 1cebd6b4bc..f0c4dc2310 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -3,7 +3,7 @@ # virtual machine remote attestation and secret injection # # Copyright (c) 2020 James Bottomley, IBM Corporation. -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -353,6 +353,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index fda7d2b9e5..327f53ff3c 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -404,6 +404,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 95b9594ddc..d093660283 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -320,6 +320,7 @@ CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf @@ -590,6 +591,7 @@ # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. # + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NULL|OvmfPkg/Library/MpInitLibDepLib/DxeMpInitLibMpDepLib.inf } diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 0d65d21e65..76fc548650 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -403,6 +403,7 @@ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf PciPcdProducerLib|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf PciExpressLib|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 6b539814bd..51db692b10 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -414,6 +414,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index e3c64456df..04d50704c7 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) Microsoft Corporation. # @@ -435,6 +435,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf @@ -826,6 +827,7 @@ # Directly use DxeMpInitLib. It depends on DxeMpInitLibMpDepLib which # checks the Protocol of gEfiMpInitLibMpDepProtocolGuid. # + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NULL|OvmfPkg/Library/MpInitLibDepLib/DxeMpInitLibMpDepLib.inf } diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index c328987e84..f1f02d969f 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -1,7 +1,7 @@ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # -# Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# Copyright (c) 2019, Citrix Systems, Inc. # Copyright (c) Microsoft Corporation. @@ -339,6 +339,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf NestedInterruptTplLib|OvmfPkg/Library/NestedInterruptTplLib/NestedInterruptTplLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf From 6b56e5c1568ae5beaa04622b5ee9ae689b88fbc8 Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:51 +0800 Subject: [PATCH 0650/1529] UefiPayloadPkg: Add CpuPageTableLib required by MpInitLib. Add CpuPageTableLib required by MpInitLib in UefiPayloadPkg. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiPayloadPkg/UefiPayloadPkg.dsc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 2dbd875f37..8cbbbe9a05 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -3,7 +3,7 @@ # # Provides drivers and definitions to create uefi payload for bootloaders. # -# Copyright (c) 2014 - 2022, Intel Corporation. All rights reserved.
+# Copyright (c) 2014 - 2023, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -340,6 +340,7 @@ DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf + CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf !if $(PERFORMANCE_MEASUREMENT_ENABLE) PerformanceLib|MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf From f34fedccc0e962fec4dd2c56183e6b60942eae85 Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:52 +0800 Subject: [PATCH 0651/1529] UefiCpuPkg: Put APs in 64 bit mode before handoff to OS. Add the 'AsmRelocateApLoopStartGeneric' for X64 processors except 64-bit AMD processors with SEV-ES. Remove the unused arguments of AsmRelocateApLoopStartGeneric, updated the stack offset. Create PageTable for the allocated reserved memory. Only keep 4GB limitation of memory allocation for the case APs still need to be transferred to 32-bit mode before OS. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 6 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 63 +++++++++----- .../Library/MpInitLib/Ia32/CreatePageTable.c | 23 ++++++ .../Library/MpInitLib/Ia32/MpFuncs.nasm | 26 +++--- UefiCpuPkg/Library/MpInitLib/MpEqu.inc | 22 ++--- UefiCpuPkg/Library/MpInitLib/MpLib.h | 43 +++++++++- .../Library/MpInitLib/X64/CreatePageTable.c | 82 +++++++++++++++++++ UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 57 ++++++++++++- 8 files changed, 273 insertions(+), 49 deletions(-) create mode 100644 UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c create mode 100644 UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index cd07de3a3c..4285dd06b4 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -1,7 +1,7 @@ ## @file # MP Initialize Library instance for DXE driver. # -# Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.
+# Copyright (c) 2016 - 2023, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -24,10 +24,12 @@ [Sources.IA32] Ia32/AmdSev.c Ia32/MpFuncs.nasm + Ia32/CreatePageTable.c [Sources.X64] X64/AmdSev.c X64/MpFuncs.nasm + X64/CreatePageTable.c [Sources.common] AmdSev.c @@ -56,6 +58,8 @@ PcdLib CcExitLib MicrocodeLib +[LibraryClasses.X64] + CpuPageTableLib [Protocols] gEfiTimerArchProtocolGuid ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index 224215878c..d292277d10 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -28,6 +28,7 @@ volatile BOOLEAN mStopCheckAllApsStatus = TRUE; RELOCATE_AP_LOOP_ENTRY mReservedApLoop; UINTN mReservedTopOfApStack; volatile UINT32 mNumberToFinish = 0; +UINTN mApPageTable; // // Begin wakeup buffer allocation below 0x88000 @@ -409,12 +410,9 @@ RelocateApLoop ( mReservedApLoop.GenericEntry ( MwaitSupport, CpuMpData->ApTargetCState, - CpuMpData->PmCodeSegment, StackStart - ProcessorNumber * AP_SAFE_STACK_SIZE, (UINTN)&mNumberToFinish, - CpuMpData->Pm16CodeSegment, - CpuMpData->SevEsAPBuffer, - CpuMpData->WakeupBuffer + mApPageTable ); } @@ -484,6 +482,9 @@ InitMpGlobalData ( EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; UINTN StackBase; CPU_INFO_IN_HOB *CpuInfoInHob; + MP_ASSEMBLY_ADDRESS_MAP *AddressMap; + UINT8 *ApLoopFunc; + UINTN ApLoopFuncSize; UINTN StackPages; UINTN FuncPages; @@ -540,6 +541,23 @@ InitMpGlobalData ( } } + AddressMap = &CpuMpData->AddressMap; + if (CpuMpData->UseSevEsAPMethod) { + // + // 64-bit AMD processors with SEV-ES + // + Address = BASE_4GB - 1; + ApLoopFunc = AddressMap->RelocateApLoopFuncAddress; + ApLoopFuncSize = AddressMap->RelocateApLoopFuncSize; + } else { + // + // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or 64-bit AMD processors without SEV-ES + // + Address = MAX_ADDRESS; + ApLoopFunc = AddressMap->RelocateApLoopFuncAddressGeneric; + ApLoopFuncSize = AddressMap->RelocateApLoopFuncSizeGeneric; + } + // // Avoid APs access invalid buffer data which allocated by BootServices, // so we will allocate reserved data for AP loop code. We also need to @@ -558,19 +576,15 @@ InitMpGlobalData ( // StackPages = EFI_SIZE_TO_PAGES (CpuMpData->CpuCount * AP_SAFE_STACK_SIZE); - FuncPages = EFI_SIZE_TO_PAGES (CpuMpData->AddressMap.RelocateApLoopFuncSize); - - Address = BASE_4GB - 1; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - StackPages + FuncPages, - &Address - ); - ASSERT_EFI_ERROR (Status); + FuncPages = EFI_SIZE_TO_PAGES (ApLoopFuncSize); - mReservedApLoop.Data = (VOID *)(UINTN)Address; - ASSERT (mReservedApLoop.Data != NULL); + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiReservedMemoryType, + StackPages + FuncPages, + &Address + ); + ASSERT_EFI_ERROR (Status); // // Make sure that the buffer memory is executable if NX protection is enabled @@ -590,11 +604,18 @@ InitMpGlobalData ( mReservedTopOfApStack = (UINTN)Address + EFI_PAGES_TO_SIZE (StackPages+FuncPages); ASSERT ((mReservedTopOfApStack & (UINTN)(CPU_STACK_ALIGNMENT - 1)) == 0); - CopyMem ( - mReservedApLoop.Data, - CpuMpData->AddressMap.RelocateApLoopFuncAddress, - CpuMpData->AddressMap.RelocateApLoopFuncSize - ); + mReservedApLoop.Data = (VOID *)(UINTN)Address; + ASSERT (mReservedApLoop.Data != NULL); + CopyMem (mReservedApLoop.Data, ApLoopFunc, ApLoopFuncSize); + if (!CpuMpData->UseSevEsAPMethod) { + // + // processors without SEV-ES + // + mApPageTable = CreatePageTable ( + (UINTN)Address, + EFI_PAGES_TO_SIZE (StackPages+FuncPages) + ); + } Status = gBS->CreateEvent ( EVT_TIMER | EVT_NOTIFY_SIGNAL, diff --git a/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c new file mode 100644 index 0000000000..bec9b247c0 --- /dev/null +++ b/UefiCpuPkg/Library/MpInitLib/Ia32/CreatePageTable.c @@ -0,0 +1,23 @@ +/** @file + Function to create page talbe. + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + Copyright (c) 2023, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include + +/** + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ) +{ + return 0; +} diff --git a/UefiCpuPkg/Library/MpInitLib/Ia32/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/Ia32/MpFuncs.nasm index bfcdbd31c1..59db4081d6 100644 --- a/UefiCpuPkg/Library/MpInitLib/Ia32/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/Ia32/MpFuncs.nasm @@ -1,5 +1,5 @@ ;------------------------------------------------------------------------------ ; -; Copyright (c) 2015 - 2022, Intel Corporation. All rights reserved.
+; Copyright (c) 2015 - 2023, Intel Corporation. All rights reserved.
; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: @@ -219,24 +219,24 @@ SwitchToRealProcEnd: RendezvousFunnelProcEnd: ;------------------------------------------------------------------------------------- -; AsmRelocateApLoop (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); +; AsmRelocateApLoopGeneric (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); ; ; The last three parameters (Pm16CodeSegment, SevEsAPJumpTable and WakeupBuffer) are ; specific to SEV-ES support and are not applicable on IA32. ;------------------------------------------------------------------------------------- -AsmRelocateApLoopStart: +AsmRelocateApLoopGenericStart: mov eax, esp - mov esp, [eax + 16] ; TopOfApStack + mov esp, [eax + 12] ; TopOfApStack push dword [eax] ; push return address for stack trace push ebp mov ebp, esp mov ebx, [eax + 8] ; ApTargetCState mov ecx, [eax + 4] ; MwaitSupport - mov eax, [eax + 20] ; CountTofinish + mov eax, [eax + 16] ; CountTofinish lock dec dword [eax] ; (*CountTofinish)-- cmp cl, 1 ; Check mwait-monitor support - jnz HltLoop -MwaitLoop: + jnz HltLoopGeneric +MwaitLoopGeneric: cli mov eax, esp xor ecx, ecx @@ -245,12 +245,12 @@ MwaitLoop: mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] shl eax, 4 mwait - jmp MwaitLoop -HltLoop: + jmp MwaitLoopGeneric +HltLoopGeneric: cli hlt - jmp HltLoop -AsmRelocateApLoopEnd: + jmp HltLoopGeneric +AsmRelocateApLoopGenericEnd: ;------------------------------------------------------------------------------------- ; AsmGetAddressMap (&AddressMap); @@ -264,8 +264,8 @@ ASM_PFX(AsmGetAddressMap): mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RendezvousFunnelAddress], RendezvousFunnelProcStart mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.ModeEntryOffset], Flat32Start - RendezvousFunnelProcStart mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RendezvousFunnelSize], RendezvousFunnelProcEnd - RendezvousFunnelProcStart - mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddress], AsmRelocateApLoopStart - mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSize], AsmRelocateApLoopEnd - AsmRelocateApLoopStart + mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressGeneric], AsmRelocateApLoopGenericStart + mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeGeneric], AsmRelocateApLoopGenericEnd - AsmRelocateApLoopGenericStart mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.ModeTransitionOffset], Flat32Start - RendezvousFunnelProcStart mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealNoNxOffset], SwitchToRealProcStart - Flat32Start mov dword [ebx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeOffset], 0 diff --git a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc index ebadcc6fb3..09c1817426 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc +++ b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc @@ -1,5 +1,5 @@ ;------------------------------------------------------------------------------ ; -; Copyright (c) 2015 - 2022, Intel Corporation. All rights reserved.
+; Copyright (c) 2015 - 2023, Intel Corporation. All rights reserved.
; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: @@ -21,15 +21,17 @@ CPU_SWITCH_STATE_LOADED equ 2 ; Equivalent NASM structure of MP_ASSEMBLY_ADDRESS_MAP ; struc MP_ASSEMBLY_ADDRESS_MAP - .RendezvousFunnelAddress CTYPE_UINTN 1 - .ModeEntryOffset CTYPE_UINTN 1 - .RendezvousFunnelSize CTYPE_UINTN 1 - .RelocateApLoopFuncAddress CTYPE_UINTN 1 - .RelocateApLoopFuncSize CTYPE_UINTN 1 - .ModeTransitionOffset CTYPE_UINTN 1 - .SwitchToRealNoNxOffset CTYPE_UINTN 1 - .SwitchToRealPM16ModeOffset CTYPE_UINTN 1 - .SwitchToRealPM16ModeSize CTYPE_UINTN 1 + .RendezvousFunnelAddress CTYPE_UINTN 1 + .ModeEntryOffset CTYPE_UINTN 1 + .RendezvousFunnelSize CTYPE_UINTN 1 + .RelocateApLoopFuncAddressGeneric CTYPE_UINTN 1 + .RelocateApLoopFuncSizeGeneric CTYPE_UINTN 1 + .RelocateApLoopFuncAddress CTYPE_UINTN 1 + .RelocateApLoopFuncSize CTYPE_UINTN 1 + .ModeTransitionOffset CTYPE_UINTN 1 + .SwitchToRealNoNxOffset CTYPE_UINTN 1 + .SwitchToRealPM16ModeOffset CTYPE_UINTN 1 + .SwitchToRealPM16ModeSize CTYPE_UINTN 1 endstruc ; diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 81a95733fc..e137545fc6 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -177,6 +177,8 @@ typedef struct { UINT8 *RendezvousFunnelAddress; UINTN ModeEntryOffset; UINTN RendezvousFunnelSize; + UINT8 *RelocateApLoopFuncAddressGeneric; + UINTN RelocateApLoopFuncSizeGeneric; UINT8 *RelocateApLoopFuncAddress; UINTN RelocateApLoopFuncSize; UINTN ModeTransitionOffset; @@ -361,6 +363,29 @@ extern EFI_GUID mCpuInitMpLibHobGuid; @param[in] ApTargetCState Target C-State value. @param[in] PmCodeSegment Protected mode code segment value. **/ +typedef + VOID +(EFIAPI *ASM_RELOCATE_AP_LOOP_GENERIC)( + IN BOOLEAN MwaitSupport, + IN UINTN ApTargetCState, + IN UINTN TopOfApStack, + IN UINTN NumberToFinish, + IN UINTN Cr3 + ); + +/** + Assembly code to place AP into safe loop mode for Amd processors + with Sev enabled. + Place AP into targeted C-State if MONITOR is supported, otherwise + place AP into hlt state. + Place AP in protected mode if the current is long mode. Due to AP maybe + wakeup by some hardware event. It could avoid accessing page table that + may not available during booting to OS. + @param[in] MwaitSupport TRUE indicates MONITOR is supported. + FALSE indicates MONITOR is not supported. + @param[in] ApTargetCState Target C-State value. + @param[in] PmCodeSegment Protected mode code segment value. +**/ typedef VOID (EFIAPI *ASM_RELOCATE_AP_LOOP)( @@ -403,9 +428,9 @@ AsmExchangeRole ( ); typedef union { - VOID *Data; - ASM_RELOCATE_AP_LOOP AmdSevEntry; // 64-bit AMD Sev processors - ASM_RELOCATE_AP_LOOP GenericEntry; // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or AMD non-Sev processors + VOID *Data; + ASM_RELOCATE_AP_LOOP AmdSevEntry; // 64-bit AMD Sev processors + ASM_RELOCATE_AP_LOOP_GENERIC GenericEntry; // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or AMD non-Sev processors } RELOCATE_AP_LOOP_ENTRY; /** @@ -471,6 +496,18 @@ GetSevEsAPMemory ( VOID ); +/** + Create 1:1 mapping page table in reserved memory to map the specified address range. + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ); + /** This function will be called by BSP to wakeup AP. diff --git a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c new file mode 100644 index 0000000000..7cf91ed9c4 --- /dev/null +++ b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c @@ -0,0 +1,82 @@ +/** @file + Function to create page talbe. + Only create page table for x64, and leave the CreatePageTable empty for Ia32. + Copyright (c) 2023, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include +#include +#include +#include +#include + +/** + Create 1:1 mapping page table in reserved memory to map the specified address range. + @param[in] LinearAddress The start of the linear address range. + @param[in] Length The length of the linear address range. + @return The page table to be created. +**/ +UINTN +CreatePageTable ( + IN UINTN Address, + IN UINTN Length + ) +{ + EFI_STATUS Status; + VOID *PageTableBuffer; + UINTN PageTableBufferSize; + UINTN PageTable; + PAGING_MODE PagingMode; + IA32_CR4 Cr4; + + IA32_MAP_ATTRIBUTE MapAttribute; + IA32_MAP_ATTRIBUTE MapMask; + + MapAttribute.Uint64 = Address; + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; + + MapMask.Bits.PageTableBaseAddress = 1; + MapMask.Bits.Present = 1; + MapMask.Bits.ReadWrite = 1; + + PageTable = 0; + PageTableBufferSize = 0; + + Cr4.UintN = AsmReadCr4 (); + + if (Cr4.Bits.LA57 == 1) { + PagingMode = Paging5Level; + } else { + PagingMode = Paging4Level; + } + + Status = PageTableMap ( + &PageTable, + PagingMode, + NULL, + &PageTableBufferSize, + Address, + Length, + &MapAttribute, + &MapMask + ); + ASSERT (Status == EFI_BUFFER_TOO_SMALL); + DEBUG ((DEBUG_INFO, "AP Page Table Buffer Size = %x\n", PageTableBufferSize)); + + PageTableBuffer = AllocateReservedPages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); + ASSERT (PageTableBuffer != NULL); + Status = PageTableMap ( + &PageTable, + PagingMode, + PageTableBuffer, + &PageTableBufferSize, + Address, + Length, + &MapAttribute, + &MapMask + ); + ASSERT_EFI_ERROR (Status); + return PageTable; +} diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 5d71995bf8..c0d7355c6b 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -1,5 +1,5 @@ ;------------------------------------------------------------------------------ ; -; Copyright (c) 2015 - 2022, Intel Corporation. All rights reserved.
+; Copyright (c) 2015 - 2023, Intel Corporation. All rights reserved.
; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: @@ -447,6 +447,58 @@ DoHlt: BITS 64 AsmRelocateApLoopEnd: +;------------------------------------------------------------------------------------- +; AsmRelocateApLoop (MwaitSupport, ApTargetCState, TopOfApStack, CountTofinish, Cr3); +; This function is called during the finalizaiton of Mp initialization before booting +; to OS, and aim to put Aps either in Mwait or HLT. +;------------------------------------------------------------------------------------- +; +----------------+ +; | Cr3 | rsp+40 +; +----------------+ +; | CountTofinish | r9 +; +----------------+ +; | TopOfApStack | r8 +; +----------------+ +; | ApTargetCState | rdx +; +----------------+ +; | MwaitSupport | rcx +; +----------------+ +; | the return | +; +----------------+ low address + +AsmRelocateApLoopGenericStart: + mov rax, r9 ; CountTofinish + lock dec dword [rax] ; (*CountTofinish)-- + + mov rax, [rsp + 40] ; Cr3 + ; Do not push on old stack, since old stack is not mapped + ; in the page table pointed by cr3 + mov cr3, rax + mov rsp, r8 ; TopOfApStack + +MwaitCheckGeneric: + cmp cl, 1 ; Check mwait-monitor support + jnz HltLoopGeneric + mov rbx, rdx ; Save C-State to ebx + +MwaitLoopGeneric: + cli + mov rax, rsp ; Set Monitor Address + xor ecx, ecx ; ecx = 0 + xor edx, edx ; edx = 0 + monitor + mov rax, rbx ; Mwait Cx, Target C-State per eax[7:4] + shl eax, 4 + mwait + jmp MwaitLoopGeneric + +HltLoopGeneric: + cli + hlt + jmp HltLoopGeneric + +AsmRelocateApLoopGenericEnd: + ;------------------------------------------------------------------------------------- ; AsmGetAddressMap (&AddressMap); ;------------------------------------------------------------------------------------- @@ -456,6 +508,9 @@ ASM_PFX(AsmGetAddressMap): mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RendezvousFunnelAddress], rax mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.ModeEntryOffset], LongModeStart - RendezvousFunnelProcStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RendezvousFunnelSize], RendezvousFunnelProcEnd - RendezvousFunnelProcStart +lea rax, [AsmRelocateApLoopGenericStart] + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressGeneric], rax + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeGeneric], AsmRelocateApLoopGenericEnd - AsmRelocateApLoopGenericStart lea rax, [AsmRelocateApLoopStart] mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddress], rax mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSize], AsmRelocateApLoopEnd - AsmRelocateApLoopStart From 27c96bf99c167d25014f4ad4ce362cac5250f201 Mon Sep 17 00:00:00 2001 From: Yuanhao Xie Date: Wed, 1 Mar 2023 14:09:53 +0800 Subject: [PATCH 0652/1529] UefiCpuPkg: Rename AsmRelocateApLoopStart. Rename AsmRelocateApLoopStart to AsmRelocateApLoopStartAmdSev Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 4 +- UefiCpuPkg/Library/MpInitLib/MpEqu.inc | 4 +- UefiCpuPkg/Library/MpInitLib/MpLib.h | 8 ++-- UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 40 +++++++++---------- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index d292277d10..330676b700 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -547,8 +547,8 @@ InitMpGlobalData ( // 64-bit AMD processors with SEV-ES // Address = BASE_4GB - 1; - ApLoopFunc = AddressMap->RelocateApLoopFuncAddress; - ApLoopFuncSize = AddressMap->RelocateApLoopFuncSize; + ApLoopFunc = AddressMap->RelocateApLoopFuncAddressAmdSev; + ApLoopFuncSize = AddressMap->RelocateApLoopFuncSizeAmdSev; } else { // // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or 64-bit AMD processors without SEV-ES diff --git a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc index 09c1817426..72af196513 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpEqu.inc +++ b/UefiCpuPkg/Library/MpInitLib/MpEqu.inc @@ -26,8 +26,8 @@ struc MP_ASSEMBLY_ADDRESS_MAP .RendezvousFunnelSize CTYPE_UINTN 1 .RelocateApLoopFuncAddressGeneric CTYPE_UINTN 1 .RelocateApLoopFuncSizeGeneric CTYPE_UINTN 1 - .RelocateApLoopFuncAddress CTYPE_UINTN 1 - .RelocateApLoopFuncSize CTYPE_UINTN 1 + .RelocateApLoopFuncAddressAmdSev CTYPE_UINTN 1 + .RelocateApLoopFuncSizeAmdSev CTYPE_UINTN 1 .ModeTransitionOffset CTYPE_UINTN 1 .SwitchToRealNoNxOffset CTYPE_UINTN 1 .SwitchToRealPM16ModeOffset CTYPE_UINTN 1 diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index e137545fc6..6f235dcf6d 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -179,8 +179,8 @@ typedef struct { UINTN RendezvousFunnelSize; UINT8 *RelocateApLoopFuncAddressGeneric; UINTN RelocateApLoopFuncSizeGeneric; - UINT8 *RelocateApLoopFuncAddress; - UINTN RelocateApLoopFuncSize; + UINT8 *RelocateApLoopFuncAddressAmdSev; + UINTN RelocateApLoopFuncSizeAmdSev; UINTN ModeTransitionOffset; UINTN SwitchToRealNoNxOffset; UINTN SwitchToRealPM16ModeOffset; @@ -388,7 +388,7 @@ typedef **/ typedef VOID -(EFIAPI *ASM_RELOCATE_AP_LOOP)( +(EFIAPI *ASM_RELOCATE_AP_LOOP_AMDSEV)( IN BOOLEAN MwaitSupport, IN UINTN ApTargetCState, IN UINTN PmCodeSegment, @@ -429,7 +429,7 @@ AsmExchangeRole ( typedef union { VOID *Data; - ASM_RELOCATE_AP_LOOP AmdSevEntry; // 64-bit AMD Sev processors + ASM_RELOCATE_AP_LOOP_AMDSEV AmdSevEntry; // 64-bit AMD Sev processors ASM_RELOCATE_AP_LOOP_GENERIC GenericEntry; // Intel processors (32-bit or 64-bit), 32-bit AMD processors, or AMD non-Sev processors } RELOCATE_AP_LOOP_ENTRY; diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index c0d7355c6b..1a64d5681f 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -277,14 +277,14 @@ CProcedureInvoke: %include "AmdSev.nasm" RendezvousFunnelProcEnd: - ;------------------------------------------------------------------------------------- -; AsmRelocateApLoop (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); +; AsmRelocateApLoopAmdSev (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); ;------------------------------------------------------------------------------------- -AsmRelocateApLoopStart: + +AsmRelocateApLoopAmdSevStart: BITS 64 cmp qword [rsp + 56], 0 ; SevEsAPJumpTable - je NoSevEs + je NoSevEsAmdSev ; ; Perform some SEV-ES related setup before leaving 64-bit mode @@ -329,7 +329,7 @@ BITS 64 pop rdx pop rcx -NoSevEs: +NoSevEsAmdSev: cli ; Disable interrupt before switching to 32-bit mode mov rax, [rsp + 40] ; CountTofinish lock dec dword [rax] ; (*CountTofinish)-- @@ -345,7 +345,7 @@ NoSevEs: push rcx ; Save MwaitSupport push rdx ; Save ApTargetCState - lea rax, [PmEntry] ; rax <- The start address of transition code + lea rax, [PmEntryAmdSev] ; rax <- The start address of transition code push r8 push rax @@ -365,10 +365,10 @@ NoSevEs: ; ; Far return into 32-bit mode ; - retfq +o64 retf BITS 32 -PmEntry: +PmEntryAmdSev: mov eax, cr0 btr eax, 31 ; Clear CR0.PG mov cr0, eax ; Disable paging and caches @@ -386,11 +386,11 @@ PmEntry: pop ecx, add esp, 4 -MwaitCheck: +MwaitCheckAmdSev: cmp cl, 1 ; Check mwait-monitor support - jnz HltLoop + jnz HltLoopAmdSev mov ebx, edx ; Save C-State to ebx -MwaitLoop: +MwaitLoopAmdSev: cli mov eax, esp ; Set Monitor Address xor ecx, ecx ; ecx = 0 @@ -399,9 +399,9 @@ MwaitLoop: mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] shl eax, 4 mwait - jmp MwaitLoop + jmp MwaitLoopAmdSev -HltLoop: +HltLoopAmdSev: pop edx ; PM16CodeSegment add esp, 4 pop ebx ; WakeupBuffer @@ -409,7 +409,7 @@ HltLoop: pop eax ; SevEsAPJumpTable add esp, 4 cmp eax, 0 ; Check for SEV-ES - je DoHlt + je DoHltAmdSev cli ; @@ -439,13 +439,13 @@ BITS 32 retf -DoHlt: +DoHltAmdSev: cli hlt - jmp DoHlt + jmp DoHltAmdSev BITS 64 -AsmRelocateApLoopEnd: +AsmRelocateApLoopAmdSevEnd: ;------------------------------------------------------------------------------------- ; AsmRelocateApLoop (MwaitSupport, ApTargetCState, TopOfApStack, CountTofinish, Cr3); @@ -511,9 +511,9 @@ ASM_PFX(AsmGetAddressMap): lea rax, [AsmRelocateApLoopGenericStart] mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressGeneric], rax mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeGeneric], AsmRelocateApLoopGenericEnd - AsmRelocateApLoopGenericStart - lea rax, [AsmRelocateApLoopStart] - mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddress], rax - mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSize], AsmRelocateApLoopEnd - AsmRelocateApLoopStart + lea rax, [AsmRelocateApLoopAmdSevStart] + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncAddressAmdSev], rax + mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.RelocateApLoopFuncSizeAmdSev], AsmRelocateApLoopAmdSevEnd - AsmRelocateApLoopAmdSevStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.ModeTransitionOffset], Flat32Start - RendezvousFunnelProcStart mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealNoNxOffset], SwitchToRealProcStart - Flat32Start mov qword [rcx + MP_ASSEMBLY_ADDRESS_MAP.SwitchToRealPM16ModeOffset], PM16Mode - RendezvousFunnelProcStart From 485b5c356e276b1b9ff4870ad073e7f72554b114 Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Wed, 1 Mar 2023 14:09:54 +0800 Subject: [PATCH 0653/1529] UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Yuanhao Xie Acked-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm | 170 ++++++++++++++++++ UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 169 ----------------- 2 files changed, 170 insertions(+), 169 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm index 7c2469f9c5..2efa3cb104 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.nasm @@ -346,3 +346,173 @@ PM16Mode: iret SwitchToRealProcEnd: + +;------------------------------------------------------------------------------------- +; AsmRelocateApLoopAmdSev (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); +;------------------------------------------------------------------------------------- + +AsmRelocateApLoopAmdSevStart: +BITS 64 + cmp qword [rsp + 56], 0 ; SevEsAPJumpTable + je NoSevEsAmdSev + + ; + ; Perform some SEV-ES related setup before leaving 64-bit mode + ; + push rcx + push rdx + + ; + ; Get the RDX reset value using CPUID + ; + mov rax, 1 + cpuid + mov rsi, rax ; Save off the reset value for RDX + + ; + ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call + ; - Must be done while in 64-bit long mode so that writes to + ; the GHCB memory will be unencrypted. + ; - No NAE events can be generated once this is set otherwise + ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. + ; + mov rcx, 0xc0010130 + rdmsr ; Retrieve current GHCB address + shl rdx, 32 + or rdx, rax + + mov rdi, rdx + xor rax, rax + mov rcx, 0x800 + shr rcx, 3 + rep stosq ; Clear the GHCB + + mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD + mov [rdx + 0x390], rax + mov rax, 114 ; Set SwExitCode valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo1 valid bit + bts [rdx + 0x3f0], rax + inc rax ; Set SwExitInfo2 valid bit + bts [rdx + 0x3f0], rax + + pop rdx + pop rcx + +NoSevEsAmdSev: + cli ; Disable interrupt before switching to 32-bit mode + mov rax, [rsp + 40] ; CountTofinish + lock dec dword [rax] ; (*CountTofinish)-- + + mov r10, [rsp + 48] ; Pm16CodeSegment + mov rax, [rsp + 56] ; SevEsAPJumpTable + mov rbx, [rsp + 64] ; WakeupBuffer + mov rsp, r9 ; TopOfApStack + + push rax ; Save SevEsAPJumpTable + push rbx ; Save WakeupBuffer + push r10 ; Save Pm16CodeSegment + push rcx ; Save MwaitSupport + push rdx ; Save ApTargetCState + + lea rax, [PmEntryAmdSev] ; rax <- The start address of transition code + + push r8 + push rax + + ; + ; Clear R8 - R15, for reset, before going into 32-bit mode + ; + xor r8, r8 + xor r9, r9 + xor r10, r10 + xor r11, r11 + xor r12, r12 + xor r13, r13 + xor r14, r14 + xor r15, r15 + + ; + ; Far return into 32-bit mode + ; +o64 retf + +BITS 32 +PmEntryAmdSev: + mov eax, cr0 + btr eax, 31 ; Clear CR0.PG + mov cr0, eax ; Disable paging and caches + + mov ecx, 0xc0000080 + rdmsr + and ah, ~ 1 ; Clear LME + wrmsr + mov eax, cr4 + and al, ~ (1 << 5) ; Clear PAE + mov cr4, eax + + pop edx + add esp, 4 + pop ecx, + add esp, 4 + +MwaitCheckAmdSev: + cmp cl, 1 ; Check mwait-monitor support + jnz HltLoopAmdSev + mov ebx, edx ; Save C-State to ebx +MwaitLoopAmdSev: + cli + mov eax, esp ; Set Monitor Address + xor ecx, ecx ; ecx = 0 + xor edx, edx ; edx = 0 + monitor + mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] + shl eax, 4 + mwait + jmp MwaitLoopAmdSev + +HltLoopAmdSev: + pop edx ; PM16CodeSegment + add esp, 4 + pop ebx ; WakeupBuffer + add esp, 4 + pop eax ; SevEsAPJumpTable + add esp, 4 + cmp eax, 0 ; Check for SEV-ES + je DoHltAmdSev + + cli + ; + ; SEV-ES is enabled, use VMGEXIT (GHCB information already + ; set by caller) + ; +BITS 64 + rep vmmcall +BITS 32 + + ; + ; Back from VMGEXIT AP_HLT_LOOP + ; Push the FLAGS/CS/IP values to use + ; + push word 0x0002 ; EFLAGS + xor ecx, ecx + mov cx, [eax + 2] ; CS + push cx + mov cx, [eax] ; IP + push cx + push word 0x0000 ; For alignment, will be discarded + + push edx + push ebx + + mov edx, esi ; Restore RDX reset value + + retf + +DoHltAmdSev: + cli + hlt + jmp DoHltAmdSev + +BITS 64 +AsmRelocateApLoopAmdSevEnd: diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 1a64d5681f..9ebe31795b 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -277,175 +277,6 @@ CProcedureInvoke: %include "AmdSev.nasm" RendezvousFunnelProcEnd: -;------------------------------------------------------------------------------------- -; AsmRelocateApLoopAmdSev (MwaitSupport, ApTargetCState, PmCodeSegment, TopOfApStack, CountTofinish, Pm16CodeSegment, SevEsAPJumpTable, WakeupBuffer); -;------------------------------------------------------------------------------------- - -AsmRelocateApLoopAmdSevStart: -BITS 64 - cmp qword [rsp + 56], 0 ; SevEsAPJumpTable - je NoSevEsAmdSev - - ; - ; Perform some SEV-ES related setup before leaving 64-bit mode - ; - push rcx - push rdx - - ; - ; Get the RDX reset value using CPUID - ; - mov rax, 1 - cpuid - mov rsi, rax ; Save off the reset value for RDX - - ; - ; Prepare the GHCB for the AP_HLT_LOOP VMGEXIT call - ; - Must be done while in 64-bit long mode so that writes to - ; the GHCB memory will be unencrypted. - ; - No NAE events can be generated once this is set otherwise - ; the AP_RESET_HOLD SW_EXITCODE will be overwritten. - ; - mov rcx, 0xc0010130 - rdmsr ; Retrieve current GHCB address - shl rdx, 32 - or rdx, rax - - mov rdi, rdx - xor rax, rax - mov rcx, 0x800 - shr rcx, 3 - rep stosq ; Clear the GHCB - - mov rax, 0x80000004 ; VMGEXIT AP_RESET_HOLD - mov [rdx + 0x390], rax - mov rax, 114 ; Set SwExitCode valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo1 valid bit - bts [rdx + 0x3f0], rax - inc rax ; Set SwExitInfo2 valid bit - bts [rdx + 0x3f0], rax - - pop rdx - pop rcx - -NoSevEsAmdSev: - cli ; Disable interrupt before switching to 32-bit mode - mov rax, [rsp + 40] ; CountTofinish - lock dec dword [rax] ; (*CountTofinish)-- - - mov r10, [rsp + 48] ; Pm16CodeSegment - mov rax, [rsp + 56] ; SevEsAPJumpTable - mov rbx, [rsp + 64] ; WakeupBuffer - mov rsp, r9 ; TopOfApStack - - push rax ; Save SevEsAPJumpTable - push rbx ; Save WakeupBuffer - push r10 ; Save Pm16CodeSegment - push rcx ; Save MwaitSupport - push rdx ; Save ApTargetCState - - lea rax, [PmEntryAmdSev] ; rax <- The start address of transition code - - push r8 - push rax - - ; - ; Clear R8 - R15, for reset, before going into 32-bit mode - ; - xor r8, r8 - xor r9, r9 - xor r10, r10 - xor r11, r11 - xor r12, r12 - xor r13, r13 - xor r14, r14 - xor r15, r15 - - ; - ; Far return into 32-bit mode - ; -o64 retf - -BITS 32 -PmEntryAmdSev: - mov eax, cr0 - btr eax, 31 ; Clear CR0.PG - mov cr0, eax ; Disable paging and caches - - mov ecx, 0xc0000080 - rdmsr - and ah, ~ 1 ; Clear LME - wrmsr - mov eax, cr4 - and al, ~ (1 << 5) ; Clear PAE - mov cr4, eax - - pop edx - add esp, 4 - pop ecx, - add esp, 4 - -MwaitCheckAmdSev: - cmp cl, 1 ; Check mwait-monitor support - jnz HltLoopAmdSev - mov ebx, edx ; Save C-State to ebx -MwaitLoopAmdSev: - cli - mov eax, esp ; Set Monitor Address - xor ecx, ecx ; ecx = 0 - xor edx, edx ; edx = 0 - monitor - mov eax, ebx ; Mwait Cx, Target C-State per eax[7:4] - shl eax, 4 - mwait - jmp MwaitLoopAmdSev - -HltLoopAmdSev: - pop edx ; PM16CodeSegment - add esp, 4 - pop ebx ; WakeupBuffer - add esp, 4 - pop eax ; SevEsAPJumpTable - add esp, 4 - cmp eax, 0 ; Check for SEV-ES - je DoHltAmdSev - - cli - ; - ; SEV-ES is enabled, use VMGEXIT (GHCB information already - ; set by caller) - ; -BITS 64 - rep vmmcall -BITS 32 - - ; - ; Back from VMGEXIT AP_HLT_LOOP - ; Push the FLAGS/CS/IP values to use - ; - push word 0x0002 ; EFLAGS - xor ecx, ecx - mov cx, [eax + 2] ; CS - push cx - mov cx, [eax] ; IP - push cx - push word 0x0000 ; For alignment, will be discarded - - push edx - push ebx - - mov edx, esi ; Restore RDX reset value - - retf - -DoHltAmdSev: - cli - hlt - jmp DoHltAmdSev - -BITS 64 -AsmRelocateApLoopAmdSevEnd: ;------------------------------------------------------------------------------------- ; AsmRelocateApLoop (MwaitSupport, ApTargetCState, TopOfApStack, CountTofinish, Cr3); From 30b8f82b689286eb186717706cf85797a6d0fa68 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 14 Feb 2023 03:19:55 +0800 Subject: [PATCH 0654/1529] CryptoPkg/BaseCryptLib: avoid using SHA1() In openssl 3.0 SHA1() goes through the provider logic, requiring a huge amount of openssl code. The individual functions do not, so use them instead. Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLib/Hash/CryptSha1.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha1.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha1.c index 1e071ce2b3..cfe1f4bc44 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha1.c +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha1.c @@ -204,6 +204,8 @@ Sha1HashAll ( OUT UINT8 *HashValue ) { + SHA_CTX Context; + // // Check input parameters. // @@ -218,11 +220,19 @@ Sha1HashAll ( // // OpenSSL SHA-1 Hash Computation. // - if (SHA1 (Data, DataSize, HashValue) == NULL) { + if (!SHA1_Init (&Context)) { return FALSE; - } else { - return TRUE; } + + if (!SHA1_Update (&Context, Data, DataSize)) { + return FALSE; + } + + if (!SHA1_Final (HashValue, &Context)) { + return FALSE; + } + + return TRUE; } #endif From 3b2da48960cdab325a32ac0a547cde52a162f930 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 14 Feb 2023 03:19:56 +0800 Subject: [PATCH 0655/1529] CryptoPkg/BaseCryptLib: avoid using SHA256() In openssl 3.0 SHA256() goes through the provider logic, requiring a huge amount of openssl code. The individual functions do not, so use them instead. Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/Hash/CryptSha256.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha256.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha256.c index f105e6e577..4d7d92812c 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha256.c +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha256.c @@ -202,6 +202,8 @@ Sha256HashAll ( OUT UINT8 *HashValue ) { + SHA256_CTX Context; + // // Check input parameters. // @@ -216,9 +218,17 @@ Sha256HashAll ( // // OpenSSL SHA-256 Hash Computation. // - if (SHA256 (Data, DataSize, HashValue) == NULL) { + if (!SHA256_Init (&Context)) { return FALSE; - } else { - return TRUE; } + + if (!SHA256_Update (&Context, Data, DataSize)) { + return FALSE; + } + + if (!SHA256_Final (HashValue, &Context)) { + return FALSE; + } + + return TRUE; } From 430a251381dd1ff24a036e15616a1bb6ef64076d Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 14 Feb 2023 03:19:57 +0800 Subject: [PATCH 0656/1529] CryptoPkg/BaseCryptLib: avoid using SHA384() In openssl 3.0 SHA384() goes through the provider logic, requiring a huge amount of openssl code. The individual functions do not, so use them instead. Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/Hash/CryptSha512.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c index 59e5708465..2ab7188035 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c @@ -204,6 +204,8 @@ Sha384HashAll ( OUT UINT8 *HashValue ) { + SHA512_CTX Context; + // // Check input parameters. // @@ -218,11 +220,19 @@ Sha384HashAll ( // // OpenSSL SHA-384 Hash Computation. // - if (SHA384 (Data, DataSize, HashValue) == NULL) { + if (!SHA384_Init (&Context)) { + return FALSE; + } + + if (!SHA384_Update (&Context, Data, DataSize)) { return FALSE; - } else { - return TRUE; } + + if (!SHA384_Final (HashValue, &Context)) { + return FALSE; + } + + return TRUE; } /** From 9105c53dd861fa7f3b438b3092cba4094c02ceeb Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 14 Feb 2023 03:19:58 +0800 Subject: [PATCH 0657/1529] CryptoPkg/BaseCryptLib: avoid using SHA512() In openssl 3.0 SHA512() goes through the provider logic, requiring a huge amount of openssl code. The individual functions do not, so use them instead. Signed-off-by: Gerd Hoffmann Reviewed-by: Jiewen Yao --- .../Library/BaseCryptLib/Hash/CryptSha512.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c index 2ab7188035..dee8f35c41 100644 --- a/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c +++ b/CryptoPkg/Library/BaseCryptLib/Hash/CryptSha512.c @@ -430,6 +430,8 @@ Sha512HashAll ( OUT UINT8 *HashValue ) { + SHA512_CTX Context; + // // Check input parameters. // @@ -444,9 +446,17 @@ Sha512HashAll ( // // OpenSSL SHA-512 Hash Computation. // - if (SHA512 (Data, DataSize, HashValue) == NULL) { + if (!SHA512_Init (&Context)) { + return FALSE; + } + + if (!SHA512_Update (&Context, Data, DataSize)) { return FALSE; - } else { - return TRUE; } + + if (!SHA512_Final (HashValue, &Context)) { + return FALSE; + } + + return TRUE; } From 8734f1ec5272fea21d9f6c216ac19001a3634ea2 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Tue, 7 Mar 2023 14:31:36 +0800 Subject: [PATCH 0658/1529] UefiCpuPkg: Calculate DisplayFamily correctly REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4348 Per SDM: DisplayFamily = Extended_Family_ID + Family_ID. DisplayModelID = (Extended_Model_ID << 4) + Family_ID. Correct the related code. Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Acked-by: Gerd Hoffmann Reviewed-by: Star Zeng Cc: Mike Maslenkin Signed-off-by: Zhiguang Liu --- UefiCpuPkg/Application/Cpuid/Cpuid.c | 6 +++--- .../Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/UefiCpuPkg/Application/Cpuid/Cpuid.c b/UefiCpuPkg/Application/Cpuid/Cpuid.c index 372c6ef87d..172476a275 100644 --- a/UefiCpuPkg/Application/Cpuid/Cpuid.c +++ b/UefiCpuPkg/Application/Cpuid/Cpuid.c @@ -1,7 +1,7 @@ /** @file UEFI Application to display CPUID leaf information. - Copyright (c) 2016 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -217,12 +217,12 @@ CpuidVersionInfo ( DisplayFamily = Eax.Bits.FamilyId; if (Eax.Bits.FamilyId == 0x0F) { - DisplayFamily |= (Eax.Bits.ExtendedFamilyId << 4); + DisplayFamily += Eax.Bits.ExtendedFamilyId; } DisplayModel = Eax.Bits.Model; if ((Eax.Bits.FamilyId == 0x06) || (Eax.Bits.FamilyId == 0x0f)) { - DisplayModel |= (Eax.Bits.ExtendedModelId << 4); + DisplayModel += (Eax.Bits.ExtendedModelId << 4); } Print (L" Family = %x Model = %x Stepping = %x\n", DisplayFamily, DisplayModel, Eax.Bits.SteppingId); diff --git a/UefiCpuPkg/Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c b/UefiCpuPkg/Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c index a8e4f920fc..552fdab417 100644 --- a/UefiCpuPkg/Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c +++ b/UefiCpuPkg/Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c @@ -1,7 +1,7 @@ /** @file CPU Features Initialize functions. - Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.
+ Copyright (c) 2017 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -67,12 +67,12 @@ FillProcessorInfo ( DisplayedFamily = Eax.Bits.FamilyId; if (Eax.Bits.FamilyId == 0x0F) { - DisplayedFamily |= (Eax.Bits.ExtendedFamilyId << 4); + DisplayedFamily += Eax.Bits.ExtendedFamilyId; } DisplayedModel = Eax.Bits.Model; if ((Eax.Bits.FamilyId == 0x06) || (Eax.Bits.FamilyId == 0x0f)) { - DisplayedModel |= (Eax.Bits.ExtendedModelId << 4); + DisplayedModel += (Eax.Bits.ExtendedModelId << 4); } CpuInfo->DisplayFamily = DisplayedFamily; From 5cb37a1120dccbdc431ed6ea518c1627c1b5fa5c Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Thu, 24 Nov 2022 17:17:54 +0100 Subject: [PATCH 0659/1529] SecurityPkg/RngDxe: Correctly update mAvailableAlgoArrayCount mAvailableAlgoArrayCount holds the count of available RNG algorithms. In a following patch, its value will be used to prevent the EFI_RNG_PROTOCOL to be installed if no RNG algorithm is available. Correctly set/reset the value for all implementations. Signed-off-by: Pierre Gondois Reviewed-by: Ard Biesheuvel --- SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c | 1 + SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c index 5ba319899c..ce49ff7ae6 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/ArmRngDxe.c @@ -40,6 +40,7 @@ FreeAvailableAlgorithms ( VOID ) { + mAvailableAlgoArrayCount = 0; FreePool (mAvailableAlgoArray); return; } diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c index 677600bed7..7e06e16e4b 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/Rand/RngDxe.c @@ -26,6 +26,11 @@ #include "RngDxeInternals.h" +// +// Count of Rng algorithms. +// +#define RNG_ALGORITHM_COUNT 2 + /** Allocate and initialize mAvailableAlgoArray with the available Rng algorithms. Also update mAvailableAlgoArrayCount. @@ -38,6 +43,7 @@ GetAvailableAlgorithms ( VOID ) { + mAvailableAlgoArrayCount = RNG_ALGORITHM_COUNT; return EFI_SUCCESS; } @@ -49,6 +55,7 @@ FreeAvailableAlgorithms ( VOID ) { + mAvailableAlgoArrayCount = 0; return; } @@ -164,7 +171,7 @@ RngGetInfo ( return EFI_INVALID_PARAMETER; } - RequiredSize = 2 * sizeof (EFI_RNG_ALGORITHM); + RequiredSize = RNG_ALGORITHM_COUNT * sizeof (EFI_RNG_ALGORITHM); if (*RNGAlgorithmListSize < RequiredSize) { *RNGAlgorithmListSize = RequiredSize; From 9dc9be0b652918f88b0c99c9e80b70dc15282c53 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Thu, 24 Nov 2022 17:17:55 +0100 Subject: [PATCH 0660/1529] SecurityPkg/RngDxe: Conditionally install EFI_RNG_PROTOCOL On Arm platforms, the number of available RNG algorithms is dynamically detected and can be 0 in the absence of FEAT_RNG and firmware TRNG. In this case, the EFI_RNG_PROTOCOL should not be installed to prevent from installing an empty protocol. Signed-off-by: Pierre Gondois [ardb: return EFI_REQUEST_UNLOAD_IMAGE instead of an error] Reviewed-by: Ard Biesheuvel --- .../RandomNumberGenerator/RngDxe/RngDxe.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c index 421abb52b8..292338b7d0 100644 --- a/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c +++ b/SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.c @@ -63,6 +63,18 @@ RngDriverEntry ( EFI_STATUS Status; EFI_HANDLE Handle; + // + // Get the list of available algorithm. + // + Status = GetAvailableAlgorithms (); + if (EFI_ERROR (Status)) { + return Status; + } + + if (mAvailableAlgoArrayCount == 0) { + return EFI_REQUEST_UNLOAD_IMAGE; + } + // // Install UEFI RNG (Random Number Generator) Protocol // @@ -74,13 +86,10 @@ RngDriverEntry ( NULL ); if (EFI_ERROR (Status)) { - return Status; + FreeAvailableAlgorithms (); } - // - // Get the list of available algorithm. - // - return GetAvailableAlgorithms (); + return Status; } /** From 120bb345bcea2e4692ba1cc53315c8a3a76996d4 Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:31:58 -0600 Subject: [PATCH 0661/1529] OvmfPkg: RiscVVirt: add SATA support Tested with a PCIe pass-thru'd AHCI controller. Cc: Sunil V L Cc: Jiewen Yao Cc: Ard Biesheuvel Signed-off-by: Andrei Warkentin --- OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc | 7 +++++++ OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc index 054d511138..28d9af4d79 100644 --- a/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc +++ b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc @@ -426,6 +426,13 @@ MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf + # + # SATA + # + MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf + MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf + MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf + # # NVME Driver # diff --git a/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf b/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf index 6072c37af0..354c9271d1 100644 --- a/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf +++ b/OvmfPkg/RiscVVirt/RiscVVirtQemu.fdf @@ -137,6 +137,13 @@ INF OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf INF MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf INF MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf +# +# SATA +# +INF MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf +INF MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf +INF MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf + # # NVME Driver # From d20a664ac0984ff8eeea0fcc58a83693384b595e Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:33:55 -0600 Subject: [PATCH 0662/1529] MdePkg: BasePeCoffLib: Allow AArch64 and x64 images in ImageFormatSupported ARM64 and X64 may allow such foreign images to be used when driver implementing EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL is present. Cc: Sunil V L Cc: Daniel Schaefer Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Andrei Warkentin --- MdePkg/Library/BasePeCoffLib/RiscV/PeCoffLoaderEx.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/MdePkg/Library/BasePeCoffLib/RiscV/PeCoffLoaderEx.c b/MdePkg/Library/BasePeCoffLib/RiscV/PeCoffLoaderEx.c index adbfe9ccf5..67c4af1d65 100644 --- a/MdePkg/Library/BasePeCoffLib/RiscV/PeCoffLoaderEx.c +++ b/MdePkg/Library/BasePeCoffLib/RiscV/PeCoffLoaderEx.c @@ -104,7 +104,15 @@ PeCoffLoaderImageFormatSupported ( IN UINT16 Machine ) { - if (Machine == IMAGE_FILE_MACHINE_RISCV64) { + /* + * ARM64 and X64 may allow such foreign images to be used when + * a driver implementing EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL is + * present. + */ + if ((Machine == IMAGE_FILE_MACHINE_RISCV64) || + (Machine == IMAGE_FILE_MACHINE_ARM64) || + (Machine == IMAGE_FILE_MACHINE_X64)) + { return TRUE; } From b6458ee4416f42491ee9deb33381f0cd44b601ec Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:43:08 -0600 Subject: [PATCH 0663/1529] MdePkg: BaseLib: don't log in RISCV InternalSwitchStack InternalSwitchStack may be called with a TPL high enough for a DebugLib implementation to assert. Other arch implementations don't log either. Cc: Daniel Schaefer Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Reviewed-by: Sunil V L Signed-off-by: Andrei Warkentin --- MdePkg/Library/BaseLib/RiscV64/InternalSwitchStack.c | 8 -------- 1 file changed, 8 deletions(-) diff --git a/MdePkg/Library/BaseLib/RiscV64/InternalSwitchStack.c b/MdePkg/Library/BaseLib/RiscV64/InternalSwitchStack.c index cf646e498a..b78424c163 100644 --- a/MdePkg/Library/BaseLib/RiscV64/InternalSwitchStack.c +++ b/MdePkg/Library/BaseLib/RiscV64/InternalSwitchStack.c @@ -44,14 +44,6 @@ InternalSwitchStack ( { BASE_LIBRARY_JUMP_BUFFER JumpBuffer; - DEBUG (( - DEBUG_INFO, - "RISC-V InternalSwitchStack Entry:%x Context1:%x Context2:%x NewStack%x\n", \ - EntryPoint, - Context1, - Context2, - NewStack - )); JumpBuffer.RA = (UINTN)EntryPoint; JumpBuffer.SP = (UINTN)NewStack - sizeof (VOID *); JumpBuffer.S0 = (UINT64)(UINTN)Context1; From 655ad1d20e69179227cd65af3d84bfd80f07fc77 Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:44:15 -0600 Subject: [PATCH 0664/1529] MdePkg: BaseCpuLib: Fix RISCV CpuSleep symbol name. CpuSleep, not _CpuSleep. Cc: Daniel Schaefer Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Reviewed-by: Sunil V L Signed-off-by: Andrei Warkentin --- MdePkg/Library/BaseCpuLib/RiscV/Cpu.S | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Library/BaseCpuLib/RiscV/Cpu.S b/MdePkg/Library/BaseCpuLib/RiscV/Cpu.S index 375b91d314..d6560087e0 100644 --- a/MdePkg/Library/BaseCpuLib/RiscV/Cpu.S +++ b/MdePkg/Library/BaseCpuLib/RiscV/Cpu.S @@ -10,9 +10,9 @@ .align 3 .section .text -.global ASM_PFX(_CpuSleep) +.global ASM_PFX(CpuSleep) -ASM_PFX(_CpuSleep): +ASM_PFX(CpuSleep): wfi ret From d7a715e8d05433c2701cdd62b9dc6906e9c8864a Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:57:22 -0600 Subject: [PATCH 0665/1529] MdeModulePkg: Dxe: add RISCV64 to mMachineTypeInfo This fixes messages like: "Image type AARCH64 can't be loaded on UEFI system" Cc: Daniel Schaefer Cc: Liming Gao Cc: Jian J Wang Reviewed-by: Sunil V L Signed-off-by: Andrei Warkentin --- MdeModulePkg/Core/Dxe/Image/Image.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Core/Dxe/Image/Image.c b/MdeModulePkg/Core/Dxe/Image/Image.c index 06cc6744b8..8704ebea9a 100644 --- a/MdeModulePkg/Core/Dxe/Image/Image.c +++ b/MdeModulePkg/Core/Dxe/Image/Image.c @@ -81,7 +81,8 @@ GLOBAL_REMOVE_IF_UNREFERENCED MACHINE_TYPE_INFO mMachineTypeInfo[] = { { EFI_IMAGE_MACHINE_IA64, L"IA64" }, { EFI_IMAGE_MACHINE_X64, L"X64" }, { EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM" }, - { EFI_IMAGE_MACHINE_AARCH64, L"AARCH64" } + { EFI_IMAGE_MACHINE_AARCH64, L"AARCH64" }, + { EFI_IMAGE_MACHINE_RISCV64, L"RISCV64" }, }; UINT16 mDxeCoreImageMachineType = 0; From 43c1ea542e297b4758aaf1262edc977e5599bd15 Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:44:51 -0600 Subject: [PATCH 0666/1529] UefiCpuPkg: CpuTimerDxeRiscV64: fix tick duration accounting The TimerDxe implementation doesn't account for the physical time passed due to timer handler execution or (perhaps even more importantly) time spent with interrupts masked. Other implementations (e.g. like the Arm one) do. If the timer tick is always incremented at a fixed rate, then you can slow down UEFI's perception of time by running long sections of code in a critical section. Cc: Daniel Schaefer Reviewed-by: Sunil V L Signed-off-by: Andrei Warkentin --- UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c | 35 ++++++++++++++++----------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c index db153f715e..287e7e1330 100644 --- a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c @@ -40,7 +40,8 @@ STATIC EFI_TIMER_NOTIFY mTimerNotifyFunction; // // The current period of the timer interrupt // -STATIC UINT64 mTimerPeriod = 0; +STATIC UINT64 mTimerPeriod = 0; +STATIC UINT64 mLastPeriodStart = 0; /** Timer Interrupt Handler. @@ -56,25 +57,33 @@ TimerInterruptHandler ( ) { EFI_TPL OriginalTPL; - UINT64 RiscvTimer; + UINT64 PeriodStart; + + PeriodStart = RiscVReadTimer (); OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL); if (mTimerNotifyFunction != NULL) { - mTimerNotifyFunction (mTimerPeriod); + // + // For any number of reasons, the ticks could be coming + // in slower than mTimerPeriod. For example, some code + // is doing a *lot* of stuff inside an EFI_TPL_HIGH + // critical section, and this should not cause the EFI + // time to increment slower. So when we take an interrupt, + // account for the actual time passed. + // + mTimerNotifyFunction (PeriodStart - mLastPeriodStart); } - RiscVDisableTimerInterrupt (); // Disable SMode timer int - RiscVClearPendingTimerInterrupt (); if (mTimerPeriod == 0) { + RiscVDisableTimerInterrupt (); gBS->RestoreTPL (OriginalTPL); - RiscVDisableTimerInterrupt (); // Disable SMode timer int return; } - RiscvTimer = RiscVReadTimer (); - SbiSetTimer (RiscvTimer += mTimerPeriod); - gBS->RestoreTPL (OriginalTPL); + mLastPeriodStart = PeriodStart; + SbiSetTimer (PeriodStart += mTimerPeriod); RiscVEnableTimerInterrupt (); // enable SMode timer int + gBS->RestoreTPL (OriginalTPL); } /** @@ -154,8 +163,6 @@ TimerDriverSetTimerPeriod ( IN UINT64 TimerPeriod ) { - UINT64 RiscvTimer; - DEBUG ((DEBUG_INFO, "TimerDriverSetTimerPeriod(0x%lx)\n", TimerPeriod)); if (TimerPeriod == 0) { @@ -164,9 +171,9 @@ TimerDriverSetTimerPeriod ( return EFI_SUCCESS; } - mTimerPeriod = TimerPeriod / 10; // convert unit from 100ns to 1us - RiscvTimer = RiscVReadTimer (); - SbiSetTimer (RiscvTimer + mTimerPeriod); + mTimerPeriod = TimerPeriod / 10; // convert unit from 100ns to 1us + mLastPeriodStart = RiscVReadTimer (); + SbiSetTimer (mLastPeriodStart + mTimerPeriod); mCpu->EnableInterrupt (mCpu); RiscVEnableTimerInterrupt (); // enable SMode timer int From 483f434244fef5f9842871e8022ef75323d9ddea Mon Sep 17 00:00:00 2001 From: Andrei Warkentin Date: Fri, 17 Feb 2023 18:42:29 -0600 Subject: [PATCH 0667/1529] UefiCpuPkg: BaseRiscV64CpuExceptionHandlerLib: clean up RegisterCpuInterruptHandler did not allow setting exception handlers for anything beyond the timer IRQ. Beyond that, it didn't meet the spec around handling of inputs. RiscVSupervisorModeTrapHandler now will invoke set handlers for both exceptions and interrupts. Two arrays of handlers are maintained - one for exceptions and one for interrupts. For unhandled traps, RiscVSupervisorModeTrapHandler dumps state using the now implemented DumpCpuContext. For EFI_SYSTEM_CONTEXT_RISCV64, extend this with the trapped PC address (SEPC), just like on AArch64 (ELR). This is necessary for X86EmulatorPkg to work as it allows a trap handler to return execution to a different place. Add SSTATUS/STVAL as well, at least for debugging purposes. There is no value in hiding this. Fix nested exception handling. Handler code should not be saving SIE (the value is saved in SSTATUS.SPIE) or directly restored (that's done by SRET). Save and restore the entire SSTATUS and STVAL, too. Cc: Daniel Schaefer Reviewed-by: Sunil V L Signed-off-by: Andrei Warkentin --- MdePkg/Include/Protocol/DebugSupport.h | 34 ++- UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c | 6 +- .../CpuExceptionHandlerLib.c | 238 ++++++++++++++++-- .../CpuExceptionHandlerLib.h | 11 +- .../SupervisorTrapHandler.S | 17 +- 5 files changed, 261 insertions(+), 45 deletions(-) diff --git a/MdePkg/Include/Protocol/DebugSupport.h b/MdePkg/Include/Protocol/DebugSupport.h index 2b0ae2d157..9742663619 100644 --- a/MdePkg/Include/Protocol/DebugSupport.h +++ b/MdePkg/Include/Protocol/DebugSupport.h @@ -613,11 +613,34 @@ typedef struct { #define EXCEPT_RISCV_STORE_AMO_ACCESS_FAULT 7 #define EXCEPT_RISCV_ENV_CALL_FROM_UMODE 8 #define EXCEPT_RISCV_ENV_CALL_FROM_SMODE 9 -#define EXCEPT_RISCV_ENV_CALL_FROM_HMODE 10 +#define EXCEPT_RISCV_ENV_CALL_FROM_VS_MODE 10 #define EXCEPT_RISCV_ENV_CALL_FROM_MMODE 11 - -#define EXCEPT_RISCV_SOFTWARE_INT 0x0 -#define EXCEPT_RISCV_TIMER_INT 0x1 +#define EXCEPT_RISCV_INST_ACCESS_PAGE_FAULT 12 +#define EXCEPT_RISCV_LOAD_ACCESS_PAGE_FAULT 13 +#define EXCEPT_RISCV_14 14 +#define EXCEPT_RISCV_STORE_ACCESS_PAGE_FAULT 15 +#define EXCEPT_RISCV_16 16 +#define EXCEPT_RISCV_17 17 +#define EXCEPT_RISCV_18 18 +#define EXCEPT_RISCV_19 19 +#define EXCEPT_RISCV_INST_GUEST_PAGE_FAULT 20 +#define EXCEPT_RISCV_LOAD_GUEST_PAGE_FAULT 21 +#define EXCEPT_RISCV_VIRTUAL_INSTRUCTION 22 +#define EXCEPT_RISCV_STORE_GUEST_PAGE_FAULT 23 +#define EXCEPT_RISCV_MAX_EXCEPTIONS (EXCEPT_RISCV_STORE_GUEST_PAGE_FAULT) + +/// +/// RISC-V processor exception types for interrupts. +/// +#define EXCEPT_RISCV_IS_IRQ(x) ((x & 0x8000000000000000UL) != 0) +#define EXCEPT_RISCV_IRQ_INDEX(x) (x & 0x7FFFFFFFFFFFFFFFUL) +#define EXCEPT_RISCV_IRQ_0 0x8000000000000000UL +#define EXCEPT_RISCV_IRQ_SOFT_FROM_SMODE 0x8000000000000001UL +#define EXCEPT_RISCV_IRQ_SOFT_FROM_VSMODE 0x8000000000000002UL +#define EXCEPT_RISCV_IRQ_SOFT_FROM_MMODE 0x8000000000000003UL +#define EXCEPT_RISCV_IRQ_4 0x8000000000000004UL +#define EXCEPT_RISCV_IRQ_TIMER_FROM_SMODE 0x8000000000000005UL +#define EXCEPT_RISCV_MAX_IRQS (EXCEPT_RISCV_IRQ_INDEX(EXCEPT_RISCV_IRQ_TIMER_FROM_SMODE)) typedef struct { UINT64 X0; @@ -652,6 +675,9 @@ typedef struct { UINT64 X29; UINT64 X30; UINT64 X31; + UINT64 SEPC; + UINT32 SSTATUS; + UINT32 STVAL; } EFI_SYSTEM_CONTEXT_RISCV64; // diff --git a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c index 287e7e1330..fa957ba5e3 100644 --- a/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c +++ b/UefiCpuPkg/CpuTimerDxeRiscV64/Timer.c @@ -278,7 +278,11 @@ TimerDriverInitialize ( // // Install interrupt handler for RISC-V Timer. // - Status = mCpu->RegisterInterruptHandler (mCpu, EXCEPT_RISCV_TIMER_INT, TimerInterruptHandler); + Status = mCpu->RegisterInterruptHandler ( + mCpu, + EXCEPT_RISCV_IRQ_TIMER_FROM_SMODE, + TimerInterruptHandler + ); ASSERT_EFI_ERROR (Status); // diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c index f1ee7d236a..bce089feb0 100644 --- a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c @@ -11,11 +11,168 @@ #include #include #include +#include +#include #include - #include "CpuExceptionHandlerLib.h" -STATIC EFI_CPU_INTERRUPT_HANDLER mInterruptHandlers[2]; +// +// Define the maximum message length +// +#define MAX_DEBUG_MESSAGE_LENGTH 0x100 + +STATIC EFI_CPU_INTERRUPT_HANDLER mExceptionHandlers[EXCEPT_RISCV_MAX_EXCEPTIONS + 1]; +STATIC EFI_CPU_INTERRUPT_HANDLER mIrqHandlers[EXCEPT_RISCV_MAX_IRQS + 1]; + +STATIC CONST CHAR8 mExceptionOrIrqUnknown[] = "Unknown"; +STATIC CONST CHAR8 *mExceptionNameStr[EXCEPT_RISCV_MAX_EXCEPTIONS + 1] = { + "EXCEPT_RISCV_INST_MISALIGNED", + "EXCEPT_RISCV_INST_ACCESS_FAULT", + "EXCEPT_RISCV_ILLEGAL_INST", + "EXCEPT_RISCV_BREAKPOINT", + "EXCEPT_RISCV_LOAD_ADDRESS_MISALIGNED", + "EXCEPT_RISCV_LOAD_ACCESS_FAULT", + "EXCEPT_RISCV_STORE_AMO_ADDRESS_MISALIGNED", + "EXCEPT_RISCV_STORE_AMO_ACCESS_FAULT", + "EXCEPT_RISCV_ENV_CALL_FROM_UMODE", + "EXCEPT_RISCV_ENV_CALL_FROM_SMODE", + "EXCEPT_RISCV_ENV_CALL_FROM_VS_MODE", + "EXCEPT_RISCV_ENV_CALL_FROM_MMODE", + "EXCEPT_RISCV_INST_ACCESS_PAGE_FAULT", + "EXCEPT_RISCV_LOAD_ACCESS_PAGE_FAULT", + "EXCEPT_RISCV_14", + "EXCEPT_RISCV_STORE_ACCESS_PAGE_FAULT", + "EXCEPT_RISCV_16", + "EXCEPT_RISCV_17", + "EXCEPT_RISCV_18", + "EXCEPT_RISCV_19", + "EXCEPT_RISCV_INST_GUEST_PAGE_FAULT", + "EXCEPT_RISCV_LOAD_GUEST_PAGE_FAULT", + "EXCEPT_RISCV_VIRTUAL_INSTRUCTION", + "EXCEPT_RISCV_STORE_GUEST_PAGE_FAULT" +}; + +STATIC CONST CHAR8 *mIrqNameStr[EXCEPT_RISCV_MAX_IRQS + 1] = { + "EXCEPT_RISCV_IRQ_0", + "EXCEPT_RISCV_IRQ_SOFT_FROM_SMODE", + "EXCEPT_RISCV_IRQ_SOFT_FROM_VSMODE", + "EXCEPT_RISCV_IRQ_SOFT_FROM_MMODE", + "EXCEPT_RISCV_IRQ_4", + "EXCEPT_RISCV_IRQ_TIMER_FROM_SMODE", +}; + +/** + Prints a message to the serial port. + + @param Format Format string for the message to print. + @param ... Variable argument list whose contents are accessed + based on the format string specified by Format. + +**/ +STATIC +VOID +EFIAPI +InternalPrintMessage ( + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; + VA_LIST Marker; + + // + // Convert the message to an ASCII String + // + VA_START (Marker, Format); + AsciiVSPrint (Buffer, sizeof (Buffer), Format, Marker); + VA_END (Marker); + + // + // Send the print string to a Serial Port + // + SerialPortWrite ((UINT8 *)Buffer, AsciiStrLen (Buffer)); +} + +/** + Get ASCII format string exception name by exception type. + + @param ExceptionType Exception type. + + @return ASCII format string exception name. +**/ +STATIC +CONST CHAR8 * +GetExceptionNameStr ( + IN EFI_EXCEPTION_TYPE ExceptionType + ) +{ + if (EXCEPT_RISCV_IS_IRQ (ExceptionType)) { + if (EXCEPT_RISCV_IRQ_INDEX (ExceptionType) > EXCEPT_RISCV_MAX_IRQS) { + return mExceptionOrIrqUnknown; + } + + return mIrqNameStr[EXCEPT_RISCV_IRQ_INDEX (ExceptionType)]; + } + + if (ExceptionType > EXCEPT_RISCV_MAX_EXCEPTIONS) { + return mExceptionOrIrqUnknown; + } + + return mExceptionNameStr[ExceptionType]; +} + +/** + Display CPU information. This can be called by 3rd-party handlers + set by RegisterCpuInterruptHandler. + + @param ExceptionType Exception type. + @param SystemContext Pointer to EFI_SYSTEM_CONTEXT. +**/ +VOID +EFIAPI +DumpCpuContext ( + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext + ) +{ + UINTN Printed; + SMODE_TRAP_REGISTERS *Regs; + + Printed = 0; + Regs = (SMODE_TRAP_REGISTERS *)SystemContext.SystemContextRiscV64; + + InternalPrintMessage ( + "!!!! RISCV64 Exception Type - %016x(%a) !!!!\n", + ExceptionType, + GetExceptionNameStr (ExceptionType) + ); + + DEBUG_CODE_BEGIN (); + + #define REGS() \ + REG (t0); REG (t1); REG (t2); REG (t3); REG (t4); REG (t5); REG (t6); \ + REG (s0); REG (s1); REG (s2); REG (s3); REG (s4); REG (s5); REG (s6); \ + REG (s7); REG (s8); REG (s9); REG (s10); REG (s11); \ + REG (a0); REG (a1); REG (a2); REG (a3); REG (a4); REG (a5); REG (a6); \ + REG (a7); \ + REG (zero); REG (ra); REG (sp); REG (gp); REG (tp); \ + REG (sepc); REG (sstatus); REG (stval); + + #define REG(x) do { \ + InternalPrintMessage ("%7a = 0x%017lx%c", #x, Regs->x, \ + (++Printed % 2) ? L'\t' : L'\n'); \ + } while (0); + + REGS (); + if (Printed % 2 != 0) { + InternalPrintMessage ("\n"); + } + + #undef REG + #undef REGS + + DEBUG_CODE_END (); +} /** Initializes all CPU exceptions entries and provides the default exception handlers. @@ -47,34 +204,59 @@ InitializeCpuExceptionHandlers ( Registers a function to be called from the processor interrupt handler. This function registers and enables the handler specified by InterruptHandler for a processor - interrupt or exception type specified by InterruptType. If InterruptHandler is NULL, then the - handler for the processor interrupt or exception type specified by InterruptType is uninstalled. + interrupt or exception type specified by ExceptionType. If InterruptHandler is NULL, then the + handler for the processor interrupt or exception type specified by ExceptionType is uninstalled. The installed handler is called once for each processor interrupt or exception. NOTE: This function should be invoked after InitializeCpuExceptionHandlers() or InitializeCpuInterruptHandlers() invoked, otherwise EFI_UNSUPPORTED returned. - @param[in] InterruptType Defines which interrupt or exception to hook. + @param[in] ExceptionType Defines which interrupt or exception to hook. @param[in] InterruptHandler A pointer to a function of type EFI_CPU_INTERRUPT_HANDLER that is called when a processor interrupt occurs. If this parameter is NULL, then the handler will be uninstalled. @retval EFI_SUCCESS The handler for the processor interrupt was successfully installed or uninstalled. - @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler for InterruptType was + @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler for ExceptionType was previously installed. - @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for InterruptType was not + @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for ExceptionType was not previously installed. - @retval EFI_UNSUPPORTED The interrupt specified by InterruptType is not supported, + @retval EFI_UNSUPPORTED The interrupt specified by ExceptionType is not supported, or this function is not supported. **/ EFI_STATUS EFIAPI RegisterCpuInterruptHandler ( - IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_EXCEPTION_TYPE ExceptionType, IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler ) { - DEBUG ((DEBUG_INFO, "%a: Type:%x Handler: %x\n", __FUNCTION__, InterruptType, InterruptHandler)); - mInterruptHandlers[InterruptType] = InterruptHandler; + DEBUG ((DEBUG_INFO, "%a: Type:%x Handler: %x\n", __FUNCTION__, ExceptionType, InterruptHandler)); + if (EXCEPT_RISCV_IS_IRQ (ExceptionType)) { + if (EXCEPT_RISCV_IRQ_INDEX (ExceptionType) > EXCEPT_RISCV_MAX_IRQS) { + return EFI_UNSUPPORTED; + } + + if (mIrqHandlers[EXCEPT_RISCV_IRQ_INDEX (ExceptionType)] != NULL) { + return EFI_ALREADY_STARTED; + } else if (InterruptHandler == NULL) { + return EFI_INVALID_PARAMETER; + } + + mIrqHandlers[EXCEPT_RISCV_IRQ_INDEX (ExceptionType)] = InterruptHandler; + } else { + if (ExceptionType > EXCEPT_RISCV_MAX_EXCEPTIONS) { + return EFI_UNSUPPORTED; + } + + if (mExceptionHandlers[ExceptionType] != NULL) { + return EFI_ALREADY_STARTED; + } else if (InterruptHandler == NULL) { + return EFI_INVALID_PARAMETER; + } + + mExceptionHandlers[ExceptionType] = InterruptHandler; + } + return EFI_SUCCESS; } @@ -113,21 +295,31 @@ RiscVSupervisorModeTrapHandler ( SMODE_TRAP_REGISTERS *SmodeTrapReg ) { - UINTN SCause; + EFI_EXCEPTION_TYPE ExceptionType; EFI_SYSTEM_CONTEXT RiscVSystemContext; + UINTN IrqIndex; RiscVSystemContext.SystemContextRiscV64 = (EFI_SYSTEM_CONTEXT_RISCV64 *)SmodeTrapReg; - // - // Check scasue register. - // - SCause = (UINTN)RiscVGetSupervisorTrapCause (); - if ((SCause & (1UL << (sizeof (UINTN) * 8- 1))) != 0) { - // - // This is interrupt event. - // - SCause &= ~(1UL << (sizeof (UINTN) * 8- 1)); - if ((SCause == IRQ_S_TIMER) && (mInterruptHandlers[EXCEPT_RISCV_TIMER_INT] != NULL)) { - mInterruptHandlers[EXCEPT_RISCV_TIMER_INT](EXCEPT_RISCV_TIMER_INT, RiscVSystemContext); + ExceptionType = (UINTN)RiscVGetSupervisorTrapCause (); + + if (EXCEPT_RISCV_IS_IRQ (ExceptionType)) { + IrqIndex = EXCEPT_RISCV_IRQ_INDEX (ExceptionType); + + if ((IrqIndex <= EXCEPT_RISCV_MAX_IRQS) && + (mIrqHandlers[IrqIndex] != NULL)) + { + mIrqHandlers[IrqIndex](ExceptionType, RiscVSystemContext); + return; + } + } else { + if ((ExceptionType <= EXCEPT_RISCV_MAX_EXCEPTIONS) && + (mExceptionHandlers[ExceptionType] != 0)) + { + mExceptionHandlers[ExceptionType](ExceptionType, RiscVSystemContext); + return; } } + + DumpCpuContext (ExceptionType, RiscVSystemContext); + CpuDeadLoop (); } diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h index 30f47e8755..9b7e1304dd 100644 --- a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.h @@ -59,7 +59,7 @@ SupervisorModeTrap ( #define SMODE_TRAP_REGS_t6 31 #define SMODE_TRAP_REGS_sepc 32 #define SMODE_TRAP_REGS_sstatus 33 -#define SMODE_TRAP_REGS_sie 34 +#define SMODE_TRAP_REGS_stval 34 #define SMODE_TRAP_REGS_last 35 #define SMODE_TRAP_REGS_OFFSET(x) ((SMODE_TRAP_REGS_##x) * __SIZEOF_POINTER__) @@ -68,7 +68,7 @@ SupervisorModeTrap ( #pragma pack(1) typedef struct { // - // Below are follow the format of EFI_SYSTEM_CONTEXT + // Below follow the format of EFI_SYSTEM_CONTEXT. // UINT64 zero; UINT64 ra; @@ -102,14 +102,9 @@ typedef struct { UINT64 t4; UINT64 t5; UINT64 t6; - // - // Below are the additional information to - // EFI_SYSTEM_CONTEXT, private to supervisor mode trap - // and not public to EFI environment. - // UINT64 sepc; UINT64 sstatus; - UINT64 sie; + UINT64 stval; } SMODE_TRAP_REGISTERS; #pragma pack() diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S index 649c4c5bec..45070b5cda 100644 --- a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/SupervisorTrapHandler.S @@ -20,14 +20,14 @@ SupervisorModeTrap: sd t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) csrr t0, CSR_SSTATUS - and t0, t0, (SSTATUS_SIE | SSTATUS_SPIE) sd t0, SMODE_TRAP_REGS_OFFSET(sstatus)(sp) csrr t0, CSR_SEPC sd t0, SMODE_TRAP_REGS_OFFSET(sepc)(sp) - csrr t0, CSR_SIE - sd t0, SMODE_TRAP_REGS_OFFSET(sie)(sp) + csrr t0, CSR_STVAL + sd t0, SMODE_TRAP_REGS_OFFSET(stval)(sp) ld t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) + sd zero, SMODE_TRAP_REGS_OFFSET(zero)(sp) sd ra, SMODE_TRAP_REGS_OFFSET(ra)(sp) sd gp, SMODE_TRAP_REGS_OFFSET(gp)(sp) sd tp, SMODE_TRAP_REGS_OFFSET(tp)(sp) @@ -59,6 +59,7 @@ SupervisorModeTrap: sd t6, SMODE_TRAP_REGS_OFFSET(t6)(sp) /* Call to Supervisor mode trap handler in CpuExceptionHandlerLib.c */ + mv a0, sp call RiscVSupervisorModeTrapHandler /* Restore all general regisers except SP */ @@ -66,6 +67,7 @@ SupervisorModeTrap: ld gp, SMODE_TRAP_REGS_OFFSET(gp)(sp) ld tp, SMODE_TRAP_REGS_OFFSET(tp)(sp) ld t2, SMODE_TRAP_REGS_OFFSET(t2)(sp) + ld t1, SMODE_TRAP_REGS_OFFSET(t1)(sp) ld s0, SMODE_TRAP_REGS_OFFSET(s0)(sp) ld s1, SMODE_TRAP_REGS_OFFSET(s1)(sp) ld a0, SMODE_TRAP_REGS_OFFSET(a0)(sp) @@ -93,13 +95,10 @@ SupervisorModeTrap: ld t0, SMODE_TRAP_REGS_OFFSET(sepc)(sp) csrw CSR_SEPC, t0 - ld t0, SMODE_TRAP_REGS_OFFSET(sie)(sp) - csrw CSR_SIE, t0 - csrr t0, CSR_SSTATUS - ld t1, SMODE_TRAP_REGS_OFFSET(sstatus)(sp) - or t0, t0, t1 + ld t0, SMODE_TRAP_REGS_OFFSET(sstatus)(sp) csrw CSR_SSTATUS, t0 - ld t1, SMODE_TRAP_REGS_OFFSET(t1)(sp) + ld t0, SMODE_TRAP_REGS_OFFSET(stval)(sp) + csrw CSR_STVAL, t0 ld t0, SMODE_TRAP_REGS_OFFSET(t0)(sp) addi sp, sp, SMODE_TRAP_REGS_SIZE sret From 5f0b08b8478a143f7a808c3c75b5e190c2bcf031 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 15 Feb 2023 15:37:32 +0100 Subject: [PATCH 0668/1529] ArmPkg/SemihostFs: replace SetMem with ZeroMem SetMem arguments 2+3 are in the wrong order, resulting in the call having no effect because Length is zero. Fix this by using ZeroMem instead. Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4205 Reported-by: Jeremy Boone Signed-off-by: Gerd Hoffmann Reviewed-by: Rebecca Cran Reviewed-by: Sami Mujawar --- ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c b/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c index 39a30533ee..9cc9ed7d36 100644 --- a/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c +++ b/ArmPkg/Filesystem/SemihostFs/Arm/SemihostFs.c @@ -574,7 +574,7 @@ ExtendFile ( } Remaining = Size; - SetMem (WriteBuffer, 0, sizeof (WriteBuffer)); + ZeroMem (WriteBuffer, sizeof (WriteBuffer)); while (Remaining > 0) { WriteNb = MIN (Remaining, sizeof (WriteBuffer)); WriteSize = WriteNb; From 96000917675a215cd391fb1a9c87fa6fe17a857b Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 9 Mar 2023 10:02:07 +0100 Subject: [PATCH 0669/1529] OvmfPkg/SmbiosPlatformDxe: tweak fallback release date In case PcdFirmwareReleaseDateString is not set use a valid date as fallback. Using "unknown" makes Windows unhappy. Fixes: 4cb94f20b002 ("OvmfPkg/SmbiosPlatformDxe: use PcdFirmware*") Reported-by: ruifeng.gao@intel.com Signed-off-by: Gerd Hoffmann Reviewed-by: Ard Biesheuvel --- OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c index dc1e6aed63..0ca3776045 100644 --- a/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c +++ b/OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.c @@ -160,7 +160,7 @@ InstallAllStructures ( DateStr = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareReleaseDateString); DateLen = StrLen (DateStr); if (DateLen < 3) { - DateStr = L"unknown"; + DateStr = L"2/2/2022"; DateLen = StrLen (DateStr); } From 7c118633e8d99604b744a0a3c195da13ad6c7aba Mon Sep 17 00:00:00 2001 From: "S, Ashraf Ali" Date: Thu, 9 Mar 2023 08:05:57 -0800 Subject: [PATCH 0670/1529] IntelFsp2Pkg: Fix GCC Compiler warning. Function definition should match with declaration. [-Wlto-type-mismatch] Cc: Chasel Chiu Cc: Nate DeSimone Cc: Sai Chaganty Cc: Star Zeng Signed-off-by: Ashraf Ali S Reviewed-by: Chasel Chiu Reviewed-by: Nate DeSimone Reviewed-by: Sai Chaganty Reviewed-by: Star Zeng --- IntelFsp2Pkg/Library/BaseFspPlatformLib/FspPlatformNotify.c | 1 + 1 file changed, 1 insertion(+) diff --git a/IntelFsp2Pkg/Library/BaseFspPlatformLib/FspPlatformNotify.c b/IntelFsp2Pkg/Library/BaseFspPlatformLib/FspPlatformNotify.c index 795bb28c0f..a5a51c804c 100644 --- a/IntelFsp2Pkg/Library/BaseFspPlatformLib/FspPlatformNotify.c +++ b/IntelFsp2Pkg/Library/BaseFspPlatformLib/FspPlatformNotify.c @@ -296,6 +296,7 @@ FspTempRamExitDone2 ( **/ VOID +EFIAPI FspWaitForNotify ( VOID ) From 226c1ec80642611cc8b64fe6853f4941770fd55b Mon Sep 17 00:00:00 2001 From: Sheng Wei Date: Tue, 28 Feb 2023 10:43:57 +0800 Subject: [PATCH 0671/1529] CryptoPkg/OpensslLib: Upgrade OpenSSL to 1.1.1t Upgrade openssl to 1.1.1t Pick up bugfixes from the latest openssl release. Cc: Jian J Wang Cc: Jiewen Yao Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Sheng Wei Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 1 + CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf | 1 + CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf | 1 + CryptoPkg/Library/OpensslLib/OpensslLibFull.inf | 1 + CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf | 1 + CryptoPkg/Library/OpensslLib/openssl | 2 +- 6 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 60c6c24b0a..1474df8125 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -162,6 +162,7 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/bn/rsa_sup_mul.c $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 103ef7bda2..3c5f6d5d17 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -163,6 +163,7 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/bn/rsa_sup_mul.c $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index c4eaea888c..a9adb94720 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -163,6 +163,7 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/bn/rsa_sup_mul.c $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index 309e43055c..4c2cbe9cf7 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -167,6 +167,7 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/bn/rsa_sup_mul.c $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 4eeeeb79bd..591c57fdc2 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -168,6 +168,7 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c + $(OPENSSL_PATH)/crypto/bn/rsa_sup_mul.c $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c diff --git a/CryptoPkg/Library/OpensslLib/openssl b/CryptoPkg/Library/OpensslLib/openssl index 129058165d..830bf8e1e4 160000 --- a/CryptoPkg/Library/OpensslLib/openssl +++ b/CryptoPkg/Library/OpensslLib/openssl @@ -1 +1 @@ -Subproject commit 129058165d195e43a0ad10111b0c2e29bdf65980 +Subproject commit 830bf8e1e4749ad65c51b6a1d0d769ae689404ba From 2652e1ab101be7291c92bf4772597742b47c72e6 Mon Sep 17 00:00:00 2001 From: Darbin Reyes Date: Tue, 7 Mar 2023 15:04:03 -0800 Subject: [PATCH 0672/1529] UefiCpuPkg/MicrocodeMeasurementDxe: Fix exception REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4360 An incorrect format specifier is being used in a DEBUG print, specifically, a variable of type EFI_STATUS was being printed with the %a format specifier (pointer to an ASCII string), thus the value of the Status variable was being treated as the address of a string, leading to a CPU exception, when encountered this bug manifests itself as a hang near "Ready to Boot Event", with the last DEBUG print being "INFO: Got MicrocodePatchHob with microcode patches starting address" followed by a CPU Exception dump. Signed-off-by: Darbin Reyes Reviewed-by: Jacob Narey Reviewed-by: Michael D Kinney Reviewed-by: Eric Dong --- UefiCpuPkg/MicrocodeMeasurementDxe/MicrocodeMeasurementDxe.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiCpuPkg/MicrocodeMeasurementDxe/MicrocodeMeasurementDxe.c b/UefiCpuPkg/MicrocodeMeasurementDxe/MicrocodeMeasurementDxe.c index 762ca159ff..5fd3b3365c 100644 --- a/UefiCpuPkg/MicrocodeMeasurementDxe/MicrocodeMeasurementDxe.c +++ b/UefiCpuPkg/MicrocodeMeasurementDxe/MicrocodeMeasurementDxe.c @@ -238,7 +238,7 @@ MeasureMicrocodePatches ( TotalMicrocodeSize) ); } else { - DEBUG ((DEBUG_ERROR, "ERROR: TpmMeasureAndLogData failed with status %a!\n", Status)); + DEBUG ((DEBUG_ERROR, "ERROR: TpmMeasureAndLogData failed with status %r!\n", Status)); } FreePool (Offsets); From c7c1584ea7bdce9c8be459efd53386f97c7fadb7 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Tue, 1 Nov 2022 09:33:15 +0800 Subject: [PATCH 0673/1529] OvmfPkg: Add CpuLib to module INFs that depend on UefiCpuLib. There are two libraries: MdePkg/CpuLib and UefiCpuPkg/UefiCpuLib and UefiCpuPkg/UefiCpuLib will be merged to MdePkg/CpuLib. To avoid build failure, add CpuLib dependency to all modules that depend on UefiCpuLib. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Acked-by: Gerd Hoffmann Signed-off-by: Zhiguang Liu --- OvmfPkg/IntelTdx/Sec/SecMain.c | 1 + OvmfPkg/IntelTdx/Sec/SecMain.inf | 1 + OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf | 1 + OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c | 1 + OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf | 1 + 5 files changed, 5 insertions(+) diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index ccb217b709..8f1f75b294 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.inf b/OvmfPkg/IntelTdx/Sec/SecMain.inf index 9cf1249d02..e112ba80bc 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.inf +++ b/OvmfPkg/IntelTdx/Sec/SecMain.inf @@ -38,6 +38,7 @@ BaseMemoryLib PcdLib UefiCpuLib + CpuLib DebugAgentLib IoLib PeCoffLib diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf index e77ad7bc92..b1c936b960 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf @@ -46,6 +46,7 @@ BaseMemoryLib PcdLib UefiCpuLib + CpuLib DebugAgentLib IoLib LocalApicLib diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c index c580a28856..063875b34b 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf index e504bda0dd..83e3c8b842 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf @@ -37,6 +37,7 @@ BaseMemoryLib PcdLib UefiCpuLib + CpuLib DebugAgentLib IoLib SynchronizationLib From d047fbe3931f51ad253ae4d6ccde9a31c4a48e24 Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:28:32 +0800 Subject: [PATCH 0674/1529] MdePkg: Move API and implementation from UefiCpuLib to CpuLib There are two libraries: MdePkg/CpuLib and UefiCpuPkg/UefiCpuLib. This patch merges UefiCpuPkg/UefiCpuLib to MdePkg/CpuLib. Change-Id: Ic26f4c2614ed6bd9840f817d50e47ac1de4bd013 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Signed-off-by: Yu Pu Reviewed-by: Liming Gao Signed-off-by: Zhiguang Liu --- MdePkg/Include/Library/CpuLib.h | 48 ++++++++++++++++++ MdePkg/Library/BaseCpuLib/BaseCpuLib.inf | 6 +++ .../BaseCpuLib}/Ia32/InitializeFpu.nasm | 0 .../BaseCpuLib}/X64/InitializeFpu.nasm | 0 .../Library/BaseCpuLib/X86BaseCpuLib.c | 2 +- UefiCpuPkg/Include/Library/UefiCpuLib.h | 49 ------------------- .../Library/BaseUefiCpuLib/BaseUefiCpuLib.inf | 8 +-- .../BaseUefiCpuLib/BaseUefiCpuLibNull.c | 18 +++++++ 8 files changed, 74 insertions(+), 57 deletions(-) rename {UefiCpuPkg/Library/BaseUefiCpuLib => MdePkg/Library/BaseCpuLib}/Ia32/InitializeFpu.nasm (100%) rename {UefiCpuPkg/Library/BaseUefiCpuLib => MdePkg/Library/BaseCpuLib}/X64/InitializeFpu.nasm (100%) rename UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.c => MdePkg/Library/BaseCpuLib/X86BaseCpuLib.c (93%) create mode 100644 UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c diff --git a/MdePkg/Include/Library/CpuLib.h b/MdePkg/Include/Library/CpuLib.h index 25f6d9478c..3f29937dc7 100644 --- a/MdePkg/Include/Library/CpuLib.h +++ b/MdePkg/Include/Library/CpuLib.h @@ -41,4 +41,52 @@ CpuFlushTlb ( VOID ); +#if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64) + +/** + 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). +**/ +VOID +EFIAPI +InitializeFloatingPointUnits ( + VOID + ); + +/** + Determine if the standard CPU signature is "AuthenticAMD". + @retval TRUE The CPU signature matches. + @retval FALSE The CPU signature does not match. +**/ +BOOLEAN +EFIAPI +StandardSignatureIsAuthenticAMD ( + VOID + ); + +/** + Return the 32bit CPU family and model value. + @return CPUID[01h].EAX with Processor Type and Stepping ID cleared. +**/ +UINT32 +EFIAPI +GetCpuFamilyModel ( + VOID + ); + +/** + Return the CPU stepping ID. + @return CPU stepping ID value in CPUID[01h].EAX. +**/ +UINT8 +EFIAPI +GetCpuSteppingId ( + VOID + ); + +#endif + #endif diff --git a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf index 5b18343c59..9a162afe6d 100644 --- a/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf +++ b/MdePkg/Library/BaseCpuLib/BaseCpuLib.inf @@ -29,16 +29,22 @@ # VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 LOONGARCH64 # +[Sources.IA32, Sources.X64] + X86BaseCpuLib.c + [Sources.IA32] Ia32/CpuSleep.c | MSFT Ia32/CpuSleep.nasm| INTEL Ia32/CpuSleepGcc.c | GCC X86CpuFlushTlb.c + Ia32/InitializeFpu.nasm + [Sources.X64] X86CpuFlushTlb.c X64/CpuSleep.nasm + X64/InitializeFpu.nasm [Sources.EBC] Ebc/CpuSleepFlushTlb.c diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/Ia32/InitializeFpu.nasm b/MdePkg/Library/BaseCpuLib/Ia32/InitializeFpu.nasm similarity index 100% rename from UefiCpuPkg/Library/BaseUefiCpuLib/Ia32/InitializeFpu.nasm rename to MdePkg/Library/BaseCpuLib/Ia32/InitializeFpu.nasm diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/X64/InitializeFpu.nasm b/MdePkg/Library/BaseCpuLib/X64/InitializeFpu.nasm similarity index 100% rename from UefiCpuPkg/Library/BaseUefiCpuLib/X64/InitializeFpu.nasm rename to MdePkg/Library/BaseCpuLib/X64/InitializeFpu.nasm diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.c b/MdePkg/Library/BaseCpuLib/X86BaseCpuLib.c similarity index 93% rename from UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.c rename to MdePkg/Library/BaseCpuLib/X86BaseCpuLib.c index 5d925bc273..1cad32a4be 100644 --- a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.c +++ b/MdePkg/Library/BaseCpuLib/X86BaseCpuLib.c @@ -13,7 +13,7 @@ #include #include -#include +#include /** Determine if the standard CPU signature is "AuthenticAMD". diff --git a/UefiCpuPkg/Include/Library/UefiCpuLib.h b/UefiCpuPkg/Include/Library/UefiCpuLib.h index 0ff4a35774..ab6982db6e 100644 --- a/UefiCpuPkg/Include/Library/UefiCpuLib.h +++ b/UefiCpuPkg/Include/Library/UefiCpuLib.h @@ -13,53 +13,4 @@ #ifndef __UEFI_CPU_LIB_H__ #define __UEFI_CPU_LIB_H__ -/** - 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). - -**/ -VOID -EFIAPI -InitializeFloatingPointUnits ( - VOID - ); - -/** - Determine if the standard CPU signature is "AuthenticAMD". - - @retval TRUE The CPU signature matches. - @retval FALSE The CPU signature does not match. - -**/ -BOOLEAN -EFIAPI -StandardSignatureIsAuthenticAMD ( - VOID - ); - -/** - Return the 32bit CPU family and model value. - - @return CPUID[01h].EAX with Processor Type and Stepping ID cleared. -**/ -UINT32 -EFIAPI -GetCpuFamilyModel ( - VOID - ); - -/** - Return the CPU stepping ID. - @return CPU stepping ID value in CPUID[01h].EAX. -**/ -UINT8 -EFIAPI -GetCpuSteppingId ( - VOID - ); - #endif diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf index 34d3a7bb43..9f8b62d87a 100644 --- a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf +++ b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf @@ -24,14 +24,8 @@ # VALID_ARCHITECTURES = IA32 X64 # -[Sources.IA32] - Ia32/InitializeFpu.nasm - -[Sources.X64] - X64/InitializeFpu.nasm - [Sources] - BaseUefiCpuLib.c + BaseUefiCpuLibNull.c [Packages] MdePkg/MdePkg.dec diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c new file mode 100644 index 0000000000..e29d2e892c --- /dev/null +++ b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c @@ -0,0 +1,18 @@ +/** @file +This library contains a dummy function to pass build. + +Copyright (c) 2022, Intel Corporation. All rights reserved. + +SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +/** + Dummy function. +**/ +VOID +Dummy ( + VOID + ) +{ +} From bc543e232fa0b8550169b4ac8c4f0da0997683cd Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:45:12 +0800 Subject: [PATCH 0675/1529] IntelFsp2Pkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Yu Pu Reviewed-by: Chasel Chiu --- IntelFsp2Pkg/FspSecCore/Fsp24SecCoreM.inf | 1 - IntelFsp2Pkg/FspSecCore/FspSecCoreM.inf | 1 - IntelFsp2Pkg/FspSecCore/SecMain.h | 1 - IntelFsp2Pkg/IntelFsp2Pkg.dsc | 1 - IntelFsp2Pkg/Tools/Tests/QemuFspPkg.dsc | 1 - IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf | 1 - IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf | 1 - IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dsc | 1 - 8 files changed, 8 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/Fsp24SecCoreM.inf b/IntelFsp2Pkg/FspSecCore/Fsp24SecCoreM.inf index e93e176f15..cb011f99f9 100644 --- a/IntelFsp2Pkg/FspSecCore/Fsp24SecCoreM.inf +++ b/IntelFsp2Pkg/FspSecCore/Fsp24SecCoreM.inf @@ -59,7 +59,6 @@ FspCommonLib FspSecPlatformLib CpuLib - UefiCpuLib FspMultiPhaseLib [Pcd] diff --git a/IntelFsp2Pkg/FspSecCore/FspSecCoreM.inf b/IntelFsp2Pkg/FspSecCore/FspSecCoreM.inf index f920f1f6d0..8029832235 100644 --- a/IntelFsp2Pkg/FspSecCore/FspSecCoreM.inf +++ b/IntelFsp2Pkg/FspSecCore/FspSecCoreM.inf @@ -59,7 +59,6 @@ FspCommonLib FspSecPlatformLib CpuLib - UefiCpuLib [Pcd] gIntelFsp2PkgTokenSpaceGuid.PcdTemporaryRamBase ## CONSUMES diff --git a/IntelFsp2Pkg/FspSecCore/SecMain.h b/IntelFsp2Pkg/FspSecCore/SecMain.h index a09653da96..023deb7e2b 100644 --- a/IntelFsp2Pkg/FspSecCore/SecMain.h +++ b/IntelFsp2Pkg/FspSecCore/SecMain.h @@ -21,7 +21,6 @@ #include #include #include -#include #include typedef diff --git a/IntelFsp2Pkg/IntelFsp2Pkg.dsc b/IntelFsp2Pkg/IntelFsp2Pkg.dsc index 0713f0028d..f236a7010b 100644 --- a/IntelFsp2Pkg/IntelFsp2Pkg.dsc +++ b/IntelFsp2Pkg/IntelFsp2Pkg.dsc @@ -27,7 +27,6 @@ PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf diff --git a/IntelFsp2Pkg/Tools/Tests/QemuFspPkg.dsc b/IntelFsp2Pkg/Tools/Tests/QemuFspPkg.dsc index 961576c9a7..3155812118 100644 --- a/IntelFsp2Pkg/Tools/Tests/QemuFspPkg.dsc +++ b/IntelFsp2Pkg/Tools/Tests/QemuFspPkg.dsc @@ -107,7 +107,6 @@ PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf !if $(TARGET) == DEBUG DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf diff --git a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf index 332509e0bc..0307ce0acc 100644 --- a/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf +++ b/IntelFsp2WrapperPkg/FspmWrapperPeim/FspmWrapperPeim.inf @@ -38,7 +38,6 @@ FspWrapperPlatformLib FspWrapperHobProcessLib CpuLib - UefiCpuLib PeCoffGetEntryPointLib PeCoffExtraActionLib PerformanceLib diff --git a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf index f9c2ffca1c..a7b28e56b5 100644 --- a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf +++ b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.inf @@ -39,7 +39,6 @@ FspWrapperPlatformLib FspWrapperHobProcessLib CpuLib - UefiCpuLib PeCoffGetEntryPointLib PeCoffExtraActionLib PerformanceLib diff --git a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dsc b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dsc index b1fc2291c8..fe621244a6 100644 --- a/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dsc +++ b/IntelFsp2WrapperPkg/IntelFsp2WrapperPkg.dsc @@ -41,7 +41,6 @@ DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf # UefiCpuPkg - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf LocalApicLib|UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf # FSP Wrapper Lib From bc6ba44ccd1fa4714d2f2d5155fcf3ccf96d44b6 Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:46:31 +0800 Subject: [PATCH 0676/1529] OvmfPkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Acked-by: Gerd Hoffmann Signed-off-by: Yu Pu Signed-off-by: Zhiguang Liu --- OvmfPkg/AmdSev/AmdSevX64.dsc | 1 - OvmfPkg/Bhyve/BhyveX64.dsc | 1 - OvmfPkg/CloudHv/CloudHvX64.dsc | 1 - OvmfPkg/IntelTdx/IntelTdxX64.dsc | 1 - OvmfPkg/IntelTdx/Sec/SecMain.c | 1 - OvmfPkg/IntelTdx/Sec/SecMain.inf | 1 - OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf | 1 - OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c | 1 - OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf | 1 - OvmfPkg/Microvm/MicrovmX64.dsc | 1 - OvmfPkg/OvmfPkgIa32.dsc | 1 - OvmfPkg/OvmfPkgIa32X64.dsc | 1 - OvmfPkg/OvmfPkgX64.dsc | 1 - OvmfPkg/OvmfXen.dsc | 1 - OvmfPkg/Sec/SecMain.c | 1 - OvmfPkg/Sec/SecMain.inf | 1 - 16 files changed, 16 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index f0c4dc2310..654c3af092 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -154,7 +154,6 @@ UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc index 66a2ae8868..d0d2712c56 100644 --- a/OvmfPkg/Bhyve/BhyveX64.dsc +++ b/OvmfPkg/Bhyve/BhyveX64.dsc @@ -160,7 +160,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index 327f53ff3c..b9820cc14b 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -181,7 +181,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibNull.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index d093660283..e6d85286e0 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -168,7 +168,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index 8f1f75b294..42a587adfa 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.inf b/OvmfPkg/IntelTdx/Sec/SecMain.inf index e112ba80bc..7fb27941b7 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.inf +++ b/OvmfPkg/IntelTdx/Sec/SecMain.inf @@ -37,7 +37,6 @@ DebugLib BaseMemoryLib PcdLib - UefiCpuLib CpuLib DebugAgentLib IoLib diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf index b1c936b960..7719b5031d 100644 --- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf +++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf @@ -45,7 +45,6 @@ DebugLib BaseMemoryLib PcdLib - UefiCpuLib CpuLib DebugAgentLib IoLib diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c index 063875b34b..ce7984cb0c 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf index 83e3c8b842..1c2e811ad3 100644 --- a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf +++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf @@ -36,7 +36,6 @@ DebugLib BaseMemoryLib PcdLib - UefiCpuLib CpuLib DebugAgentLib IoLib diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 76fc548650..384b0b7afc 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -179,7 +179,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 22dc29330d..9e4705f29b 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -182,7 +182,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 51db692b10..86940e9af5 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -186,7 +186,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 04d50704c7..00f7005fca 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -199,7 +199,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index f1f02d969f..990225d2dd 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -161,7 +161,6 @@ DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index 4bb3b64170..e96726d6ec 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -18,7 +18,6 @@ #include #include #include -#include #include #include #include diff --git a/OvmfPkg/Sec/SecMain.inf b/OvmfPkg/Sec/SecMain.inf index 561a840f29..3c47a664a9 100644 --- a/OvmfPkg/Sec/SecMain.inf +++ b/OvmfPkg/Sec/SecMain.inf @@ -45,7 +45,6 @@ PeiServicesLib PcdLib CpuLib - UefiCpuLib DebugAgentLib IoLib PeCoffLib From 5c51f94f7fee67e3edd0413a5a44f7c5f4134842 Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:47:27 +0800 Subject: [PATCH 0677/1529] PcAtChipsetPkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Cc: Ray Ni Signed-off-by: Yu Pu Reviewed-by: Ray Ni --- PcAtChipsetPkg/PcAtChipsetPkg.dsc | 1 - 1 file changed, 1 deletion(-) diff --git a/PcAtChipsetPkg/PcAtChipsetPkg.dsc b/PcAtChipsetPkg/PcAtChipsetPkg.dsc index 451e60ddc8..2f02ecf6fd 100644 --- a/PcAtChipsetPkg/PcAtChipsetPkg.dsc +++ b/PcAtChipsetPkg/PcAtChipsetPkg.dsc @@ -42,7 +42,6 @@ ResetSystemLib|PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.inf IoApicLib|PcAtChipsetPkg/Library/BaseIoApicLib/BaseIoApicLib.inf LocalApicLib|UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf From 7fd8074b6f6bce09bb11e15731211ca5757c5035 Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:47:53 +0800 Subject: [PATCH 0678/1529] SourceLevelDebugPkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Cc: Hao A Wu Acked-by: Hao A Wu Signed-off-by: Yu Pu Reviewed-by: Ray Ni --- SourceLevelDebugPkg/SourceLevelDebugPkg.dsc | 1 - 1 file changed, 1 deletion(-) diff --git a/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc b/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc index eba64a7b78..986dd5a769 100644 --- a/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc +++ b/SourceLevelDebugPkg/SourceLevelDebugPkg.dsc @@ -35,7 +35,6 @@ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf LocalApicLib|UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf From 23ce61fa4f655c1c005baeb3bcdbe4a1a387bc32 Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:48:24 +0800 Subject: [PATCH 0679/1529] UefiCpuPkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Signed-off-by: Yu Pu Reviewed-by: Ray Ni --- UefiCpuPkg/CpuDxe/CpuDxe.h | 1 - UefiCpuPkg/CpuDxe/CpuDxe.inf | 1 - UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.c | 1 - UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf | 1 - UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c | 1 - UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf | 1 - UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 1 - UefiCpuPkg/Library/MpInitLib/MpLib.h | 1 - UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 1 - UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 1 - UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 1 - UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h | 1 - UefiCpuPkg/SecCore/SecCore.inf | 1 - UefiCpuPkg/SecCore/SecCoreNative.inf | 1 - UefiCpuPkg/SecCore/SecMain.h | 1 - 15 files changed, 15 deletions(-) diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.h b/UefiCpuPkg/CpuDxe/CpuDxe.h index 2208671cb9..49a390b4c4 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.h +++ b/UefiCpuPkg/CpuDxe/CpuDxe.h @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.inf b/UefiCpuPkg/CpuDxe/CpuDxe.inf index 2352418992..1d3e9f8cdb 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.inf +++ b/UefiCpuPkg/CpuDxe/CpuDxe.inf @@ -33,7 +33,6 @@ UefiBootServicesTableLib UefiDriverEntryPoint LocalApicLib - UefiCpuLib UefiLib CpuExceptionHandlerLib HobLib diff --git a/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.c b/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.c index a944c3d01c..008b8a070b 100644 --- a/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.c +++ b/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.c @@ -22,7 +22,6 @@ #include #include #include -#include // // Library internal functions diff --git a/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf b/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf index a85b69e0a1..8c4eb65548 100644 --- a/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf +++ b/UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf @@ -39,7 +39,6 @@ IoLib PcdLib CpuLib - UefiCpuLib [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuInitIpiDelayInMicroSeconds ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c index 1e45ffc318..0ba0499631 100644 --- a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c +++ b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c @@ -23,7 +23,6 @@ #include #include #include -#include #include // diff --git a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf index 31ebdd39c6..713f1859c2 100644 --- a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf +++ b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf @@ -39,7 +39,6 @@ IoLib PcdLib CpuLib - UefiCpuLib [Pcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuInitIpiDelayInMicroSeconds ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index 4285dd06b4..67ebf7254c 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -51,7 +51,6 @@ HobLib MtrrLib CpuLib - UefiCpuLib UefiBootServicesTableLib DebugAgentLib SynchronizationLib diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 6f235dcf6d..b694c7b40f 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf index afd551bb0f..78eded96bf 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf @@ -49,7 +49,6 @@ HobLib MtrrLib CpuLib - UefiCpuLib SynchronizationLib PeiServicesLib PcdLib diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index c3731f174b..a5c2bdd971 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -45,7 +45,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include -#include #include #include #include diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index 9bfa8c1a76..158e05e264 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -89,7 +89,6 @@ HobLib PciLib LocalApicLib - UefiCpuLib SmmCpuPlatformHookLib CpuExceptionHandlerLib UefiLib diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h index 0e60509e20..964dd52817 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h @@ -14,7 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include -#include #include #include "SmmProfileArch.h" diff --git a/UefiCpuPkg/SecCore/SecCore.inf b/UefiCpuPkg/SecCore/SecCore.inf index f021997f27..3758aded3b 100644 --- a/UefiCpuPkg/SecCore/SecCore.inf +++ b/UefiCpuPkg/SecCore/SecCore.inf @@ -48,7 +48,6 @@ PcdLib DebugAgentLib CpuLib - UefiCpuLib PeCoffGetEntryPointLib PeCoffExtraActionLib CpuExceptionHandlerLib diff --git a/UefiCpuPkg/SecCore/SecCoreNative.inf b/UefiCpuPkg/SecCore/SecCoreNative.inf index e0a1b44a7e..1ee6ff7d88 100644 --- a/UefiCpuPkg/SecCore/SecCoreNative.inf +++ b/UefiCpuPkg/SecCore/SecCoreNative.inf @@ -45,7 +45,6 @@ PcdLib DebugAgentLib CpuLib - UefiCpuLib PeCoffGetEntryPointLib PeCoffExtraActionLib CpuExceptionHandlerLib diff --git a/UefiCpuPkg/SecCore/SecMain.h b/UefiCpuPkg/SecCore/SecMain.h index 26c54bd926..880e6cd1b8 100644 --- a/UefiCpuPkg/SecCore/SecMain.h +++ b/UefiCpuPkg/SecCore/SecMain.h @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include From 959d59dafe7cd167d1d6b4b6d627efe5c646836c Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 29 Mar 2022 11:49:14 +0800 Subject: [PATCH 0680/1529] UefiPayloadPkg: Remove UefiCpuLib from module INFs. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib, remove the dependency of UefiCpuLib. Reviewed-by: Guo Dong Reviewed-by: James Lu Reviewed-by: Gua Guo Cc: Ray Ni Cc: Maurice Ma Cc: Benjamin You Cc: Sean Rhodes Signed-off-by: Yu Pu Reviewed-by: Ray Ni --- UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h | 1 - UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf | 1 - UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf | 1 - UefiPayloadPkg/UefiPayloadPkg.dsc | 1 - 4 files changed, 4 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h index d1c7425b28..ad8a9fd22b 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h +++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf index 95446dd997..d47e8e76cf 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf +++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf @@ -55,7 +55,6 @@ PeCoffLib PlatformSupportLib CpuLib - UefiCpuLib [Guids] gEfiMemoryTypeInformationGuid diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf index 3b4836042a..c4f4f28eaa 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf +++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf @@ -53,7 +53,6 @@ HobLib PeCoffLib CpuLib - UefiCpuLib [Guids] gEfiMemoryTypeInformationGuid diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 8cbbbe9a05..35e3bfff35 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -221,7 +221,6 @@ UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf # From 8ae3cdd4d610ff1a5b5f891354c70a20e8577d11 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Thu, 8 Sep 2022 18:35:50 +0100 Subject: [PATCH 0681/1529] DynamicTablesPkg: Add SMBIOS String table helper library The Section 6.1.3, SMBIOS specification version 3.6.0 describes the handling of test strings in SMBIOS tables. Text strings are added at the end of the formatted portion of the SMBIOS structure and are referenced by index in the SMBIOS structure. Therefore, introduce a SmbiosStringTableLib to simplify the publishing of the string set. SmbiosStringTableLib introduces a concept of string table which records the references to the SMBIOS strings as they are added and returns an string reference which is then assigned to the string field in the formatted portion of the SMBIOS structure. Once all strings are added, the library provides an interface to get the required size for the string set. This allows sufficient memory to be allocated for the SMBIOS table. The library also provides an interface to publish the string set in accordance with the SMBIOS specification. Example: EFI_STATUS BuildSmbiosType17Table () { STRING_TABLE StrTable; UINT8 DevLocatorRef; UINT8 BankLocatorRef; SMBIOS_TABLE_TYPE17 *SmbiosRecord; CHAR8 *StringSet; ... // Initialize string table for 7 strings StringTableInitialize (&StrTable, 7); StringTableAddString (&StrTable, "SIMM 3", &DevLocatorRef); StringTableAddString (&StrTable, "Bank 0", &BankLocatorRef); ... SmbiosRecord = AllocateZeroPool ( sizeof (SMBIOS_TABLE_TYPE17) + StringTableGetStringSetSize (&StrTable) ); ... SmbiosRecord->DeviceLocator = DevLocatorRef; SmbiosRecord->BankLocator = BankLocatorRef; ... // get the string set area StringSet = (CHAR8*)(SmbiosRecord + 1); // publish the string set StringTablePublishStringSet ( &StrTable, StringSet, StringTableGetStringSetSize (&StrTable) ); // free string table StringTableFree (&StrTable); return EFI_SUCCESS; } Signed-off-by: Sami Mujawar Reviewed-by: Pierre Gondois Cc: Alexei Fedorov Cc: Pierre Gondois Cc: Girish Mahadevan Cc: Jeff Brasen Cc: Ashish Singhal Cc: Nick Ramirez Cc: William Watson Cc: Samer El-Haj-Mahmoud --- DynamicTablesPkg/DynamicTables.dsc.inc | 1 + DynamicTablesPkg/DynamicTablesPkg.dec | 5 +- DynamicTablesPkg/DynamicTablesPkg.dsc | 3 +- .../Include/Library/SmbiosStringTableLib.h | 119 +++++++++ .../SmbiosStringTableLib.c | 227 ++++++++++++++++++ .../SmbiosStringTableLib.inf | 25 ++ 6 files changed, 378 insertions(+), 2 deletions(-) create mode 100644 DynamicTablesPkg/Include/Library/SmbiosStringTableLib.h create mode 100644 DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.c create mode 100644 DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf diff --git a/DynamicTablesPkg/DynamicTables.dsc.inc b/DynamicTablesPkg/DynamicTables.dsc.inc index 3e38fa0d0d..9d4312c4e8 100644 --- a/DynamicTablesPkg/DynamicTables.dsc.inc +++ b/DynamicTablesPkg/DynamicTables.dsc.inc @@ -18,6 +18,7 @@ SsdtPcieSupportLib|DynamicTablesPkg/Library/Common/SsdtPcieSupportLib/SsdtPcieSupportLib.inf SsdtSerialPortFixupLib|DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.inf TableHelperLib|DynamicTablesPkg/Library/Common/TableHelperLib/TableHelperLib.inf + SmbiosStringTableLib|DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf [Components.common] # diff --git a/DynamicTablesPkg/DynamicTablesPkg.dec b/DynamicTablesPkg/DynamicTablesPkg.dec index adc2e67cbf..cfbcbb9569 100644 --- a/DynamicTablesPkg/DynamicTablesPkg.dec +++ b/DynamicTablesPkg/DynamicTablesPkg.dec @@ -1,7 +1,7 @@ ## @file # dec file for Dynamic Tables Framework. # -# Copyright (c) 2017 - 2021, Arm Limited. All rights reserved.
+# Copyright (c) 2017 - 2022, Arm Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -39,6 +39,9 @@ ## @libraryclass Defines a set of helper methods. TableHelperLib|Include/Library/TableHelperLib.h + ## @libraryclass Defines a set of SMBIOS string helper methods. + SmbiosStringTableLib|Include/Library/SmbiosStringTableLib.h + [Protocols] # Configuration Manager Protocol GUID gEdkiiConfigurationManagerProtocolGuid = { 0xd85a4835, 0x5a82, 0x4894, { 0xac, 0x2, 0x70, 0x6f, 0x43, 0xd5, 0x97, 0x8e } } diff --git a/DynamicTablesPkg/DynamicTablesPkg.dsc b/DynamicTablesPkg/DynamicTablesPkg.dsc index 07cc837552..bd5084a900 100644 --- a/DynamicTablesPkg/DynamicTablesPkg.dsc +++ b/DynamicTablesPkg/DynamicTablesPkg.dsc @@ -2,7 +2,7 @@ # Dsc file for Dynamic Tables Framework. # # Copyright (c) 2019, Linaro Limited. All rights reserved.
-# Copyright (c) 2019 - 2021, Arm Limited. All rights reserved.
+# Copyright (c) 2019 - 2022, Arm Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -46,6 +46,7 @@ DynamicTablesPkg/Library/Common/TableHelperLib/TableHelperLib.inf DynamicTablesPkg/Library/FdtHwInfoParserLib/FdtHwInfoParserLib.inf DynamicTablesPkg/Library/Common/DynamicPlatRepoLib/DynamicPlatRepoLib.inf + DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES diff --git a/DynamicTablesPkg/Include/Library/SmbiosStringTableLib.h b/DynamicTablesPkg/Include/Library/SmbiosStringTableLib.h new file mode 100644 index 0000000000..fb183d427f --- /dev/null +++ b/DynamicTablesPkg/Include/Library/SmbiosStringTableLib.h @@ -0,0 +1,119 @@ +/** @file + SMBIOS String Table Helper library. + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef SMBIOS_STRING_TABLE_H_ +#define SMBIOS_STRING_TABLE_H_ + +/** A structure representing a string in the string table. +*/ +typedef struct StringElement { + /// Length of the string (does not include the NULL termination) + UINTN StringLen; + + /// Reference to the string + CONST CHAR8 *String; +} STRING_ELEMENT; + +/** A structure representing a string table. +*/ +typedef struct StringTable { + /// Count of strings in the table + UINT8 StrCount; + + /// Total length of all strings in the table (does not include + // the NULL termination for each string) + UINTN TotalStrLen; + + /// Maximum string count + UINT8 MaxStringElements; + + /// Pointer to the string table elements + STRING_ELEMENT *Elements; +} STRING_TABLE; + +/** Add a string to the string table + + @param[in] StrTable Pointer to the string table + @param[in] Str Pointer to the string + @param[out] StrRef Optional pointer to retrieve the string field + reference of the string in the string table + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_BUFFER_TOO_SMALL Insufficient space to add string +**/ +EFI_STATUS +EFIAPI +StringTableAddString ( + IN STRING_TABLE *CONST StrTable, + IN CONST CHAR8 *Str, + OUT UINT8 *StrRef OPTIONAL + ); + +/** Returns the total size required to publish the strings to the SMBIOS + string area. + + @param[in] StrTable Pointer to the string table + + @return Total size required to publish the strings in the SMBIOS string area. +**/ +UINTN +EFIAPI +StringTableGetStringSetSize ( + IN STRING_TABLE *CONST StrTable + ); + +/** Iterate through the string table and publish the strings in the SMBIOS + string area. + + @param[in] StrTable Pointer to the string table + @param[in] SmbiosStringAreaStart Start address of the SMBIOS string area. + @param[in] SmbiosStringAreaSize Size of the SMBIOS string area. + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_BUFFER_TOO_SMALL Insufficient space to publish strings +**/ +EFI_STATUS +EFIAPI +StringTablePublishStringSet ( + IN STRING_TABLE *CONST StrTable, + IN CHAR8 *CONST SmbiosStringAreaStart, + IN CONST UINTN SmbiosStringAreaSize + ); + +/** Initialise the string table and allocate memory for the string elements. + + @param[in] StrTable Pointer to the string table + @param[in] MaxStringElements Maximum number of strings that the string + table can hold. + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_OUT_OF_RESOURCES Failed to allocate memory for string elements +**/ +EFI_STATUS +EFIAPI +StringTableInitialize ( + IN STRING_TABLE *CONST StrTable, + IN UINTN MaxStringElements + ); + +/** Free memory allocated for the string elements in the string table. + + @param[in] StrTable Pointer to the string table + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer or string elements +**/ +EFI_STATUS +EFIAPI +StringTableFree ( + IN STRING_TABLE *CONST StrTable + ); + +#endif // SMBIOS_STRING_TABLE_H_ diff --git a/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.c b/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.c new file mode 100644 index 0000000000..9eb4a7b22d --- /dev/null +++ b/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.c @@ -0,0 +1,227 @@ +/** @file + SMBIOS String Table Helper + + Copyright (c) 2022, Arm Limited. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - DSP0134 - SMBIOS Specification Version 3.6.0, 2022-06-17 +**/ + +#include +#include +#include +#include +#include + +/** Add a string to the string table. + + @param[in] StrTable Pointer to the string table + @param[in] Str Pointer to the string + @param[out] StrRef Optional pointer to retrieve the string field + reference of the string in the string table + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_BUFFER_TOO_SMALL Insufficient space to add string +**/ +EFI_STATUS +EFIAPI +StringTableAddString ( + IN STRING_TABLE *CONST StrTable, + IN CONST CHAR8 *Str, + OUT UINT8 *StrRef OPTIONAL + ) +{ + UINTN StrLength; + STRING_ELEMENT *StrElement; + + if ((StrTable == NULL) || (Str == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if (StrTable->StrCount >= StrTable->MaxStringElements) { + return EFI_BUFFER_TOO_SMALL; + } + + StrLength = AsciiStrLen (Str); + if (StrLength == 0) { + return EFI_INVALID_PARAMETER; + } + + // Update the string element + StrElement = &StrTable->Elements[StrTable->StrCount]; + StrElement->StringLen = StrLength; + StrElement->String = Str; + + // Update String table information + StrTable->TotalStrLen += StrLength; + StrTable->StrCount++; + + // Return the index of the string in the string table if requested + if (StrRef != NULL) { + // Note: SMBIOS string field references start at 1. So, return the + // StrCount as the string reference after it is updated. + *StrRef = StrTable->StrCount; + } + + return EFI_SUCCESS; +} + +/** Returns the total size required to publish the strings to the SMBIOS + string area. + + @param[in] StrTable Pointer to the string table + + @return Total size required to publish the strings in the SMBIOS string area. +**/ +UINTN +EFIAPI +StringTableGetStringSetSize ( + IN STRING_TABLE *CONST StrTable + ) +{ + if (StrTable == NULL) { + ASSERT (0); + return 0; + } + + // See Section 6.1.3 Text strings, SMBIOS Specification Version 3.6.0 + // - If the formatted portion of the structure contains string-reference + // fields and all the string fields are set to 0 (no string references), + // the formatted section of the structure is followed by two null (00h) + // BYTES. + // - Each string is terminated with a null (00h) BYTE + // - and the set of strings is terminated with an additional null (00h) BYTE. + + // Therefore, if string count = 0, return 2 + // if string count > 0, the string set size = + // StrTable->TotalStrLen (total length of the strings in the string table) + // + StrTable->StrCount (add string count to include '\0' for each string) + // +1 (an additional '\0' is required at the end of the string set). + return (StrTable->StrCount == 0) ? 2 : + (StrTable->TotalStrLen + StrTable->StrCount + 1); +} + +/** Iterate through the string table and publish the strings in the SMBIOS + string area. + + @param[in] StrTable Pointer to the string table + @param[in] SmbiosStringAreaStart Start address of the SMBIOS string area. + @param[in] SmbiosStringAreaSize Size of the SMBIOS string area. + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_BUFFER_TOO_SMALL Insufficient space to publish strings +**/ +EFI_STATUS +EFIAPI +StringTablePublishStringSet ( + IN STRING_TABLE *CONST StrTable, + IN CHAR8 *CONST SmbiosStringAreaStart, + IN CONST UINTN SmbiosStringAreaSize + ) +{ + UINT8 Index; + STRING_ELEMENT *StrElement; + CHAR8 *SmbiosString; + UINTN BytesRemaining; + UINTN BytesCopied; + + if ((StrTable == NULL) || (SmbiosStringAreaStart == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if (SmbiosStringAreaSize < StringTableGetStringSetSize (StrTable)) { + return EFI_BUFFER_TOO_SMALL; + } + + SmbiosString = SmbiosStringAreaStart; + BytesRemaining = SmbiosStringAreaSize; + + if (StrTable->StrCount == 0) { + // See Section 6.1.3 Text strings, SMBIOS Specification Version 3.6.0 + // If the formatted portion of the structure contains string-reference + // fields and all the string fields are set to 0 (no string references), + // the formatted section of the structure is followed by two null (00h) + // BYTES. + *SmbiosString++ = '\0'; + } else { + for (Index = 0; Index < StrTable->StrCount; Index++) { + StrElement = &StrTable->Elements[Index]; + AsciiStrCpyS (SmbiosString, BytesRemaining, StrElement->String); + + // See Section 6.1.3 Text strings, SMBIOS Specification Version 3.6.0 + // - Each string is terminated with a null (00h) BYTE + // Bytes Copied = String length + 1 for the string NULL terminator. + BytesCopied = StrElement->StringLen + 1; + BytesRemaining -= BytesCopied; + SmbiosString += BytesCopied; + } + } + + // See Section 6.1.3 Text strings, SMBIOS Specification Version 3.6.0 + // - the set of strings is terminated with an additional null (00h) BYTE. + *SmbiosString = '\0'; + return EFI_SUCCESS; +} + +/** Initialise the string table and allocate memory for the string elements. + + @param[in] StrTable Pointer to the string table + @param[in] MaxStringElements Maximum number of strings that the string + table can hold. + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer + @return EFI_OUT_OF_RESOURCES Failed to allocate memory for string elements +**/ +EFI_STATUS +EFIAPI +StringTableInitialize ( + IN STRING_TABLE *CONST StrTable, + IN UINTN MaxStringElements + ) +{ + STRING_ELEMENT *Elements; + + if ((StrTable == NULL) || (MaxStringElements > MAX_UINT8)) { + return EFI_INVALID_PARAMETER; + } + + ZeroMem (StrTable, sizeof (STRING_TABLE)); + + Elements = (STRING_ELEMENT *)AllocateZeroPool ( + sizeof (STRING_ELEMENT) * MaxStringElements + ); + if (Elements == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + StrTable->Elements = Elements; + StrTable->MaxStringElements = (UINT8)MaxStringElements; + return EFI_SUCCESS; +} + +/** Free memory allocated for the string elements in the string table. + + @param[in] StrTable Pointer to the string table + + @return EFI_SUCCESS Success + @return EFI_INVALID_PARAMETER Invalid string table pointer or string elements +**/ +EFI_STATUS +EFIAPI +StringTableFree ( + IN STRING_TABLE *CONST StrTable + ) +{ + if ((StrTable == NULL) || (StrTable->Elements == NULL)) { + return EFI_INVALID_PARAMETER; + } + + FreePool (StrTable->Elements); + ZeroMem (StrTable, sizeof (STRING_TABLE)); + return EFI_SUCCESS; +} diff --git a/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf b/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf new file mode 100644 index 0000000000..88624c50e3 --- /dev/null +++ b/DynamicTablesPkg/Library/Common/SmbiosStringTableLib/SmbiosStringTableLib.inf @@ -0,0 +1,25 @@ +## @file +# SMBIOS String Table Helper library. +# +# Copyright (c) 2022, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x0001001B + BASE_NAME = SmbiosStringTableLib + FILE_GUID = 8C570DD8-531E-473F-85C6-9252746DBAC1 + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = SmbiosStringTableLib + +[Sources] + SmbiosStringTableLib.c + +[Packages] + MdePkg/MdePkg.dec + DynamicTablesPkg/DynamicTablesPkg.dec + +[LibraryClasses] + BaseLib From d1aba39a5690672538921983cf426800df6c2095 Mon Sep 17 00:00:00 2001 From: "Palomino Sosa, Guillermo A" Date: Tue, 7 Feb 2023 11:07:23 +0800 Subject: [PATCH 0682/1529] BaseTools: Generate compile information in build report REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2850 Add "-Y REPORT_INFO" option to build command to generate compile information as part of BuildReport. This option generates files to be used by external tools as IDE's to enhance functionality. Files are created inside build folder: ///CompileInfo Files created: * compile_commands.json - Compilation Database. To be used by IDE's to enable advance features * cscope.files - List of files used in compilation. Used by Cscope to parse C code and provide browse functionality. * module_report.json - Module data form buildReport in Json format. Signed-off-by: Guillermo Antonio Palomino Sosa Reviewed-by: Bob Feng --- BaseTools/Source/Python/build/BuildReport.py | 139 +++++++++++++++++- BaseTools/Source/Python/build/buildoptions.py | 4 +- 2 files changed, 140 insertions(+), 3 deletions(-) diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Source/Python/build/BuildReport.py index 468772930c..33b43d471f 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -10,6 +10,8 @@ ## Import Modules # +import json +from pathlib import Path import Common.LongFilePathOs as os import re import platform @@ -41,6 +43,7 @@ import collections from Common.Expression import * from GenFds.AprioriSection import DXE_APRIORI_GUID, PEI_APRIORI_GUID +from AutoGen.IncludesAutoGen import IncludesAutoGen ## Pattern to extract contents in EDK DXS files gDxsDependencyPattern = re.compile(r"DEPENDENCY_START(.+)DEPENDENCY_END", re.DOTALL) @@ -2298,6 +2301,10 @@ def AddPlatformReport(self, Wa, MaList=None): def GenerateReport(self, BuildDuration, AutoGenTime, MakeTime, GenFdsTime): if self.ReportFile: try: + + if "COMPILE_INFO" in self.ReportType: + self.GenerateCompileInfo() + File = [] for (Wa, MaList) in self.ReportList: PlatformReport(Wa, MaList, self.ReportType).GenerateReport(File, BuildDuration, AutoGenTime, MakeTime, GenFdsTime, self.ReportType) @@ -2310,7 +2317,137 @@ def GenerateReport(self, BuildDuration, AutoGenTime, MakeTime, GenFdsTime): EdkLogger.error("BuildReport", CODE_ERROR, "Unknown fatal error when generating build report", ExtraData=self.ReportFile, RaiseError=False) EdkLogger.quiet("(Python %s on %s\n%s)" % (platform.python_version(), sys.platform, traceback.format_exc())) + + ## + # Generates compile data files to be used by external tools. + # Compile information will be generated in ///CompileInfo + # Files generated: compile_commands.json, cscope.files, modules_report.json + # + # @param self The object pointer + # + def GenerateCompileInfo(self): + try: + # Lists for the output elements + compile_commands = [] + used_files = set() + module_report = [] + + for (Wa, MaList) in self.ReportList: + # Obtain list of all processed Workspace files + for file_path in Wa._GetMetaFiles(Wa.BuildTarget, Wa.ToolChain): + used_files.add(file_path) + + for autoGen in Wa.AutoGenObjectList: + + # Loop through all modules + for module in (autoGen.LibraryAutoGenList + autoGen.ModuleAutoGenList): + + used_files.add(module.MetaFile.Path) + + # Main elements of module report + module_report_data = {} + module_report_data["Name"] = module.Name + module_report_data["Arch"] = module.Arch + module_report_data["Path"] = module.MetaFile.Path + module_report_data["Guid"] = module.Guid + module_report_data["BuildType"] = module.BuildType + module_report_data["IsLibrary"] = module.IsLibrary + module_report_data["SourceDir"] = module.SourceDir + module_report_data["Files"] = [] + + # Files used by module + for data_file in module.SourceFileList: + module_report_data["Files"].append({"Name": data_file.Name, "Path": data_file.Path}) + + # Libraries used by module + module_report_data["Libraries"] = [] + for data_library in module.LibraryAutoGenList: + module_report_data["Libraries"].append({"Path": data_library.MetaFile.Path}) + + # Packages used by module + module_report_data["Packages"] = [] + for data_package in module.PackageList: + module_report_data["Packages"].append({"Path": data_package.MetaFile.Path, "Includes": []}) + # Includes path used in package + for data_package_include in data_package.Includes: + module_report_data["Packages"][-1]["Includes"].append(data_package_include.Path) + + # PPI's in module + module_report_data["PPI"] = [] + for data_ppi in module.PpiList.keys(): + module_report_data["PPI"].append({"Name": data_ppi, "Guid": module.PpiList[data_ppi]}) + + # Protocol's in module + module_report_data["Protocol"] = [] + for data_protocol in module.ProtocolList.keys(): + module_report_data["Protocol"].append({"Name": data_protocol, "Guid": module.ProtocolList[data_protocol]}) + + # PCD's in module + module_report_data["Pcd"] = [] + for data_pcd in module.LibraryPcdList: + module_report_data["Pcd"].append({"Space": data_pcd.TokenSpaceGuidCName, + "Name": data_pcd.TokenCName, + "Value": data_pcd.TokenValue, + "Guid": data_pcd.TokenSpaceGuidValue, + "DatumType": data_pcd.DatumType, + "Type": data_pcd.Type, + "DefaultValue": data_pcd.DefaultValue}) + # Add module to report + module_report.append(module_report_data) + + # Include file dependencies to used files + includes_autogen = IncludesAutoGen(module.MakeFileDir, module) + for dep in includes_autogen.DepsCollection: + used_files.add(dep) + + inc_flag = "-I" # Default include flag + if module.BuildRuleFamily == TAB_COMPILER_MSFT: + inc_flag = "/I" + + for source in module.SourceFileList: + used_files.add(source.Path) + compile_command = {} + if source.Ext in [".c", ".cc", ".cpp"]: + # + # Generate compile command for each c file + # + compile_command["file"] = source.Path + compile_command["directory"] = source.Dir + build_command = module.BuildRules[source.Ext].CommandList[0] + build_command_variables = re.findall(r"\$\((.*?)\)", build_command) + for var in build_command_variables: + var_tokens = var.split("_") + var_main = var_tokens[0] + if len(var_tokens) == 1: + var_value = module.BuildOption[var_main]["PATH"] + else: + var_value = module.BuildOption[var_main][var_tokens[1]] + build_command = build_command.replace(f"$({var})", var_value) + include_files = f" {inc_flag}".join(module.IncludePathList) + build_command = build_command.replace("${src}", include_files) + build_command = build_command.replace("${dst}", module.OutputDir) + + # Remove un defined macros + compile_command["command"] = re.sub(r"\$\(.*?\)", "", build_command) + compile_commands.append(compile_command) + + # Create output folder if doesn't exist + compile_info_folder = Path(Wa.BuildDir).joinpath("CompileInfo") + compile_info_folder.mkdir(exist_ok=True) + + # Sort and save files + compile_commands.sort(key=lambda x: x["file"]) + SaveFileOnChange(compile_info_folder.joinpath(f"compile_commands.json"),json.dumps(compile_commands, indent=2), False) + + SaveFileOnChange(compile_info_folder.joinpath(f"cscope.files"), "\n".join(sorted(used_files)), False) + + module_report.sort(key=lambda x: x["Path"]) + SaveFileOnChange(compile_info_folder.joinpath(f"module_report.json"), json.dumps(module_report, indent=2), False) + + except: + EdkLogger.error("BuildReport", CODE_ERROR, "Unknown fatal error when generating build report compile information", ExtraData=self.ReportFile, RaiseError=False) + EdkLogger.quiet("(Python %s on %s\n%s)" % (platform.python_version(), sys.platform, traceback.format_exc())) + # This acts like the main() function for the script, unless it is 'import'ed into another script. if __name__ == '__main__': pass - diff --git a/BaseTools/Source/Python/build/buildoptions.py b/BaseTools/Source/Python/build/buildoptions.py index 8334604b46..5ec561f7ec 100644 --- a/BaseTools/Source/Python/build/buildoptions.py +++ b/BaseTools/Source/Python/build/buildoptions.py @@ -84,8 +84,8 @@ def GetOption(self): Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".") Parser.add_option("-y", "--report-file", action="store", dest="ReportFile", help="Create/overwrite the report to the specified filename.") - Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD', 'LIBRARY', 'FLASH', 'DEPEX', 'BUILD_FLAGS', 'FIXED_ADDRESS', 'HASH', 'EXECUTION_ORDER'], dest="ReportType", default=[], - help="Flags that control the type of build report to generate. Must be one of: [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS, HASH, EXECUTION_ORDER]. "\ + Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD', 'LIBRARY', 'FLASH', 'DEPEX', 'BUILD_FLAGS', 'FIXED_ADDRESS', 'HASH', 'EXECUTION_ORDER', 'COMPILE_INFO'], dest="ReportType", default=[], + help="Flags that control the type of build report to generate. Must be one of: [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS, HASH, EXECUTION_ORDER, COMPILE_INFO]. "\ "To specify more than one flag, repeat this option on the command line and the default flag set is [PCD, LIBRARY, FLASH, DEPEX, HASH, BUILD_FLAGS, FIXED_ADDRESS]") Parser.add_option("-F", "--flag", action="store", type="string", dest="Flag", help="Specify the specific option to parse EDK UNI file. Must be one of: [-c, -s]. -c is for EDK framework UNI file, and -s is for EDK UEFI UNI file. "\ From 209d7158f783ae03bdc81137a8787c539549d035 Mon Sep 17 00:00:00 2001 From: Guillermo Antonio Palomino Sosa Date: Mon, 27 Feb 2023 17:31:49 -0600 Subject: [PATCH 0683/1529] BaseTools: Extend fields for module_report.json Adding following fields to module_report.json: * LibraryClass * ModuleEntryPointList * ConstructorList * DestructorList Signed-off-by: Guillermo Antonio Palomino Sosa Reviewed-by: Bob Feng --- BaseTools/Source/Python/build/BuildReport.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Source/Python/build/BuildReport.py index 33b43d471f..26dfe53fff 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -2354,6 +2354,10 @@ def GenerateCompileInfo(self): module_report_data["IsLibrary"] = module.IsLibrary module_report_data["SourceDir"] = module.SourceDir module_report_data["Files"] = [] + module_report_data["LibraryClass"] = module.Module.LibraryClass + module_report_data["ModuleEntryPointList"] = module.Module.ModuleEntryPointList + module_report_data["ConstructorList"] = module.Module.ConstructorList + module_report_data["DestructorList"] = module.Module.DestructorList # Files used by module for data_file in module.SourceFileList: From 03b79eec2824412fb3b9a6a3a9c5602bd317a5f7 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 11 Mar 2023 11:31:51 -0800 Subject: [PATCH 0684/1529] ShellPkg/Library: Fix 32-bit truncation of pointer values REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4366 Update C and UNI files that are incorrectly using %x or %08x instead of %p for pointer values. On 64-bit systems, this is truncating pointer values above 4GB. In reviewing ShellPkg for this issue some unused UNI strings with incorrect format specifiers were removed instead of being fixed. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Michael D Kinney Reviewed-by: Ray Ni --- .../UefiHandleParsingLib.uni | 18 +++++------ .../UefiShellDebug1CommandsLib.uni | 2 -- .../Library/UefiShellDriver1CommandsLib/Dh.c | 2 +- .../UefiShellDriver1CommandsLib.uni | 31 +------------------ .../UefiShellLevel2CommandsLib.uni | 3 +- 5 files changed, 12 insertions(+), 44 deletions(-) diff --git a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.uni b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.uni index aa3396cea9..6bcb3cd9e4 100644 --- a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.uni +++ b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.uni @@ -173,7 +173,7 @@ #string STR_HII #language en-US "HII" #string STR_HII_FORM_CALLBACK #language en-US "HIICallback" -#string STR_TXT_OUT_DUMP_HEADER #language en-US " Address: %%H%X%%N Attrib %02x" +#string STR_TXT_OUT_DUMP_HEADER #language en-US " Address: %%H%p%%N Attrib %02x" #string STR_TXT_OUT_DUMP_LINE #language en-US "\r\n %c mode %d: Col %d Row %d" #string STR_DRIVER_FAM_OVERRIDE #language en-US "DriverFamilyOverride" @@ -361,7 +361,7 @@ #string STR_DEBUGSUPPORT_INFO #language en-US " Isa = %s" #string STR_DEBUGSUPPORT_UNKNOWN #language en-US " Unknown (%%H%s%%N)" -#string STR_PCIRB_DUMP_PH #language en-US " ParentHandle..: %%H%x%%N\r\n" +#string STR_PCIRB_DUMP_PH #language en-US " ParentHandle..: %%H%p%%N\r\n" #string STR_PCIRB_DUMP_SEG #language en-US " Segment #.....: %%H%x%%N\r\n" #string STR_PCIRB_DUMP_ATT #language en-US " Attributes....: %%H%x%%N\r\n" #string STR_PCIRB_DUMP_SUPPORTS #language en-US " Supports......: %%H%x%%N\r\n" @@ -375,7 +375,7 @@ " Device #......: %02x\r\n" " Function #....: %02x\r\n" " ROM Size......: %lx\r\n" - " ROM Location..: %08x\r\n" + " ROM Location..: %p\r\n" " Vendor ID.....: %04x\r\n" " Device ID.....: %04x\r\n" " Class Code....: %02x %02x %02x\r\n" @@ -388,18 +388,18 @@ #string STR_LI_DUMP_NAME #language en-US " Name..........: %%H%s%%N\r\n" #string STR_LI_DUMP_MAIN #language en-US " Revision......: %%H0x%08x%%N\r\n" - " ParentHandle..: %%H%x%%N\r\n" - " SystemTable...: %%H%x%%N\r\n" - " DeviceHandle..: %%H%x%%N\r\n" + " ParentHandle..: %%H%p%%N\r\n" + " SystemTable...: %%H%p%%N\r\n" + " DeviceHandle..: %%H%p%%N\r\n" " FilePath......: %%H%s%%N\r\n" " PdbFileName...: %%H%a%%N\r\n" " OptionsSize...: %%H%x%%N\r\n" - " LoadOptions...: %%H%x%%N\r\n" - " ImageBase.....: %%H%x%%N\r\n" + " LoadOptions...: %%H%p%%N\r\n" + " ImageBase.....: %%H%p%%N\r\n" " ImageSize.....: %%H%Lx%%N\r\n" " CodeType......: %%H%s%%N\r\n" " DataType......: %%H%s%%N\r\n" - " Unload........: %%H%x%%N" + " Unload........: %%H%p%%N" #string STR_GOP_DUMP_MAIN #language en-US " Max Mode..............: %%H0x%08x%%N\r\n" " Current Mode..........: %%H0x%08x%%N\r\n" diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni index b1d239ed37..4fedc0d149 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni @@ -103,7 +103,6 @@ #string STR_DMEM_HEADER_ROW #language en-US "Memory Address %016LX %X Bytes\r\n" #string STR_DMEM_MMIO_HEADER_ROW #language en-US "Memory Mapped IO Address %016LX %X Bytes\r\n" -#string STR_DMEM_DATA_ROW #language en-US "%08X: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x *%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c*\r\n" #string STR_DMEM_SYSTEM_TABLE #language en-US "\r\nValid EFI Header at Address %016Lx\r\n" "---------------------------------------------\r\n" "System: Table Structure size %08x revision %08x\r\n" @@ -1171,4 +1170,3 @@ " \r\n" " * To edit memory region starting at address 0x00000000 with size of 2 bytes:\r\n" " fs0:\> hexedit -m 0 2\r\n" - diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c index dd9aba50d7..d17d50fe13 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c @@ -325,7 +325,7 @@ GetProtocolInfoString ( Status = gBS->HandleProtocol (TheHandle, ProtocolGuidArray[ProtocolIndex], &Instance); if (!EFI_ERROR (Status)) { StrnCatGrow (&RetVal, &Size, L"(%H", 0); - UnicodeSPrint (InstanceStr, sizeof (InstanceStr), L"%x", Instance); + UnicodeSPrint (InstanceStr, sizeof (InstanceStr), L"%p", Instance); StrnCatGrow (&RetVal, &Size, InstanceStr, 0); StrnCatGrow (&RetVal, &Size, L"%N)", 0); } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.uni b/ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.uni index fc4986c8c6..230779a4b3 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.uni +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.uni @@ -101,7 +101,7 @@ #string STR_DH_OUTPUT_GUID_HEADER #language en-US "Handle dump by protocol '%g'\r\n" #string STR_DH_OUTPUT_NAME_HEADER #language en-US "Handle dump by protocol '%s'\r\n" #string STR_DH_OUTPUT_SINGLE_D #language en-US "%H%02x%N: %s\r\n" -#string STR_DH_OUTPUT_SINGLE #language en-US "%H%02x%N: %x\r\n%s" +#string STR_DH_OUTPUT_SINGLE #language en-US "%H%02x%N: %p\r\n%s" #string STR_DH_OUTPUT_SFO #language en-US "%s, %s, %s, %H%02x%N, %s, %s\r\n" #string STR_DH_OUTPUT_DRIVER1 #language en-US " Controller Name : %H%s%N\r\n" #string STR_DH_OUTPUT_DRIVER2 #language en-US " Device Path : %H%s%N\r\n" @@ -128,18 +128,6 @@ #string STR_DEV_TREE_OUTPUT #language en-US "Ctrl[%H%02x%N] %s\r\n" #string STR_UNLOAD_CONF #language en-US "%HUnload%N - Handle [%H%02x%N]. [y/n]?\r\n" -#string STR_UNLOAD_VERBOSE #language en-US "" -"Handle [%H%02x%N] (%08x)\r\n" -" Image (%08x)\r\n" -" ParentHandle..: %08x\r\n" -" SystemTable...: %08x\r\n" -" DeviceHandle..: %08x\r\n" -" FilePath......: %s\r\n" -" PDBFileName...: %a\r\n" -" ImageBase.....: %08x\r\n" -" ImageSize.....: %Ld\r\n" -" CodeType......: %s\r\n" -" DataType......: %s\r\n" #string STR_OPENINFO_HEADER_LINE #language en-US "Handle %H%02x%N (%H%0p%N)\r\n" #string STR_OPENINFO_LINE #language en-US " Drv[%H%02x%N] Ctrl[%H%02x%N] Cnt(%H%02x%N) %H%s Image%N(%s)\r\n" @@ -734,20 +722,3 @@ " violation.\r\n" " SHELL_INVALID_PARAMETER One of the passed in parameters was incorrectly\r\n" " formatted or its value was out of bounds.\r\n" - - - - - - - - - - - - - - - - - diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.uni b/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.uni index 8ce015746f..0a0cd3090e 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.uni +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.uni @@ -134,7 +134,7 @@ #string STR_LOAD_NOT_IMAGE #language en-US "Image '%s' is not an image.\r\n" #string STR_LOAD_NOT_DRIVER #language en-US "Image '%s' is not a driver.\r\n" -#string STR_LOAD_LOADED #language en-US "Image '%s' loaded at %x - %r\r\n" +#string STR_LOAD_LOADED #language en-US "Image '%s' loaded at %p - %r\r\n" #string STR_LOAD_ERROR #language en-US "Image '%s' error in StartImage: %r\r\n" #string STR_LS_LINE_START_ALL #language en-US "%t %5s %1c % ,L11d " @@ -1076,4 +1076,3 @@ " SHELL_SECURITY_VIOLATION This function was not performed due to a security\r\n" " violation.\r\n" " SHELL_NOT_FOUND The target file-system was not found.\r\n" - From 719b85dccea5dd2de1395acc17bf94422ab01c33 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Mon, 13 Mar 2023 15:03:57 +0800 Subject: [PATCH 0685/1529] UefiCpuPkg/PiSmmCpuDxeSmm: Fix S3 failure in SmmRestoreCpu REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4368 This issue is caused by the commit: ec07fd0e35d90dbcc36be300a9ceeac29c5de2ad GetFirstGuidHob() should not be used after exit boot service. Cc: Eric Dong Cc: Ray Ni Cc: Zeng Star Cc: Laszlo Ersek Cc: Gerd Hoffmann Signed-off-by: Jiaxin Wu Reviewed-by: Star Zeng Reviewed-by: Gerd Hoffmann Tested-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c index d408b3f9f7..240eee6a7d 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c @@ -823,19 +823,7 @@ SmmRestoreCpu ( InitializeCpuBeforeRebase (); } - // - // Make sure the gSmmBaseHobGuid existence status is the same between normal and S3 boot. - // - ASSERT (mSmmRelocated == (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL)); - if (mSmmRelocated != (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL)) { - DEBUG (( - DEBUG_ERROR, - "gSmmBaseHobGuid %a produced in normal boot but %a in S3 boot!", - mSmmRelocated ? "is" : "is not", - mSmmRelocated ? "is not" : "is" - )); - CpuDeadLoop (); - } + DEBUG ((DEBUG_INFO, "SmmRestoreCpu: mSmmRelocated is %d\n", mSmmRelocated)); // // Check whether Smm Relocation is done or not. From c9c90044e8bc65e936a559b25cb91fbb4681b076 Mon Sep 17 00:00:00 2001 From: MarsX Lin Date: Tue, 14 Mar 2023 17:08:59 +0800 Subject: [PATCH 0686/1529] UefiPayloadPkg: Correct MAX_LOGICAL_PROCESSORS value REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4372 Correct MAX_LOGICAL_PROCESSORS value to 1024 Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: MarsX Lin --- UefiPayloadPkg/UefiPayloadPkg.dsc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 35e3bfff35..bca5d3f335 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -59,7 +59,7 @@ # # CPU options # - DEFINE MAX_LOGICAL_PROCESSORS = 256 + DEFINE MAX_LOGICAL_PROCESSORS = 1024 # # PCI options From 1658cd2303980a61e1ab5255c5b89225078d1078 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Wed, 15 Mar 2023 12:47:29 +0530 Subject: [PATCH 0687/1529] OvmfPkg/PlatformCI: Add CI coverage for RiscVVirtQemu Add support for building RiscVVirtQemu platform in CI. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Signed-off-by: Sunil V L Acked-by: Gerd Hoffmann --- .../.azurepipelines/Ubuntu-GCC5.yml | 9 +++++ OvmfPkg/PlatformCI/QemuBuild.py | 37 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 OvmfPkg/PlatformCI/QemuBuild.py diff --git a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml index 1cf9bdf8b9..ad43f9fad2 100644 --- a/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml +++ b/OvmfPkg/PlatformCI/.azurepipelines/Ubuntu-GCC5.yml @@ -174,6 +174,15 @@ jobs: Run.Flags: "QEMU_SKIP=TRUE" Run: $(should_run) + QEMU_RISCV64_DEBUG: + Build.File: "$(package)/PlatformCI/QemuBuild.py" + Build.Arch: "RISCV64" + Build.Flags: "" + Build.Target: "DEBUG" + # this build is for RISC-V qemu virt not qemu-kvm + Run.Flags: "QEMU_SKIP=TRUE" + Run: $(should_run) + workspace: clean: all diff --git a/OvmfPkg/PlatformCI/QemuBuild.py b/OvmfPkg/PlatformCI/QemuBuild.py new file mode 100644 index 0000000000..c737d98d51 --- /dev/null +++ b/OvmfPkg/PlatformCI/QemuBuild.py @@ -0,0 +1,37 @@ +# @file +# Script to Build OVMF UEFI firmware +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from PlatformBuildLib import SettingsManager +from PlatformBuildLib import PlatformBuilder + + # ####################################################################################### # + # Common Configuration # + # ####################################################################################### # +class CommonPlatform(): + ''' Common settings for this platform. Define static data here and use + for the different parts of stuart + ''' + PackagesSupported = ("OvmfPkg",) + ArchSupported = ("RISCV64",) + TargetsSupported = ("DEBUG", "RELEASE", "NOOPT") + Scopes = ('ovmf', 'edk2-build') + WorkspaceRoot = os.path.realpath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..")) + + @classmethod + def GetDscName(cls, ArchCsv: str) -> str: + ''' return the DSC given the architectures requested. + + ArchCsv: csv string containing all architectures to build + ''' + return "RiscVVirt/RiscVVirtQemu.dsc" + +import PlatformBuildLib +PlatformBuildLib.CommonPlatform = CommonPlatform From 741a13d19115ace580c0b86c574085ac3b0d79a0 Mon Sep 17 00:00:00 2001 From: Tuan Phan Date: Fri, 10 Mar 2023 13:50:19 -0800 Subject: [PATCH 0688/1529] MdePkg/BaseCacheMaintenanceLib: RISC-V: Fix InvalidateInstructionCacheRange When the range instruction cache invalidating not supported, the whole instruction cache should be invalidated instead. Signed-off-by: Tuan Phan Reviewed-by: Sunil V L --- MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c b/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c index 67a3387ff3..9a6d57d841 100644 --- a/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c +++ b/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c @@ -76,7 +76,12 @@ InvalidateInstructionCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ( + (DEBUG_WARN, + "%a:RISC-V unsupported function.\n" + "Invalidating the whole instruction cache instead.\n", __func__) + ); + InvalidateInstructionCache (); return Address; } From 27e884ceaa3264fe58f76a9a04862123218724cc Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 9 Feb 2023 09:46:37 +0100 Subject: [PATCH 0689/1529] ArmPkg/ArmMmuLib ARM: Remove half baked large page support Large page support on 32-bit ARM is essentially a glorified contiguous bit where 16 consecutive entries describing a contiguous range with the same attributes are presented in a way that permits the TLB to cache its translation with a single entry. This was never wired up completely, and does not add a lot of value in EFI, where the page granularity is 4k and we expect to be able to set RO and XP permissions on individual pages. Given that large page support complicates the handling of the XN bit at the page level (which is in a different place depending on whether the page is small or large), let's just rip it out. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/Arm/Mmu.c | 8 ++-- ArmPkg/Include/Chipset/ArmV7Mmu.h | 40 +++++-------------- .../Library/ArmMmuLib/Arm/ArmMmuLibConvert.c | 7 ++-- ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c | 2 +- .../Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 2 +- 5 files changed, 20 insertions(+), 39 deletions(-) diff --git a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c index 2daf47ba6f..ea856f5cdd 100644 --- a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c @@ -165,7 +165,7 @@ SyncCacheConfigPage ( // Convert SectionAttributes into PageAttributes NextPageAttributes = - TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (*NextSectionAttributes, 0) | + TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (*NextSectionAttributes) | TT_DESCRIPTOR_CONVERT_TO_PAGE_AP (*NextSectionAttributes); // obtain page table base @@ -212,7 +212,7 @@ SyncCacheConfigPage ( // Convert back PageAttributes into SectionAttributes *NextSectionAttributes = - TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (NextPageAttributes, 0) | + TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (NextPageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_AP (NextPageAttributes); return EFI_SUCCESS; @@ -399,7 +399,7 @@ GetMemoryRegionPage ( UINT32 PageDescriptor; // Convert the section attributes into page attributes - PageAttributes = ConvertSectionAttributesToPageAttributes (*RegionAttributes, 0); + PageAttributes = ConvertSectionAttributesToPageAttributes (*RegionAttributes); // Calculate index into first level translation table for start of modification TableIndex = ((*BaseAddress) & TT_DESCRIPTOR_PAGE_INDEX_MASK) >> TT_DESCRIPTOR_PAGE_BASE_SHIFT; @@ -479,7 +479,7 @@ GetMemoryRegion ( ASSERT (PageTableIndex < TRANSLATION_TABLE_PAGE_COUNT); PageAttributes = PageTable[PageTableIndex] & TT_DESCRIPTOR_PAGE_ATTRIBUTE_MASK; - *RegionAttributes = TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (PageAttributes, 0) | + *RegionAttributes = TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (PageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_AP (PageAttributes); } diff --git a/ArmPkg/Include/Chipset/ArmV7Mmu.h b/ArmPkg/Include/Chipset/ArmV7Mmu.h index db99527d6e..7501ebfdf9 100644 --- a/ArmPkg/Include/Chipset/ArmV7Mmu.h +++ b/ArmPkg/Include/Chipset/ArmV7Mmu.h @@ -98,9 +98,8 @@ #define TT_DESCRIPTOR_PAGE_AP_RO_NO ((1UL << 9) | (1UL << 4)) #define TT_DESCRIPTOR_PAGE_AP_RO_RO ((1UL << 9) | (3UL << 4)) -#define TT_DESCRIPTOR_SECTION_XN_MASK (0x1UL << 4) -#define TT_DESCRIPTOR_PAGE_XN_MASK (0x1UL << 0) -#define TT_DESCRIPTOR_LARGEPAGE_XN_MASK (0x1UL << 15) +#define TT_DESCRIPTOR_SECTION_XN_MASK (0x1UL << 4) +#define TT_DESCRIPTOR_PAGE_XN_MASK (0x1UL << 0) #define TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK ((3UL << 12) | (1UL << 3) | (1UL << 2)) #define TT_DESCRIPTOR_SECTION_CACHEABLE_MASK (1UL << 3) @@ -124,30 +123,14 @@ #define TT_DESCRIPTOR_PAGE_CACHE_POLICY_WRITE_BACK_ALLOC ((1UL << 6) | (1UL << 3) | (1UL << 2)) #define TT_DESCRIPTOR_PAGE_CACHE_POLICY_NON_SHAREABLE_DEVICE ((2UL << 6) | (0UL << 3) | (0UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_MASK ((3UL << 12) | (1UL << 3) | (1UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_STRONGLY_ORDERED ((0UL << 12) | (0UL << 3) | (0UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_SHAREABLE_DEVICE ((0UL << 12) | (0UL << 3) | (1UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_WRITE_THROUGH_NO_ALLOC ((0UL << 12) | (1UL << 3) | (0UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_WRITE_BACK_NO_ALLOC ((0UL << 12) | (1UL << 3) | (1UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_NON_CACHEABLE ((1UL << 12) | (0UL << 3) | (0UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_WRITE_BACK_ALLOC ((1UL << 12) | (1UL << 3) | (1UL << 2)) -#define TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_NON_SHAREABLE_DEVICE ((2UL << 12) | (0UL << 3) | (0UL << 2)) - -#define TT_DESCRIPTOR_CONVERT_TO_PAGE_AP(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_AP_MASK) >> 6) & TT_DESCRIPTOR_PAGE_AP_MASK) -#define TT_DESCRIPTOR_CONVERT_TO_PAGE_NG(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_NG_MASK) >> 6) & TT_DESCRIPTOR_PAGE_NG_MASK) -#define TT_DESCRIPTOR_CONVERT_TO_PAGE_S(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_S_MASK) >> 6) & TT_DESCRIPTOR_PAGE_S_MASK) -#define TT_DESCRIPTOR_CONVERT_TO_PAGE_XN(Desc, IsLargePage) ((IsLargePage)?\ - ((((Desc) & TT_DESCRIPTOR_SECTION_XN_MASK) << 11) & TT_DESCRIPTOR_LARGEPAGE_XN_MASK): \ - ((((Desc) & TT_DESCRIPTOR_SECTION_XN_MASK) >> 4) & TT_DESCRIPTOR_PAGE_XN_MASK)) -#define TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY(Desc, IsLargePage) (IsLargePage? \ - (((Desc) & TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK) & TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_MASK): \ - (((((Desc) & (0x3 << 12)) >> 6) | (Desc & (0x3 << 2))))) - -#define TT_DESCRIPTOR_CONVERT_TO_SECTION_AP(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_AP_MASK) << 6) & TT_DESCRIPTOR_SECTION_AP_MASK) - -#define TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY(Desc, IsLargePage) (IsLargePage? \ - (((Desc) & TT_DESCRIPTOR_LARGEPAGE_CACHE_POLICY_MASK) & TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK): \ - (((((Desc) & (0x3 << 6)) << 6) | (Desc & (0x3 << 2))))) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_AP(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_AP_MASK) >> 6) & TT_DESCRIPTOR_PAGE_AP_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_NG(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_NG_MASK) >> 6) & TT_DESCRIPTOR_PAGE_NG_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_S(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_S_MASK) >> 6) & TT_DESCRIPTOR_PAGE_S_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_XN(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_XN_MASK) >> 4) & TT_DESCRIPTOR_PAGE_XN_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 12)) >> 6) | (Desc & (0x3 << 2))) + +#define TT_DESCRIPTOR_CONVERT_TO_SECTION_AP(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_AP_MASK) << 6) & TT_DESCRIPTOR_SECTION_AP_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 6)) << 6) | (Desc & (0x3 << 2))) #define TT_DESCRIPTOR_SECTION_ATTRIBUTE_MASK (TT_DESCRIPTOR_SECTION_NS_MASK | TT_DESCRIPTOR_SECTION_NG_MASK | \ TT_DESCRIPTOR_SECTION_S_MASK | TT_DESCRIPTOR_SECTION_AP_MASK | \ @@ -230,8 +213,7 @@ typedef UINT32 ARM_PAGE_TABLE_ENTRY; UINT32 ConvertSectionAttributesToPageAttributes ( - IN UINT32 SectionAttributes, - IN BOOLEAN IsLargePage + IN UINT32 SectionAttributes ); #endif // ARMV7_MMU_H_ diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c index bee8ad7028..6e2f08a7ce 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c @@ -15,16 +15,15 @@ UINT32 ConvertSectionAttributesToPageAttributes ( - IN UINT32 SectionAttributes, - IN BOOLEAN IsLargePage + IN UINT32 SectionAttributes ) { UINT32 PageAttributes; PageAttributes = 0; - PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (SectionAttributes, IsLargePage); + PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_AP (SectionAttributes); - PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_XN (SectionAttributes, IsLargePage); + PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_XN (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_NG (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_S (SectionAttributes); diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c index 9e304ea05e..28cc9b2fe0 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c @@ -145,7 +145,7 @@ PopulateLevel2PageTable ( ); // Translate the Section Descriptor into Page Descriptor - SectionDescriptor = TT_DESCRIPTOR_PAGE_TYPE_PAGE | ConvertSectionAttributesToPageAttributes (*SectionEntry, FALSE); + SectionDescriptor = TT_DESCRIPTOR_PAGE_TYPE_PAGE | ConvertSectionAttributesToPageAttributes (*SectionEntry); BaseSectionAddress = TT_DESCRIPTOR_SECTION_BASE_ADDRESS (*SectionEntry); diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index b402197ade..9ca00c976d 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -53,7 +53,7 @@ ConvertSectionToPages ( // Get section attributes and convert to page attributes SectionDescriptor = FirstLevelTable[FirstLevelIdx]; - PageDescriptor = TT_DESCRIPTOR_PAGE_TYPE_PAGE | ConvertSectionAttributesToPageAttributes (SectionDescriptor, FALSE); + PageDescriptor = TT_DESCRIPTOR_PAGE_TYPE_PAGE | ConvertSectionAttributesToPageAttributes (SectionDescriptor); // Allocate a page table for the 4KB entries (we use up a full page even though we only need 1KB) PageTable = (volatile ARM_PAGE_TABLE_ENTRY *)AllocatePages (1); From 0cae6f690966e3578050fda452ae82da8925e64d Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 9 Feb 2023 10:01:45 +0100 Subject: [PATCH 0690/1529] ArmPkg/ArmMmuLib ARM: Split off XN page descriptor bit from type field With large page support out of the picture, we can treat bits 1 and 0 of the page descriptor as individual valid and XN bits, instead of treating XN as a page type. Doing so aligns the handling of the attribute with the section descriptor layout, as well as the XN handling on AArch64, and this is beneficial for maintainability. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Include/Chipset/ArmV7Mmu.h | 8 +++----- ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 12 ++++++------ 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/ArmPkg/Include/Chipset/ArmV7Mmu.h b/ArmPkg/Include/Chipset/ArmV7Mmu.h index 7501ebfdf9..6a2584ceb3 100644 --- a/ArmPkg/Include/Chipset/ArmV7Mmu.h +++ b/ArmPkg/Include/Chipset/ArmV7Mmu.h @@ -54,11 +54,9 @@ #define TT_DESCRIPTOR_SECTION_TYPE_IS_PAGE_TABLE(Desc) (((Desc) & 3UL) == TT_DESCRIPTOR_SECTION_TYPE_PAGE_TABLE) // Translation table descriptor types -#define TT_DESCRIPTOR_PAGE_TYPE_MASK (3UL << 0) -#define TT_DESCRIPTOR_PAGE_TYPE_FAULT (0UL << 0) -#define TT_DESCRIPTOR_PAGE_TYPE_PAGE (2UL << 0) -#define TT_DESCRIPTOR_PAGE_TYPE_PAGE_XN (3UL << 0) -#define TT_DESCRIPTOR_PAGE_TYPE_LARGEPAGE (1UL << 0) +#define TT_DESCRIPTOR_PAGE_TYPE_MASK (1UL << 1) +#define TT_DESCRIPTOR_PAGE_TYPE_FAULT (0UL << 1) +#define TT_DESCRIPTOR_PAGE_TYPE_PAGE (1UL << 1) // Section descriptor definitions #define TT_DESCRIPTOR_SECTION_SIZE (0x00100000) diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index 9ca00c976d..12d0f4c30f 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -104,12 +104,8 @@ UpdatePageEntries ( // EntryMask: bitmask of values to change (1 = change this value, 0 = leave alone) // EntryValue: values at bit positions specified by EntryMask - EntryMask = TT_DESCRIPTOR_PAGE_TYPE_MASK | TT_DESCRIPTOR_PAGE_AP_MASK; - if ((Attributes & EFI_MEMORY_XP) != 0) { - EntryValue = TT_DESCRIPTOR_PAGE_TYPE_PAGE_XN; - } else { - EntryValue = TT_DESCRIPTOR_PAGE_TYPE_PAGE; - } + EntryMask = TT_DESCRIPTOR_PAGE_TYPE_MASK | TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_XN_MASK; + EntryValue = TT_DESCRIPTOR_PAGE_TYPE_PAGE; // Although the PI spec is unclear on this, the GCD guarantees that only // one Attribute bit is set at a time, so the order of the conditionals below @@ -148,6 +144,10 @@ UpdatePageEntries ( EntryValue |= TT_DESCRIPTOR_PAGE_AP_RW_RW; } + if ((Attributes & EFI_MEMORY_XP) != 0) { + EntryValue |= TT_DESCRIPTOR_PAGE_XN_MASK; + } + // Obtain page table base FirstLevelTable = (ARM_FIRST_LEVEL_DESCRIPTOR *)ArmGetTTBR0BaseAddress (); From dd62d514ba5e737c82bde590193d3ba9b98e5faf Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Feb 2023 19:29:09 +0100 Subject: [PATCH 0691/1529] ArmPkg/CpuDxe ARM: Fix page-to-section attribute conversion The section-to-page attribute conversion takes the shareability and execute-never attributes into account, whereas the page-to-section counterpart does not. The result is that GetMemoryRegionPage () -which takes a section attribute argument (via *RegionAttributes) that is ostensibly based on the first page in the range, but differs from the actual page attributes when converted back- may return with a RegionLength of zero. This is incorrect, and confuses code that scans a region by calling GetMemoryRegion () in sequence. So fix the conversion, and ASSERT () on a non-zero region length. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/Arm/Mmu.c | 3 +++ ArmPkg/Include/Chipset/ArmV7Mmu.h | 2 ++ 2 files changed, 5 insertions(+) diff --git a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c index ea856f5cdd..8eb1f71395 100644 --- a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c @@ -480,6 +480,8 @@ GetMemoryRegion ( PageAttributes = PageTable[PageTableIndex] & TT_DESCRIPTOR_PAGE_ATTRIBUTE_MASK; *RegionAttributes = TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (PageAttributes) | + TT_DESCRIPTOR_CONVERT_TO_SECTION_S (PageAttributes) | + TT_DESCRIPTOR_CONVERT_TO_SECTION_XN (PageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_AP (PageAttributes); } @@ -494,6 +496,7 @@ GetMemoryRegion ( // Scan the page table to find the end of the region. Status = GetMemoryRegionPage (PageTable, BaseAddress, RegionLength, RegionAttributes); + ASSERT (*RegionLength > 0); // If we have found the end of the region (Status == EFI_SUCCESS) then we exit the for-loop if (Status == EFI_SUCCESS) { diff --git a/ArmPkg/Include/Chipset/ArmV7Mmu.h b/ArmPkg/Include/Chipset/ArmV7Mmu.h index 6a2584ceb3..e0219747df 100644 --- a/ArmPkg/Include/Chipset/ArmV7Mmu.h +++ b/ArmPkg/Include/Chipset/ArmV7Mmu.h @@ -128,6 +128,8 @@ #define TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 12)) >> 6) | (Desc & (0x3 << 2))) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_AP(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_AP_MASK) << 6) & TT_DESCRIPTOR_SECTION_AP_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_SECTION_S(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_S_MASK) << 6) & TT_DESCRIPTOR_SECTION_S_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_SECTION_XN(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_XN_MASK) << 4) & TT_DESCRIPTOR_SECTION_XN_MASK) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 6)) << 6) | (Desc & (0x3 << 2))) #define TT_DESCRIPTOR_SECTION_ATTRIBUTE_MASK (TT_DESCRIPTOR_SECTION_NS_MASK | TT_DESCRIPTOR_SECTION_NG_MASK | \ From e9d727a22d85551100939038f27a789c48789d7b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 7 Feb 2023 17:32:19 +0100 Subject: [PATCH 0692/1529] ArmPkg/ArmMmuLib ARM: Isolate the access flag from AP mask Split the ARM permission fields in the short descriptors into an access flag and AP[2:1] as per the recommendation in the ARM ARM. This makes the access flag available separately, which allows us to implement EFI_MEMORY_RP memory analogous to how it will be implemented for AArch64. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/Arm/Mmu.c | 47 ++++++++++--------- ArmPkg/Include/Chipset/ArmV7Mmu.h | 42 +++++++++++------ ArmPkg/Library/ArmLib/Arm/ArmV7Support.S | 2 + .../Library/ArmMmuLib/Arm/ArmMmuLibConvert.c | 1 + .../Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 12 ++++- 5 files changed, 64 insertions(+), 40 deletions(-) diff --git a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c index 8eb1f71395..07faab8216 100644 --- a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c @@ -50,30 +50,27 @@ SectionToGcdAttributes ( // determine protection attributes switch (SectionAttributes & TT_DESCRIPTOR_SECTION_AP_MASK) { - case TT_DESCRIPTOR_SECTION_AP_NO_NO: // no read, no write - // *GcdAttributes |= EFI_MEMORY_RO | EFI_MEMORY_RP; - break; - - case TT_DESCRIPTOR_SECTION_AP_RW_NO: + case TT_DESCRIPTOR_SECTION_AP_NO_RW: case TT_DESCRIPTOR_SECTION_AP_RW_RW: // normal read/write access, do not add additional attributes break; // read only cases map to write-protect - case TT_DESCRIPTOR_SECTION_AP_RO_NO: + case TT_DESCRIPTOR_SECTION_AP_NO_RO: case TT_DESCRIPTOR_SECTION_AP_RO_RO: *GcdAttributes |= EFI_MEMORY_RO; break; - - default: - return EFI_UNSUPPORTED; } // now process eXectue Never attribute - if ((SectionAttributes & TT_DESCRIPTOR_SECTION_XN_MASK) != 0 ) { + if ((SectionAttributes & TT_DESCRIPTOR_SECTION_XN_MASK) != 0) { *GcdAttributes |= EFI_MEMORY_XP; } + if ((SectionAttributes & TT_DESCRIPTOR_SECTION_AF) == 0) { + *GcdAttributes |= EFI_MEMORY_RP; + } + return EFI_SUCCESS; } @@ -114,30 +111,27 @@ PageToGcdAttributes ( // determine protection attributes switch (PageAttributes & TT_DESCRIPTOR_PAGE_AP_MASK) { - case TT_DESCRIPTOR_PAGE_AP_NO_NO: // no read, no write - // *GcdAttributes |= EFI_MEMORY_RO | EFI_MEMORY_RP; - break; - - case TT_DESCRIPTOR_PAGE_AP_RW_NO: + case TT_DESCRIPTOR_PAGE_AP_NO_RW: case TT_DESCRIPTOR_PAGE_AP_RW_RW: // normal read/write access, do not add additional attributes break; // read only cases map to write-protect - case TT_DESCRIPTOR_PAGE_AP_RO_NO: + case TT_DESCRIPTOR_PAGE_AP_NO_RO: case TT_DESCRIPTOR_PAGE_AP_RO_RO: *GcdAttributes |= EFI_MEMORY_RO; break; - - default: - return EFI_UNSUPPORTED; } // now process eXectue Never attribute - if ((PageAttributes & TT_DESCRIPTOR_PAGE_XN_MASK) != 0 ) { + if ((PageAttributes & TT_DESCRIPTOR_PAGE_XN_MASK) != 0) { *GcdAttributes |= EFI_MEMORY_XP; } + if ((PageAttributes & TT_DESCRIPTOR_PAGE_AF) == 0) { + *GcdAttributes |= EFI_MEMORY_RP; + } + return EFI_SUCCESS; } @@ -166,6 +160,7 @@ SyncCacheConfigPage ( // Convert SectionAttributes into PageAttributes NextPageAttributes = TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (*NextSectionAttributes) | + TT_DESCRIPTOR_CONVERT_TO_PAGE_AF (*NextSectionAttributes) | TT_DESCRIPTOR_CONVERT_TO_PAGE_AP (*NextSectionAttributes); // obtain page table base @@ -174,7 +169,7 @@ SyncCacheConfigPage ( for (i = 0; i < TRANSLATION_TABLE_PAGE_COUNT; i++) { if ((SecondLevelTable[i] & TT_DESCRIPTOR_PAGE_TYPE_MASK) == TT_DESCRIPTOR_PAGE_TYPE_PAGE) { // extract attributes (cacheability and permissions) - PageAttributes = SecondLevelTable[i] & (TT_DESCRIPTOR_PAGE_CACHE_POLICY_MASK | TT_DESCRIPTOR_PAGE_AP_MASK); + PageAttributes = SecondLevelTable[i] & (TT_DESCRIPTOR_PAGE_CACHE_POLICY_MASK | TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_AF); if (NextPageAttributes == 0) { // start on a new region @@ -213,6 +208,7 @@ SyncCacheConfigPage ( // Convert back PageAttributes into SectionAttributes *NextSectionAttributes = TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (NextPageAttributes) | + TT_DESCRIPTOR_CONVERT_TO_SECTION_AF (NextPageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_AP (NextPageAttributes); return EFI_SUCCESS; @@ -256,14 +252,14 @@ SyncCacheConfig ( FirstLevelTable = (ARM_FIRST_LEVEL_DESCRIPTOR *)(ArmGetTTBR0BaseAddress ()); // Get the first region - NextSectionAttributes = FirstLevelTable[0] & (TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK | TT_DESCRIPTOR_SECTION_AP_MASK); + NextSectionAttributes = FirstLevelTable[0] & (TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK | TT_DESCRIPTOR_SECTION_AP_MASK | TT_DESCRIPTOR_SECTION_AF); // iterate through each 1MB descriptor NextRegionBase = NextRegionLength = 0; for (i = 0; i < TRANSLATION_TABLE_SECTION_COUNT; i++) { if ((FirstLevelTable[i] & TT_DESCRIPTOR_SECTION_TYPE_MASK) == TT_DESCRIPTOR_SECTION_TYPE_SECTION) { // extract attributes (cacheability and permissions) - SectionAttributes = FirstLevelTable[i] & (TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK | TT_DESCRIPTOR_SECTION_AP_MASK); + SectionAttributes = FirstLevelTable[i] & (TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK | TT_DESCRIPTOR_SECTION_AP_MASK | TT_DESCRIPTOR_SECTION_AF); if (NextSectionAttributes == 0) { // start on a new region @@ -383,6 +379,10 @@ EfiAttributeToArmAttribute ( ArmAttributes |= TT_DESCRIPTOR_SECTION_XN_MASK; } + if ((EfiAttributes & EFI_MEMORY_RP) == 0) { + ArmAttributes |= TT_DESCRIPTOR_SECTION_AF; + } + return ArmAttributes; } @@ -482,6 +482,7 @@ GetMemoryRegion ( *RegionAttributes = TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY (PageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_S (PageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_XN (PageAttributes) | + TT_DESCRIPTOR_CONVERT_TO_SECTION_AF (PageAttributes) | TT_DESCRIPTOR_CONVERT_TO_SECTION_AP (PageAttributes); } diff --git a/ArmPkg/Include/Chipset/ArmV7Mmu.h b/ArmPkg/Include/Chipset/ArmV7Mmu.h index e0219747df..da4f3160f8 100644 --- a/ArmPkg/Include/Chipset/ArmV7Mmu.h +++ b/ArmPkg/Include/Chipset/ArmV7Mmu.h @@ -80,21 +80,21 @@ #define TT_DESCRIPTOR_PAGE_S_NOT_SHARED (0UL << 10) #define TT_DESCRIPTOR_PAGE_S_SHARED (1UL << 10) -#define TT_DESCRIPTOR_SECTION_AP_MASK ((1UL << 15) | (3UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_NO_NO ((0UL << 15) | (0UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_RW_NO ((0UL << 15) | (1UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_RW_RO ((0UL << 15) | (2UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_RW_RW ((0UL << 15) | (3UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_RO_NO ((1UL << 15) | (1UL << 10)) -#define TT_DESCRIPTOR_SECTION_AP_RO_RO ((1UL << 15) | (3UL << 10)) - -#define TT_DESCRIPTOR_PAGE_AP_MASK ((1UL << 9) | (3UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_NO_NO ((0UL << 9) | (0UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_RW_NO ((0UL << 9) | (1UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_RW_RO ((0UL << 9) | (2UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_RW_RW ((0UL << 9) | (3UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_RO_NO ((1UL << 9) | (1UL << 4)) -#define TT_DESCRIPTOR_PAGE_AP_RO_RO ((1UL << 9) | (3UL << 4)) +#define TT_DESCRIPTOR_SECTION_AP_MASK ((1UL << 15) | (1UL << 11)) +#define TT_DESCRIPTOR_SECTION_AP_NO_RW ((0UL << 15) | (0UL << 11)) +#define TT_DESCRIPTOR_SECTION_AP_RW_RW ((0UL << 15) | (1UL << 11)) +#define TT_DESCRIPTOR_SECTION_AP_NO_RO ((1UL << 15) | (0UL << 11)) +#define TT_DESCRIPTOR_SECTION_AP_RO_RO ((1UL << 15) | (1UL << 11)) + +#define TT_DESCRIPTOR_SECTION_AF (1UL << 10) + +#define TT_DESCRIPTOR_PAGE_AP_MASK ((1UL << 9) | (1UL << 5)) +#define TT_DESCRIPTOR_PAGE_AP_NO_RW ((0UL << 9) | (0UL << 5)) +#define TT_DESCRIPTOR_PAGE_AP_RW_RW ((0UL << 9) | (1UL << 5)) +#define TT_DESCRIPTOR_PAGE_AP_NO_RO ((1UL << 9) | (0UL << 5)) +#define TT_DESCRIPTOR_PAGE_AP_RO_RO ((1UL << 9) | (1UL << 5)) + +#define TT_DESCRIPTOR_PAGE_AF (1UL << 4) #define TT_DESCRIPTOR_SECTION_XN_MASK (0x1UL << 4) #define TT_DESCRIPTOR_PAGE_XN_MASK (0x1UL << 0) @@ -124,20 +124,24 @@ #define TT_DESCRIPTOR_CONVERT_TO_PAGE_AP(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_AP_MASK) >> 6) & TT_DESCRIPTOR_PAGE_AP_MASK) #define TT_DESCRIPTOR_CONVERT_TO_PAGE_NG(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_NG_MASK) >> 6) & TT_DESCRIPTOR_PAGE_NG_MASK) #define TT_DESCRIPTOR_CONVERT_TO_PAGE_S(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_S_MASK) >> 6) & TT_DESCRIPTOR_PAGE_S_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_PAGE_AF(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_AF) >> 6) & TT_DESCRIPTOR_PAGE_AF) #define TT_DESCRIPTOR_CONVERT_TO_PAGE_XN(Desc) ((((Desc) & TT_DESCRIPTOR_SECTION_XN_MASK) >> 4) & TT_DESCRIPTOR_PAGE_XN_MASK) #define TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 12)) >> 6) | (Desc & (0x3 << 2))) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_AP(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_AP_MASK) << 6) & TT_DESCRIPTOR_SECTION_AP_MASK) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_S(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_S_MASK) << 6) & TT_DESCRIPTOR_SECTION_S_MASK) +#define TT_DESCRIPTOR_CONVERT_TO_SECTION_AF(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_AF) << 6) & TT_DESCRIPTOR_SECTION_AF) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_XN(Desc) ((((Desc) & TT_DESCRIPTOR_PAGE_XN_MASK) << 4) & TT_DESCRIPTOR_SECTION_XN_MASK) #define TT_DESCRIPTOR_CONVERT_TO_SECTION_CACHE_POLICY(Desc) ((((Desc) & (0x3 << 6)) << 6) | (Desc & (0x3 << 2))) #define TT_DESCRIPTOR_SECTION_ATTRIBUTE_MASK (TT_DESCRIPTOR_SECTION_NS_MASK | TT_DESCRIPTOR_SECTION_NG_MASK | \ TT_DESCRIPTOR_SECTION_S_MASK | TT_DESCRIPTOR_SECTION_AP_MASK | \ + TT_DESCRIPTOR_SECTION_AF | \ TT_DESCRIPTOR_SECTION_XN_MASK | TT_DESCRIPTOR_SECTION_CACHE_POLICY_MASK) #define TT_DESCRIPTOR_PAGE_ATTRIBUTE_MASK (TT_DESCRIPTOR_PAGE_NG_MASK | TT_DESCRIPTOR_PAGE_S_MASK | \ TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_XN_MASK | \ + TT_DESCRIPTOR_PAGE_AF | \ TT_DESCRIPTOR_PAGE_CACHE_POLICY_MASK) #define TT_DESCRIPTOR_SECTION_DOMAIN_MASK (0x0FUL << 5) @@ -159,6 +163,7 @@ TT_DESCRIPTOR_SECTION_S_SHARED | \ TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ TT_DESCRIPTOR_SECTION_AP_RW_RW | \ + TT_DESCRIPTOR_SECTION_AF | \ TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_BACK_ALLOC) #define TT_DESCRIPTOR_SECTION_WRITE_THROUGH(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ @@ -166,6 +171,7 @@ TT_DESCRIPTOR_SECTION_S_SHARED | \ TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ TT_DESCRIPTOR_SECTION_AP_RW_RW | \ + TT_DESCRIPTOR_SECTION_AF | \ TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_THROUGH_NO_ALLOC) #define TT_DESCRIPTOR_SECTION_DEVICE(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ @@ -174,6 +180,7 @@ TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ TT_DESCRIPTOR_SECTION_AP_RW_RW | \ TT_DESCRIPTOR_SECTION_XN_MASK | \ + TT_DESCRIPTOR_SECTION_AF | \ TT_DESCRIPTOR_SECTION_CACHE_POLICY_SHAREABLE_DEVICE) #define TT_DESCRIPTOR_SECTION_UNCACHED(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ @@ -181,28 +188,33 @@ TT_DESCRIPTOR_SECTION_S_NOT_SHARED | \ TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ TT_DESCRIPTOR_SECTION_AP_RW_RW | \ + TT_DESCRIPTOR_SECTION_AF | \ TT_DESCRIPTOR_SECTION_CACHE_POLICY_NON_CACHEABLE) #define TT_DESCRIPTOR_PAGE_WRITE_BACK (TT_DESCRIPTOR_PAGE_TYPE_PAGE | \ TT_DESCRIPTOR_PAGE_NG_GLOBAL | \ TT_DESCRIPTOR_PAGE_S_SHARED | \ TT_DESCRIPTOR_PAGE_AP_RW_RW | \ + TT_DESCRIPTOR_PAGE_AF | \ TT_DESCRIPTOR_PAGE_CACHE_POLICY_WRITE_BACK_ALLOC) #define TT_DESCRIPTOR_PAGE_WRITE_THROUGH (TT_DESCRIPTOR_PAGE_TYPE_PAGE | \ TT_DESCRIPTOR_PAGE_NG_GLOBAL | \ TT_DESCRIPTOR_PAGE_S_SHARED | \ TT_DESCRIPTOR_PAGE_AP_RW_RW | \ + TT_DESCRIPTOR_PAGE_AF | \ TT_DESCRIPTOR_PAGE_CACHE_POLICY_WRITE_THROUGH_NO_ALLOC) #define TT_DESCRIPTOR_PAGE_DEVICE (TT_DESCRIPTOR_PAGE_TYPE_PAGE | \ TT_DESCRIPTOR_PAGE_NG_GLOBAL | \ TT_DESCRIPTOR_PAGE_S_NOT_SHARED | \ TT_DESCRIPTOR_PAGE_AP_RW_RW | \ + TT_DESCRIPTOR_PAGE_AF | \ TT_DESCRIPTOR_PAGE_XN_MASK | \ TT_DESCRIPTOR_PAGE_CACHE_POLICY_SHAREABLE_DEVICE) #define TT_DESCRIPTOR_PAGE_UNCACHED (TT_DESCRIPTOR_PAGE_TYPE_PAGE | \ TT_DESCRIPTOR_PAGE_NG_GLOBAL | \ TT_DESCRIPTOR_PAGE_S_NOT_SHARED | \ TT_DESCRIPTOR_PAGE_AP_RW_RW | \ + TT_DESCRIPTOR_PAGE_AF | \ TT_DESCRIPTOR_PAGE_CACHE_POLICY_NON_CACHEABLE) // First Level Descriptors diff --git a/ArmPkg/Library/ArmLib/Arm/ArmV7Support.S b/ArmPkg/Library/ArmLib/Arm/ArmV7Support.S index 4925f6628e..1f396adffc 100644 --- a/ArmPkg/Library/ArmLib/Arm/ArmV7Support.S +++ b/ArmPkg/Library/ArmLib/Arm/ArmV7Support.S @@ -16,6 +16,7 @@ .set CTRL_C_BIT, (1 << 2) .set CTRL_B_BIT, (1 << 7) .set CTRL_I_BIT, (1 << 12) +.set CTRL_AFE_BIT,(1 << 29) ASM_FUNC(ArmInvalidateDataCacheEntryByMVA) @@ -64,6 +65,7 @@ ASM_FUNC(ArmInvalidateInstructionCache) ASM_FUNC(ArmEnableMmu) mrc p15,0,R0,c1,c0,0 orr R0,R0,#1 + orr R0,R0,#CTRL_AFE_BIT mcr p15,0,R0,c1,c0,0 dsb isb diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c index 6e2f08a7ce..52dbfd7140 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibConvert.c @@ -23,6 +23,7 @@ ConvertSectionAttributesToPageAttributes ( PageAttributes = 0; PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_CACHE_POLICY (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_AP (SectionAttributes); + PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_AF (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_XN (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_NG (SectionAttributes); PageAttributes |= TT_DESCRIPTOR_CONVERT_TO_PAGE_S (SectionAttributes); diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index 12d0f4c30f..484c674766 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -104,7 +104,7 @@ UpdatePageEntries ( // EntryMask: bitmask of values to change (1 = change this value, 0 = leave alone) // EntryValue: values at bit positions specified by EntryMask - EntryMask = TT_DESCRIPTOR_PAGE_TYPE_MASK | TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_XN_MASK; + EntryMask = TT_DESCRIPTOR_PAGE_TYPE_MASK | TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_XN_MASK | TT_DESCRIPTOR_PAGE_AF; EntryValue = TT_DESCRIPTOR_PAGE_TYPE_PAGE; // Although the PI spec is unclear on this, the GCD guarantees that only @@ -138,6 +138,10 @@ UpdatePageEntries ( return EFI_UNSUPPORTED; } + if ((Attributes & EFI_MEMORY_RP) == 0) { + EntryValue |= TT_DESCRIPTOR_PAGE_AF; + } + if ((Attributes & EFI_MEMORY_RO) != 0) { EntryValue |= TT_DESCRIPTOR_PAGE_AP_RO_RO; } else { @@ -237,7 +241,7 @@ UpdateSectionEntries ( // Make sure we handle a section range that is unmapped EntryMask = TT_DESCRIPTOR_SECTION_TYPE_MASK | TT_DESCRIPTOR_SECTION_XN_MASK | - TT_DESCRIPTOR_SECTION_AP_MASK; + TT_DESCRIPTOR_SECTION_AP_MASK | TT_DESCRIPTOR_SECTION_AF; EntryValue = TT_DESCRIPTOR_SECTION_TYPE_SECTION; // Although the PI spec is unclear on this, the GCD guarantees that only @@ -281,6 +285,10 @@ UpdateSectionEntries ( EntryValue |= TT_DESCRIPTOR_SECTION_XN_MASK; } + if ((Attributes & EFI_MEMORY_RP) == 0) { + EntryValue |= TT_DESCRIPTOR_SECTION_AF; + } + // obtain page table base FirstLevelTable = (ARM_FIRST_LEVEL_DESCRIPTOR *)ArmGetTTBR0BaseAddress (); From 453a7eecc0cf7b5c8cbe838418453a9959c88afb Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 9 Feb 2023 10:23:03 +0100 Subject: [PATCH 0693/1529] ArmPkg/ArmMmuLib ARM: Clear individual permission bits Currently, the MMU code that is supposed to clear the RO or XP attributes from a region just clears both unconditionally. This approximates the desired behavior to some extent, but it does mean that setting the RO bit first on a code region, and then clearing the XP bit results both RO and XP being cleared, and we end up with writable code, and avoiding that is the point of all these protections. Once we introduce RP support, this will only get worse, so let's fix this up, by reshuffling the attribute update code to take the entry mask from the caller, and use the mask to preserve other attributes when clearing RO or XP. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- .../Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 94 ++++++++++++++++--- 1 file changed, 81 insertions(+), 13 deletions(-) diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index 484c674766..23f613f5db 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -81,12 +81,12 @@ UpdatePageEntries ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, IN UINT64 Attributes, + IN UINT32 EntryMask, OUT BOOLEAN *FlushTlbs OPTIONAL ) { EFI_STATUS Status; UINT32 EntryValue; - UINT32 EntryMask; UINT32 FirstLevelIdx; UINT32 Offset; UINT32 NumPageEntries; @@ -104,7 +104,6 @@ UpdatePageEntries ( // EntryMask: bitmask of values to change (1 = change this value, 0 = leave alone) // EntryValue: values at bit positions specified by EntryMask - EntryMask = TT_DESCRIPTOR_PAGE_TYPE_MASK | TT_DESCRIPTOR_PAGE_AP_MASK | TT_DESCRIPTOR_PAGE_XN_MASK | TT_DESCRIPTOR_PAGE_AF; EntryValue = TT_DESCRIPTOR_PAGE_TYPE_PAGE; // Although the PI spec is unclear on this, the GCD guarantees that only @@ -220,11 +219,11 @@ EFI_STATUS UpdateSectionEntries ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, - IN UINT64 Attributes + IN UINT64 Attributes, + IN UINT32 EntryMask ) { EFI_STATUS Status; - UINT32 EntryMask; UINT32 EntryValue; UINT32 FirstLevelIdx; UINT32 NumSections; @@ -240,8 +239,6 @@ UpdateSectionEntries ( // EntryValue: values at bit positions specified by EntryMask // Make sure we handle a section range that is unmapped - EntryMask = TT_DESCRIPTOR_SECTION_TYPE_MASK | TT_DESCRIPTOR_SECTION_XN_MASK | - TT_DESCRIPTOR_SECTION_AP_MASK | TT_DESCRIPTOR_SECTION_AF; EntryValue = TT_DESCRIPTOR_SECTION_TYPE_SECTION; // Although the PI spec is unclear on this, the GCD guarantees that only @@ -310,6 +307,7 @@ UpdateSectionEntries ( (FirstLevelIdx + i) << TT_DESCRIPTOR_SECTION_BASE_SHIFT, TT_DESCRIPTOR_SECTION_SIZE, Attributes, + ConvertSectionAttributesToPageAttributes (EntryMask), NULL ); } else { @@ -340,11 +338,26 @@ UpdateSectionEntries ( return Status; } +/** + Update the permission or memory type attributes on a range of memory. + + @param BaseAddress The start of the region. + @param Length The size of the region. + @param Attributes A mask of EFI_MEMORY_xx constants. + @param SectionMask A mask of short descriptor section attributes + describing which descriptor bits to update. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +STATIC EFI_STATUS -ArmSetMemoryAttributes ( +SetMemoryAttributes ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, - IN UINT64 Attributes + IN UINT64 Attributes, + IN UINT32 SectionMask ) { EFI_STATUS Status; @@ -375,7 +388,12 @@ ArmSetMemoryAttributes ( Attributes )); - Status = UpdateSectionEntries (BaseAddress, ChunkLength, Attributes); + Status = UpdateSectionEntries ( + BaseAddress, + ChunkLength, + Attributes, + SectionMask + ); FlushTlbs = TRUE; } else { @@ -401,6 +419,7 @@ ArmSetMemoryAttributes ( BaseAddress, ChunkLength, Attributes, + ConvertSectionAttributesToPageAttributes (SectionMask), &FlushTlbs ); } @@ -420,13 +439,47 @@ ArmSetMemoryAttributes ( return Status; } +/** + Update the permission or memory type attributes on a range of memory. + + @param BaseAddress The start of the region. + @param Length The size of the region. + @param Attributes A mask of EFI_MEMORY_xx constants. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +ArmSetMemoryAttributes ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ) +{ + return SetMemoryAttributes ( + BaseAddress, + Length, + Attributes, + TT_DESCRIPTOR_SECTION_TYPE_MASK | + TT_DESCRIPTOR_SECTION_XN_MASK | + TT_DESCRIPTOR_SECTION_AP_MASK | + TT_DESCRIPTOR_SECTION_AF + ); +} + EFI_STATUS ArmSetMemoryRegionNoExec ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ) { - return ArmSetMemoryAttributes (BaseAddress, Length, EFI_MEMORY_XP); + return SetMemoryAttributes ( + BaseAddress, + Length, + EFI_MEMORY_XP, + TT_DESCRIPTOR_SECTION_XN_MASK + ); } EFI_STATUS @@ -435,7 +488,12 @@ ArmClearMemoryRegionNoExec ( IN UINT64 Length ) { - return ArmSetMemoryAttributes (BaseAddress, Length, __EFI_MEMORY_RWX); + return SetMemoryAttributes ( + BaseAddress, + Length, + 0, + TT_DESCRIPTOR_SECTION_XN_MASK + ); } EFI_STATUS @@ -444,7 +502,12 @@ ArmSetMemoryRegionReadOnly ( IN UINT64 Length ) { - return ArmSetMemoryAttributes (BaseAddress, Length, EFI_MEMORY_RO); + return SetMemoryAttributes ( + BaseAddress, + Length, + EFI_MEMORY_RO, + TT_DESCRIPTOR_SECTION_AP_MASK + ); } EFI_STATUS @@ -453,5 +516,10 @@ ArmClearMemoryRegionReadOnly ( IN UINT64 Length ) { - return ArmSetMemoryAttributes (BaseAddress, Length, __EFI_MEMORY_RWX); + return SetMemoryAttributes ( + BaseAddress, + Length, + 0, + TT_DESCRIPTOR_SECTION_AP_MASK + ); } From d2213bc8eeed5bff95bcd7c3603892fc0b41ed4b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 7 Feb 2023 16:09:56 +0100 Subject: [PATCH 0694/1529] ArmPkg/ArmMmuLib: Implement EFI_MEMORY_RP using access flag Implement support for read-protected memory by wiring it up to the access flag in the page table descriptor. The resulting mapping is implicitly non-writable and non-executable as well, but this is good enough for implementing this attribute, as we never rely on write or execute permissions without read permissions. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c | 8 ++- ArmPkg/Include/Library/ArmMmuLib.h | 34 +++++++++++ .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 58 ++++++++++++++++++- .../Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 48 +++++++++++++++ 4 files changed, 144 insertions(+), 4 deletions(-) diff --git a/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c b/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c index 8bb33046e7..8bda11f08a 100644 --- a/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c @@ -64,6 +64,10 @@ PageAttributeToGcdAttribute ( } // Determine protection attributes + if ((PageAttributes & TT_AF) == 0) { + GcdAttributes |= EFI_MEMORY_RP; + } + if (((PageAttributes & TT_AP_MASK) == TT_AP_NO_RO) || ((PageAttributes & TT_AP_MASK) == TT_AP_RO_RO)) { @@ -301,7 +305,9 @@ EfiAttributeToArmAttribute ( } // Set the access flag to match the block attributes - ArmAttributes |= TT_AF; + if ((EfiAttributes & EFI_MEMORY_RP) == 0) { + ArmAttributes |= TT_AF; + } // Determine protection attributes if ((EfiAttributes & EFI_MEMORY_RO) != 0) { diff --git a/ArmPkg/Include/Library/ArmMmuLib.h b/ArmPkg/Include/Library/ArmMmuLib.h index b745e2230e..4cf59a1e37 100644 --- a/ArmPkg/Include/Library/ArmMmuLib.h +++ b/ArmPkg/Include/Library/ArmMmuLib.h @@ -21,6 +21,40 @@ ArmConfigureMmu ( OUT UINTN *TranslationTableSize OPTIONAL ); +/** + Convert a region of memory to read-protected, by clearing the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +EFIAPI +ArmSetMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ); + +/** + Convert a region of memory to read-enabled, by setting the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +EFIAPI +ArmClearMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ); + EFI_STATUS EFIAPI ArmSetMemoryRegionNoExec ( diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 764c7d362e..6d21a2e41d 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -438,7 +438,11 @@ GcdAttributeToPageAttribute ( PageAttributes |= TT_AP_NO_RO; } - return PageAttributes | TT_AF; + if ((GcdAttributes & EFI_MEMORY_RP) == 0) { + PageAttributes |= TT_AF; + } + + return PageAttributes; } EFI_STATUS @@ -459,9 +463,9 @@ ArmSetMemoryAttributes ( // No memory type was set in Attributes, so we are going to update the // permissions only. // - PageAttributes &= TT_AP_MASK | TT_UXN_MASK | TT_PXN_MASK; + PageAttributes &= TT_AP_MASK | TT_UXN_MASK | TT_PXN_MASK | TT_AF; PageAttributeMask = ~(TT_ADDRESS_MASK_BLOCK_ENTRY | TT_AP_MASK | - TT_PXN_MASK | TT_XN_MASK); + TT_PXN_MASK | TT_XN_MASK | TT_AF); } return UpdateRegionMapping ( @@ -534,6 +538,54 @@ ArmClearMemoryRegionNoExec ( ); } +/** + Convert a region of memory to read-protected, by clearing the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +ArmSetMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ) +{ + return SetMemoryRegionAttribute ( + BaseAddress, + Length, + 0, + ~(TT_ADDRESS_MASK_BLOCK_ENTRY | TT_AF) + ); +} + +/** + Convert a region of memory to read-enabled, by setting the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +ArmClearMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ) +{ + return SetMemoryRegionAttribute ( + BaseAddress, + Length, + TT_AF, + ~TT_ADDRESS_MASK_BLOCK_ENTRY + ); +} + EFI_STATUS ArmSetMemoryRegionReadOnly ( IN EFI_PHYSICAL_ADDRESS BaseAddress, diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index 23f613f5db..247cf87bf3 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -523,3 +523,51 @@ ArmClearMemoryRegionReadOnly ( TT_DESCRIPTOR_SECTION_AP_MASK ); } + +/** + Convert a region of memory to read-protected, by clearing the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +ArmSetMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ) +{ + return SetMemoryAttributes ( + BaseAddress, + Length, + EFI_MEMORY_RP, + TT_DESCRIPTOR_SECTION_AF + ); +} + +/** + Convert a region of memory to read-enabled, by setting the access flag. + + @param BaseAddress The start of the region. + @param Length The size of the region. + + @retval EFI_SUCCESS The attributes were set successfully. + @retval EFI_OUT_OF_RESOURCES The operation failed due to insufficient memory. + +**/ +EFI_STATUS +ArmClearMemoryRegionNoAccess ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ) +{ + return SetMemoryAttributes ( + BaseAddress, + Length, + 0, + TT_DESCRIPTOR_SECTION_AF + ); +} From 298f8a6adf86827b8a3486c7b7e15a2bd3aceab7 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 7 Feb 2023 18:27:15 +0100 Subject: [PATCH 0695/1529] ArmVirtPkg: Enable stack guard Enable the stack guard in ArmVirtPkg builds, so that stack overflows are caught as they occur, rather than when they happen to hit a read-only memory region. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmVirtPkg/ArmVirt.dsc.inc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc index 74d98e6314..5b18184be2 100644 --- a/ArmVirtPkg/ArmVirt.dsc.inc +++ b/ArmVirtPkg/ArmVirt.dsc.inc @@ -363,6 +363,8 @@ # gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5 + gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard|TRUE + [Components.common] # # Ramdisk support From 35cdf40639c05c5d274edccccbc4ff4a48cd3925 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 8 Feb 2023 18:19:36 +0100 Subject: [PATCH 0696/1529] ArmPkg/ArmMmuLib: Avoid splitting block entries if possible Currently, the ARM MMU page table logic will break down any block entry that overlaps with the region being mapped, even if the block entry in question is using the same attributes as the new region. This means that creating a non-executable mapping inside a region that is already mapped non-executable at a coarser granularity may trigger a call to AllocatePages (), which may recurse back into the page table code to update the attributes on the newly allocated page tables. Let's avoid this, by preserving the block entry if it already covers the region being mapped with the correct attributes. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 10 ++++++++++ ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 6d21a2e41d..1ce200c43c 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -251,6 +251,16 @@ UpdateRegionMappingRecursive ( ASSERT (Level < 3); if (!IsTableEntry (*Entry, Level)) { + // + // If the region we are trying to map is already covered by a block + // entry with the right attributes, don't bother splitting it up. + // + if (IsBlockEntry (*Entry, Level) && + ((*Entry & TT_ATTRIBUTES_MASK & ~AttributeClearMask) == AttributeSetMask)) + { + continue; + } + // // No table entry exists yet, so we need to allocate a page table // for the next level. diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c index 247cf87bf3..299d38ad07 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibUpdate.c @@ -170,6 +170,17 @@ UpdatePageEntries ( // Does this descriptor need to be converted from section entry to 4K pages? if (!TT_DESCRIPTOR_SECTION_TYPE_IS_PAGE_TABLE (Descriptor)) { + // + // If the section mapping covers the requested region with the expected + // attributes, splitting it is unnecessary, and should be avoided as it + // may result in unbounded recursion when using a strict NX policy. + // + if ((EntryValue & ~TT_DESCRIPTOR_PAGE_TYPE_MASK & EntryMask) == + (ConvertSectionAttributesToPageAttributes (Descriptor) & EntryMask)) + { + continue; + } + Status = ConvertSectionToPages (FirstLevelIdx << TT_DESCRIPTOR_SECTION_BASE_SHIFT); if (EFI_ERROR (Status)) { // Exit for loop From c0bfc9605b799229f6cf1ec069dd15e515844ff9 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 31 Jan 2023 23:23:14 +0100 Subject: [PATCH 0697/1529] ArmPkg/CpuDxe: Expose unified region-to-EFI attribute conversion In preparation for introducing an implementation of the EFI memory attributes protocol that is shared between ARM and AArch64, unify the existing code that converts a page table descriptor into a EFI_MEMORY_xx bitfield, so it can be called from the generic code. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c | 17 +++++++++++++ ArmPkg/Drivers/CpuDxe/Arm/Mmu.c | 38 +++++++++++++++++++++++++++++ ArmPkg/Drivers/CpuDxe/CpuDxe.h | 14 +++++++++++ 3 files changed, 69 insertions(+) diff --git a/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c b/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c index 8bda11f08a..0859c7418a 100644 --- a/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/AArch64/Mmu.c @@ -83,6 +83,23 @@ PageAttributeToGcdAttribute ( return GcdAttributes; } +/** + Convert an arch specific set of page attributes into a mask + of EFI_MEMORY_xx constants. + + @param PageAttributes The set of page attributes. + + @retval The mask of EFI_MEMORY_xx constants. + +**/ +UINT64 +RegionAttributeToGcdAttribute ( + IN UINTN PageAttributes + ) +{ + return PageAttributeToGcdAttribute (PageAttributes); +} + STATIC UINT64 GetFirstPageAttribute ( diff --git a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c index 07faab8216..afd6aab602 100644 --- a/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c +++ b/ArmPkg/Drivers/CpuDxe/Arm/Mmu.c @@ -13,6 +13,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "CpuDxe.h" +/** + Convert a set of ARM short descriptor section attributes into a mask + of EFI_MEMORY_xx constants. + + @param SectionAttributes The set of page attributes. + @param GcdAttributes Pointer to the return value. + +**/ +STATIC EFI_STATUS SectionToGcdAttributes ( IN UINT32 SectionAttributes, @@ -74,6 +83,35 @@ SectionToGcdAttributes ( return EFI_SUCCESS; } +/** + Convert an arch specific set of page attributes into a mask + of EFI_MEMORY_xx constants. + + @param PageAttributes The set of page attributes. + + @retval The mask of EFI_MEMORY_xx constants. + +**/ +UINT64 +RegionAttributeToGcdAttribute ( + IN UINTN PageAttributes + ) +{ + UINT64 Result; + + SectionToGcdAttributes (PageAttributes, &Result); + return Result; +} + +/** + Convert a set of ARM short descriptor page attributes into a mask + of EFI_MEMORY_xx constants. + + @param PageAttributes The set of page attributes. + @param GcdAttributes Pointer to the return value. + +**/ +STATIC EFI_STATUS PageToGcdAttributes ( IN UINT32 PageAttributes, diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.h b/ArmPkg/Drivers/CpuDxe/CpuDxe.h index ff672390ce..39e1bbed44 100644 --- a/ArmPkg/Drivers/CpuDxe/CpuDxe.h +++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.h @@ -126,4 +126,18 @@ SetGcdMemorySpaceAttributes ( IN UINT64 Attributes ); +/** + Convert an arch specific set of page attributes into a mask + of EFI_MEMORY_xx constants. + + @param PageAttributes The set of page attributes. + + @retval The mask of EFI_MEMORY_xx constants. + +**/ +UINT64 +RegionAttributeToGcdAttribute ( + IN UINTN PageAttributes + ); + #endif // CPU_DXE_H_ From e40915539043d19f3a5ac159c77c1daa16fe7705 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 2 Feb 2023 10:29:07 +0100 Subject: [PATCH 0698/1529] MdePkg: Add Memory Attribute Protocol definition Add the Memory Attribute Protocol definition, which was adopted and included in version 2.10 of the UEFI specification. Link: https://bugzilla.tianocore.org/show_bug.cgi?id=3519 Signed-off-by: Ard Biesheuvel Reviewed-by: Liming Gao Reviewed-by: Leif Lindholm --- MdePkg/Include/Protocol/MemoryAttribute.h | 142 ++++++++++++++++++++++ MdePkg/MdePkg.dec | 3 + 2 files changed, 145 insertions(+) create mode 100644 MdePkg/Include/Protocol/MemoryAttribute.h diff --git a/MdePkg/Include/Protocol/MemoryAttribute.h b/MdePkg/Include/Protocol/MemoryAttribute.h new file mode 100644 index 0000000000..e1530ed9ef --- /dev/null +++ b/MdePkg/Include/Protocol/MemoryAttribute.h @@ -0,0 +1,142 @@ +/** @file + + EFI Memory Attribute Protocol provides retrieval and update service + for memory attributes in EFI environment. + + Copyright (c) 2021, Intel Corporation. All rights reserved.
+ Copyright (c) 2023, Google LLC. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef EFI_MEMORY_ATTRIBUTE_H_ +#define EFI_MEMORY_ATTRIBUTE_H_ + +#define EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID \ + { \ + 0xf4560cf6, 0x40ec, 0x4b4a, { 0xa1, 0x92, 0xbf, 0x1d, 0x57, 0xd0, 0xb1, 0x89 } \ + } + +typedef struct _EFI_MEMORY_ATTRIBUTE_PROTOCOL EFI_MEMORY_ATTRIBUTE_PROTOCOL; + +/** + This function set given attributes of the memory region specified by + BaseAddress and Length. + + The valid Attributes is EFI_MEMORY_RP, EFI_MEMORY_XP, and EFI_MEMORY_RO. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes The bit mask of attributes to set for the memory + region. + + @retval EFI_SUCCESS The attributes were set for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes specified an illegal combination of + attributes that cannot be set together. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + The bit mask of attributes is not supported for + the memory resource range specified by + BaseAddress and Length. + @retval EFI_OUT_OF_RESOURCES Requested attributes cannot be applied due to + lack of system resources. + @retval EFI_ACCESS_DENIED Attributes for the requested memory region are + controlled by system firmware and cannot be + updated via the protocol. + +**/ +typedef +EFI_STATUS +(EFIAPI *EFI_SET_MEMORY_ATTRIBUTES)( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ); + +/** + This function clears given attributes of the memory region specified by + BaseAddress and Length. + + The valid Attributes is EFI_MEMORY_RP, EFI_MEMORY_XP, and EFI_MEMORY_RO. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes The bit mask of attributes to clear for the memory + region. + + @retval EFI_SUCCESS The attributes were cleared for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes specified an illegal combination of + attributes that cannot be cleared together. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + The bit mask of attributes is not supported for + the memory resource range specified by + BaseAddress and Length. + @retval EFI_OUT_OF_RESOURCES Requested attributes cannot be applied due to + lack of system resources. + @retval EFI_ACCESS_DENIED Attributes for the requested memory region are + controlled by system firmware and cannot be + updated via the protocol. + +**/ +typedef +EFI_STATUS +(EFIAPI *EFI_CLEAR_MEMORY_ATTRIBUTES)( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ); + +/** + This function retrieves the attributes of the memory region specified by + BaseAddress and Length. If different attributes are obtained from different + parts of the memory region, EFI_NO_MAPPING will be returned. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes Pointer to attributes returned. + + @retval EFI_SUCCESS The attributes got for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes is NULL. + @retval EFI_NO_MAPPING Attributes are not consistent cross the memory + region. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + +**/ +typedef +EFI_STATUS +(EFIAPI *EFI_GET_MEMORY_ATTRIBUTES)( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + OUT UINT64 *Attributes + ); + +/// +/// EFI Memory Attribute Protocol provides services to retrieve or update +/// attribute of memory in the EFI environment. +/// +struct _EFI_MEMORY_ATTRIBUTE_PROTOCOL { + EFI_GET_MEMORY_ATTRIBUTES GetMemoryAttributes; + EFI_SET_MEMORY_ATTRIBUTES SetMemoryAttributes; + EFI_CLEAR_MEMORY_ATTRIBUTES ClearMemoryAttributes; +}; + +extern EFI_GUID gEfiMemoryAttributeProtocolGuid; + +#endif diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 80b6559053..2d643bede1 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -1922,6 +1922,9 @@ ## Include/Protocol/RedfishDiscover.h gEfiRedfishDiscoverProtocolGuid = { 0x5db12509, 0x4550, 0x4347, { 0x96, 0xb3, 0x73, 0xc0, 0xff, 0x6e, 0x86, 0x9f }} + ## Include/Protocol/MemoryAttribute.h + gEfiMemoryAttributeProtocolGuid = { 0xf4560cf6, 0x40ec, 0x4b4a, { 0xa1, 0x92, 0xbf, 0x1d, 0x57, 0xd0, 0xb1, 0x89 }} + # # Protocols defined in Shell2.0 # From efa4857168986caf799fcca791045a90563cb710 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 31 Jan 2023 23:26:25 +0100 Subject: [PATCH 0699/1529] ArmPkg/CpuDxe: Implement EFI memory attributes protocol Expose the protocol introduced in v2.10 that permits the caller to manage mapping permissions in the page tables. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Drivers/CpuDxe/CpuDxe.c | 2 + ArmPkg/Drivers/CpuDxe/CpuDxe.h | 3 + ArmPkg/Drivers/CpuDxe/CpuDxe.inf | 2 + ArmPkg/Drivers/CpuDxe/MemoryAttribute.c | 319 ++++++++++++++++++++++++ 4 files changed, 326 insertions(+) create mode 100644 ArmPkg/Drivers/CpuDxe/MemoryAttribute.c diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.c b/ArmPkg/Drivers/CpuDxe/CpuDxe.c index e6742f0a25..d04958e79e 100644 --- a/ArmPkg/Drivers/CpuDxe/CpuDxe.c +++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.c @@ -244,6 +244,8 @@ CpuDxeInitialize ( &mCpuHandle, &gEfiCpuArchProtocolGuid, &mCpu, + &gEfiMemoryAttributeProtocolGuid, + &mMemoryAttribute, NULL ); diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.h b/ArmPkg/Drivers/CpuDxe/CpuDxe.h index 39e1bbed44..c6613b939a 100644 --- a/ArmPkg/Drivers/CpuDxe/CpuDxe.h +++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.h @@ -30,9 +30,12 @@ #include #include #include +#include extern BOOLEAN mIsFlushingGCD; +extern EFI_MEMORY_ATTRIBUTE_PROTOCOL mMemoryAttribute; + /** This function registers and enables the handler specified by InterruptHandler for a processor interrupt or exception type specified by InterruptType. If InterruptHandler is NULL, then the diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.inf b/ArmPkg/Drivers/CpuDxe/CpuDxe.inf index 10792b393f..e732e21cb9 100644 --- a/ArmPkg/Drivers/CpuDxe/CpuDxe.inf +++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.inf @@ -23,6 +23,7 @@ CpuDxe.h CpuMmuCommon.c Exception.c + MemoryAttribute.c [Sources.ARM] Arm/Mmu.c @@ -53,6 +54,7 @@ [Protocols] gEfiCpuArchProtocolGuid + gEfiMemoryAttributeProtocolGuid [Guids] gEfiDebugImageInfoTableGuid diff --git a/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c b/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c new file mode 100644 index 0000000000..cbc8261a68 --- /dev/null +++ b/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c @@ -0,0 +1,319 @@ +/** @file + + Copyright (c) 2023, Google LLC. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "CpuDxe.h" + +/** + Check whether the provided memory range is covered by a single entry of type + EfiGcdSystemMemory in the GCD memory map. + + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + + @return Whether the region is system memory or not. +**/ +STATIC +BOOLEAN +RegionIsSystemMemory ( + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length + ) +{ + EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor; + EFI_PHYSICAL_ADDRESS GcdEndAddress; + EFI_STATUS Status; + + Status = gDS->GetMemorySpaceDescriptor (BaseAddress, &GcdDescriptor); + if (EFI_ERROR (Status) || + (GcdDescriptor.GcdMemoryType != EfiGcdMemoryTypeSystemMemory)) + { + return FALSE; + } + + GcdEndAddress = GcdDescriptor.BaseAddress + GcdDescriptor.Length; + + // + // Return TRUE if the GCD descriptor covers the range entirely + // + return GcdEndAddress >= (BaseAddress + Length); +} + +/** + This function retrieves the attributes of the memory region specified by + BaseAddress and Length. If different attributes are obtained from different + parts of the memory region, EFI_NO_MAPPING will be returned. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes Pointer to attributes returned. + + @retval EFI_SUCCESS The attributes got for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes is NULL. + @retval EFI_NO_MAPPING Attributes are not consistent cross the memory + region. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + +**/ +STATIC +EFI_STATUS +GetMemoryAttributes ( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + OUT UINT64 *Attributes + ) +{ + UINTN RegionAddress; + UINTN RegionLength; + UINTN RegionAttributes; + UINTN Union; + UINTN Intersection; + EFI_STATUS Status; + + if ((Length == 0) || (Attributes == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if (!RegionIsSystemMemory (BaseAddress, Length)) { + return EFI_UNSUPPORTED; + } + + DEBUG (( + DEBUG_VERBOSE, + "%a: BaseAddress == 0x%lx, Length == 0x%lx\n", + __FUNCTION__, + BaseAddress, + Length + )); + + Union = 0; + Intersection = MAX_UINTN; + + for (RegionAddress = (UINTN)BaseAddress; + RegionAddress < (UINTN)(BaseAddress + Length); + RegionAddress += RegionLength) + { + Status = GetMemoryRegion ( + &RegionAddress, + &RegionLength, + &RegionAttributes + ); + + DEBUG (( + DEBUG_VERBOSE, + "%a: RegionAddress == 0x%lx, RegionLength == 0x%lx, RegionAttributes == 0x%lx\n", + __FUNCTION__, + (UINT64)RegionAddress, + (UINT64)RegionLength, + (UINT64)RegionAttributes + )); + + if (EFI_ERROR (Status)) { + return EFI_NO_MAPPING; + } + + Union |= RegionAttributes; + Intersection &= RegionAttributes; + } + + DEBUG (( + DEBUG_VERBOSE, + "%a: Union == %lx, Intersection == %lx\n", + __FUNCTION__, + (UINT64)Union, + (UINT64)Intersection + )); + + if (Union != Intersection) { + return EFI_NO_MAPPING; + } + + *Attributes = RegionAttributeToGcdAttribute (Union); + *Attributes &= EFI_MEMORY_RP | EFI_MEMORY_RO | EFI_MEMORY_XP; + return EFI_SUCCESS; +} + +/** + This function set given attributes of the memory region specified by + BaseAddress and Length. + + The valid Attributes is EFI_MEMORY_RP, EFI_MEMORY_XP, and EFI_MEMORY_RO. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes The bit mask of attributes to set for the memory + region. + + @retval EFI_SUCCESS The attributes were set for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes specified an illegal combination of + attributes that cannot be set together. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + The bit mask of attributes is not supported for + the memory resource range specified by + BaseAddress and Length. + @retval EFI_OUT_OF_RESOURCES Requested attributes cannot be applied due to + lack of system resources. + @retval EFI_ACCESS_DENIED Attributes for the requested memory region are + controlled by system firmware and cannot be + updated via the protocol. + +**/ +STATIC +EFI_STATUS +SetMemoryAttributes ( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ) +{ + EFI_STATUS Status; + + DEBUG (( + DEBUG_INFO, + "%a: BaseAddress == 0x%lx, Length == 0x%lx, Attributes == 0x%lx\n", + __FUNCTION__, + (UINTN)BaseAddress, + (UINTN)Length, + (UINTN)Attributes + )); + + if ((Length == 0) || + ((Attributes & ~(EFI_MEMORY_RO | EFI_MEMORY_RP | EFI_MEMORY_XP)) != 0)) + { + return EFI_INVALID_PARAMETER; + } + + if (!RegionIsSystemMemory (BaseAddress, Length)) { + return EFI_UNSUPPORTED; + } + + if ((Attributes & EFI_MEMORY_RP) != 0) { + Status = ArmSetMemoryRegionNoAccess (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + if ((Attributes & EFI_MEMORY_RO) != 0) { + Status = ArmSetMemoryRegionReadOnly (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + if ((Attributes & EFI_MEMORY_XP) != 0) { + Status = ArmSetMemoryRegionNoExec (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + return EFI_SUCCESS; +} + +/** + This function clears given attributes of the memory region specified by + BaseAddress and Length. + + The valid Attributes is EFI_MEMORY_RP, EFI_MEMORY_XP, and EFI_MEMORY_RO. + + @param This The EFI_MEMORY_ATTRIBUTE_PROTOCOL instance. + @param BaseAddress The physical address that is the start address of + a memory region. + @param Length The size in bytes of the memory region. + @param Attributes The bit mask of attributes to clear for the memory + region. + + @retval EFI_SUCCESS The attributes were cleared for the memory region. + @retval EFI_INVALID_PARAMETER Length is zero. + Attributes specified an illegal combination of + attributes that cannot be cleared together. + @retval EFI_UNSUPPORTED The processor does not support one or more + bytes of the memory resource range specified + by BaseAddress and Length. + The bit mask of attributes is not supported for + the memory resource range specified by + BaseAddress and Length. + @retval EFI_OUT_OF_RESOURCES Requested attributes cannot be applied due to + lack of system resources. + @retval EFI_ACCESS_DENIED Attributes for the requested memory region are + controlled by system firmware and cannot be + updated via the protocol. + +**/ +STATIC +EFI_STATUS +ClearMemoryAttributes ( + IN EFI_MEMORY_ATTRIBUTE_PROTOCOL *This, + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes + ) +{ + EFI_STATUS Status; + + DEBUG (( + DEBUG_INFO, + "%a: BaseAddress == 0x%lx, Length == 0x%lx, Attributes == 0x%lx\n", + __FUNCTION__, + (UINTN)BaseAddress, + (UINTN)Length, + (UINTN)Attributes + )); + + if ((Length == 0) || + ((Attributes & ~(EFI_MEMORY_RO | EFI_MEMORY_RP | EFI_MEMORY_XP)) != 0)) + { + return EFI_INVALID_PARAMETER; + } + + if (!RegionIsSystemMemory (BaseAddress, Length)) { + return EFI_UNSUPPORTED; + } + + if ((Attributes & EFI_MEMORY_RP) != 0) { + Status = ArmClearMemoryRegionNoAccess (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + if ((Attributes & EFI_MEMORY_RO) != 0) { + Status = ArmClearMemoryRegionReadOnly (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + if ((Attributes & EFI_MEMORY_XP) != 0) { + Status = ArmClearMemoryRegionNoExec (BaseAddress, Length); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } + } + + return EFI_SUCCESS; +} + +EFI_MEMORY_ATTRIBUTE_PROTOCOL mMemoryAttribute = { + GetMemoryAttributes, + SetMemoryAttributes, + ClearMemoryAttributes +}; From 26f143818faa75577d3a63c0eb8b5e384bef7c27 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 13 Feb 2023 09:30:05 +0100 Subject: [PATCH 0700/1529] ArmPkg/Mmu: Remove handling of NONSECURE memory regions Non-secure memory is a distinction that only matters when executing code in the secure world that reasons about the secure vs non-secure address spaces. EDK2 was not designed for that, and the AArch64 version of the MMU handling library already treats them as identical, so let's just drop the ARM memory region types that mark memory as 'non-secure' explicitly. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Include/Chipset/ArmV7Mmu.h | 51 +++++++------------ ArmPkg/Include/Library/ArmLib.h | 11 ---- .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 5 -- ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c | 33 +++--------- 4 files changed, 24 insertions(+), 76 deletions(-) diff --git a/ArmPkg/Include/Chipset/ArmV7Mmu.h b/ArmPkg/Include/Chipset/ArmV7Mmu.h index da4f3160f8..89b81e33d0 100644 --- a/ArmPkg/Include/Chipset/ArmV7Mmu.h +++ b/ArmPkg/Include/Chipset/ArmV7Mmu.h @@ -157,39 +157,24 @@ #define TT_DESCRIPTOR_PAGE_BASE_ADDRESS(a) ((a) & TT_DESCRIPTOR_PAGE_BASE_ADDRESS_MASK) #define TT_DESCRIPTOR_PAGE_BASE_SHIFT 12 -#define TT_DESCRIPTOR_SECTION_WRITE_BACK(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ - ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ - TT_DESCRIPTOR_SECTION_NG_GLOBAL | \ - TT_DESCRIPTOR_SECTION_S_SHARED | \ - TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ - TT_DESCRIPTOR_SECTION_AP_RW_RW | \ - TT_DESCRIPTOR_SECTION_AF | \ - TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_BACK_ALLOC) -#define TT_DESCRIPTOR_SECTION_WRITE_THROUGH(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ - ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ - TT_DESCRIPTOR_SECTION_NG_GLOBAL | \ - TT_DESCRIPTOR_SECTION_S_SHARED | \ - TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ - TT_DESCRIPTOR_SECTION_AP_RW_RW | \ - TT_DESCRIPTOR_SECTION_AF | \ - TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_THROUGH_NO_ALLOC) -#define TT_DESCRIPTOR_SECTION_DEVICE(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ - ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ - TT_DESCRIPTOR_SECTION_NG_GLOBAL | \ - TT_DESCRIPTOR_SECTION_S_NOT_SHARED | \ - TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ - TT_DESCRIPTOR_SECTION_AP_RW_RW | \ - TT_DESCRIPTOR_SECTION_XN_MASK | \ - TT_DESCRIPTOR_SECTION_AF | \ - TT_DESCRIPTOR_SECTION_CACHE_POLICY_SHAREABLE_DEVICE) -#define TT_DESCRIPTOR_SECTION_UNCACHED(NonSecure) (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ - ((NonSecure) ? TT_DESCRIPTOR_SECTION_NS : 0) | \ - TT_DESCRIPTOR_SECTION_NG_GLOBAL | \ - TT_DESCRIPTOR_SECTION_S_NOT_SHARED | \ - TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ - TT_DESCRIPTOR_SECTION_AP_RW_RW | \ - TT_DESCRIPTOR_SECTION_AF | \ - TT_DESCRIPTOR_SECTION_CACHE_POLICY_NON_CACHEABLE) +#define TT_DESCRIPTOR_SECTION_DEFAULT (TT_DESCRIPTOR_SECTION_TYPE_SECTION | \ + TT_DESCRIPTOR_SECTION_NG_GLOBAL | \ + TT_DESCRIPTOR_SECTION_S_SHARED | \ + TT_DESCRIPTOR_SECTION_DOMAIN(0) | \ + TT_DESCRIPTOR_SECTION_AP_RW_RW | \ + TT_DESCRIPTOR_SECTION_AF) + +#define TT_DESCRIPTOR_SECTION_WRITE_BACK (TT_DESCRIPTOR_SECTION_DEFAULT | \ + TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_BACK_ALLOC) + +#define TT_DESCRIPTOR_SECTION_WRITE_THROUGH (TT_DESCRIPTOR_SECTION_DEFAULT | \ + TT_DESCRIPTOR_SECTION_CACHE_POLICY_WRITE_THROUGH_NO_ALLOC) + +#define TT_DESCRIPTOR_SECTION_DEVICE (TT_DESCRIPTOR_SECTION_DEFAULT | \ + TT_DESCRIPTOR_SECTION_CACHE_POLICY_SHAREABLE_DEVICE) + +#define TT_DESCRIPTOR_SECTION_UNCACHED (TT_DESCRIPTOR_SECTION_DEFAULT | \ + TT_DESCRIPTOR_SECTION_CACHE_POLICY_NON_CACHEABLE) #define TT_DESCRIPTOR_PAGE_WRITE_BACK (TT_DESCRIPTOR_PAGE_TYPE_PAGE | \ TT_DESCRIPTOR_PAGE_NG_GLOBAL | \ diff --git a/ArmPkg/Include/Library/ArmLib.h b/ArmPkg/Include/Library/ArmLib.h index fa605f128b..a53f60d988 100644 --- a/ArmPkg/Include/Library/ArmLib.h +++ b/ArmPkg/Include/Library/ArmLib.h @@ -25,29 +25,18 @@ EFI_MEMORY_WT | EFI_MEMORY_WB | \ EFI_MEMORY_UCE) -/** - * The UEFI firmware must not use the ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_* attributes. - * - * The Non Secure memory attribute (ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_*) should only - * be used in Secure World to distinguished Secure to Non-Secure memory. - */ typedef enum { ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED = 0, - ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED, ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK, - ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK, // On some platforms, memory mapped flash region is designed as not supporting // shareable attribute, so WRITE_BACK_NONSHAREABLE is added for such special // need. // Do NOT use below two attributes if you are not sure. ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE, - ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK_NONSHAREABLE, ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH, - ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH, ARM_MEMORY_REGION_ATTRIBUTE_DEVICE, - ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE } ARM_MEMORY_REGION_ATTRIBUTES; #define IS_ARM_MEMORY_REGION_ATTRIBUTES_SECURE(attr) ((UINT32)(attr) & 1) diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 1ce200c43c..ee4c5c995c 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -39,26 +39,21 @@ ArmMemoryAttributeToPageAttribute ( { switch (Attributes) { case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK_NONSHAREABLE: return TT_ATTR_INDX_MEMORY_WRITE_BACK; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK: return TT_ATTR_INDX_MEMORY_WRITE_BACK | TT_SH_INNER_SHAREABLE; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH: return TT_ATTR_INDX_MEMORY_WRITE_THROUGH | TT_SH_INNER_SHAREABLE; // Uncached and device mappings are treated as outer shareable by default, case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED: return TT_ATTR_INDX_MEMORY_NON_CACHEABLE; default: ASSERT (0); case ARM_MEMORY_REGION_ATTRIBUTE_DEVICE: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE: if (ArmReadCurrentEL () == AARCH64_EL2) { return TT_ATTR_INDX_DEVICE_MEMORY | TT_XN_MASK; } else { diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c index 28cc9b2fe0..1542983574 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c @@ -100,24 +100,19 @@ PopulateLevel2PageTable ( switch (Attributes) { case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK: PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_BACK; break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK_NONSHAREABLE: PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_BACK; PageAttributes &= ~TT_DESCRIPTOR_PAGE_S_SHARED; break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH: PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_THROUGH; break; case ARM_MEMORY_REGION_ATTRIBUTE_DEVICE: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE: PageAttributes = TT_DESCRIPTOR_PAGE_DEVICE; break; case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED: - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED: PageAttributes = TT_DESCRIPTOR_PAGE_UNCACHED; break; default: @@ -239,39 +234,23 @@ FillTranslationTable ( switch (MemoryRegion->Attributes) { case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK (0); + Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK; break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK (0); + Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK; Attributes &= ~TT_DESCRIPTOR_SECTION_S_SHARED; break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH (0); + Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH; break; case ARM_MEMORY_REGION_ATTRIBUTE_DEVICE: - Attributes = TT_DESCRIPTOR_SECTION_DEVICE (0); + Attributes = TT_DESCRIPTOR_SECTION_DEVICE; break; case ARM_MEMORY_REGION_ATTRIBUTE_UNCACHED_UNBUFFERED: - Attributes = TT_DESCRIPTOR_SECTION_UNCACHED (0); - break; - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK (1); - break; - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_BACK_NONSHAREABLE: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK (1); - Attributes &= ~TT_DESCRIPTOR_SECTION_S_SHARED; - break; - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_WRITE_THROUGH: - Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH (1); - break; - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_DEVICE: - Attributes = TT_DESCRIPTOR_SECTION_DEVICE (1); - break; - case ARM_MEMORY_REGION_ATTRIBUTE_NONSECURE_UNCACHED_UNBUFFERED: - Attributes = TT_DESCRIPTOR_SECTION_UNCACHED (1); + Attributes = TT_DESCRIPTOR_SECTION_UNCACHED; break; default: - Attributes = TT_DESCRIPTOR_SECTION_UNCACHED (0); + Attributes = TT_DESCRIPTOR_SECTION_UNCACHED; break; } From 9dd7a01ac8b481858790c5b28e0ad497c117b281 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 10 Feb 2023 17:52:45 +0100 Subject: [PATCH 0701/1529] ArmPkg/ArmMmuLib: Introduce region types for RO/XP WB cached memory To prepare for the enablement of booting EFI with the SCTLR.WXN control enabled, which makes all writeable memory regions non-executable by default, introduce a memory type that we will use to describe the flash region that carries the SEC and PEIM modules that execute in place. Even if these are implicitly read-only due to the ROM nature, they need to be mapped with read-only attributes in the page tables to be able to execute from them. Also add the XP counterpart which will be used for all normal DRAM right at the outset. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/Include/Library/ArmLib.h | 6 ++++ .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 31 +++++++++++++++---- ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c | 16 ++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/ArmPkg/Include/Library/ArmLib.h b/ArmPkg/Include/Library/ArmLib.h index a53f60d988..fb1ae57b35 100644 --- a/ArmPkg/Include/Library/ArmLib.h +++ b/ArmPkg/Include/Library/ArmLib.h @@ -35,6 +35,12 @@ typedef enum { // Do NOT use below two attributes if you are not sure. ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE, + // Special region types for memory that must be mapped with read-only or + // non-execute permissions from the very start, e.g., to support the use + // of the WXN virtual memory control. + ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_RO, + ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_XP, + ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH, ARM_MEMORY_REGION_ATTRIBUTE_DEVICE, } ARM_MEMORY_REGION_ATTRIBUTES; diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index ee4c5c995c..7acfd2e89a 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -37,12 +37,35 @@ ArmMemoryAttributeToPageAttribute ( IN ARM_MEMORY_REGION_ATTRIBUTES Attributes ) { + UINT64 Permissions; + + switch (Attributes) { + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_RO: + Permissions = TT_AP_NO_RO; + break; + + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_XP: + case ARM_MEMORY_REGION_ATTRIBUTE_DEVICE: + if (ArmReadCurrentEL () == AARCH64_EL2) { + Permissions = TT_XN_MASK; + } else { + Permissions = TT_UXN_MASK | TT_PXN_MASK; + } + + break; + default: + Permissions = 0; + break; + } + switch (Attributes) { case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_NONSHAREABLE: return TT_ATTR_INDX_MEMORY_WRITE_BACK; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK: - return TT_ATTR_INDX_MEMORY_WRITE_BACK | TT_SH_INNER_SHAREABLE; + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_RO: + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_XP: + return TT_ATTR_INDX_MEMORY_WRITE_BACK | TT_SH_INNER_SHAREABLE | Permissions; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: return TT_ATTR_INDX_MEMORY_WRITE_THROUGH | TT_SH_INNER_SHAREABLE; @@ -54,11 +77,7 @@ ArmMemoryAttributeToPageAttribute ( default: ASSERT (0); case ARM_MEMORY_REGION_ATTRIBUTE_DEVICE: - if (ArmReadCurrentEL () == AARCH64_EL2) { - return TT_ATTR_INDX_DEVICE_MEMORY | TT_XN_MASK; - } else { - return TT_ATTR_INDX_DEVICE_MEMORY | TT_UXN_MASK | TT_PXN_MASK; - } + return TT_ATTR_INDX_DEVICE_MEMORY | Permissions; } } diff --git a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c index 1542983574..00c5f42cd9 100644 --- a/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/Arm/ArmMmuLibCore.c @@ -106,6 +106,14 @@ PopulateLevel2PageTable ( PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_BACK; PageAttributes &= ~TT_DESCRIPTOR_PAGE_S_SHARED; break; + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_RO: + PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_BACK; + PageAttributes |= TT_DESCRIPTOR_PAGE_AP_NO_RO; + break; + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_XP: + PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_BACK; + PageAttributes |= TT_DESCRIPTOR_PAGE_XN_MASK; + break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: PageAttributes = TT_DESCRIPTOR_PAGE_WRITE_THROUGH; break; @@ -240,6 +248,14 @@ FillTranslationTable ( Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK; Attributes &= ~TT_DESCRIPTOR_SECTION_S_SHARED; break; + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_RO: + Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK; + Attributes |= TT_DESCRIPTOR_SECTION_AP_NO_RO; + break; + case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_BACK_XP: + Attributes = TT_DESCRIPTOR_SECTION_WRITE_BACK; + Attributes |= TT_DESCRIPTOR_SECTION_XN_MASK; + break; case ARM_MEMORY_REGION_ATTRIBUTE_WRITE_THROUGH: Attributes = TT_DESCRIPTOR_SECTION_WRITE_THROUGH; break; From b3e5b28287c9e89d5e85bd3e50332e5df45301f2 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 13 Feb 2023 12:31:06 +0100 Subject: [PATCH 0702/1529] ArmVirtPkg/ArmVirtQemu: Use PEI flavor of ArmMmuLib for all PEIMs The PEI flavor of the ArmMmuLib will install a HOB that exposes its implementation of the special helper routine that is used to update live entries, so that other instantiations of ArmMmuLib can invoke it. This is needed to ensure that splitting page tables using break-before-make (BBM) does not unmap the code that is performing the split. However, the BASE variety of ArmMmuLib discovers the HOB and sets a global pointer to refer to it, which is not possible in PEIMs, and so all PEIMs must use the PEI variety of this library if one does. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmVirtPkg/ArmVirtQemu.dsc | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc index 72a0cacab4..449e73b9e1 100644 --- a/ArmVirtPkg/ArmVirtQemu.dsc +++ b/ArmVirtPkg/ArmVirtQemu.dsc @@ -107,6 +107,9 @@ Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2DeviceLibDTpm.inf !endif +[LibraryClasses.AARCH64.PEIM] + ArmMmuLib|ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf + [LibraryClasses.common.DXE_DRIVER] ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf @@ -333,12 +336,7 @@ ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf MdeModulePkg/Core/Pei/PeiMain.inf ArmPlatformPkg/PlatformPei/PlatformPeim.inf - ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf { - -!if $(ARCH) == AARCH64 - ArmMmuLib|ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf -!endif - } + ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf ArmPkg/Drivers/CpuPei/CpuPei.inf !if $(TPM2_ENABLE) == TRUE From f978f2b5b18b6b74fda4063381b3f762a7849062 Mon Sep 17 00:00:00 2001 From: Matt DeVillier Date: Sat, 10 Dec 2022 04:45:38 +0800 Subject: [PATCH 0703/1529] MdeModulePkg/BmBoot: Skip removable media if it is not present Only enumerate devices that have media present. Cc: Hao A Wu Cc: Jian J Wang Cc: Liming Gao Cc: Zhichao Gao Cc: Ray Ni Reviewed-by: Sean Rhodes Signed-off-by: Matt DeVillier Reviewed-by: Ray Ni --- MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c index 962892d38f..bde22fa659 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c @@ -2218,6 +2218,15 @@ BmEnumerateBootOptions ( continue; } + // + // Skip removable media if not present + // + if ((BlkIo->Media->RemovableMedia == TRUE) && + (BlkIo->Media->MediaPresent == FALSE)) + { + continue; + } + Description = BmGetBootDescription (Handles[Index]); BootOptions = ReallocatePool ( sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount), From 162200c279cf8298d2bdf1c8fe1ee662a5591ad8 Mon Sep 17 00:00:00 2001 From: Gang Chen Date: Tue, 3 Jan 2023 13:57:38 +0800 Subject: [PATCH 0704/1529] CryptoPkg/Library: add -Wno-unused-but-set-variable for openssl The GCC warning fix is not in 1.1.1x. Ignore the warning type -Wno-unused-but-set-variable with GCC compiler in the build option. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Gang Chen Reviewed-by: Jiewen Yao --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 2 ++ CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf | 2 ++ CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf | 2 ++ CryptoPkg/Library/OpensslLib/OpensslLibFull.inf | 2 ++ CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf | 2 ++ 5 files changed, 10 insertions(+) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 1474df8125..86a00b1c4b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -642,6 +642,8 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + # Revisit after switching to 3.0 branch + GCC:*_GCC5_*_CC_FLAGS = -Wno-unused-but-set-variable # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf index 3c5f6d5d17..2e4f95909b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibAccel.inf @@ -690,6 +690,8 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + # Revisit after switching to 3.0 branch + GCC:*_GCC5_*_CC_FLAGS = -Wno-unused-but-set-variable # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index a9adb94720..637d4769e8 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -592,6 +592,8 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + # Revisit after switching to 3.0 branch + GCC:*_GCC5_*_CC_FLAGS = -Wno-unused-but-set-variable # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf index 4c2cbe9cf7..c5f90221fc 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFull.inf @@ -697,6 +697,8 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + # Revisit after switching to 3.0 branch + GCC:*_GCC5_*_CC_FLAGS = -Wno-unused-but-set-variable # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf index 591c57fdc2..076295244a 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibFullAccel.inf @@ -745,6 +745,8 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + # Revisit after switching to 3.0 branch + GCC:*_GCC5_*_CC_FLAGS = -Wno-unused-but-set-variable # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types From 414d4f193113f7a49b9245670d3df3bc7dcf015d Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 9 Feb 2023 07:24:16 -0700 Subject: [PATCH 0705/1529] MdePkg: Update Base.h to be compliant with C11 With the introduction of the use of _Static_assert, edk2 requires a C11 compatible compiler. Update Include/Base.h to be compliant with C11. As of C11, the maximum type of an enum is type `int`. Since the UEFI Specification 2.3.1 Errata C allows either `int` or `unsigned int`, fix the 32-bit enum check to use a signed int. Since the UEFI 2.3 Specification only allowed signed int, update the comment to reference 2.3.1 Errata C where the change was made to allow unsigned int. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney --- MdePkg/Include/Base.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/MdePkg/Include/Base.h b/MdePkg/Include/Base.h index d209e6de28..e89c84962a 100644 --- a/MdePkg/Include/Base.h +++ b/MdePkg/Include/Base.h @@ -796,9 +796,9 @@ STATIC_ASSERT (sizeof (L"A") == 4, "sizeof (L\"A\") does not meet UEFI Specif // // The following three enum types are used to verify that the compiler // configuration for enum types is compliant with Section 2.3.1 of the -// UEFI 2.3 Specification. These enum types and enum values are not -// intended to be used. A prefix of '__' is used avoid conflicts with -// other types. +// UEFI 2.3.1 Errata C Specification. These enum types and enum values +// are not intended to be used. A prefix of '__' is used avoid +// conflicts with other types. // typedef enum { __VerifyUint8EnumValue = 0xff @@ -809,12 +809,12 @@ typedef enum { } __VERIFY_UINT16_ENUM_SIZE; typedef enum { - __VerifyUint32EnumValue = 0xffffffff -} __VERIFY_UINT32_ENUM_SIZE; + __VerifyInt32EnumValue = 0x7fffffff +} __VERIFY_INT32_ENUM_SIZE; STATIC_ASSERT (sizeof (__VERIFY_UINT8_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); STATIC_ASSERT (sizeof (__VERIFY_UINT16_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); -STATIC_ASSERT (sizeof (__VERIFY_UINT32_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (sizeof (__VERIFY_INT32_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); /** Macro that returns a pointer to the data structure that contains a specified field of From df5e07ee7cd14b1acc6320426ad6a5fc18f0f2fc Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 9 Feb 2023 07:29:22 -0700 Subject: [PATCH 0706/1529] MdePkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout MdePkg. Visual Studio versions before VS 2015 don't support __func__ and so will fail to compile. A workaround is to define __func__ as __FUNCTION__ : #define __func__ __FUNCTION__ Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Sunil V L --- MdePkg/Include/Library/PerformanceLib.h | 12 ++++++------ MdePkg/Include/Library/UnitTestLib.h | 18 +++++++++--------- .../BaseCacheMaintenanceLib/LoongArchCache.c | 6 +++--- .../BaseCacheMaintenanceLib/RiscVCache.c | 10 +++++----- MdePkg/Library/BaseLib/SafeString.c | 2 +- .../BaseOrderedCollectionRedBlackTreeLib.c | 4 ++-- MdePkg/Library/DxeRngLib/DxeRngLib.c | 14 +++++++------- 7 files changed, 33 insertions(+), 33 deletions(-) diff --git a/MdePkg/Include/Library/PerformanceLib.h b/MdePkg/Include/Library/PerformanceLib.h index 34ec956b9c..d0f2dfb070 100644 --- a/MdePkg/Include/Library/PerformanceLib.h +++ b/MdePkg/Include/Library/PerformanceLib.h @@ -526,7 +526,7 @@ LogPerformanceMeasurement ( #define PERF_EVENT_SIGNAL_BEGIN(EventGuid) \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, EventGuid, __FUNCTION__ , 0, PERF_EVENTSIGNAL_START_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, EventGuid, __func__ , 0, PERF_EVENTSIGNAL_START_ID); \ } \ } while (FALSE) @@ -542,7 +542,7 @@ LogPerformanceMeasurement ( #define PERF_EVENT_SIGNAL_END(EventGuid) \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, EventGuid, __FUNCTION__ , 0, PERF_EVENTSIGNAL_END_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, EventGuid, __func__ , 0, PERF_EVENTSIGNAL_END_ID); \ } \ } while (FALSE) @@ -558,7 +558,7 @@ LogPerformanceMeasurement ( #define PERF_CALLBACK_BEGIN(TriggerGuid) \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, TriggerGuid, __FUNCTION__ , 0, PERF_CALLBACK_START_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, TriggerGuid, __func__ , 0, PERF_CALLBACK_START_ID); \ } \ } while (FALSE) @@ -574,7 +574,7 @@ LogPerformanceMeasurement ( #define PERF_CALLBACK_END(TriggerGuid) \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, TriggerGuid, __FUNCTION__ , 0, PERF_CALLBACK_END_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, TriggerGuid, __func__ , 0, PERF_CALLBACK_END_ID); \ } \ } while (FALSE) @@ -589,7 +589,7 @@ LogPerformanceMeasurement ( #define PERF_FUNCTION_BEGIN() \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, NULL, __FUNCTION__ , 0, PERF_FUNCTION_START_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, NULL, __func__ , 0, PERF_FUNCTION_START_ID); \ } \ } while (FALSE) @@ -604,7 +604,7 @@ LogPerformanceMeasurement ( #define PERF_FUNCTION_END() \ do { \ if (LogPerformanceMeasurementEnabled (PERF_GENERAL_TYPE)) { \ - LogPerformanceMeasurement (&gEfiCallerIdGuid, NULL, __FUNCTION__ , 0, PERF_FUNCTION_END_ID); \ + LogPerformanceMeasurement (&gEfiCallerIdGuid, NULL, __func__ , 0, PERF_FUNCTION_END_ID); \ } \ } while (FALSE) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 71c205b1b1..321a310602 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -348,7 +348,7 @@ SaveFrameworkState ( @param[in] Expression Expression to be evaluated for TRUE. **/ #define UT_ASSERT_TRUE(Expression) \ - if(!UnitTestAssertTrue ((Expression), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #Expression)) { \ + if(!UnitTestAssertTrue ((Expression), __func__, DEBUG_LINE_NUMBER, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -360,7 +360,7 @@ SaveFrameworkState ( @param[in] Expression Expression to be evaluated for FALSE. **/ #define UT_ASSERT_FALSE(Expression) \ - if(!UnitTestAssertFalse ((Expression), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #Expression)) { \ + if(!UnitTestAssertFalse ((Expression), __func__, DEBUG_LINE_NUMBER, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -373,7 +373,7 @@ SaveFrameworkState ( @param[in] ValueB Value to be compared for equality (64-bit comparison). **/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual ((UINT64)(ValueA), (UINT64)(ValueB), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertEqual ((UINT64)(ValueA), (UINT64)(ValueB), __func__, DEBUG_LINE_NUMBER, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -387,7 +387,7 @@ SaveFrameworkState ( @param[in] Length Number of bytes to compare in BufferA and BufferB. **/ #define UT_ASSERT_MEM_EQUAL(BufferA, BufferB, Length) \ - if(!UnitTestAssertMemEqual ((VOID *)(UINTN)(BufferA), (VOID *)(UINTN)(BufferB), (UINTN)Length, __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #BufferA, #BufferB)) { \ + if(!UnitTestAssertMemEqual ((VOID *)(UINTN)(BufferA), (VOID *)(UINTN)(BufferB), (UINTN)Length, __func__, DEBUG_LINE_NUMBER, __FILE__, #BufferA, #BufferB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -400,7 +400,7 @@ SaveFrameworkState ( @param[in] ValueB Value to be compared for inequality (64-bit comparison). **/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual ((UINT64)(ValueA), (UINT64)(ValueB), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertNotEqual ((UINT64)(ValueA), (UINT64)(ValueB), __func__, DEBUG_LINE_NUMBER, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -412,7 +412,7 @@ SaveFrameworkState ( @param[in] Status EFI_STATUS value to check. **/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError ((Status), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #Status)) { \ + if(!UnitTestAssertNotEfiError ((Status), __func__, DEBUG_LINE_NUMBER, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -425,7 +425,7 @@ SaveFrameworkState ( @param[in] Expected EFI_STATUS values to compare for equality. **/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual ((Status), (Expected), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #Status)) { \ + if(!UnitTestAssertStatusEqual ((Status), (Expected), __func__, DEBUG_LINE_NUMBER, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -437,7 +437,7 @@ SaveFrameworkState ( @param[in] Pointer Pointer to be checked against NULL. **/ #define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull ((Pointer), __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, #Pointer)) { \ + if(!UnitTestAssertNotNull ((Pointer), __func__, DEBUG_LINE_NUMBER, __FILE__, #Pointer)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -482,7 +482,7 @@ extern BASE_LIBRARY_JUMP_BUFFER *gUnitTestExpectAssertFailureJumpBuffer; } \ if (!UnitTestExpectAssertFailure ( \ UnitTestJumpStatus, \ - __FUNCTION__, DEBUG_LINE_NUMBER, __FILE__, \ + __func__, DEBUG_LINE_NUMBER, __FILE__, \ #FunctionCall, Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } \ diff --git a/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c b/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c index 4c8773278c..617b0f4218 100644 --- a/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c +++ b/MdePkg/Library/BaseCacheMaintenanceLib/LoongArchCache.c @@ -100,7 +100,7 @@ WriteBackInvalidateDataCache ( VOID ) { - DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __func__)); } /** @@ -136,7 +136,7 @@ WriteBackInvalidateDataCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __func__)); return Address; } @@ -191,7 +191,7 @@ WriteBackDataCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Not currently implemented on LoongArch.\n", __func__)); return Address; } diff --git a/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c b/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c index 9a6d57d841..d08fb9f193 100644 --- a/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c +++ b/MdePkg/Library/BaseCacheMaintenanceLib/RiscVCache.c @@ -101,7 +101,7 @@ WriteBackInvalidateDataCache ( VOID ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __func__)); } /** @@ -137,7 +137,7 @@ WriteBackInvalidateDataCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __func__)); return Address; } @@ -157,7 +157,7 @@ WriteBackDataCache ( VOID ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __func__)); } /** @@ -192,7 +192,7 @@ WriteBackDataCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __func__)); return Address; } @@ -250,6 +250,6 @@ InvalidateDataCacheRange ( IN UINTN Length ) { - DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:RISC-V unsupported function.\n", __func__)); return Address; } diff --git a/MdePkg/Library/BaseLib/SafeString.c b/MdePkg/Library/BaseLib/SafeString.c index b75b333817..954d3f8c89 100644 --- a/MdePkg/Library/BaseLib/SafeString.c +++ b/MdePkg/Library/BaseLib/SafeString.c @@ -17,7 +17,7 @@ if (!(Expression)) { \ DEBUG ((DEBUG_VERBOSE, \ "%a(%d) %a: SAFE_STRING_CONSTRAINT_CHECK(%a) failed. Return %r\n", \ - __FILE__, DEBUG_LINE_NUMBER, __FUNCTION__, DEBUG_EXPRESSION_STRING (Expression), Status)); \ + __FILE__, DEBUG_LINE_NUMBER, __func__, DEBUG_EXPRESSION_STRING (Expression), Status)); \ return Status; \ } \ } while (FALSE) diff --git a/MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.c b/MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.c index f47301de89..a23113f9c9 100644 --- a/MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.c +++ b/MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.c @@ -1416,7 +1416,7 @@ RedBlackTreeValidate ( CONST RED_BLACK_TREE_NODE *Last; CONST RED_BLACK_TREE_NODE *Node; - DEBUG ((DEBUG_VERBOSE, "%a: Tree=%p\n", __FUNCTION__, Tree)); + DEBUG ((DEBUG_VERBOSE, "%a: Tree=%p\n", __func__, Tree)); // // property #5 @@ -1459,7 +1459,7 @@ RedBlackTreeValidate ( DEBUG (( DEBUG_VERBOSE, "%a: Tree=%p BlackHeight=%Ld Count=%Ld\n", - __FUNCTION__, + __func__, Tree, (INT64)BlackHeight, (INT64)ForwardCount diff --git a/MdePkg/Library/DxeRngLib/DxeRngLib.c b/MdePkg/Library/DxeRngLib/DxeRngLib.c index 82129aa445..46aea51592 100644 --- a/MdePkg/Library/DxeRngLib/DxeRngLib.c +++ b/MdePkg/Library/DxeRngLib/DxeRngLib.c @@ -37,43 +37,43 @@ GenerateRandomNumberViaNist800Algorithm ( RngProtocol = NULL; if (Buffer == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Buffer == NULL.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Buffer == NULL.\n", __func__)); return EFI_INVALID_PARAMETER; } Status = gBS->LocateProtocol (&gEfiRngProtocolGuid, NULL, (VOID **)&RngProtocol); if (EFI_ERROR (Status) || (RngProtocol == NULL)) { - DEBUG ((DEBUG_ERROR, "%a: Could not locate RNG prototocol, Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Could not locate RNG prototocol, Status = %r\n", __func__, Status)); return Status; } Status = RngProtocol->GetRNG (RngProtocol, &gEfiRngAlgorithmSp80090Ctr256Guid, BufferSize, Buffer); - DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm CTR-256 - Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm CTR-256 - Status = %r\n", __func__, Status)); if (!EFI_ERROR (Status)) { return Status; } Status = RngProtocol->GetRNG (RngProtocol, &gEfiRngAlgorithmSp80090Hmac256Guid, BufferSize, Buffer); - DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm HMAC-256 - Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm HMAC-256 - Status = %r\n", __func__, Status)); if (!EFI_ERROR (Status)) { return Status; } Status = RngProtocol->GetRNG (RngProtocol, &gEfiRngAlgorithmSp80090Hash256Guid, BufferSize, Buffer); - DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm Hash-256 - Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm Hash-256 - Status = %r\n", __func__, Status)); if (!EFI_ERROR (Status)) { return Status; } // If all the other methods have failed, use the default method from the RngProtocol Status = RngProtocol->GetRNG (RngProtocol, NULL, BufferSize, Buffer); - DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm Hash-256 - Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: GetRNG algorithm Hash-256 - Status = %r\n", __func__, Status)); if (!EFI_ERROR (Status)) { return Status; } // If we get to this point, we have failed - DEBUG ((DEBUG_ERROR, "%a: GetRNG() failed, staus = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: GetRNG() failed, staus = %r\n", __func__, Status)); return Status; }// GenerateRandomNumberViaNist800Algorithm() From d8f6b10528aef9a4973d879c6e01e8dc2280160f Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Tue, 7 Mar 2023 12:08:59 +0800 Subject: [PATCH 0707/1529] RedfishPkg/Library: Redfish BMC USBNIC Host Interface BMC exposed USB NIC platform Redfish Host Interface library implementation. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Nickle Wang --- RedfishPkg/Include/Library/RedfishDebugLib.h | 3 +- .../PlatformHostInterfaceBmcUsbNicLib.c | 1291 +++++++++++++++++ .../PlatformHostInterfaceBmcUsbNicLib.h | 84 ++ .../PlatformHostInterfaceBmcUsbNicLib.inf | 48 + RedfishPkg/RedfishPkg.dec | 10 + 5 files changed, 1435 insertions(+), 1 deletion(-) create mode 100644 RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c create mode 100644 RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.h create mode 100644 RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf diff --git a/RedfishPkg/Include/Library/RedfishDebugLib.h b/RedfishPkg/Include/Library/RedfishDebugLib.h index 21f01353ed..913f2b2f35 100644 --- a/RedfishPkg/Include/Library/RedfishDebugLib.h +++ b/RedfishPkg/Include/Library/RedfishDebugLib.h @@ -14,7 +14,8 @@ #include #include -#define DEBUG_REDFISH_NETWORK DEBUG_INFO ///< Debug error level for Redfish networking function +#define DEBUG_REDFISH_NETWORK DEBUG_INFO ///< Debug error level for Redfish networking function +#define DEBUG_REDFISH_HOST_INTERFACE DEBUG_INFO ///< Debug error level for Redfish networking function /** diff --git a/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c new file mode 100644 index 0000000000..122473dbe4 --- /dev/null +++ b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c @@ -0,0 +1,1291 @@ +/** @file + Source file to provide the platform Redfish Host Interface information + of USB NIC Device exposed by BMC. + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "PlatformHostInterfaceBmcUsbNicLib.h" + +static EFI_GUID mPlatformHostInterfaceBmcUsbNicReadinessGuid = + BMC_USB_NIC_HOST_INTERFASCE_READINESS_GUID; +static EFI_EVENT mPlatformHostInterfaceSnpEvent = NULL; +static VOID *mPlatformHostInterfaceSnpRegistration = NULL; + +static LIST_ENTRY mBmcUsbNic; +static LIST_ENTRY mBmcIpmiLan; + +/** + Probe if the system supports Redfish Host Interface Credentail + Bootstrapping. + + @retval TRUE Yes, it is supported. + TRUE No, it is not supported. + +**/ +BOOLEAN +ProbeRedfishCredentialBootstrap ( + VOID + ) +{ + EFI_STATUS Status; + IPMI_BOOTSTRAP_CREDENTIALS_COMMAND_DATA CommandData; + IPMI_BOOTSTRAP_CREDENTIALS_RESULT_RESPONSE ResponseData; + UINT32 ResponseSize; + BOOLEAN ReturnBool; + + DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + + // + // IPMI callout to NetFn 2C, command 02 + // Request data: + // Byte 1: REDFISH_IPMI_GROUP_EXTENSION + // Byte 2: DisableBootstrapControl + // + CommandData.GroupExtensionId = REDFISH_IPMI_GROUP_EXTENSION; + CommandData.DisableBootstrapControl = REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_ENABLE; + ResponseData.CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + ResponseSize = sizeof (ResponseData); + // + // Response data: Ignored. + // + Status = IpmiSubmitCommand ( + IPMI_NETFN_GROUP_EXT, + REDFISH_IPMI_GET_BOOTSTRAP_CREDENTIALS_CMD, + (UINT8 *)&CommandData, + sizeof (CommandData), + (UINT8 *)&ResponseData, + &ResponseSize + ); + if (!EFI_ERROR (Status) && + ((ResponseData.CompletionCode == IPMI_COMP_CODE_NORMAL) || + (ResponseData.CompletionCode == REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED) + )) + { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is supported\n", __FUNCTION__)); + ReturnBool = TRUE; + } else { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is not supported\n", __FUNCTION__)); + ReturnBool = FALSE; + } + + return ReturnBool; +} + +/** + Get platform Redfish host interface device descriptor. + + @param[in] DeviceType Pointer to retrieve device type. + @param[out] DeviceDescriptor Pointer to retrieve REDFISH_INTERFACE_DATA, caller has to free + this memory using FreePool(). + + @retval EFI_NOT_FOUND No Redfish host interface descriptor provided on this platform. + +**/ +EFI_STATUS +RedfishPlatformHostInterfaceDeviceDescriptor ( + IN UINT8 *DeviceType, + OUT REDFISH_INTERFACE_DATA **DeviceDescriptor + ) +{ + HOST_INTERFACE_BMC_USB_NIC_INFO *ThisInstance; + REDFISH_INTERFACE_DATA *InterfaceData; + + DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + + if (IsListEmpty (&mBmcUsbNic)) { + return EFI_NOT_FOUND; + } + + // Check if BMC exposed USB NIC is found and ready for using. + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *)GetFirstNode (&mBmcUsbNic); + while (TRUE) { + if (ThisInstance->IsExposedByBmc && ThisInstance->IsSuppportedHostInterface) { + *DeviceType = REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2; + + // Fill up REDFISH_INTERFACE_DATA defined in Redfish host interface spec v1.3 + InterfaceData = (REDFISH_INTERFACE_DATA *)AllocateZeroPool (USB_INTERFACE_DEVICE_DESCRIPTOR_V2_SIZE_1_3); + if (InterfaceData == NULL) { + DEBUG ((DEBUG_ERROR, "Failed to allocate memory for REDFISH_INTERFACE_DATA\n")); + return EFI_OUT_OF_RESOURCES; + } + + InterfaceData->DeviceType = REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2; + InterfaceData->DeviceDescriptor.UsbDeviceV2.Length = USB_INTERFACE_DEVICE_DESCRIPTOR_V2_SIZE_1_3; + InterfaceData->DeviceDescriptor.UsbDeviceV2.IdVendor = ThisInstance->UsbVendorId; + InterfaceData->DeviceDescriptor.UsbDeviceV2.IdProduct = ThisInstance->UsbProductId; + InterfaceData->DeviceDescriptor.UsbDeviceV2.SerialNumberStr = 0; + CopyMem ( + (VOID *)&InterfaceData->DeviceDescriptor.UsbDeviceV2.MacAddress, + (VOID *)&ThisInstance->MacAddress, + sizeof (InterfaceData->DeviceDescriptor.UsbDeviceV2.MacAddress) + ); + InterfaceData->DeviceDescriptor.UsbDeviceV2.Characteristics |= (UINT16)ThisInstance->CredentialBootstrapping; + InterfaceData->DeviceDescriptor.UsbDeviceV2.CredentialBootstrappingHandle = 0; + *DeviceDescriptor = InterfaceData; + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " REDFISH_INTERFACE_DATA is returned successfully.\n")); + return EFI_SUCCESS; + } + + if (IsNodeAtEnd (&mBmcUsbNic, &ThisInstance->NextInstance)) { + break; + } + + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *) + GetNextNode (&mBmcUsbNic, &ThisInstance->NextInstance); + } + + return EFI_NOT_FOUND; +} + +/** + Get platform Redfish host interface protocol data. + Caller should pass NULL in ProtocolRecord to retrive the first protocol record. + Then continuously pass previous ProtocolRecord for retrieving the next ProtocolRecord. + + @param[in, out] ProtocolRecord Pointer to retrieve the first or the next protocol record. + caller has to free the new protocol record returned from + this function using FreePool(). + @param[in] IndexOfProtocolData The index of protocol data. + + @retval EFI_NOT_FOUND No more protocol records. + +**/ +EFI_STATUS +RedfishPlatformHostInterfaceProtocolData ( + IN OUT MC_HOST_INTERFACE_PROTOCOL_RECORD **ProtocolRecord, + IN UINT8 IndexOfProtocolData + ) +{ + HOST_INTERFACE_BMC_USB_NIC_INFO *ThisInstance; + MC_HOST_INTERFACE_PROTOCOL_RECORD *ThisProtocolRecord; + REDFISH_OVER_IP_PROTOCOL_DATA *RedfishOverIpData; + UINT8 HostNameLength; + CHAR8 *HostNameString; + + DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + + if (IsListEmpty (&mBmcUsbNic) || (IndexOfProtocolData > 0)) { + return EFI_NOT_FOUND; + } + + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *)GetFirstNode (&mBmcUsbNic); + while (TRUE) { + if (ThisInstance->IsExposedByBmc && ThisInstance->IsSuppportedHostInterface) { + // Get the host name before allocating memory. + HostNameString = (CHAR8 *)PcdGetPtr (PcdRedfishHostName); + HostNameLength = (UINT8)AsciiStrSize (HostNameString); + ThisProtocolRecord = (MC_HOST_INTERFACE_PROTOCOL_RECORD *)AllocateZeroPool ( + sizeof (MC_HOST_INTERFACE_PROTOCOL_RECORD) - 1 + + sizeof (REDFISH_OVER_IP_PROTOCOL_DATA) + + HostNameLength + ); + if (ThisProtocolRecord == NULL) { + DEBUG ((DEBUG_ERROR, " Allocate memory fail for MC_HOST_INTERFACE_PROTOCOL_RECORD.\n")); + return EFI_OUT_OF_RESOURCES; + } + + ThisProtocolRecord->ProtocolType = MCHostInterfaceProtocolTypeRedfishOverIP; + ThisProtocolRecord->ProtocolTypeDataLen = sizeof (REDFISH_OVER_IP_PROTOCOL_DATA) + HostNameLength; + RedfishOverIpData = (REDFISH_OVER_IP_PROTOCOL_DATA *)&ThisProtocolRecord->ProtocolTypeData[0]; + // + // Fill up REDFISH_OVER_IP_PROTOCOL_DATA + // + + // Service UUID + ZeroMem ((VOID *)&RedfishOverIpData->ServiceUuid, sizeof (EFI_GUID)); + if (StrLen ((CONST CHAR16 *)PcdGetPtr (PcdRedfishServiceUuid)) != 0) { + StrToGuid ((CONST CHAR16 *)PcdGetPtr (PcdRedfishServiceUuid), &RedfishOverIpData->ServiceUuid); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Service UUID: %g", &RedfishOverIpData->ServiceUuid)); + } + + // HostIpAddressFormat and RedfishServiceIpDiscoveryType + RedfishOverIpData->HostIpAssignmentType = RedfishHostIpAssignmentUnknown; + RedfishOverIpData->RedfishServiceIpDiscoveryType = RedfishHostIpAssignmentUnknown; + if (ThisInstance->IpAssignedType == IpmiStaticAddrsss) { + RedfishOverIpData->HostIpAssignmentType = RedfishHostIpAssignmentStatic; + RedfishOverIpData->RedfishServiceIpDiscoveryType = RedfishHostIpAssignmentStatic; + } else if (ThisInstance->IpAssignedType == IpmiDynamicAddressBmcDhcp) { + RedfishOverIpData->HostIpAssignmentType = RedfishHostIpAssignmentDhcp; + RedfishOverIpData->RedfishServiceIpDiscoveryType = RedfishHostIpAssignmentDhcp; + } + + // HostIpAddressFormat and RedfishServiceIpAddressFormat, only support IPv4 for now. + RedfishOverIpData->HostIpAddressFormat = REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4; + RedfishOverIpData->RedfishServiceIpAddressFormat = REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4; + + // HostIpAddress + CopyMem ( + (VOID *)RedfishOverIpData->HostIpAddress, + (VOID *)ThisInstance->HostIpAddressIpv4, + sizeof (ThisInstance->HostIpAddressIpv4) + ); + + // HostIpMask and RedfishServiceIpMask + CopyMem ( + (VOID *)RedfishOverIpData->HostIpMask, + (VOID *)ThisInstance->SubnetMaskIpv4, + sizeof (ThisInstance->SubnetMaskIpv4) + ); + CopyMem ( + (VOID *)RedfishOverIpData->RedfishServiceIpMask, + (VOID *)ThisInstance->SubnetMaskIpv4, + sizeof (ThisInstance->SubnetMaskIpv4) + ); + + // RedfishServiceIpAddress + CopyMem ( + (VOID *)RedfishOverIpData->RedfishServiceIpAddress, + (VOID *)ThisInstance->RedfishIpAddressIpv4, + sizeof (ThisInstance->RedfishIpAddressIpv4) + ); + + // RedfishServiceIpPort + RedfishOverIpData->RedfishServiceIpPort = 0; + + // RedfishServiceVlanId + RedfishOverIpData->RedfishServiceVlanId = ThisInstance->VLanId; + + // RedfishServiceHostnameLength + RedfishOverIpData->RedfishServiceHostnameLength = HostNameLength; + + // Redfish host name. + CopyMem ( + (VOID *)&RedfishOverIpData->RedfishServiceHostname, + (VOID *)HostNameString, + HostNameLength + ); + + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " MC_HOST_INTERFACE_PROTOCOL_RECORD is returned successfully.\n")); + *ProtocolRecord = ThisProtocolRecord; + return EFI_SUCCESS; + } + + if (IsNodeAtEnd (&mBmcUsbNic, &ThisInstance->NextInstance)) { + break; + } + + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *) + GetNextNode (&mBmcUsbNic, &ThisInstance->NextInstance); + } + + return EFI_NOT_FOUND; +} + +/** + This function retrieve the information of BMC USB NIC. + + @retval EFI_SUCCESS All necessary information is retrieved. + @retval EFI_NOT_FOUND There is no BMC exposed USB NIC. + @retval Others Other errors. + +**/ +EFI_STATUS +RetrievedBmcUsbNicInfo ( + VOID + ) +{ + EFI_STATUS Status; + UINT32 ResponseDataSize; + HOST_INTERFACE_BMC_USB_NIC_INFO *ThisInstance; + IPMI_GET_LAN_CONFIGURATION_PARAMETERS_REQUEST GetLanConfigReq; + IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *GetLanConfigReps; + IPMI_LAN_IP_ADDRESS_SRC *IpAddressSrc; + IPMI_LAN_IP_ADDRESS *DestIpAddress; + IPMI_LAN_SUBNET_MASK *SubnetMask; + IPMI_LAN_DEFAULT_GATEWAY *DefaultGateway; + IPMI_LAN_VLAN_ID *LanVlanId; + EFI_USB_DEVICE_DESCRIPTOR UsbDeviceDescriptor; + + DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + + if (IsListEmpty (&mBmcUsbNic)) { + return EFI_NOT_FOUND; + } + + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *)GetFirstNode (&mBmcUsbNic); + while (TRUE) { + if (ThisInstance->IsExposedByBmc) { + ThisInstance->IsSuppportedHostInterface = FALSE; + + // Probe if Redfish Host Interface Credential Bootstrapping is supported. + ThisInstance->CredentialBootstrapping = ProbeRedfishCredentialBootstrap (); + + // Get IP address source + GetLanConfigReq.SetSelector = 0; + GetLanConfigReq.BlockSelector = 0; + GetLanConfigReq.ChannelNumber.Bits.ChannelNo = ThisInstance->IpmiLanChannelNumber; + GetLanConfigReq.ChannelNumber.Bits.GetParameter = 0; + GetLanConfigReq.ChannelNumber.Bits.Reserved = 0; + GetLanConfigReq.ParameterSelector = IpmiLanIpAddressSource; + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + sizeof (IPMI_LAN_IP_ADDRESS_SRC); + GetLanConfigReps = (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if (EFI_ERROR (Status) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG ((DEBUG_ERROR, " Failed to get IP address source at channel %d: %r, 0x%02x.\n", ThisInstance->IpmiLanChannelNumber, Status, GetLanConfigReps->CompletionCode)); + FreePool (GetLanConfigReps); + return Status; + } + + IpAddressSrc = (IPMI_LAN_IP_ADDRESS_SRC *)(GetLanConfigReps + 1); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " IP address source at channel %d: %x\n", ThisInstance->IpmiLanChannelNumber, IpAddressSrc->Bits.AddressSrc)); + ThisInstance->IpAssignedType = IpAddressSrc->Bits.AddressSrc; + FreePool (GetLanConfigReps); + + // Get LAN IPv4 IP address + GetLanConfigReq.ParameterSelector = IpmiLanIpAddress; + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + sizeof (IPMI_LAN_IP_ADDRESS); + GetLanConfigReps = (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if (EFI_ERROR (Status) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG ((DEBUG_ERROR, " Failed to get Dest IP address at channel %d: %r, 0x%02x.\n", ThisInstance->IpmiLanChannelNumber, Status, GetLanConfigReps->CompletionCode)); + FreePool (GetLanConfigReps); + return Status; + } + + DestIpAddress = (IPMI_LAN_IP_ADDRESS *)(GetLanConfigReps + 1); + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " Dest IP address at channel %d: %d.%d.%d.%d\n", + ThisInstance->IpmiLanChannelNumber, + DestIpAddress->IpAddress[0], + DestIpAddress->IpAddress[1], + DestIpAddress->IpAddress[2], + DestIpAddress->IpAddress[3] + )); + CopyMem ((VOID *)&ThisInstance->RedfishIpAddressIpv4, (VOID *)&DestIpAddress->IpAddress, sizeof (DestIpAddress->IpAddress)); + // + // According to UEFI spec, the IP address at BMC USB NIC host end is the IP address at BMC end minus 1. + // + CopyMem ((VOID *)&ThisInstance->HostIpAddressIpv4, (VOID *)&DestIpAddress->IpAddress, sizeof (DestIpAddress->IpAddress)); + ThisInstance->HostIpAddressIpv4[sizeof (ThisInstance->HostIpAddressIpv4) - 1] -= 1; + FreePool (GetLanConfigReps); + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " Host IP address at channel %d: %d.%d.%d.%d\n", + ThisInstance->IpmiLanChannelNumber, + ThisInstance->HostIpAddressIpv4[0], + ThisInstance->HostIpAddressIpv4[1], + ThisInstance->HostIpAddressIpv4[2], + ThisInstance->HostIpAddressIpv4[3] + )); + + // Get IPv4 subnet mask + GetLanConfigReq.ParameterSelector = IpmiLanSubnetMask; + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + sizeof (IPMI_LAN_SUBNET_MASK); + GetLanConfigReps = (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if ((EFI_ERROR (Status)) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG ((DEBUG_ERROR, " Failed to get subnet mask at channel %d: %r, 0x%02x.\n", ThisInstance->IpmiLanChannelNumber, Status, GetLanConfigReps->CompletionCode)); + FreePool (GetLanConfigReps); + return Status; + } + + SubnetMask = (IPMI_LAN_SUBNET_MASK *)(GetLanConfigReps + 1); + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " Subnet mask at channel %d: %d.%d.%d.%d\n", + ThisInstance->IpmiLanChannelNumber, + SubnetMask->IpAddress[0], + SubnetMask->IpAddress[1], + SubnetMask->IpAddress[2], + SubnetMask->IpAddress[3] + )); + CopyMem ((VOID *)&ThisInstance->SubnetMaskIpv4, (VOID *)&SubnetMask->IpAddress, sizeof (SubnetMask->IpAddress)); + FreePool (GetLanConfigReps); + + // Get Gateway IP address. + GetLanConfigReq.ParameterSelector = IpmiLanDefaultGateway; + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + sizeof (IPMI_LAN_DEFAULT_GATEWAY); + GetLanConfigReps = (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if ((EFI_ERROR (Status)) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG ((DEBUG_ERROR, " Failed to get default gateway at channel %d: %r, 0x%02x.\n", ThisInstance->IpmiLanChannelNumber, Status, GetLanConfigReps->CompletionCode)); + FreePool (GetLanConfigReps); + return Status; + } + + DefaultGateway = (IPMI_LAN_DEFAULT_GATEWAY *)(GetLanConfigReps + 1); + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " Gateway at channel %d: %d.%d.%d.%d\n", + ThisInstance->IpmiLanChannelNumber, + DefaultGateway->IpAddress[0], + DefaultGateway->IpAddress[1], + DefaultGateway->IpAddress[2], + DefaultGateway->IpAddress[3] + )); + CopyMem ((VOID *)&ThisInstance->GatewayIpv4, (VOID *)&DefaultGateway->IpAddress, sizeof (DefaultGateway->IpAddress)); + FreePool (GetLanConfigReps); + + // Get VLAN ID + GetLanConfigReq.ParameterSelector = IpmiLanVlanId; + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + sizeof (IPMI_LAN_VLAN_ID); + GetLanConfigReps = (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if ((EFI_ERROR (Status)) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG ((DEBUG_ERROR, " Failed to get VLAN ID at channel %d: %r, 0x%02x.\n", ThisInstance->IpmiLanChannelNumber, Status, GetLanConfigReps->CompletionCode)); + FreePool (GetLanConfigReps); + return Status; + } + + LanVlanId = (IPMI_LAN_VLAN_ID *)(GetLanConfigReps + 1); + ThisInstance->VLanId = 0; + if (LanVlanId->Data2.Bits.Enabled == 1) { + ThisInstance->VLanId = LanVlanId->Data1.VanIdLowByte | (LanVlanId->Data2.Bits.VanIdHighByte << 8); + } + + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " VLAN ID %x\n", ThisInstance->VLanId)); + + FreePool (GetLanConfigReps); + + // + // Read USB device information. + // + if (ThisInstance->ThisUsbIo != NULL) { + Status = ThisInstance->ThisUsbIo->UsbGetDeviceDescriptor (ThisInstance->ThisUsbIo, &UsbDeviceDescriptor); + if (!EFI_ERROR (Status)) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " USB NIC Vendor ID: 0x%04x, Device ID: 0x%04x\n", UsbDeviceDescriptor.IdVendor, UsbDeviceDescriptor.IdProduct)); + ThisInstance->UsbVendorId = UsbDeviceDescriptor.IdVendor; + ThisInstance->UsbProductId = UsbDeviceDescriptor.IdProduct; + } else { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Fail to get USB device descriptor.\n")); + } + } + + // All information is retrieved. + ThisInstance->IsSuppportedHostInterface = TRUE; + return EFI_SUCCESS; + } + + if (IsNodeAtEnd (&mBmcUsbNic, &ThisInstance->NextInstance)) { + break; + } + + ThisInstance = (HOST_INTERFACE_BMC_USB_NIC_INFO *) + GetNextNode (&mBmcUsbNic, &ThisInstance->NextInstance); + } + + return EFI_NOT_FOUND; +} + +/** + This function caches the found IPMI LAN channel. So we + don't have to sedn IPMI commands again if the USB NIC is + connected later. + + @param[in] ChannelNum The IPMI channel number. + @param[in] IpmiLanChannelMacAddress Pointer to EFI_MAC_ADDRESS. + @param[in] IpmiLanMacAddressSize The MAC address size. + + @retval EFI_SUCCESS IPMI LAN channel is cached. + @retval EFI_OUT_OF_RESOURCE Memory allocated failed. + @retval Others Other errors. + +**/ +EFI_STATUS +CacheIpmiLanMac ( + IN UINT8 ChannelNum, + IN EFI_MAC_ADDRESS *IpmiLanChannelMacAddress, + IN UINT8 IpmiLanMacAddressSize + ) +{ + BMC_IPMI_LAN_CHANNEL_INFO *ChannelInfo; + + ChannelInfo = (BMC_IPMI_LAN_CHANNEL_INFO *)AllocateZeroPool (sizeof (BMC_IPMI_LAN_CHANNEL_INFO)); + if (ChannelInfo == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + ChannelInfo->Channel = ChannelNum; + CopyMem ((VOID *)&ChannelInfo->MacAddress.Addr, (VOID *)IpmiLanChannelMacAddress->Addr, IpmiLanMacAddressSize); + ChannelInfo->MacAddressSize = IpmiLanMacAddressSize; + InitializeListHead (&ChannelInfo->NextInstance); + InsertTailList (&mBmcIpmiLan, &ChannelInfo->NextInstance); + return EFI_SUCCESS; +} + +/** + This function checks if the IPMI channel already identified + previously. + + @param[in] ChannelNum The IPMI channel number. + @param[out] CachedIpmiLanChannel Pointer to retrieve the cached + BMC_IPMI_LAN_CHANNEL_INFO. + + @retval EFI_SUCCESS IPMI LAN channel is found. + @retval Others Other errors. + +**/ +EFI_STATUS +CheckCachedIpmiLanMac ( + IN UINT8 ChannelNum, + OUT BMC_IPMI_LAN_CHANNEL_INFO **CachedIpmiLanChannel + ) +{ + BMC_IPMI_LAN_CHANNEL_INFO *ThisInstance; + + if (IsListEmpty (&mBmcIpmiLan)) { + return EFI_NOT_FOUND; + } + + ThisInstance = (BMC_IPMI_LAN_CHANNEL_INFO *)GetFirstNode (&mBmcIpmiLan); + while (TRUE) { + if (ThisInstance->Channel == ChannelNum) { + *CachedIpmiLanChannel = ThisInstance; + return EFI_SUCCESS; + } + + if (IsNodeAtEnd (&mBmcIpmiLan, &ThisInstance->NextInstance)) { + break; + } + + ThisInstance = (BMC_IPMI_LAN_CHANNEL_INFO *) + GetNextNode (&mBmcIpmiLan, &ThisInstance->NextInstance); + } + + return EFI_NOT_FOUND; +} + +/** + This function goes through IPMI channels to find the + mactched MAC addrss of BMC USB NIC endpoint. + + @param[in] UsbNicInfo The instance of HOST_INTERFACE_BMC_USB_NIC_INFO. + + @retval EFI_SUCCESS Yes, USB NIC exposed by BMC is found. + @retval EFI_NOT_FOUND No, USB NIC exposed by BMC is not found + on the existing SNP handle. + @retval Others Other errors. + +**/ +EFI_STATUS +HostInterfaceIpmiCheckMacAddress ( + IN HOST_INTERFACE_BMC_USB_NIC_INFO *UsbNicInfo + ) +{ + EFI_STATUS Status; + EFI_STATUS ExitStatus; + UINTN ChannelNum; + UINT32 ResponseDataSize; + IPMI_GET_CHANNEL_INFO_REQUEST GetChanelInfoRequest; + IPMI_GET_CHANNEL_INFO_RESPONSE GetChanelInfoResponse; + IPMI_GET_LAN_CONFIGURATION_PARAMETERS_REQUEST GetLanConfigReq; + IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *GetLanConfigReps; + BMC_IPMI_LAN_CHANNEL_INFO *CachedIpmiLanChannel; + UINT8 IpmiLanMacAddressSize; + EFI_MAC_ADDRESS IpmiLanChannelMacAddress; + BOOLEAN AlreadyCached; + + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + + GetLanConfigReps = NULL; + AlreadyCached = FALSE; + if (!IsListEmpty (&mBmcIpmiLan)) { + AlreadyCached = TRUE; + } + + // Initial the get MAC address request. + GetLanConfigReq.SetSelector = 0; + GetLanConfigReq.BlockSelector = 0; + GetLanConfigReq.ParameterSelector = IpmiLanMacAddress; + + ExitStatus = EFI_NOT_FOUND; + for (ChannelNum = IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_1; + ChannelNum <= IPMI_CHANNEL_NUMBER_IMPLEMENTATION_SPECIFIC_11; + ChannelNum++) + { + IpmiLanMacAddressSize = 0; + + // Check if the IPMI channel information is already cached. + Status = EFI_NOT_FOUND; + if (AlreadyCached) { + Status = CheckCachedIpmiLanMac ((UINT8)ChannelNum, &CachedIpmiLanChannel); + } + + if (Status == EFI_SUCCESS) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Got cached IPMI LAN info.\n")); + IpmiLanMacAddressSize = sizeof (IPMI_LAN_MAC_ADDRESS); + CopyMem ((VOID *)&IpmiLanChannelMacAddress.Addr, (VOID *)&CachedIpmiLanChannel->MacAddress.Addr, IpmiLanMacAddressSize); + } else { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " No cached IPMI LAN info\n")); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Send NetFn = App, Command = 0x42 to channel %d\n", ChannelNum)); + GetChanelInfoRequest.ChannelNumber.Bits.ChannelNo = (UINT8)ChannelNum; + Status = IpmiGetChannelInfo ( + &GetChanelInfoRequest, + &GetChanelInfoResponse, + &ResponseDataSize + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " - Fails to send command.\n", ChannelNum)); + continue; + } + + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " - Response data size = 0x%x\n", ResponseDataSize)); + if ((GetChanelInfoResponse.CompletionCode != IPMI_COMP_CODE_NORMAL) || (ResponseDataSize == 0)) { + DEBUG ((DEBUG_ERROR, " - Command returned fail: 0x%x.\n", GetChanelInfoResponse.CompletionCode)); + continue; + } + + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " - Channel protocol = 0x%x, Media = 0x%x\n", + GetChanelInfoResponse.ProtocolType.Bits.ChannelProtocolType, + GetChanelInfoResponse.MediumType.Bits.ChannelMediumType + )); + + if (GetChanelInfoResponse.ChannelNumber.Bits.ChannelNo != ChannelNum) { + DEBUG (( + DEBUG_ERROR, + " - ChannelNumber = %d in the response which is not macthed to the request.\n", + GetChanelInfoResponse.ChannelNumber.Bits.ChannelNo + )); + continue; + } + + if ((GetChanelInfoResponse.MediumType.Bits.ChannelMediumType == IPMI_CHANNEL_MEDIA_TYPE_802_3_LAN) && + (GetChanelInfoResponse.ProtocolType.Bits.ChannelProtocolType == IPMI_CHANNEL_PROTOCOL_TYPE_IPMB_1_0)) + { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " - Channel %d is a LAN device!\n", ChannelNum)); + + ResponseDataSize = sizeof (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE) + + sizeof (IPMI_LAN_MAC_ADDRESS); + if (GetLanConfigReps == NULL) { + GetLanConfigReps = + (IPMI_GET_LAN_CONFIGURATION_PARAMETERS_RESPONSE *)AllocateZeroPool (ResponseDataSize); + if (GetLanConfigReps == NULL) { + DEBUG ((DEBUG_ERROR, " Allocate memory failed for getting MAC address.\n")); + continue; + } + } + + GetLanConfigReq.ChannelNumber.Bits.ChannelNo = (UINT8)ChannelNum; + GetLanConfigReps->CompletionCode = IPMI_COMP_CODE_UNSPECIFIED; + Status = IpmiGetLanConfigurationParameters ( + &GetLanConfigReq, + GetLanConfigReps, + &ResponseDataSize + ); + if (EFI_ERROR (Status) || (GetLanConfigReps->CompletionCode != IPMI_COMP_CODE_NORMAL)) { + DEBUG (( + DEBUG_ERROR, + " Fails to get MAC address of channel %d, CompletionCode = %02x.\n", + ChannelNum, + GetLanConfigReps->CompletionCode + )); + continue; + } else { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " The MAC address of channel %d.\n", ChannelNum)); + DEBUG (( + DEBUG_REDFISH_HOST_INTERFACE, + " %02x:%02x:%02x:%02x:%02x:%02x\n", + *((UINT8 *)(GetLanConfigReps + 1) + 0), + *((UINT8 *)(GetLanConfigReps + 1) + 1), + *((UINT8 *)(GetLanConfigReps + 1) + 2), + *((UINT8 *)(GetLanConfigReps + 1) + 3), + *((UINT8 *)(GetLanConfigReps + 1) + 4), + *((UINT8 *)(GetLanConfigReps + 1) + 5) + )); + IpmiLanMacAddressSize = sizeof (IPMI_LAN_MAC_ADDRESS); + CopyMem ((VOID *)&IpmiLanChannelMacAddress.Addr, (VOID *)(GetLanConfigReps + 1), IpmiLanMacAddressSize); + } + } + } + + if (IpmiLanMacAddressSize != 0) { + if (!AlreadyCached) { + // Cache this IPMI LAN channel. + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Cache this IPMI LAN channel.\n")); + CacheIpmiLanMac ((UINT8)ChannelNum, &IpmiLanChannelMacAddress, IpmiLanMacAddressSize); + } + + // + // According to design spec in Readme file under RedfishPkg. + // Compare the first five MAC address and + // the 6th MAC address. + // + if ((IpmiLanMacAddressSize != UsbNicInfo->MacAddressSize) || + (CompareMem ( + (VOID *)UsbNicInfo->MacAddress, + (VOID *)&IpmiLanChannelMacAddress.Addr, + IpmiLanMacAddressSize - 1 + ) != 0) || + (IpmiLanChannelMacAddress.Addr[IpmiLanMacAddressSize - 1] != + *(UsbNicInfo->MacAddress + IpmiLanMacAddressSize - 1) - 1) + ) + { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " MAC address is not matched.\n")); + continue; + } + + // This is the NIC exposed by BMC. + UsbNicInfo->IpmiLanChannelNumber = (UINT8)ChannelNum; + UsbNicInfo->IsExposedByBmc = TRUE; + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " MAC address is matched.\n")); + ExitStatus = EFI_SUCCESS; + break; + } + } + + if (GetLanConfigReps != NULL) { + FreePool (GetLanConfigReps); + } + + return ExitStatus; +} + +/** + This function searches the next MSG_USB_DP device path node. + + @param[in] ThisDevicePath Device path to search. + + @retval NULL MSG_USB_DP is not found. + Otherwise MSG_USB_DP is found. + +**/ +EFI_DEVICE_PATH_PROTOCOL * +UsbNicGetNextMsgUsbDp ( + IN EFI_DEVICE_PATH_PROTOCOL *ThisDevicePath + ) +{ + if (ThisDevicePath == NULL) { + return NULL; + } + + while (TRUE) { + ThisDevicePath = NextDevicePathNode (ThisDevicePath); + if (IsDevicePathEnd (ThisDevicePath)) { + return NULL; + } + + if ((ThisDevicePath->Type == MESSAGING_DEVICE_PATH) && (ThisDevicePath->SubType == MSG_USB_DP)) { + return ThisDevicePath; + } + } + + return NULL; +} + +/** + This function search the UsbIo handle that matches the UsbDevicePath. + + @param[in] UsbDevicePath Device path of this SNP handle. + @param[out] UsbIo Return the UsbIo protocol. + + @retval EFI_SUCCESS Yes, UsbIo protocl is found. + @retval EFI_NOT_FOUND No, UsbIo protocl is not found + @retval Others Other errors. + +**/ +EFI_STATUS +UsbNicSearchUsbIo ( + IN EFI_DEVICE_PATH_PROTOCOL *UsbDevicePath, + OUT EFI_USB_IO_PROTOCOL **UsbIo + ) +{ + EFI_STATUS Status; + UINTN BufferSize; + EFI_HANDLE *HandleBuffer; + UINT16 Length; + UINTN Index; + CHAR16 *DevicePathStr; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + EFI_DEVICE_PATH_PROTOCOL *ThisDevicePath; + EFI_DEVICE_PATH_PROTOCOL *ThisDevicePathEnd; + EFI_DEVICE_PATH_PROTOCOL *ThisUsbDevicePath; + EFI_DEVICE_PATH_PROTOCOL *ThisUsbDevicePathEnd; + + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "Device path on the EFI handle which has UsbIo and SNP instaleld on it.\n")); + DevicePathStr = ConvertDevicePathToText (UsbDevicePath, FALSE, FALSE); + if (DevicePathStr != NULL) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%s\n", DevicePathStr)); + FreePool (DevicePathStr); + } else { + DEBUG ((DEBUG_ERROR, "Failed to convert device path.\n")); + return EFI_INVALID_PARAMETER; + } + + BufferSize = 0; + HandleBuffer = NULL; + *UsbIo = NULL; + Status = gBS->LocateHandle ( + ByProtocol, + &gEfiUsbIoProtocolGuid, + NULL, + &BufferSize, + NULL + ); + if (Status == EFI_BUFFER_TOO_SMALL) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " %d UsbIo protocol instances.\n", BufferSize/sizeof (EFI_HANDLE))); + HandleBuffer = AllocateZeroPool (BufferSize); + if (HandleBuffer == NULL) { + DEBUG ((DEBUG_ERROR, " Falied to allocate buffer for the handles.\n")); + return EFI_OUT_OF_RESOURCES; + } + + Status = gBS->LocateHandle ( + ByProtocol, + &gEfiUsbIoProtocolGuid, + NULL, + &BufferSize, + HandleBuffer + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Falied to locate UsbIo protocol handles.\n")); + FreePool (HandleBuffer); + return Status; + } + } else { + return Status; + } + + for (Index = 0; Index < (BufferSize/sizeof (EFI_HANDLE)); Index++) { + Status = gBS->HandleProtocol ( + *(HandleBuffer + Index), + &gEfiDevicePathProtocolGuid, + (VOID **)&ThisDevicePath + ); + if (EFI_ERROR (Status)) { + continue; + } + + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "Device path on #%d instance of UsbIo.\n", Index)); + DevicePathStr = ConvertDevicePathToText (ThisDevicePath, FALSE, FALSE); + if (DevicePathStr != NULL) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%s\n", DevicePathStr)); + FreePool (DevicePathStr); + } else { + DEBUG ((DEBUG_ERROR, "Failed to convert device path on #%d instance of UsbIo.\n", Index)); + continue; + } + + Status = EFI_NOT_FOUND; + + // Search for the starting MSG_USB_DP node. + ThisUsbDevicePath = UsbDevicePath; + if ((DevicePathType (ThisUsbDevicePath) != MESSAGING_DEVICE_PATH) || + (DevicePathSubType (ThisUsbDevicePath) != MSG_USB_DP)) + { + ThisUsbDevicePath = UsbNicGetNextMsgUsbDp (ThisUsbDevicePath); + if (ThisUsbDevicePath == NULL) { + continue; + } + } + + if ((DevicePathType (ThisDevicePath) != MESSAGING_DEVICE_PATH) || + (DevicePathSubType (ThisDevicePath) != MSG_USB_DP)) + { + ThisDevicePath = UsbNicGetNextMsgUsbDp (ThisDevicePath); + if (ThisDevicePath == NULL) { + continue; + } + } + + // Search for the ending MSG_USB_DP node. + ThisDevicePathEnd = ThisDevicePath; + ThisUsbDevicePathEnd = ThisUsbDevicePath; + while (TRUE) { + TempDevicePath = UsbNicGetNextMsgUsbDp (ThisDevicePathEnd); + if (TempDevicePath == NULL) { + break; + } + + ThisDevicePathEnd = TempDevicePath; + } + + while (TRUE) { + TempDevicePath = UsbNicGetNextMsgUsbDp (ThisUsbDevicePathEnd); + if (TempDevicePath == NULL) { + break; + } + + ThisUsbDevicePathEnd = TempDevicePath; + } + + // Compare these two device paths + Length = (UINT16)((UINTN)(UINT8 *)ThisDevicePathEnd + DevicePathNodeLength (ThisDevicePathEnd) - (UINTN)(UINT8 *)ThisDevicePath); + if (Length != ((UINTN)(UINT8 *)ThisUsbDevicePathEnd + DevicePathNodeLength (ThisUsbDevicePathEnd) - (UINTN)(UINT8 *)ThisUsbDevicePath)) { + continue; + } + + if (CompareMem ( + (VOID *)ThisDevicePath, + (VOID *)ThisUsbDevicePath, + Length + ) == 0) + { + Status = EFI_SUCCESS; + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "EFI handle with the correct UsbIo is found at #%d instance of UsbIo.\n", Index)); + break; + } + } + + if (Status == EFI_SUCCESS) { + // Locate UsbIo from this handle. + Status = gBS->HandleProtocol ( + *(HandleBuffer + Index), + &gEfiUsbIoProtocolGuid, + (VOID **)UsbIo + ); + return Status; + } + + return EFI_NOT_FOUND; +} + +/** + This function identifies if the USB NIC is exposed by BMC as + the host-BMC channel. + + @param[in] Handle This is the EFI handle with SNP installed. + @param[in] UsbDevicePath USB device path. + + @retval EFI_SUCCESS Yes, USB NIC exposed by BMC is found. + @retval EFI_NOT_FOUND No, USB NIC exposed by BMC is not found + on the existing SNP handle. + @retval Others Other errors. + +**/ +EFI_STATUS +IdentifyUsbNicBmcChannel ( + IN EFI_HANDLE Handle, + IN EFI_DEVICE_PATH_PROTOCOL *UsbDevicePath + ) +{ + UINTN Index; + EFI_STATUS Status; + EFI_SIMPLE_NETWORK_PROTOCOL *Snp; + EFI_USB_IO_PROTOCOL *UsbIo; + HOST_INTERFACE_BMC_USB_NIC_INFO *BmcUsbNic; + + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + Status = gBS->HandleProtocol ( + Handle, + &gEfiSimpleNetworkProtocolGuid, + (VOID **)&Snp + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Failed to locate SNP.\n")); + return Status; + } + + Status = UsbNicSearchUsbIo (UsbDevicePath, &UsbIo); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Failed to find USBIO.\n")); + return Status; + } + + // Get the MAC address of this SNP instance. + BmcUsbNic = AllocateZeroPool (sizeof (HOST_INTERFACE_BMC_USB_NIC_INFO)); + if (BmcUsbNic == NULL) { + DEBUG ((DEBUG_ERROR, " Failed to allocate memory for HOST_INTERFACE_BMC_USB_NIC_INFO.\n")); + return EFI_OUT_OF_RESOURCES; + } + + InitializeListHead (&BmcUsbNic->NextInstance); + BmcUsbNic->MacAddressSize = Snp->Mode->HwAddressSize; + BmcUsbNic->MacAddress = AllocateZeroPool (sizeof (BmcUsbNic->MacAddressSize)); + if (BmcUsbNic->MacAddress == NULL) { + DEBUG ((DEBUG_ERROR, " Failed to allocate memory for HW MAC addresss.\n")); + FreePool (BmcUsbNic); + return EFI_OUT_OF_RESOURCES; + } + + CopyMem ( + (VOID *)BmcUsbNic->MacAddress, + (VOID *)&Snp->Mode->CurrentAddress, + BmcUsbNic->MacAddressSize + ); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " MAC address (in size %d) for this SNP instance:\n ", BmcUsbNic->MacAddressSize)); + for (Index = 0; Index < BmcUsbNic->MacAddressSize; Index++) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%02x ", *(BmcUsbNic->MacAddress + Index))); + } + + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "\n")); + BmcUsbNic->ThisSnp = Snp; + BmcUsbNic->ThisUsbIo = UsbIo; + + Status = HostInterfaceIpmiCheckMacAddress (BmcUsbNic); + if (Status == EFI_SUCCESS) { + BmcUsbNic->IsExposedByBmc = TRUE; + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " BMC exposed USB NIC is found.\n")); + } else { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " BMC exposed USB NIC is not found.\n")); + } + + InsertTailList (&mBmcUsbNic, &BmcUsbNic->NextInstance); + return Status; +} + +/** + This function checks if the USB NIC exposed by BMC + on each handle has SNP protocol installed on it. + + @param[in] HandleNumer Number of handles to check. + @param[in] HandleBuffer Handles buffer. + + @retval EFI_SUCCESS Yes, USB NIC exposed by BMC is found. + @retval EFI_NOT_FOUND No, USB NIC exposed by BMC is not found + on the existing SNP handle. + @retval Others Other errors. + +**/ +EFI_STATUS +CheckBmcUsbNicOnHandles ( + IN UINTN HandleNumer, + IN EFI_HANDLE *HandleBuffer + ) +{ + UINTN Index; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + BOOLEAN GotOneUsbNIc; + + if ((HandleNumer == 0) || (HandleBuffer == NULL)) { + return EFI_INVALID_PARAMETER; + } + + DEBUG ((DEBUG_INFO, "%a: Entry, #%d SNP handle\n", __FUNCTION__, HandleNumer)); + + GotOneUsbNIc = FALSE; + for (Index = 0; Index < HandleNumer; Index++) { + Status = gBS->HandleProtocol ( + *(HandleBuffer + Index), + &gEfiDevicePathProtocolGuid, + (VOID **)&DevicePath + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Failed to locate SNP on %d handle.\n", __FUNCTION__, Index)); + continue; + } + + // Check if this is an BMC exposed USB NIC device. + while (TRUE) { + if ((DevicePath->Type == MESSAGING_DEVICE_PATH) && (DevicePath->SubType == MSG_USB_DP)) { + Status = IdentifyUsbNicBmcChannel (*(HandleBuffer + Index), DevicePath); + if (!EFI_ERROR (Status)) { + GotOneUsbNIc = TRUE; + break; + } + } + + DevicePath = NextDevicePathNode (DevicePath); + if (IsDevicePathEnd (DevicePath)) { + break; + } + } + } + + if (GotOneUsbNIc) { + return EFI_SUCCESS; + } + + return EFI_NOT_FOUND; +} + +/** + This function checks if the USB NIC exposed by BMC + is already connected. + + @param[in] Registration Locate SNP protocol from the notification + registeration key. + NULL means locate SNP protocol from the existing + handles. + + @retval EFI_SUCCESS Yes, USB NIC exposed by BMC is found. + @retval EFI_NOT_FOUND No, USB NIC exposed by BMC is not found + on the existing SNP handle. + @retval Others Other errors. + +**/ +EFI_STATUS +CheckBmcUsbNic ( + VOID *Registration + ) +{ + EFI_STATUS Status; + EFI_HANDLE Handle; + UINTN BufferSize; + EFI_HANDLE *HandleBuffer; + + DEBUG ((DEBUG_INFO, "%a: Entry, the registration key - 0x%08x.\n", __FUNCTION__, Registration)); + + Handle = NULL; + Status = EFI_SUCCESS; + BufferSize = 0; + + Status = gBS->LocateHandle ( + Registration == NULL ? ByProtocol : ByRegisterNotify, + &gEfiSimpleNetworkProtocolGuid, + Registration, + &BufferSize, + NULL + ); + if (Status == EFI_BUFFER_TOO_SMALL) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " %d SNP protocol instances.\n", BufferSize/sizeof (EFI_HANDLE))); + HandleBuffer = AllocateZeroPool (BufferSize); + if (HandleBuffer == NULL) { + DEBUG ((DEBUG_ERROR, " Falied to allocate buffer for the handles.\n")); + return EFI_OUT_OF_RESOURCES; + } + + Status = gBS->LocateHandle ( + Registration == NULL ? ByProtocol : ByRegisterNotify, + &gEfiSimpleNetworkProtocolGuid, + Registration, + &BufferSize, + HandleBuffer + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Falied to locate SNP protocol handles.\n")); + FreePool (HandleBuffer); + return Status; + } + } else if (EFI_ERROR (Status)) { + return Status; + } + + // Check USB NIC on handles. + Status = CheckBmcUsbNicOnHandles (BufferSize/sizeof (EFI_HANDLE), HandleBuffer); + if (!EFI_ERROR (Status)) { + // Retrieve the rest of BMC USB NIC information for Redfish over IP information + // and USB Network Interface V2. + Status = RetrievedBmcUsbNicInfo (); + if (!EFI_ERROR (Status)) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Install protocol to notify the platform Redfish Host Interface information is ready.\n")); + Status = gBS->InstallProtocolInterface ( + &Handle, + &mPlatformHostInterfaceBmcUsbNicReadinessGuid, + EFI_NATIVE_INTERFACE, + NULL + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, " Install protocol fail %r.\n", Status)); + } + } + } + + FreePool (HandleBuffer); + return Status; +} + +/** + Notification event of SNP readiness. + + @param[in] Event Event whose notification function is being invoked. + @param[in] Context The pointer to the notification function's context, + which is implementation-dependent. + +**/ +VOID +EFIAPI +PlatformHostInterfaceSnpCallback ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + + CheckBmcUsbNic (mPlatformHostInterfaceSnpRegistration); + return; +} + +/** + Get the EFI protocol GUID installed by platform library which + indicates the necessary information is ready for building + SMBIOS 42h record. + + @param[out] InformationReadinessGuid Pointer to retrive the protocol + GUID. + + @retval EFI_SUCCESS Notification is required for building up + SMBIOS type 42h record. + @retval EFI_UNSUPPORTED Notification is not required for building up + SMBIOS type 42h record. + @retval EFI_ALREADY_STARTED Platform host information is already ready. + @retval Others Other errors. +**/ +EFI_STATUS +RedfishPlatformHostInterfaceNotification ( + OUT EFI_GUID **InformationReadinessGuid + ) +{ + EFI_STATUS Status; + + DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + + *InformationReadinessGuid = NULL; + InitializeListHead (&mBmcUsbNic); + InitializeListHead (&mBmcIpmiLan); + + // + // Check if USB NIC exposed by BMC is already + // connected. + // + Status = CheckBmcUsbNic (NULL); + if (!EFI_ERROR (Status)) { + return EFI_ALREADY_STARTED; + } + + if (Status == EFI_NOT_FOUND) { + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%a: BMC USB NIC is not found. Register the notification.\n", __FUNCTION__)); + + // Register the notification of SNP installation. + Status = gBS->CreateEvent ( + EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + PlatformHostInterfaceSnpCallback, + NULL, + &mPlatformHostInterfaceSnpEvent + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Fail to create event for the installation of SNP protocol.", __FUNCTION__)); + return Status; + } + + Status = gBS->RegisterProtocolNotify ( + &gEfiSimpleNetworkProtocolGuid, + mPlatformHostInterfaceSnpEvent, + &mPlatformHostInterfaceSnpRegistration + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Fail to register event for the installation of SNP protocol.", __FUNCTION__)); + return Status; + } + + *InformationReadinessGuid = &mPlatformHostInterfaceBmcUsbNicReadinessGuid; + return EFI_SUCCESS; + } + + DEBUG ((DEBUG_ERROR, "%a: Something wrong when look for BMC USB NIC.\n", __FUNCTION__)); + return Status; +} diff --git a/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.h b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.h new file mode 100644 index 0000000000..669c304fc3 --- /dev/null +++ b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.h @@ -0,0 +1,84 @@ +/** @file + Header file to provide the platform Redfish Host Interface information + of USB NIC Device exposed by BMC. + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef PLATFORM_HOST_INTERFACE_BMC_USB_NIC_LIB_H_ +#define PLATFORM_HOST_INTERFACE_BMC_USB_NIC_LIB_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define BMC_USB_NIC_HOST_INTERFASCE_READINESS_GUID \ + { \ + 0xDD96F5D7, 0x4AE1, 0x4E6C, {0xA1, 0x30, 0xA5, 0xAC, 0x77, 0xDD, 0xE4, 0xA5} \ + } + +// +// This is the structure for BMC exposed +// USB NIC information. +// +typedef struct { + LIST_ENTRY NextInstance; ///< Link to the next instance. + BOOLEAN IsExposedByBmc; ///< Flag indicates this USB NIC is + ///< exposed by BMC. + BOOLEAN IsSuppportedHostInterface; ///< This BMC USB NIC is supported + ///< as Redfish host interface + EFI_SIMPLE_NETWORK_PROTOCOL *ThisSnp; ///< The SNP instance associated with + ///< this USB NIC. + EFI_USB_IO_PROTOCOL *ThisUsbIo; ///< The USBIO instance associated with + ///< this USB NIC. + UINT16 UsbVendorId; ///< USB Vendor ID of this BMC exposed USB NIC. + UINT16 UsbProductId; ///< USB Product ID of this BMC exposed USB NIC. + UINTN MacAddressSize; ///< HW address size. + UINT8 *MacAddress; ///< HW address. + UINT8 IpmiLanChannelNumber; ///< BMC IPMI Lan Channel number. + + // + // Below is the infortmation for building SMBIOS type 42. + // + UINT8 IpAssignedType; ///< Redfish service IP assign type. + UINT8 IpAddressFormat; ///< Redfish service IP version. + UINT8 HostIpAddressIpv4[4]; ///< Host IP address. + UINT8 RedfishIpAddressIpv4[4]; ///< Redfish service IP address. + UINT8 SubnetMaskIpv4[4]; ///< Subnet mask. + UINT8 GatewayIpv4[4]; ///< Gateway IP address. + UINT16 VLanId; ///< VLAN ID. + BOOLEAN CredentialBootstrapping; ///< If Credential bootstrapping is + ///< supported. +} HOST_INTERFACE_BMC_USB_NIC_INFO; + +// +// This is the structure for caching +// BMC IPMI LAN Channel +// +typedef struct { + LIST_ENTRY NextInstance; ///< Link to the next IPMI LAN Channel. + UINT8 Channel; ///< IPMI Channel number. + EFI_MAC_ADDRESS MacAddress; ///< IPMI LAN Channel MAC address. + UINT8 MacAddressSize; ///< MAC address size; +} BMC_IPMI_LAN_CHANNEL_INFO; +#endif diff --git a/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf new file mode 100644 index 0000000000..f2c7d7fec8 --- /dev/null +++ b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf @@ -0,0 +1,48 @@ +## @file +# Module to provide the platform Redfish Host Interface information +# of USB NIC Device exposed by BMC. +# +# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001000b + BASE_NAME = PlatformHostInterfaceBmcUsbNicLib + FILE_GUID = C4837B58-225E-4352-8FDC-4C52A5D65891 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = PlatformHostInterfaceBmcUsbNicLib + +[Sources] + PlatformHostInterfaceBmcUsbNicLib.c + PlatformHostInterfaceBmcUsbNicLib.h + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + NetworkPkg/NetworkPkg.dec + RedfishPkg/RedfishPkg.dec + +[LibraryClasses] + BaseMemoryLib + DebugLib + IpmiLib + IpmiCommandLib + MemoryAllocationLib + UefiLib + UefiBootServicesTableLib + +[Protocols] + gEfiSimpleNetworkProtocolGuid ## CONSUMED + gEfiUsbIoProtocolGuid ## CONSUMED + gEfiDevicePathProtocolGuid ## CONSUMED + +[Pcd] + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishHostName ## CONSUMED + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishServiceUuid ## CONSUMED + +[Depex] + gIpmiProtocolGuid diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index 53e52c2b00..42d28d6dac 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -113,3 +113,13 @@ # Default is set to not add. # gEfiRedfishPkgTokenSpaceGuid.PcdRedfishRestExAddingExpect|FALSE|BOOLEAN|0x00001004 + # + # Use PCD to declare the Redfish host nmae becasue there is no + # specification for that. + # + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishHostName|"Redfish service"|VOID*|0x00001005 + # + # Use PCD to declare the Redfish service UUID becasue there is no + # specification for that. + # + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishServiceUuid|L"00000000-0000-0000-0000-000000000000"|VOID*|0x00001006 From d7df84c7246f085866eae43f86b91c497ea7f5a0 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Tue, 27 Dec 2022 10:55:27 +0800 Subject: [PATCH 0708/1529] RedfishPkg: Update Redfish DSC Update Redfish DSC for PlatformHostInterfaceBmcUsbNicLib. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Nickle Wang --- RedfishPkg/RedfishPkg.dsc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/RedfishPkg/RedfishPkg.dsc b/RedfishPkg/RedfishPkg.dsc index cf25b63cc2..223ab72c1d 100644 --- a/RedfishPkg/RedfishPkg.dsc +++ b/RedfishPkg/RedfishPkg.dsc @@ -3,6 +3,7 @@ # # Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2021 Hewlett-Packard Enterprise Development LP. +# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -34,6 +35,7 @@ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf RedfishPlatformHostInterfaceLib|RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.inf + RedfishPlatformHostInterfaceLib|RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf HttpLib|NetworkPkg/Library/DxeHttpLib/DxeHttpLib.inf HttpIoLib|NetworkPkg/Library/DxeHttpIoLib/DxeHttpIoLib.inf NetLib|NetworkPkg/Library/DxeNetLib/DxeNetLib.inf @@ -41,6 +43,10 @@ RedfishPlatformCredentialLib|RedfishPkg/Library/PlatformCredentialLibNull/PlatformCredentialLibNull.inf RedfishContentCodingLib|RedfishPkg/Library/RedfishContentCodingLibNull/RedfishContentCodingLibNull.inf + # NULL instance of IPMI related library. + IpmiLib|MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.inf + IpmiCommandLib|MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf + [LibraryClasses.ARM, LibraryClasses.AARCH64] # # This library provides the instrinsic functions generated by a given compiler. @@ -51,6 +57,7 @@ [Components] RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.inf + RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf RedfishPkg/Library/PlatformCredentialLibNull/PlatformCredentialLibNull.inf RedfishPkg/Library/RedfishContentCodingLibNull/RedfishContentCodingLibNull.inf RedfishPkg/Library/DxeRestExLib/DxeRestExLib.inf From 42e880b8d568c55d9bcc0ba53e40f69d567607bc Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Sat, 7 Jan 2023 23:23:37 +0800 Subject: [PATCH 0709/1529] RedfishPkg: Update Readme.md Update readme.md and add figures to delineate the relationship of edk2 Redfish, USB NIC and IPMI. Signed-off-by: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Reviewed-by: Nickle Wang --- .../Documents/Media/BmcExposedUsbNic.svg | 283 +++++++++++++++ .../Media/EmualtorPlatformLibrary.svg | 286 +++++++++++++++ .../Media/PlatformWihtBmcLibrary.svg | 328 ++++++++++++++++++ RedfishPkg/Readme.md | 112 +++++- 4 files changed, 1001 insertions(+), 8 deletions(-) create mode 100644 RedfishPkg/Documents/Media/BmcExposedUsbNic.svg create mode 100644 RedfishPkg/Documents/Media/EmualtorPlatformLibrary.svg create mode 100644 RedfishPkg/Documents/Media/PlatformWihtBmcLibrary.svg diff --git a/RedfishPkg/Documents/Media/BmcExposedUsbNic.svg b/RedfishPkg/Documents/Media/BmcExposedUsbNic.svg new file mode 100644 index 0000000000..c7088eb8d5 --- /dev/null +++ b/RedfishPkg/Documents/Media/BmcExposedUsbNic.svg @@ -0,0 +1,283 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + EDKII Network Stacks(UEFI Driver Model) + + + + + + + + EFI REST EX(UEFI Driver Model) + + + + + + + + BMC ExposedUSB Network Interface Device + + + + + + + + + + Redfish Service + + + + + + + + + + + + + + + + + + + + EDKII Redfish Host Interface(DXE Driver) + + + + + + BMC + + + + + + On Network + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + EDKII Redfish Credential(DXE Driver) + + + + + + + + + + + + + + + + + + + + + + EDKII USB Stacks(UEFI Driver Model) + + + + + + + + + + + + + + + + + + + + + + EFI Redfish Discovery(UEFI Driver Model) + + + + + + + + diff --git a/RedfishPkg/Documents/Media/EmualtorPlatformLibrary.svg b/RedfishPkg/Documents/Media/EmualtorPlatformLibrary.svg new file mode 100644 index 0000000000..33aa6c79df --- /dev/null +++ b/RedfishPkg/Documents/Media/EmualtorPlatformLibrary.svg @@ -0,0 +1,286 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Redfish Service + + + + + + + + + + + + On Network + + + + + + + + EDKII Redfish Credential(DXE Driver) + + + + + + + + EDKII Redfish Host Interface(DXE Driver) + + + + + + + + Platform Redfish Credential Library + + + + + + + + Platform Redfish Host Interface Library + + + + + + EmulatorPkg Library Instance + + + + + + EmulatorPkg Library Instance + + + + + + + + + + + + + + + + + + + + + EFI Variable + + + + + + + + + + + + + + + RedfishPlatformConfg.efi + + + + + + + + + + + + + Information of SMBIOS 42 Record + + + + + + Hardcoded Redfish Credential + + + + + + Redfish Profile Simulator + + + + + + + + + + + + + + + + + diff --git a/RedfishPkg/Documents/Media/PlatformWihtBmcLibrary.svg b/RedfishPkg/Documents/Media/PlatformWihtBmcLibrary.svg new file mode 100644 index 0000000000..e52d8478a8 --- /dev/null +++ b/RedfishPkg/Documents/Media/PlatformWihtBmcLibrary.svg @@ -0,0 +1,328 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Redfish Service + + + + + + + + + + + + On Network + + + + + + + + EDKII Redfish Credential(DXE Driver) + + + + + + + + EDKII Redfish Host Interface(DXE Driver) + + + + + + + + Platform Redfish Credential Library + + + + + + + + Platform Redfish Host Interface Library + + + + + + Platform with BMC Library Instance + + + + + + + + + + + + + + + + + + + + Send IPMI NetFn App and IPMI NetFn Transprort commands to acquire the network Information to build up SMBIOS 42 Record + + + + + + Platform with BMC Library Instance + + + + + + + + + + + + BMC + + + + + + + + IpmiCommandLibrary + + + + + + + + IpmiTransportProtocol + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + BMC ExposedUSB Network Interface Device + + + + + + + + + + + + + Get Redfish Credential using IPMI Group Extension (Body code 52h for Redfish) + + + + + + + + diff --git a/RedfishPkg/Readme.md b/RedfishPkg/Readme.md index a0e9f0892c..7defe78eb1 100644 --- a/RedfishPkg/Readme.md +++ b/RedfishPkg/Readme.md @@ -50,12 +50,107 @@ The library is incorporated with RedfishLib ***[[13]](#[0])*** to encode and dec * **RedfishPkg\Library\JsonLib** ***[[14]](#[0])*** This is the wrapper of open source project ***[Jansson](https://digip.org/jansson)***, which is the library that provides APIs to manipulate JSON payload. -## Platform Components for EDK2 EmulatorPkg: - * **RedfishPlatformCredentialLib** - the EDK2 Emulator platform implementation of acquiring credential to build up the communication between UEFI firmware and Redfish service. ***[[10]](#[0])*** - - * **RedfishPlatformHostInterfaceLib** - EDK2 Emulator platform implementation which provides the information of building up SMBIOS type 42h record. ***[[11]](#[0])*** +## Platform Components +### **EDK2 EmulatorPkg** +![EDK2 EmulatorPkg Figure](https://github.com/tianocore/edk2/blob/master/RedfishPkg/Documents/Media/EmualtorPlatformLibrary.svg?raw=true) + + * **RedfishPlatformCredentialLib**
+ The EDK2 Emulator platform implementation of acquiring credential to build up the communication between + UEFI firmware and Redfish service. ***[[10]](#[0])*** + + The Redfish credential is hardcoded in the EmulatorPkg RedfishPlatformCredentialLib. The credential is + used to access to the Redfish service hosted by [Redfish Profile Simulator](https://github.com/DMTF/Redfish-Profile-Simulator). + + * **RedfishPlatformHostInterfaceLib**
+ EDK2 Emulator platform implementation which provides the information of building up SMBIOS type 42h + record. ***[[11]](#[0])*** + + EmulatorPkg RedfishPlatformHostInterfaceLib library consumes the EFI Variable which is created + by [RedfishPlatformConfig EFI application](https://github.com/tianocore/edk2/tree/master/EmulatorPkg/Application/RedfishPlatformConfig). RedfishPlatformConfig EFI application stores not all of SMBIOS + Type42 record information but the necessary network properties of Redfish Host Interface in EFI + Variable. + +### **Platform with BMC and the BMC-Exposed USB Network Device** +![Platform with BMC Figure](https://github.com/tianocore/edk2/blob/master/RedfishPkg/Documents/Media/BmcExposedUsbNic.svg?raw=true) + +Server platform with BMC as the server management entity may expose the [USB Network Interface Device (NIC)](https://www.usb.org/document-library/class-definitions-communication-devices-12) +to the platform, which is so called the in-band host-BMC transport interface. The USB NIC exposed by BMC is +usually a link-local network device which has two network endpoints at host and BMC ends. The endpoint at +host side is connected to the platform USB port, and it is enumerated by edk2 USB BUS driver. The edk2 USB +NIC driver then produces the **EFI Network Interface Identifier Protocol** +*(EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL_GUID_31)* and connected by EFI Simple +Network Protocol (SNP) driver and the upper layer edk2 network drivers. The applications can then utilize +the network stack built up on top of USB NIC to communicate with Redfish service hosted by BMC.
+BMC-exposed USB NIC is mainly designed for the communication between host and BMC-hosted Redfish service. +BMC-exposed USB NIC can be public to host through [Redfish Host Interface Specification](https://www.dmtf.org/sites/default/files/standards/documents/DSP0270_1.3.0.pdf) and discovered by edk2 Redfish discovery +driver. The [Redfish Host Interface Specification](https://www.dmtf.org/sites/default/files/standards/documents/DSP0270_1.3.0.pdf) describes the dedicated host interface between host and +BMC. The specification follows the [SMBIOS Type 42 format](https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.6.0.pdf) and defines the host interface as: +- Network Host Interface type (40h) +- Redfish over IP Protocol (04h) + +
+ +![Platform BMC Library Figure](https://github.com/tianocore/edk2/blob/master/RedfishPkg/Documents/Media/PlatformWihtBmcLibrary.svg?raw=true) + + * **RedfishPlatformCredentialLib**
+RedfishPlatformCredentialLib library instance on the platform with BMC uses Redfish Credential +Bootstrapping IPMI commands defined in [Redfish Host Interface Specification](https://www.dmtf.org/sites/default/files/standards/documents/DSP0270_1.3.0.pdf) to acquire the Redfish credential from BMC. edk2 +Redfish firmware then uses this credential to access to Redfish service hosted by BMC. + + * **RedfishPlatformHostInterfaceLib**
+BMC-exposed USB NIC, a IPMI Message channel is reported by BMC as a "IPMB-1.0" protocol and "802.3 LAN" +medium channel. edk2 firmware can issue a series of IPMI commands to acquire the channel +application information (NetFn App), transport network properties (NetFn Transport) and other necessary +information to build up the SMBIOS type 42h record. +In order to recognize the specific BMC-exposed USB NIC in case the platform has more than one USB NIC +devices attached, the MAC address specified in the EFI Device Path Protocol of SNP EFI handle is used to +match with the MAC address of IPMI message channel. Due to the network information such as the MAC +address, IP address, Subnet mask and Gateway are assigned by BMC, edk2 Redfish implementation needs a +programmatic way to recognize the BMC-exposed USB NIC. + + * **MAC address:** Searching for the BMC-exposed USB NIC
+ The last byte of host-end USB NIC MAC address is the last byte of BMC-end USB NIC MAC address minus 1. + RedfishPlatformHostInterfaceLib issues the NetFn Transport IPMI command to get the MAC address of each + channel and checks them with the MAC address specified in the EFI Device Path Protocol.
+ + **_For example:_**
+ BMC-end USB NIC MAC address: 11-22-33-44-55-00
+ Host-end USB NIC MAC address: 11-22-33-44-55-ff + + * **IP Address:** Acquiring the host-end USB NIC IP Address
+ The last byte of host-end USB NIC IPv4 address is the last byte of BMC-end USB NIC IPv4 address minus 1. + + **_For example:_**
+ BMC-end USB NIC IPv4 address: 165.10.0.10
+ Host-end USB NIC IPv4 address: 165.10.0.9 + + * **Other Network Properties**:
+ Due to the host-end USB NIC and BMC-end USB NIC is a link-local network. Both of them have the same + network properties such as subnet mask and gateway. RedfishPlatformHostInterfaceLib issues the NetFn + Transport IPMI command to get the network properties of BMC-end USB NIC and apply it on host-end USB + NIC. + + * **IPMI Commands that Used to Build up Redfish Host Interface** + + Standard IPMI commands those are used to build up the Redfish Host Interface for BMC-exposed USB NIC. + The USB NIC exposed by BMC must be reported as one of the message channels as 802.3 LAN/IPMB 1.0 message + channel. + + | IPMI NetFn | IPMI Command| Purpose | Corresponding Host Interface Field| + |------------|-------------|---------|-----------------------------------| + | App
(0x06) | 0x42 | Check the message channel's medium type and protocol.
Medium: 802.3 LAN
Protocol: IPMB 1.0| None| + | Transport
(0x0C) | 0x02 | Get MAC address of message channel. Used to match with the MAC address populated in EFI Device Path of network device| None| + | Group Ext
(0x2C) | Group Extension ID: 0x52
Command: 0x02 | Check if Redfish bootstrap credential is supported or not.| In Device Descriptor Data, Credential Bootstrapping Handle| + | Transport
(0x0C) | Command: 0x02
Parameter: 0x04 | Get BMC-end message channel IP address source| In Protocol Specific Record Data
- Host IP Assignment Type
- Redfish Service IP Discovery Type
- Generate the Host-side IP address|. + | Transport
(0x0C) | Command: 0x02
Parameter: 0x03 | Get BMC-end message channel IPv4 address| In Protocol Specific Record Data
- Host IP Address Format
- Host IP Address| + | Transport
(0x0C) | Command: 0x02
Parameter: 0x06 | Get BMC-end message channel IPv4 subnet mask| In Protocol Specific Record Data
- Host IP Mask
- Redfish Service IP Mask| + | Transport
(0x0C) | Command: 0x02
Parameter: 0x12 | Get BMC-end message channel gateway IP address| None, used to configure edk2 network configuration| + | Transport
(0x0C) | Command: 0x02
Parameter: 0x14 | Get BMC-end message channel VLAN ID| In Protocol Specific Record Data
Redfish Service VLAN ID| + + **__NOTE__** +``` +Current RedfishPlatformHostInterfaceLib implementation of BMC-exposed USB NIC can only support IPv4 address format. +``` ## Miscellaneous: @@ -65,7 +160,6 @@ The library is incorporated with RedfishLib ***[[13]](#[0])*** to encode and dec For example, run shell command "RedfishPlatformConfig.efi -s 192.168.10.101 255.255.255.0 192.168.10.123 255.255.255.0", which means the source IP address is 192.168.10.101, and the Redfish Server IP address is 192.168.10.123. ``` - * **Redfish Profile Simulator** Refer to [Redfish Profile Simulator](https://github.com/DMTF/Redfish-Profile-Simulator) to set up the Redfish service. We are also in the progress to contribute bug fixes and enhancements to the mainstream Redfish Profile Simulator in order to incorporate with EDK2 Redfish solution. @@ -121,7 +215,9 @@ The library is incorporated with RedfishLib ***[[13]](#[0])*** to encode and dec 1. [DSP0270](https://www.dmtf.org/sites/default/files/standards/documents/DSP0270_1.3.0.pdf) - Redfish Host Interface Specification, 1.3.0 2. [DSP0266](https://www.dmtf.org/sites/default/files/standards/documents/DSP0266_1.12.0.pdf) - Redfish Specification, 1.12.0 3. Redfish Schemas - https://redfish.dmtf.org/schemas/v1/ -4. UEFI Specification - http://uefi.org/specifications +4. SMBIOS - https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.6.0.pdf +5. USB CDC - https://www.usb.org/document-library/class-definitions-communication-devices-12 +6. UEFI Specification - http://uefi.org/specifications ## The Contributors Thanks to the below predecessors who contributed to the UEFI EDK2 Redfish Prove of Concept code.\ From f5571a6c26c27c5f56e9ae8da693216b3ec5ff2b Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 3 Mar 2023 18:35:53 +0800 Subject: [PATCH 0710/1529] SecurityPkg/DxeImageVerificationLib: Check result of GetEfiGlobalVariable2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Call gRT->GetVariable() directly to read the SecureBoot variable. It is one byte in size so we can easily place it on the stack instead of having GetEfiGlobalVariable2() allocate it for us, which avoids a few possible error cases. Skip secure boot checks if (and only if): (a) the SecureBoot variable is not present (EFI_NOT_FOUND) according to the return value, or (b) the SecureBoot variable was read successfully and is set to SECURE_BOOT_MODE_DISABLE. Previously the code skipped the secure boot checks on *any* gRT->GetVariable() error (GetEfiGlobalVariable2 sets the variable value to NULL in that case) and also on memory allocation failures. Fixes: CVE-2019-14560 Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=2167 Signed-off-by: Gerd Hoffmann Suggested-by: Marvin Häuser Reviewed-by: Min Xu Reviewed-by: Jiewen Yao --- .../DxeImageVerificationLib.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c index 66e2f5eaa3..b3d40c21e9 100644 --- a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c +++ b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c @@ -1671,7 +1671,8 @@ DxeImageVerificationHandler ( EFI_IMAGE_EXECUTION_ACTION Action; WIN_CERTIFICATE *WinCertificate; UINT32 Policy; - UINT8 *SecureBoot; + UINT8 SecureBoot; + UINTN SecureBootSize; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; UINT32 NumberOfRvaAndSizes; WIN_CERTIFICATE_EFI_PKCS *PkcsCertData; @@ -1686,6 +1687,8 @@ DxeImageVerificationHandler ( RETURN_STATUS PeCoffStatus; EFI_STATUS HashStatus; EFI_STATUS DbStatus; + EFI_STATUS VarStatus; + UINT32 VarAttr; BOOLEAN IsFound; SignatureList = NULL; @@ -1742,24 +1745,26 @@ DxeImageVerificationHandler ( CpuDeadLoop (); } - GetEfiGlobalVariable2 (EFI_SECURE_BOOT_MODE_NAME, (VOID **)&SecureBoot, NULL); + SecureBootSize = sizeof (SecureBoot); + VarStatus = gRT->GetVariable (EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid, &VarAttr, &SecureBootSize, &SecureBoot); // // Skip verification if SecureBoot variable doesn't exist. // - if (SecureBoot == NULL) { + if (VarStatus == EFI_NOT_FOUND) { return EFI_SUCCESS; } // // Skip verification if SecureBoot is disabled but not AuditMode // - if (*SecureBoot == SECURE_BOOT_MODE_DISABLE) { - FreePool (SecureBoot); + if ((VarStatus == EFI_SUCCESS) && + (VarAttr == (EFI_VARIABLE_BOOTSERVICE_ACCESS | + EFI_VARIABLE_RUNTIME_ACCESS)) && + (SecureBoot == SECURE_BOOT_MODE_DISABLE)) + { return EFI_SUCCESS; } - FreePool (SecureBoot); - // // Read the Dos header. // From 57155adc4380166615258de77642392f96dee7cd Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 10 Mar 2023 20:48:48 +0800 Subject: [PATCH 0711/1529] UefiCpuPkg/PiSmmCpuDxeSmm: drop support for obsolete processors It's highly unlikely the code ever runs on processors which are almost 30 years old. Drop the code handling them. Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4345 Signed-off-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index d2d0950f3b..55a9f79da8 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -871,24 +871,14 @@ PiCpuSmmEntry ( // DEBUG ((DEBUG_INFO, "PiCpuSmmEntry: gSmmBaseHobGuid not found!\n")); // - // Allocate buffer for all of the tiles. + // very old processors (i486 + pentium) need 32k not 4k alignment, exclude them. // - // Intel(R) 64 and IA-32 Architectures Software Developer's Manual - // Volume 3C, Section 34.11 SMBASE Relocation - // For Pentium and Intel486 processors, the SMBASE values must be - // aligned on a 32-KByte boundary or the processor will enter shutdown - // state during the execution of a RSM instruction. + ASSERT (FamilyId >= 6); // - // Intel486 processors: FamilyId is 4 - // Pentium processors : FamilyId is 5 + // Allocate buffer for all of the tiles. // BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)); - if ((FamilyId == 4) || (FamilyId == 5)) { - Buffer = AllocateAlignedCodePages (BufferPages, SIZE_32KB); - } else { - Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); - } - + Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); ASSERT (Buffer != NULL); DEBUG ((DEBUG_INFO, "New Allcoated SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE (BufferPages))); } From d980ca1ee46cb7ad3dfa2512c972e050669cbec0 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 10 Mar 2023 20:48:49 +0800 Subject: [PATCH 0712/1529] UefiCpuPkg/PiSmmCpuDxeSmm: fix error handling ASSERT() is not proper handling of allocation failures, it gets compiled out on RELEASE builds. Print a message and enter dead loop instead. Signed-off-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index 55a9f79da8..cf69161caa 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -879,6 +879,12 @@ PiCpuSmmEntry ( // BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)); Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); + if (Buffer == NULL) { + DEBUG ((DEBUG_ERROR, "Failed to allocate %d pages.\n", BufferPages)); + CpuDeadLoop (); + return EFI_OUT_OF_RESOURCES; + } + ASSERT (Buffer != NULL); DEBUG ((DEBUG_INFO, "New Allcoated SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE (BufferPages))); } From 5fae4f5f34df17b74ed6aa8ab53c7df7c4530fee Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Fri, 17 Mar 2023 13:19:21 +0100 Subject: [PATCH 0713/1529] OvmfPkg/PlatformBootManagerLib: use utf8 for the serial console. Time to leave behind relics from the last century and arrive in the modern world. Drop PC-ANSI Terminal Type for the serial console, use UTF-8 instead. Signed-off-by: Gerd Hoffmann --- OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.h | 4 ++-- OvmfPkg/Library/PlatformBootManagerLib/PlatformData.c | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.h b/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.h index 1676d61616..18b3deb9db 100644 --- a/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.h +++ b/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.h @@ -126,7 +126,7 @@ extern VENDOR_DEVICE_PATH gTerminalTypeDeviceNode; 1 \ } -#define gPcAnsiTerminal \ +#define gVtUtf8Terminal \ { \ { \ MESSAGING_DEVICE_PATH, \ @@ -136,7 +136,7 @@ extern VENDOR_DEVICE_PATH gTerminalTypeDeviceNode; (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) \ } \ }, \ - DEVICE_PATH_MESSAGING_PC_ANSI \ + DEVICE_PATH_MESSAGING_VT_UTF8 \ } #define gEndEntire \ diff --git a/OvmfPkg/Library/PlatformBootManagerLib/PlatformData.c b/OvmfPkg/Library/PlatformBootManagerLib/PlatformData.c index 6536d9fe36..c1801725c2 100644 --- a/OvmfPkg/Library/PlatformBootManagerLib/PlatformData.c +++ b/OvmfPkg/Library/PlatformBootManagerLib/PlatformData.c @@ -47,7 +47,7 @@ typedef struct { ACPI_HID_DEVICE_PATH gPnpPs2KeyboardDeviceNode = gPnpPs2Keyboard; ACPI_HID_DEVICE_PATH gPnp16550ComPortDeviceNode = gPnp16550ComPort; UART_DEVICE_PATH gUartDeviceNode = gUart; -VENDOR_DEVICE_PATH gTerminalTypeDeviceNode = gPcAnsiTerminal; +VENDOR_DEVICE_PATH gTerminalTypeDeviceNode = gVtUtf8Terminal; // // Platform specific keyboard device path @@ -83,7 +83,7 @@ VENDOR_UART_DEVICE_PATH gDebugAgentUartDevicePath = { 0, // Parity - Default 0, // StopBits - Default }, - gPcAnsiTerminal, + gVtUtf8Terminal, gEndEntire }; @@ -168,7 +168,7 @@ STATIC VENDOR_UART_DEVICE_PATH gXenConsoleDevicePath = { FixedPcdGet8 (PcdUartDefaultParity), FixedPcdGet8 (PcdUartDefaultStopBits), }, - gPcAnsiTerminal, + gVtUtf8Terminal, gEndEntire }; From 6a1dadec65a77f49970a7f91b1a87ccea45e9d6c Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Sun, 19 Feb 2023 23:21:43 -0700 Subject: [PATCH 0714/1529] BaseTools: Source/C/Common: Fix doc block locations and convert to Doxygen Move the documentation blocks from between the parameter list and function body to above the function. Convert all the documentation blocks to Doxygen format. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/Common/BasePeCoff.c | 182 ++-- BaseTools/Source/C/Common/CommonLib.c | 311 +++---- BaseTools/Source/C/Common/CommonLib.h | 14 +- BaseTools/Source/C/Common/Compress.h | 45 +- BaseTools/Source/C/Common/Crc32.c | 30 +- BaseTools/Source/C/Common/Crc32.h | 30 +- BaseTools/Source/C/Common/Decompress.c | 382 +++------ BaseTools/Source/C/Common/Decompress.h | 100 +-- BaseTools/Source/C/Common/EfiCompress.c | 442 +++------- BaseTools/Source/C/Common/EfiUtilityMsgs.c | 472 ++++------ .../Source/C/Common/FirmwareVolumeBuffer.c | 803 ++++++------------ BaseTools/Source/C/Common/FvLib.c | 387 ++++----- BaseTools/Source/C/Common/MemoryFile.c | 76 +- BaseTools/Source/C/Common/MemoryFile.h | 68 +- BaseTools/Source/C/Common/MyAlloc.c | 155 ++-- BaseTools/Source/C/Common/MyAlloc.h | 146 ++-- BaseTools/Source/C/Common/OsPath.c | 97 +-- BaseTools/Source/C/Common/OsPath.h | 90 +- .../Source/C/Common/ParseGuidedSectionTools.c | 82 +- .../Source/C/Common/ParseGuidedSectionTools.h | 91 +- BaseTools/Source/C/Common/ParseInf.c | 221 ++--- BaseTools/Source/C/Common/ParseInf.h | 196 ++--- BaseTools/Source/C/Common/PcdValueCommon.c | 293 +++---- BaseTools/Source/C/Common/PcdValueCommon.h | 141 +-- BaseTools/Source/C/Common/PeCoffLoaderEx.c | 56 +- BaseTools/Source/C/Common/SimpleFileParsing.c | 398 ++++----- BaseTools/Source/C/Common/StringFuncs.c | 204 ++--- BaseTools/Source/C/Common/StringFuncs.h | 165 +--- BaseTools/Source/C/Common/TianoCompress.c | 460 +++------- 29 files changed, 2072 insertions(+), 4065 deletions(-) diff --git a/BaseTools/Source/C/Common/BasePeCoff.c b/BaseTools/Source/C/Common/BasePeCoff.c index 30400d1341..b8bfb7b58b 100644 --- a/BaseTools/Source/C/Common/BasePeCoff.c +++ b/BaseTools/Source/C/Common/BasePeCoff.c @@ -77,6 +77,16 @@ PeCoffLoaderRelocateLoongArch64Image ( IN UINT64 Adjust ); +/** + Retrieves the PE or TE Header from a PE/COFF or TE image + + @param ImageContext The context of the image being loaded + @param PeHdr The buffer in which to return the PE header + @param TeHdr The buffer in which to return the TE header + + @return RETURN_SUCCESS if the PE or TE Header is read, + Otherwise, the error status from reading the PE/COFF or TE image using the ImageRead function. +**/ STATIC RETURN_STATUS PeCoffLoaderGetPeHeader ( @@ -84,26 +94,6 @@ PeCoffLoaderGetPeHeader ( OUT EFI_IMAGE_OPTIONAL_HEADER_UNION **PeHdr, OUT EFI_TE_IMAGE_HEADER **TeHdr ) -/*++ - -Routine Description: - - Retrieves the PE or TE Header from a PE/COFF or TE image - -Arguments: - - ImageContext - The context of the image being loaded - - PeHdr - The buffer in which to return the PE header - - TeHdr - The buffer in which to return the TE header - -Returns: - - RETURN_SUCCESS if the PE or TE Header is read, - Otherwise, the error status from reading the PE/COFF or TE image using the ImageRead function. - ---*/ { RETURN_STATUS Status; EFI_IMAGE_DOS_HEADER DosHdr; @@ -150,6 +140,17 @@ Routine Description: return RETURN_SUCCESS; } +/** + Checks the PE or TE header of a PE/COFF or TE image to determine if it supported + + @param ImageContext The context of the image being loaded + @param PeHdr The buffer in which to return the PE header + @param TeHdr The buffer in which to return the TE header + + @retval RETURN_SUCCESS if the PE/COFF or TE image is supported + @retval RETURN_UNSUPPORTED of the PE/COFF or TE image is not supported. + +**/ STATIC RETURN_STATUS PeCoffLoaderCheckImageType ( @@ -157,26 +158,6 @@ PeCoffLoaderCheckImageType ( IN EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr, IN EFI_TE_IMAGE_HEADER *TeHdr ) -/*++ - -Routine Description: - - Checks the PE or TE header of a PE/COFF or TE image to determine if it supported - -Arguments: - - ImageContext - The context of the image being loaded - - PeHdr - The buffer in which to return the PE header - - TeHdr - The buffer in which to return the TE header - -Returns: - - RETURN_SUCCESS if the PE/COFF or TE image is supported - RETURN_UNSUPPORTED of the PE/COFF or TE image is not supported. - ---*/ { // // See if the machine type is supported. @@ -239,31 +220,24 @@ Routine Description: return RETURN_SUCCESS; } +/** + Retrieves information on a PE/COFF image + + @param This Calling context + @param ImageContext The context of the image being loaded + + @retval RETURN_SUCCESS The information on the PE/COFF image was collected. + @retval RETURN_INVALID_PARAMETER ImageContext is NULL. + @retval RETURN_UNSUPPORTED The PE/COFF image is not supported. + @retval Otherwise The error status from reading the PE/COFF image using the + ImageContext->ImageRead() function + +**/ RETURN_STATUS EFIAPI PeCoffLoaderGetImageInfo ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) -/*++ - -Routine Description: - - Retrieves information on a PE/COFF image - -Arguments: - - This - Calling context - ImageContext - The context of the image being loaded - -Returns: - - RETURN_SUCCESS - The information on the PE/COFF image was collected. - RETURN_INVALID_PARAMETER - ImageContext is NULL. - RETURN_UNSUPPORTED - The PE/COFF image is not supported. - Otherwise - The error status from reading the PE/COFF image using the - ImageContext->ImageRead() function - ---*/ { RETURN_STATUS Status; EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr; @@ -539,29 +513,21 @@ Routine Description: return RETURN_SUCCESS; } +/** + Converts an image address to the loaded address + + @param ImageContext The context of the image being loaded + @param Address The address to be converted to the loaded address + + @return NULL if the address can not be converted, otherwise, the converted address + +--*/ STATIC VOID * PeCoffLoaderImageAddress ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext, IN UINTN Address ) -/*++ - -Routine Description: - - Converts an image address to the loaded address - -Arguments: - - ImageContext - The context of the image being loaded - - Address - The address to be converted to the loaded address - -Returns: - - NULL if the address can not be converted, otherwise, the converted address - ---*/ { if (Address >= ImageContext->ImageSize) { ImageContext->ImageError = IMAGE_ERROR_INVALID_IMAGE_ADDRESS; @@ -571,30 +537,22 @@ Routine Description: return (UINT8 *) ((UINTN) ImageContext->ImageAddress + Address); } +/** + Relocates a PE/COFF image in memory + + @param This Calling context + @param ImageContext Contains information on the loaded image to relocate + + @retval RETURN_SUCCESS if the PE/COFF image was relocated + @retval RETURN_LOAD_ERROR if the image is not a valid PE/COFF image + @retval RETURN_UNSUPPORTED not support + +**/ RETURN_STATUS EFIAPI PeCoffLoaderRelocateImage ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) -/*++ - -Routine Description: - - Relocates a PE/COFF image in memory - -Arguments: - - This - Calling context - - ImageContext - Contains information on the loaded image to relocate - -Returns: - - RETURN_SUCCESS if the PE/COFF image was relocated - RETURN_LOAD_ERROR if the image is not a valid PE/COFF image - RETURN_UNSUPPORTED not support - ---*/ { RETURN_STATUS Status; EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr; @@ -853,31 +811,23 @@ Routine Description: return RETURN_SUCCESS; } +/** + Loads a PE/COFF image into memory + + @param This Calling context + @param ImageContext Contains information on image to load into memory + + @retval RETURN_SUCCESS if the PE/COFF image was loaded + @retval RETURN_BUFFER_TOO_SMALL if the caller did not provide a large enough buffer + @retval RETURN_LOAD_ERROR if the image is a runtime driver with no relocations + @retval RETURN_INVALID_PARAMETER if the image address is invalid + +**/ RETURN_STATUS EFIAPI PeCoffLoaderLoadImage ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) -/*++ - -Routine Description: - - Loads a PE/COFF image into memory - -Arguments: - - This - Calling context - - ImageContext - Contains information on image to load into memory - -Returns: - - RETURN_SUCCESS if the PE/COFF image was loaded - RETURN_BUFFER_TOO_SMALL if the caller did not provide a large enough buffer - RETURN_LOAD_ERROR if the image is a runtime driver with no relocations - RETURN_INVALID_PARAMETER if the image address is invalid - ---*/ { RETURN_STATUS Status; EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHdr; diff --git a/BaseTools/Source/C/Common/CommonLib.c b/BaseTools/Source/C/Common/CommonLib.c index 7fb4ab764f..b2cde6d481 100644 --- a/BaseTools/Source/C/Common/CommonLib.c +++ b/BaseTools/Source/C/Common/CommonLib.c @@ -26,28 +26,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent } \ } while (FALSE) +/** + Set Buffer to zero for Size bytes. + + @param Buffer Memory to set. + @param Size Number of bytes to set +**/ VOID PeiZeroMem ( IN VOID *Buffer, IN UINTN Size ) -/*++ - -Routine Description: - - Set Buffer to zero for Size bytes. - -Arguments: - - Buffer - Memory to set. - - Size - Number of bytes to set - -Returns: - - None - ---*/ { INT8 *Ptr; @@ -57,31 +46,19 @@ Routine Description: } } +/** + Copy Length bytes from Source to Destination. + + @param Destination Target of copy + @param Source Place to copy from + @param Length Number of bytes to copy +**/ VOID PeiCopyMem ( IN VOID *Destination, IN VOID *Source, IN UINTN Length ) -/*++ - -Routine Description: - - Copy Length bytes from Source to Destination. - -Arguments: - - Destination - Target of copy - - Source - Place to copy from - - Length - Number of bytes to copy - -Returns: - - None - ---*/ { CHAR8 *Destination8; CHAR8 *Source8; @@ -112,27 +89,20 @@ CopyMem ( PeiCopyMem (Destination, Source, Length); } +/** + Compares to GUIDs + + @param Guid1 guid to compare + @param Guid2 guid to compare + + @retval = 0 if Guid1 == Guid2 + @retval != 0 if Guid1 != Guid2 +**/ INTN CompareGuid ( IN EFI_GUID *Guid1, IN EFI_GUID *Guid2 ) -/*++ - -Routine Description: - - Compares to GUIDs - -Arguments: - - Guid1 - guid to compare - Guid2 - guid to compare - -Returns: - = 0 if Guid1 == Guid2 - != 0 if Guid1 != Guid2 - ---*/ { INT32 *g1; INT32 *g2; @@ -152,34 +122,25 @@ Routine Description: return r; } +/** + This function opens a file and reads it into a memory buffer. The function + will allocate the memory buffer and returns the size of the buffer. + @param InputFileName The name of the file to read. + @param InputFileImage A pointer to the memory buffer. + @param BytesRead The size of the memory buffer. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER One of the input parameters was invalid. + @retval EFI_ABORTED An error occurred. + @retval EFI_OUT_OF_RESOURCES No resource to complete operations. +**/ EFI_STATUS GetFileImage ( IN CHAR8 *InputFileName, OUT CHAR8 **InputFileImage, OUT UINT32 *BytesRead ) -/*++ - -Routine Description: - - This function opens a file and reads it into a memory buffer. The function - will allocate the memory buffer and returns the size of the buffer. - -Arguments: - - InputFileName The name of the file to read. - InputFileImage A pointer to the memory buffer. - BytesRead The size of the memory buffer. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_INVALID_PARAMETER One of the input parameters was invalid. - EFI_ABORTED An error occurred. - EFI_OUT_OF_RESOURCES No resource to complete operations. - ---*/ { FILE *InputFile; UINT32 FileSize; @@ -255,32 +216,24 @@ Routine Description: return EFI_SUCCESS; } +/** + This function opens a file and writes OutputFileImage into the file. + + @param OutputFileName The name of the file to write. + @param OutputFileImage A pointer to the memory buffer. + @param BytesToWrite The size of the memory buffer. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER One of the input parameters was invalid. + @retval EFI_ABORTED An error occurred. + @retval EFI_OUT_OF_RESOURCES No resource to complete operations. +**/ EFI_STATUS PutFileImage ( IN CHAR8 *OutputFileName, IN CHAR8 *OutputFileImage, IN UINT32 BytesToWrite ) -/*++ - -Routine Description: - - This function opens a file and writes OutputFileImage into the file. - -Arguments: - - OutputFileName The name of the file to write. - OutputFileImage A pointer to the memory buffer. - BytesToWrite The size of the memory buffer. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_INVALID_PARAMETER One of the input parameters was invalid. - EFI_ABORTED An error occurred. - EFI_OUT_OF_RESOURCES No resource to complete operations. - ---*/ { FILE *OutputFile; UINT32 BytesWrote; @@ -320,52 +273,36 @@ Routine Description: return EFI_SUCCESS; } +/** + This function calculates the value needed for a valid UINT8 checksum + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + + @return The 8 bit checksum value needed. +**/ UINT8 CalculateChecksum8 ( IN UINT8 *Buffer, IN UINTN Size ) -/*++ - -Routine Description: - - This function calculates the value needed for a valid UINT8 checksum - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 8 bit checksum value needed. - ---*/ { return (UINT8) (0x100 - CalculateSum8 (Buffer, Size)); } +/** + This function calculates the UINT8 sum for the requested region. + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + + @return The 8 bit checksum value needed. +**/ UINT8 CalculateSum8 ( IN UINT8 *Buffer, IN UINTN Size ) -/*++ - -Routine Description:: - - This function calculates the UINT8 sum for the requested region. - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 8 bit checksum value needed. - ---*/ { UINTN Index; UINT8 Sum; @@ -382,52 +319,36 @@ Routine Description:: return Sum; } +/** + This function calculates the value needed for a valid UINT16 checksum + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + + @return The 16 bit checksum value needed. +**/ UINT16 CalculateChecksum16 ( IN UINT16 *Buffer, IN UINTN Size ) -/*++ - -Routine Description:: - - This function calculates the value needed for a valid UINT16 checksum - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 16 bit checksum value needed. - ---*/ { return (UINT16) (0x10000 - CalculateSum16 (Buffer, Size)); } +/** + This function calculates the UINT16 sum for the requested region. + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + + @return The 16 bit checksum +**/ UINT16 CalculateSum16 ( IN UINT16 *Buffer, IN UINTN Size ) -/*++ - -Routine Description: - - This function calculates the UINT16 sum for the requested region. - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 16 bit checksum - ---*/ { UINTN Index; UINT16 Sum; @@ -444,26 +365,18 @@ Routine Description: return (UINT16) Sum; } +/** + This function prints a GUID to STDOUT. + + @param Guid Pointer to a GUID to print. + + @retval EFI_SUCCESS The GUID was printed. + @retval EFI_INVALID_PARAMETER The input was NULL. +**/ EFI_STATUS PrintGuid ( IN EFI_GUID *Guid ) -/*++ - -Routine Description: - - This function prints a GUID to STDOUT. - -Arguments: - - Guid Pointer to a GUID to print. - -Returns: - - EFI_SUCCESS The GUID was printed. - EFI_INVALID_PARAMETER The input was NULL. - ---*/ { if (Guid == NULL) { Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value"); @@ -487,6 +400,18 @@ Routine Description: return EFI_SUCCESS; } +/** + This function prints a GUID to a buffer + + @param Guid Pointer to a GUID to print. + @param Buffer Pointer to a user-provided buffer to print to + @param BufferLen Size of the Buffer + @param Uppercase If use upper case. + + @retval EFI_SUCCESS The GUID was printed. + @retval EFI_INVALID_PARAMETER The input was NULL. + @retval EFI_BUFFER_TOO_SMALL The input buffer was not big enough +**/ EFI_STATUS PrintGuidToBuffer ( IN EFI_GUID *Guid, @@ -494,26 +419,6 @@ PrintGuidToBuffer ( IN UINT32 BufferLen, IN BOOLEAN Uppercase ) -/*++ - -Routine Description: - - This function prints a GUID to a buffer - -Arguments: - - Guid - Pointer to a GUID to print. - Buffer - Pointer to a user-provided buffer to print to - BufferLen - Size of the Buffer - Uppercase - If use upper case. - -Returns: - - EFI_SUCCESS The GUID was printed. - EFI_INVALID_PARAMETER The input was NULL. - EFI_BUFFER_TOO_SMALL The input buffer was not big enough - ---*/ { if (Guid == NULL) { Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value"); @@ -591,22 +496,17 @@ char *strlwr(char *s) // CHAR8 mCommonLibFullPath[MAX_LONG_FILE_PATH]; +/** + Convert FileName to the long file path, which can support larger than 260 length. + + @param FileName FileName. + + @return LongFilePath A pointer to the converted long file path. +**/ CHAR8 * LongFilePath ( IN CHAR8 *FileName ) -/*++ - -Routine Description: - Convert FileName to the long file path, which can support larger than 260 length. - -Arguments: - FileName - FileName. - -Returns: - LongFilePath A pointer to the converted long file path. - ---*/ { #ifdef __GNUC__ // @@ -2188,4 +2088,3 @@ SplitStr ( *List = Str; return ReturnStr; } - diff --git a/BaseTools/Source/C/Common/CommonLib.h b/BaseTools/Source/C/Common/CommonLib.h index 0f05d88db2..a841029c2a 100644 --- a/BaseTools/Source/C/Common/CommonLib.h +++ b/BaseTools/Source/C/Common/CommonLib.h @@ -95,13 +95,6 @@ GetFileImage ( ) ; -EFI_STATUS -PutFileImage ( - IN CHAR8 *OutputFileName, - IN CHAR8 *OutputFileImage, - IN UINT32 BytesToWrite - ) -; /*++ Routine Description: @@ -122,6 +115,13 @@ Routine Description: EFI_OUT_OF_RESOURCES No resource to complete operations. **/ +EFI_STATUS +PutFileImage ( + IN CHAR8 *OutputFileName, + IN CHAR8 *OutputFileImage, + IN UINT32 BytesToWrite + ) +; UINT8 CalculateChecksum8 ( diff --git a/BaseTools/Source/C/Common/Compress.h b/BaseTools/Source/C/Common/Compress.h index 40255a9665..499e183c2b 100644 --- a/BaseTools/Source/C/Common/Compress.h +++ b/BaseTools/Source/C/Common/Compress.h @@ -15,13 +15,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "CommonLib.h" #include -/*++ - -Routine Description: +/** Tiano compression routine. - ---*/ +**/ EFI_STATUS TianoCompress ( IN UINT8 *SrcBuffer, @@ -31,13 +28,9 @@ TianoCompress ( ) ; -/*++ - -Routine Description: - +/** Efi compression routine. - ---*/ +**/ EFI_STATUS EfiCompress ( IN UINT8 *SrcBuffer, @@ -47,29 +40,21 @@ EfiCompress ( ) ; -/*++ - -Routine Description: - +/** The compression routine. -Arguments: - - SrcBuffer - The buffer storing the source data - SrcSize - The size of source data - DstBuffer - The buffer to store the compressed data - DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. + @param SrcBuffer The buffer storing the source data + @param SrcSize The size of source data + @param DstBuffer The buffer to store the compressed data + @param DstSize On input, the size of DstBuffer; On output, + the size of the actual compressed data. -Returns: - - EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case, + @retval EFI_BUFFER_TOO_SMALL The DstBuffer is too small. In this case, DstSize contains the size needed. - EFI_SUCCESS - Compression is successful. - EFI_OUT_OF_RESOURCES - No resource to complete function. - EFI_INVALID_PARAMETER - Parameter supplied is wrong. - ---*/ + @retval EFI_SUCCESS Compression is successful. + @retval EFI_OUT_OF_RESOURCES No resource to complete function. + @retval EFI_INVALID_PARAMETER Parameter supplied is wrong. +**/ typedef EFI_STATUS (*COMPRESS_FUNCTION) ( diff --git a/BaseTools/Source/C/Common/Crc32.c b/BaseTools/Source/C/Common/Crc32.c index 7281d5f0e9..00cae94898 100644 --- a/BaseTools/Source/C/Common/Crc32.c +++ b/BaseTools/Source/C/Common/Crc32.c @@ -268,31 +268,23 @@ UINT32 mCrcTable[256] = { 0x2D02EF8D }; +/** + The CalculateCrc32 routine. + + @param Data The buffer containing the data to be processed + @param DataSize The size of data to be processed + @param CrcOut A pointer to the caller allocated UINT32 that on + contains the CRC32 checksum of Data + + @retval EFI_SUCCESS Calculation is successful. + @retval EFI_INVALID_PARAMETER Data / CrcOut = NULL, or DataSize = 0 +**/ EFI_STATUS CalculateCrc32 ( IN UINT8 *Data, IN UINTN DataSize, IN OUT UINT32 *CrcOut ) -/*++ - -Routine Description: - - The CalculateCrc32 routine. - -Arguments: - - Data - The buffer containing the data to be processed - DataSize - The size of data to be processed - CrcOut - A pointer to the caller allocated UINT32 that on - contains the CRC32 checksum of Data - -Returns: - - EFI_SUCCESS - Calculation is successful. - EFI_INVALID_PARAMETER - Data / CrcOut = NULL, or DataSize = 0 - ---*/ { UINT32 Crc; UINTN Index; diff --git a/BaseTools/Source/C/Common/Crc32.h b/BaseTools/Source/C/Common/Crc32.h index 61f99b96b5..3f6b5b35fc 100644 --- a/BaseTools/Source/C/Common/Crc32.h +++ b/BaseTools/Source/C/Common/Crc32.h @@ -11,31 +11,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include +/** + The CalculateCrc32 routine. + + @param Data The buffer containing the data to be processed + @param DataSize The size of data to be processed + @param CrcOut A pointer to the caller allocated UINT32 that on + contains the CRC32 checksum of Data + + @retval EFI_SUCCESS - Calculation is successful. + @retval EFI_INVALID_PARAMETER - Data / CrcOut = NULL, or DataSize = 0 +**/ EFI_STATUS CalculateCrc32 ( IN UINT8 *Data, IN UINTN DataSize, IN OUT UINT32 *CrcOut ) -/*++ - -Routine Description: - - The CalculateCrc32 routine. - -Arguments: - - Data - The buffer containing the data to be processed - DataSize - The size of data to be processed - CrcOut - A pointer to the caller allocated UINT32 that on - contains the CRC32 checksum of Data - -Returns: - - EFI_SUCCESS - Calculation is successful. - EFI_INVALID_PARAMETER - Data / CrcOut = NULL, or DataSize = 0 - ---*/ ; #endif diff --git a/BaseTools/Source/C/Common/Decompress.c b/BaseTools/Source/C/Common/Decompress.c index d85098f131..a0f54c0834 100644 --- a/BaseTools/Source/C/Common/Decompress.c +++ b/BaseTools/Source/C/Common/Decompress.c @@ -62,26 +62,18 @@ typedef struct { STATIC UINT16 mPbit = EFIPBIT; +/** + Shift mBitBuf NumOfBits left. Read in NumOfBits of bits from source. + + @param Sd The global scratch data + @param NumOfBit The number of bits to shift and read. +**/ STATIC VOID FillBuf ( IN SCRATCH_DATA *Sd, IN UINT16 NumOfBits ) -/*++ - -Routine Description: - - Shift mBitBuf NumOfBits left. Read in NumOfBits of bits from source. - -Arguments: - - Sd - The global scratch data - NumOfBit - The number of bits to shift and read. - -Returns: (VOID) - ---*/ { Sd->mBitBuf = (UINT32) (((UINT64)Sd->mBitBuf) << NumOfBits); @@ -112,30 +104,22 @@ Returns: (VOID) Sd->mBitBuf |= Sd->mSubBitBuf >> Sd->mBitCount; } +/** + Get NumOfBits of bits out from mBitBuf. Fill mBitBuf with subsequent + NumOfBits of bits from source. Returns NumOfBits of bits that are + popped out. + + @param Sd The global scratch data. + @param NumOfBits The number of bits to pop and read. + + @return The bits that are popped out. +**/ STATIC UINT32 GetBits ( IN SCRATCH_DATA *Sd, IN UINT16 NumOfBits ) -/*++ - -Routine Description: - - Get NumOfBits of bits out from mBitBuf. Fill mBitBuf with subsequent - NumOfBits of bits from source. Returns NumOfBits of bits that are - popped out. - -Arguments: - - Sd - The global scratch data. - NumOfBits - The number of bits to pop and read. - -Returns: - - The bits that are popped out. - ---*/ { UINT32 OutBits; @@ -146,6 +130,18 @@ Routine Description: return OutBits; } +/** + Creates Huffman Code mapping table according to code length array. + + @param Sd The global scratch data + @param NumOfChar Number of symbols in the symbol set + @param BitLen Code length array + @param TableBits The width of the mapping table + @param Table The table + + @retval 0 - OK. + @retval BAD_TABLE - The table is corrupted. +**/ STATIC UINT16 MakeTable ( @@ -155,26 +151,6 @@ MakeTable ( IN UINT16 TableBits, OUT UINT16 *Table ) -/*++ - -Routine Description: - - Creates Huffman Code mapping table according to code length array. - -Arguments: - - Sd - The global scratch data - NumOfChar - Number of symbols in the symbol set - BitLen - Code length array - TableBits - The width of the mapping table - Table - The table - -Returns: - - 0 - OK. - BAD_TABLE - The table is corrupted. - ---*/ { UINT16 Count[17]; UINT16 Weight[17]; @@ -290,26 +266,18 @@ Routine Description: return 0; } +/** + Decodes a position value. + + @param Sd the global scratch data + + @return The position value decoded. +**/ STATIC UINT32 DecodeP ( IN SCRATCH_DATA *Sd ) -/*++ - -Routine Description: - - Decodes a position value. - -Arguments: - - Sd - the global scratch data - -Returns: - - The position value decoded. - ---*/ { UINT16 Val; UINT32 Mask; @@ -344,6 +312,17 @@ Routine Description: return Pos; } +/** + Reads code lengths for the Extra Set or the Position Set + + @param Sd The global scratch data + @param nn Number of symbols + @param nbit Number of bits needed to represent nn + @param Special The special symbol that needs to be taken care of + + @retval 0 - OK. + @retval BAD_TABLE - Table is corrupted. +**/ STATIC UINT16 ReadPTLen ( @@ -352,25 +331,6 @@ ReadPTLen ( IN UINT16 nbit, IN UINT16 Special ) -/*++ - -Routine Description: - - Reads code lengths for the Extra Set or the Position Set - -Arguments: - - Sd - The global scratch data - nn - Number of symbols - nbit - Number of bits needed to represent nn - Special - The special symbol that needs to be taken care of - -Returns: - - 0 - OK. - BAD_TABLE - Table is corrupted. - ---*/ { UINT16 Number; UINT16 CharC; @@ -430,24 +390,16 @@ Routine Description: return MakeTable (Sd, nn, Sd->mPTLen, 8, Sd->mPTTable); } +/** + Reads code lengths for Char&Len Set. + + @param Sd the global scratch data +**/ STATIC VOID ReadCLen ( SCRATCH_DATA *Sd ) -/*++ - -Routine Description: - - Reads code lengths for Char&Len Set. - -Arguments: - - Sd - the global scratch data - -Returns: (VOID) - ---*/ { UINT16 Number; UINT16 CharC; @@ -526,26 +478,18 @@ Returns: (VOID) return ; } +/** + Decode a character/length value. + + @param Sd The global scratch data. + + @return The value decoded. +**/ STATIC UINT16 DecodeC ( SCRATCH_DATA *Sd ) -/*++ - -Routine Description: - - Decode a character/length value. - -Arguments: - - Sd - The global scratch data. - -Returns: - - The value decoded. - ---*/ { UINT16 Index2; UINT32 Mask; @@ -592,24 +536,16 @@ Routine Description: return Index2; } +/** + Decode the source data and put the resulting data into the destination buffer. + + @param Sd The global scratch data + **/ STATIC VOID Decode ( SCRATCH_DATA *Sd ) -/*++ - -Routine Description: - - Decode the source data and put the resulting data into the destination buffer. - -Arguments: - - Sd - The global scratch data - -Returns: (VOID) - - --*/ { UINT16 BytesRemain; UINT32 DataIdx; @@ -669,6 +605,17 @@ Returns: (VOID) return ; } +/** + The implementation of EFI_DECOMPRESS_PROTOCOL.GetInfo(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param DstSize The size of destination buffer. + @param ScratchSize The size of scratch buffer. + + @retval EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successfully retrieved. + @retval EFI_INVALID_PARAMETER - The source data is corrupted +**/ EFI_STATUS GetInfo ( IN VOID *Source, @@ -676,25 +623,6 @@ GetInfo ( OUT UINT32 *DstSize, OUT UINT32 *ScratchSize ) -/*++ - -Routine Description: - - The implementation of EFI_DECOMPRESS_PROTOCOL.GetInfo(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - DstSize - The size of destination buffer. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successfully retrieved. - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { UINT8 *Src; UINT32 CompSize; @@ -716,6 +644,19 @@ Routine Description: return EFI_SUCCESS; } +/** + The implementation Efi and Tiano Decompress(). + + @param Source - The source buffer containing the compressed data. + @param SrcSize - The size of source buffer + @param Destination - The destination buffer to store the decompressed data + @param DstSize - The size of destination buffer. + @param Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. + @param ScratchSize - The size of scratch buffer. + + @retval EFI_SUCCESS - Decompression is successful + @retval EFI_INVALID_PARAMETER - The source data is corrupted +**/ EFI_STATUS Decompress ( IN VOID *Source, @@ -725,27 +666,6 @@ Decompress ( IN OUT VOID *Scratch, IN UINT32 ScratchSize ) -/*++ - -Routine Description: - - The implementation Efi and Tiano Decompress(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - Destination - The destination buffer to store the decompressed data - DstSize - The size of destination buffer. - Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - Decompression is successful - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { UINT32 Index; UINT32 CompSize; @@ -811,6 +731,17 @@ Routine Description: return Status; } +/** + The implementation Efi Decompress GetInfo(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param DstSize The size of destination buffer. + @param ScratchSize The size of scratch buffer. + + @retval EFI_SUCCESS The size of destination buffer and the size of scratch buffer are successfully retrieved. + @retval EFI_INVALID_PARAMETER The source data is corrupted +**/ EFI_STATUS EfiGetInfo ( IN VOID *Source, @@ -818,29 +749,21 @@ EfiGetInfo ( OUT UINT32 *DstSize, OUT UINT32 *ScratchSize ) -/*++ - -Routine Description: - - The implementation Efi Decompress GetInfo(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - DstSize - The size of destination buffer. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successfully retrieved. - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { return GetInfo (Source, SrcSize, DstSize, ScratchSize); } +/** + The implementation Tiano Decompress GetInfo(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param DstSize The size of destination buffer. + @param ScratchSize The size of scratch buffer. + + @retval EFI_SUCCESS The size of destination buffer and the size of scratch buffer are successfully retrieved. + @retval EFI_INVALID_PARAMETER The source data is corrupted +**/ EFI_STATUS TianoGetInfo ( IN VOID *Source, @@ -848,29 +771,23 @@ TianoGetInfo ( OUT UINT32 *DstSize, OUT UINT32 *ScratchSize ) -/*++ - -Routine Description: - - The implementation Tiano Decompress GetInfo(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - DstSize - The size of destination buffer. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successfully retrieved. - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { return GetInfo (Source, SrcSize, DstSize, ScratchSize); } +/** + The implementation of Efi Decompress(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param Destination The destination buffer to store the decompressed data + @param DstSize The size of destination buffer. + @param Scratch The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. + @param ScratchSize The size of scratch buffer. + + @retval EFI_SUCCESS Decompression is successful + @retval EFI_INVALID_PARAMETER The source data is corrupted +**/ EFI_STATUS EfiDecompress ( IN VOID *Source, @@ -880,32 +797,24 @@ EfiDecompress ( IN OUT VOID *Scratch, IN UINT32 ScratchSize ) -/*++ - -Routine Description: - - The implementation of Efi Decompress(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - Destination - The destination buffer to store the decompressed data - DstSize - The size of destination buffer. - Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - Decompression is successful - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { mPbit = EFIPBIT; return Decompress (Source, SrcSize, Destination, DstSize, Scratch, ScratchSize); } +/** + The implementation of Tiano Decompress(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param Destination The destination buffer to store the decompressed data + @param DstSize The size of destination buffer. + @param Scratch The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. + @param ScratchSize The size of scratch buffer. + + @retval EFI_SUCCESS Decompression is successful + @retval EFI_INVALID_PARAMETER The source data is corrupted +**/ EFI_STATUS TianoDecompress ( IN VOID *Source, @@ -915,27 +824,6 @@ TianoDecompress ( IN OUT VOID *Scratch, IN UINT32 ScratchSize ) -/*++ - -Routine Description: - - The implementation of Tiano Decompress(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - Destination - The destination buffer to store the decompressed data - DstSize - The size of destination buffer. - Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - Decompression is successful - EFI_INVALID_PARAMETER - The source data is corrupted - ---*/ { mPbit = MAXPBIT; return Decompress (Source, SrcSize, Destination, DstSize, Scratch, ScratchSize); diff --git a/BaseTools/Source/C/Common/Decompress.h b/BaseTools/Source/C/Common/Decompress.h index 983a27d8fc..00a1e31b8c 100644 --- a/BaseTools/Source/C/Common/Decompress.h +++ b/BaseTools/Source/C/Common/Decompress.h @@ -11,13 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -EFI_STATUS -EfiGetInfo ( - IN VOID *Source, - IN UINT32 SrcSize, - OUT UINT32 *DstSize, - OUT UINT32 *ScratchSize - ); /** Routine Description: @@ -37,7 +30,27 @@ Routine Description: EFI_INVALID_PARAMETER - The source data is corrupted **/ +EFI_STATUS +EfiGetInfo ( + IN VOID *Source, + IN UINT32 SrcSize, + OUT UINT32 *DstSize, + OUT UINT32 *ScratchSize + ); + +/** + The implementation of Efi Decompress(). + + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param Destination The destination buffer to store the decompressed data + @param DstSize The size of destination buffer. + @param Scratch The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. + @param ScratchSize The size of scratch buffer. + @retval EFI_SUCCESS Decompression is successful + @retval EFI_INVALID_PARAMETER The source data is corrupted +**/ EFI_STATUS EfiDecompress ( IN VOID *Source, @@ -47,28 +60,18 @@ EfiDecompress ( IN OUT VOID *Scratch, IN UINT32 ScratchSize ); -/** - -Routine Description: - - The implementation of Efi Decompress(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - Destination - The destination buffer to store the decompressed data - DstSize - The size of destination buffer. - Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. - ScratchSize - The size of scratch buffer. -Returns: +/** + The implementation Tiano Decompress GetInfo(). - EFI_SUCCESS - Decompression is successful - EFI_INVALID_PARAMETER - The source data is corrupted + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param DstSize The size of destination buffer. + @param ScratchSize The size of scratch buffer. + @retval EFI_SUCCESS The size of destination buffer and the size of scratch buffer are successfully retrieved. + @retval EFI_INVALID_PARAMETER The source data is corrupted **/ - EFI_STATUS TianoGetInfo ( IN VOID *Source, @@ -76,26 +79,20 @@ TianoGetInfo ( OUT UINT32 *DstSize, OUT UINT32 *ScratchSize ); -/** - -Routine Description: - - The implementation Tiano Decompress GetInfo(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - DstSize - The size of destination buffer. - ScratchSize - The size of scratch buffer. -Returns: +/** + The implementation of Tiano Decompress(). - EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successfully retrieved. - EFI_INVALID_PARAMETER - The source data is corrupted + @param Source The source buffer containing the compressed data. + @param SrcSize The size of source buffer + @param Destination The destination buffer to store the decompressed data + @param DstSize The size of destination buffer. + @param Scratch The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. + @param ScratchSize The size of scratch buffer. + @retval EFI_SUCCESS Decompression is successful + @retval EFI_INVALID_PARAMETER The source data is corrupted **/ - EFI_STATUS TianoDecompress ( IN VOID *Source, @@ -105,27 +102,6 @@ TianoDecompress ( IN OUT VOID *Scratch, IN UINT32 ScratchSize ); -/** - -Routine Description: - - The implementation of Tiano Decompress(). - -Arguments: - - Source - The source buffer containing the compressed data. - SrcSize - The size of source buffer - Destination - The destination buffer to store the decompressed data - DstSize - The size of destination buffer. - Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. - ScratchSize - The size of scratch buffer. - -Returns: - - EFI_SUCCESS - Decompression is successful - EFI_INVALID_PARAMETER - The source data is corrupted - -**/ typedef EFI_STATUS diff --git a/BaseTools/Source/C/Common/EfiCompress.c b/BaseTools/Source/C/Common/EfiCompress.c index db5ebe3157..0db958b853 100644 --- a/BaseTools/Source/C/Common/EfiCompress.c +++ b/BaseTools/Source/C/Common/EfiCompress.c @@ -250,6 +250,20 @@ STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NU // functions // +/** + The main compression routine. + + @param SrcBuffer The buffer storing the source data + @param SrcSize The size of source data + @param DstBuffer The buffer to store the compressed data + @param DstSize On input, the size of DstBuffer; On output, + the size of the actual compressed data. + + @retval EFI_BUFFER_TOO_SMALL The DstBuffer is too small. In this case, + DstSize contains the size needed. + @retval EFI_SUCCESS Compression is successful. + +**/ EFI_STATUS EfiCompress ( IN UINT8 *SrcBuffer, @@ -257,27 +271,6 @@ EfiCompress ( IN UINT8 *DstBuffer, IN OUT UINT32 *DstSize ) -/*++ - -Routine Description: - - The main compression routine. - -Arguments: - - SrcBuffer - The buffer storing the source data - SrcSize - The size of source data - DstBuffer - The buffer to store the compressed data - DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. - -Returns: - - EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case, - DstSize contains the size needed. - EFI_SUCCESS - Compression is successful. - ---*/ { EFI_STATUS Status = EFI_SUCCESS; @@ -345,24 +338,16 @@ Routine Description: } +/** + Put a dword to output stream + + @param Data the dword to put +**/ STATIC VOID PutDword( IN UINT32 Data ) -/*++ - -Routine Description: - - Put a dword to output stream - -Arguments: - - Data - the dword to put - -Returns: (VOID) - ---*/ { if (mDst < mDstUpperLimit) { *mDst++ = (UINT8)(((UINT8)(Data )) & 0xff); @@ -381,23 +366,15 @@ Returns: (VOID) } } +/** + Allocate memory spaces for data structures used in compression process + + @retval EFI_SUCCESS Memory is allocated successfully + @retva; EFI_OUT_OF_RESOURCES Allocation fails +**/ STATIC EFI_STATUS AllocateMemory () -/*++ - -Routine Description: - - Allocate memory spaces for data structures used in compression process - -Arguments: (VOID) - -Returns: - - EFI_SUCCESS - Memory is allocated successfully - EFI_OUT_OF_RESOURCES - Allocation fails - ---*/ { UINT32 i; @@ -432,19 +409,11 @@ Arguments: (VOID) return EFI_SUCCESS; } +/** + Called when compression is completed to free memory previously allocated. +**/ VOID FreeMemory () -/*++ - -Routine Description: - - Called when compression is completed to free memory previously allocated. - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { if (mText) { free (mText); @@ -481,21 +450,12 @@ Returns: (VOID) return; } - +/** + Initialize String Info Log data structures +**/ STATIC VOID InitSlide () -/*++ - -Routine Description: - - Initialize String Info Log data structures - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE i; @@ -517,29 +477,20 @@ Returns: (VOID) } } +/** + Find child node given the parent node and the edge character + + @param q the parent node + @param c the edge character + @return The child node (NIL if not found) +**/ STATIC NODE Child ( IN NODE q, IN UINT8 c ) -/*++ - -Routine Description: - - Find child node given the parent node and the edge character - -Arguments: - - q - the parent node - c - the edge character - -Returns: - - The child node (NIL if not found) - ---*/ { NODE r; @@ -552,6 +503,13 @@ Routine Description: return r; } +/** + Create a new child for a given parent node. + + @param q the parent node + @param c the edge character + @param r the child node +**/ STATIC VOID MakeChild ( @@ -559,21 +517,6 @@ MakeChild ( IN UINT8 c, IN NODE r ) -/*++ - -Routine Description: - - Create a new child for a given parent node. - -Arguments: - - q - the parent node - c - the edge character - r - the child node - -Returns: (VOID) - ---*/ { NODE h, t; @@ -587,24 +530,16 @@ Returns: (VOID) mChildCount[q]++; } +/** + Split a node. + + @param Old the node to split +**/ STATIC VOID Split ( NODE Old ) -/*++ - -Routine Description: - - Split a node. - -Arguments: - - Old - the node to split - -Returns: (VOID) - ---*/ { NODE New, t; @@ -624,20 +559,12 @@ Returns: (VOID) MakeChild(New, mText[mPos + mMatchLen], mPos); } +/** + Insert string info for current position into the String Info Log +**/ STATIC VOID InsertNode () -/*++ - -Routine Description: - - Insert string info for current position into the String Info Log - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE q, r, j, t; UINT8 c, *t1, *t2; @@ -739,21 +666,13 @@ Returns: (VOID) } +/** + Delete outdated string info. (The Usage of PERC_FLAG + ensures a clean deletion) +**/ STATIC VOID DeleteNode () -/*++ - -Routine Description: - - Delete outdated string info. (The Usage of PERC_FLAG - ensures a clean deletion) - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE q, r, s, t, u; @@ -813,21 +732,13 @@ Returns: (VOID) mAvail = r; } +/** + Advance the current position (read in new data if needed). + Delete outdated string info. Find a match string for current position. +**/ STATIC VOID GetNextMatch () -/*++ - -Routine Description: - - Advance the current position (read in new data if needed). - Delete outdated string info. Find a match string for current position. - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 n; @@ -842,23 +753,15 @@ Returns: (VOID) InsertNode(); } +/** + The main controlling routine for compression process. + + @retval EFI_SUCCESS The compression is successful + @retval EFI_OUT_0F_RESOURCES Not enough memory for compression process +**/ STATIC EFI_STATUS Encode () -/*++ - -Routine Description: - - The main controlling routine for compression process. - -Arguments: (VOID) - -Returns: - - EFI_SUCCESS - The compression is successful - EFI_OUT_0F_RESOURCES - Not enough memory for compression process - ---*/ { EFI_STATUS Status; INT32 LastMatchLen; @@ -920,20 +823,12 @@ Arguments: (VOID) return EFI_SUCCESS; } +/** + Count the frequencies for the Extra Set +**/ STATIC VOID CountTFreq () -/*++ - -Routine Description: - - Count the frequencies for the Extra Set - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 i, k, n, Count; @@ -969,6 +864,13 @@ Returns: (VOID) } } +/** + Outputs the code length array for the Extra Set or the Position Set. + + @param n the number of symbols + @param nbit the number of bits needed to represent 'n' + @param Special the special symbol that needs to be take care of +**/ STATIC VOID WritePTLen ( @@ -976,21 +878,6 @@ WritePTLen ( IN INT32 nbit, IN INT32 Special ) -/*++ - -Routine Description: - - Outputs the code length array for the Extra Set or the Position Set. - -Arguments: - - n - the number of symbols - nbit - the number of bits needed to represent 'n' - Special - the special symbol that needs to be take care of - -Returns: (VOID) - ---*/ { INT32 i, k; @@ -1015,20 +902,12 @@ Returns: (VOID) } } +/** + Outputs the code length array for Char&Length Set +**/ STATIC VOID WriteCLen () -/*++ - -Routine Description: - - Outputs the code length array for Char&Length Set - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 i, k, n, Count; @@ -1096,20 +975,12 @@ EncodeP ( } } +/** + Huffman code the block and output it. +**/ STATIC VOID SendBlock () -/*++ - -Routine Description: - - Huffman code the block and output it. - -Argument: (VOID) - -Returns: (VOID) - ---*/ { UINT32 i, k, Flags, Root, Pos, Size; Flags = 0; @@ -1164,27 +1035,18 @@ Returns: (VOID) } } +/** + Outputs an Original Character or a Pointer + @param c The original character or the 'String Length' element of a Pointer + @param p The 'Position' field of a Pointer +**/ STATIC VOID Output ( IN UINT32 c, IN UINT32 p ) -/*++ - -Routine Description: - - Outputs an Original Character or a Pointer - -Arguments: - - c - The original character or the 'String Length' element of a Pointer - p - The 'Position' field of a Pointer - -Returns: (VOID) - ---*/ { STATIC UINT32 CPos; @@ -1263,26 +1125,18 @@ MakeCrcTable () } } +/** + Outputs rightmost n bits of x + + @param n the rightmost n bits of the data is used + @param x the data +**/ STATIC VOID PutBits ( IN INT32 n, IN UINT32 x ) -/*++ - -Routine Description: - - Outputs rightmost n bits of x - -Arguments: - - n - the rightmost n bits of the data is used - x - the data - -Returns: (VOID) - ---*/ { UINT8 Temp; @@ -1311,28 +1165,20 @@ Returns: (VOID) } } +/** + Read in source data + + @param p the buffer to hold the data + @param n number of bytes to read + + @return number of bytes actually read +**/ STATIC INT32 FreadCrc ( OUT UINT8 *p, IN INT32 n ) -/*++ - -Routine Description: - - Read in source data - -Arguments: - - p - the buffer to hold the data - n - number of bytes to read - -Returns: - - number of bytes actually read - ---*/ { INT32 i; @@ -1358,24 +1204,16 @@ InitPutBits () mSubBitBuf = 0; } +/** + Count the number of each code length for a Huffman tree. + + @param i the top node +**/ STATIC VOID CountLen ( IN INT32 i ) -/*++ - -Routine Description: - - Count the number of each code length for a Huffman tree. - -Arguments: - - i - the top node - -Returns: (VOID) - ---*/ { STATIC INT32 Depth = 0; @@ -1389,22 +1227,16 @@ Returns: (VOID) } } +/** + Create code length array for a Huffman tree + + @param Root the root of the tree +**/ STATIC VOID MakeLen ( IN INT32 Root ) -/*++ - -Routine Description: - - Create code length array for a Huffman tree - -Arguments: - - Root - the root of the tree - ---*/ { INT32 i, k; UINT32 Cum; @@ -1468,6 +1300,13 @@ DownHeap ( mHeap[i] = (INT16)k; } +/** + Assign code to each symbol based on the code length array + + @param n number of symbols + @param Len the code length array + @param Code stores codes for each symbol +**/ STATIC VOID MakeCode ( @@ -1475,21 +1314,6 @@ MakeCode ( IN UINT8 Len[], OUT UINT16 Code[] ) -/*++ - -Routine Description: - - Assign code to each symbol based on the code length array - -Arguments: - - n - number of symbols - Len - the code length array - Code - stores codes for each symbol - -Returns: (VOID) - ---*/ { INT32 i; UINT16 Start[18]; @@ -1503,6 +1327,16 @@ Returns: (VOID) } } +/** + Generates Huffman codes given a frequency distribution of symbols + + @param NParm number of symbols + @param FreqParm frequency of each symbol + @param LenParm code length for each symbol + @param CodeParm code for each symbol + + @return Root of the Huffman tree. +**/ STATIC INT32 MakeTree ( @@ -1511,24 +1345,6 @@ MakeTree ( OUT UINT8 LenParm[], OUT UINT16 CodeParm[] ) -/*++ - -Routine Description: - - Generates Huffman codes given a frequency distribution of symbols - -Arguments: - - NParm - number of symbols - FreqParm - frequency of each symbol - LenParm - code length for each symbol - CodeParm - code for each symbol - -Returns: - - Root of the Huffman tree. - ---*/ { INT32 i, j, k, Avail; diff --git a/BaseTools/Source/C/Common/EfiUtilityMsgs.c b/BaseTools/Source/C/Common/EfiUtilityMsgs.c index f8d2a40be1..faf354064c 100644 --- a/BaseTools/Source/C/Common/EfiUtilityMsgs.c +++ b/BaseTools/Source/C/Common/EfiUtilityMsgs.c @@ -36,65 +36,59 @@ PrintLimitExceeded ( VOID ); -VOID -Error ( - CHAR8 *FileName, - UINT32 LineNumber, - UINT32 MessageCode, - CHAR8 *Text, - CHAR8 *MsgFmt, - ... - ) -/*++ - -Routine Description: +/** Prints an error message. -Arguments: All arguments are optional, though the printed message may be useless if at least something valid is not specified. - FileName - name of the file or application. If not specified, then the + @note: + We print the following (similar to the Warn() and Debug() + W + Typical error/warning message format: + + bin\VfrCompile.cpp(330) : error C2660: 'AddVfrDataStructField' : function does not take 2 parameters + + BUGBUG -- these three utility functions are almost identical, and + should be modified to share code. + + Visual Studio does not find error messages with: + + " error :" + " error 1:" + " error c1:" + " error 1000:" + " error c100:" + + It does find: + " error c1000:" + + @param FileName name of the file or application. If not specified, then the utility name (as set by the utility calling SetUtilityName() earlier) is used. Otherwise "Unknown utility" is used. - LineNumber - the line number of error, typically used by parsers. If the + @param LineNumber the line number of error, typically used by parsers. If the utility is not a parser, then 0 should be specified. Otherwise the FileName and LineNumber info can be used to cause MS Visual Studio to jump to the error. - MessageCode - an application-specific error code that can be referenced in + @param MessageCode an application-specific error code that can be referenced in other documentation. - Text - the text in question, typically used by parsers. + @param Text the text in question, typically used by parsers. - MsgFmt - the format string for the error message. Can contain formatting + @param MsgFmt the format string for the error message. Can contain formatting controls for use with the varargs. - -Returns: - None. - -Notes: - We print the following (similar to the Warn() and Debug() - W - Typical error/warning message format: - - bin\VfrCompile.cpp(330) : error C2660: 'AddVfrDataStructField' : function does not take 2 parameters - - BUGBUG -- these three utility functions are almost identical, and - should be modified to share code. - - Visual Studio does not find error messages with: - - " error :" - " error 1:" - " error c1:" - " error 1000:" - " error c100:" - - It does find: - " error c1000:" ---*/ +**/ +VOID +Error ( + CHAR8 *FileName, + UINT32 LineNumber, + UINT32 MessageCode, + CHAR8 *Text, + CHAR8 *MsgFmt, + ... + ) { va_list List; // @@ -127,6 +121,14 @@ Routine Description: va_end (List); } +/** + Print a parser error, using the source file name and line number + set by a previous call to SetParserPosition(). + + @param MessageCode application-specific error code + @param Text text to print in the error message + @param MsgFmt format string to print at the end of the error message +**/ VOID ParserError ( UINT32 MessageCode, @@ -134,21 +136,6 @@ ParserError ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a parser error, using the source file name and line number - set by a previous call to SetParserPosition(). - -Arguments: - MessageCode - application-specific error code - Text - text to print in the error message - MsgFmt - format string to print at the end of the error message - -Returns: - NA - ---*/ { va_list List; // @@ -181,6 +168,14 @@ Routine Description: va_end (List); } +/** + Print a parser warning, using the source file name and line number + set by a previous call to SetParserPosition(). + + @param ErrorCode application-specific error code + @param OffendingText text to print in the warning message + @param MsgFmt format string to print at the end of the warning message +**/ VOID ParserWarning ( UINT32 ErrorCode, @@ -188,21 +183,6 @@ ParserWarning ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a parser warning, using the source file name and line number - set by a previous call to SetParserPosition(). - -Arguments: - ErrorCode - application-specific error code - OffendingText - text to print in the warning message - MsgFmt - format string to print at the end of the warning message - -Returns: - NA - ---*/ { va_list List; // @@ -241,6 +221,19 @@ Routine Description: // } } +/** + Print a warning message. + + @param FileName name of the file where the warning was detected, or the name + of the application that detected the warning + @param LineNumber the line number where the warning was detected (parsers). + 0 should be specified if the utility is not a parser. + @param MessageCode an application-specific warning code that can be referenced in + other documentation. + @param Text the text in question (parsers) + @param MsgFmt the format string for the warning message. Can contain formatting + controls for use with varargs. +**/ VOID Warning ( CHAR8 *FileName, @@ -250,30 +243,6 @@ Warning ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a warning message. - -Arguments: - FileName - name of the file where the warning was detected, or the name - of the application that detected the warning - - LineNumber - the line number where the warning was detected (parsers). - 0 should be specified if the utility is not a parser. - - MessageCode - an application-specific warning code that can be referenced in - other documentation. - - Text - the text in question (parsers) - - MsgFmt - the format string for the warning message. Can contain formatting - controls for use with varargs. - -Returns: - None. - ---*/ { va_list List; @@ -313,6 +282,18 @@ Routine Description: va_end (List); } +/** + Print a Debug message. + + @param FileName typically the name of the utility printing the debug message, but + can be the name of a file being parsed. + @param LineNumber the line number in FileName (parsers) + @param MsgLevel Debug message print level (0~9) + @param Text the text in question (parsers) + @param MsgFmt the format string for the debug message. Can contain formatting + controls for use with varargs. + +**/ VOID DebugMsg ( CHAR8 *FileName, @@ -322,28 +303,6 @@ DebugMsg ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a Debug message. - -Arguments: - FileName - typically the name of the utility printing the debug message, but - can be the name of a file being parsed. - - LineNumber - the line number in FileName (parsers) - - MsgLevel - Debug message print level (0~9) - - Text - the text in question (parsers) - - MsgFmt - the format string for the debug message. Can contain formatting - controls for use with varargs. - -Returns: - None. - ---*/ { va_list List; // @@ -358,64 +317,52 @@ Routine Description: va_end (List); } -VOID -PrintMessage ( - CHAR8 *Type, - CHAR8 *FileName, - UINT32 LineNumber, - UINT32 MessageCode, - CHAR8 *Text, - CHAR8 *MsgFmt, - va_list List - ) -/*++ - -Routine Description: +/** Worker routine for all the utility printing services. Prints the message in a format that Visual Studio will find when scanning build outputs for errors or warnings. -Arguments: - Type - "warning" or "error" string to insert into the message to be - printed. The first character of this string (converted to uppercase) - is used to precede the MessageCode value in the output string. + @note: + If FileName == NULL then this utility will use the string passed into SetUtilityName(). - FileName - name of the file where the warning was detected, or the name - of the application that detected the warning + LineNumber is only used if the caller is a parser, in which case FileName refers to the + file being parsed. - LineNumber - the line number where the warning was detected (parsers). - 0 should be specified if the utility is not a parser. + Text and MsgFmt are both optional, though it would be of little use calling this function with + them both NULL. - MessageCode - an application-specific warning code that can be referenced in - other documentation. + Output will typically be of the form: + () : : : - Text - part of the message to print + Parser (LineNumber != 0) + VfrCompile.cpp(330) : error E2660: AddVfrDataStructField : function does not take 2 parameters + Generic utility (LineNumber == 0) + UtilityName : error E1234 : Text string : MsgFmt string and args - MsgFmt - the format string for the message. Can contain formatting + @param Type "warning" or "error" string to insert into the message to be + printed. The first character of this string (converted to uppercase) + is used to precede the MessageCode value in the output string. + @param FileName name of the file where the warning was detected, or the name + of the application that detected the warning + @param LineNumber the line number where the warning was detected (parsers). + 0 should be specified if the utility is not a parser. + @param MessageCode an application-specific warning code that can be referenced in + other documentation. + @param Text part of the message to print + @param MsgFmt the format string for the message. Can contain formatting controls for use with varargs. - List - the variable list. - -Returns: - None. - -Notes: - If FileName == NULL then this utility will use the string passed into SetUtilityName(). - - LineNumber is only used if the caller is a parser, in which case FileName refers to the - file being parsed. - - Text and MsgFmt are both optional, though it would be of little use calling this function with - them both NULL. - - Output will typically be of the form: - () : : : - - Parser (LineNumber != 0) - VfrCompile.cpp(330) : error E2660: AddVfrDataStructField : function does not take 2 parameters - Generic utility (LineNumber == 0) - UtilityName : error E1234 : Text string : MsgFmt string and args - ---*/ + @param List the variable list. +**/ +VOID +PrintMessage ( + CHAR8 *Type, + CHAR8 *FileName, + UINT32 LineNumber, + UINT32 MessageCode, + CHAR8 *Text, + CHAR8 *MsgFmt, + va_list List + ) { CHAR8 Line[MAX_LINE_LEN]; CHAR8 Line2[MAX_LINE_LEN]; @@ -523,24 +470,19 @@ Routine Description: } +/** + Print message into stdout. + + @param MsgFmt the format string for the message. Can contain formatting + controls for use with varargs. + @param List the variable list. +**/ STATIC VOID PrintSimpleMessage ( CHAR8 *MsgFmt, va_list List ) -/*++ -Routine Description: - Print message into stdout. - -Arguments: - MsgFmt - the format string for the message. Can contain formatting - controls for use with varargs. - List - the variable list. - -Returns: - None. ---*/ { CHAR8 Line[MAX_LINE_LEN]; // @@ -552,51 +494,37 @@ Routine Description: } } +/** + Set the position in a file being parsed. This can be used to + print error messages deeper down in a parser. + + @param SourceFileName name of the source file being parsed + @param LineNum line number of the source file being parsed +**/ VOID ParserSetPosition ( CHAR8 *SourceFileName, UINT32 LineNum ) -/*++ - -Routine Description: - Set the position in a file being parsed. This can be used to - print error messages deeper down in a parser. - -Arguments: - SourceFileName - name of the source file being parsed - LineNum - line number of the source file being parsed - -Returns: - NA - ---*/ { mSourceFileName = SourceFileName; mSourceFileLineNum = LineNum; } -VOID -SetUtilityName ( - CHAR8 *UtilityName - ) -/*++ - -Routine Description: +/** All printed error/warning/debug messages follow the same format, and typically will print a filename or utility name followed by the error text. However if a filename is not passed to the print routines, then they'll print the utility name if you call this function early in your app to set the utility name. -Arguments: - UtilityName - name of the utility, which will be printed with all - error/warning/debug messages. - -Returns: - NA - ---*/ + @param UtilityName name of the utility, which will be printed with all + error/warning/debug messages. +**/ +VOID +SetUtilityName ( + CHAR8 *UtilityName + ) { // // Save the name of the utility in our local variable. Make sure its @@ -613,69 +541,48 @@ Routine Description: } } -STATUS -GetUtilityStatus ( - VOID - ) -/*++ - -Routine Description: +/** When you call Error() or Warning(), this module keeps track of it and sets a local mStatus to STATUS_ERROR or STATUS_WARNING. When the utility exits, it can call this function to get the status and use it as a return value. -Arguments: - None. - -Returns: - Worst-case status reported, as defined by which print function was called. - ---*/ + @return Worst-case status reported, as defined by which print function was called. +**/ +STATUS +GetUtilityStatus ( + VOID + ) { return mStatus; } +/** + Set the printing message Level. This is used by the PrintMsg() function + to determine when/if a message should be printed. + + @param LogLevel 0~50 to specify the different level message. +**/ VOID SetPrintLevel ( UINT64 LogLevel ) -/*++ - -Routine Description: - Set the printing message Level. This is used by the PrintMsg() function - to determine when/if a message should be printed. - -Arguments: - LogLevel - 0~50 to specify the different level message. - -Returns: - NA - ---*/ { mPrintLogLevel = LogLevel; } +/** + Print a verbose level message. + + @param MsgFmt the format string for the message. Can contain formatting + controls for use with varargs. + @param List the variable list. +**/ VOID VerboseMsg ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a verbose level message. - -Arguments: - MsgFmt - the format string for the message. Can contain formatting - controls for use with varargs. - List - the variable list. - -Returns: - NA - ---*/ { va_list List; // @@ -690,25 +597,18 @@ Routine Description: va_end (List); } +/** + Print a default level message. + + @param MsgFmt the format string for the message. Can contain formatting + controls for use with varargs. + @param List the variable list. +**/ VOID NormalMsg ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a default level message. - -Arguments: - MsgFmt - the format string for the message. Can contain formatting - controls for use with varargs. - List - the variable list. - -Returns: - NA - ---*/ { va_list List; // @@ -723,25 +623,18 @@ Routine Description: va_end (List); } +/** + Print a key level message. + + @param MsgFmt the format string for the message. Can contain formatting + controls for use with varargs. + @param List the variable list. +**/ VOID KeyMsg ( CHAR8 *MsgFmt, ... ) -/*++ - -Routine Description: - Print a key level message. - -Arguments: - MsgFmt - the format string for the message. Can contain formatting - controls for use with varargs. - List - the variable list. - -Returns: - NA - ---*/ { va_list List; // @@ -756,28 +649,21 @@ Routine Description: va_end (List); } +/** + Set the limits of how many errors, warnings, and errors+warnings + we will print. + + @param MaxErrors maximum number of error messages to print + @param MaxWarnings maximum number of warning messages to print + @param MaxWarningsPlusErrors + maximum number of errors+warnings to print +**/ VOID SetPrintLimits ( UINT32 MaxErrors, UINT32 MaxWarnings, UINT32 MaxWarningsPlusErrors ) -/*++ - -Routine Description: - Set the limits of how many errors, warnings, and errors+warnings - we will print. - -Arguments: - MaxErrors - maximum number of error messages to print - MaxWarnings - maximum number of warning messages to print - MaxWarningsPlusErrors - - maximum number of errors+warnings to print - -Returns: - NA - ---*/ { mMaxErrors = MaxErrors; mMaxWarnings = MaxWarnings; diff --git a/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c b/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c index ace26eb71c..40e068c303 100644 --- a/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c +++ b/BaseTools/Source/C/Common/FirmwareVolumeBuffer.c @@ -78,29 +78,21 @@ FvBufCalculateChecksum8 ( // Procedures start // +/** + Clears out all files from the Fv buffer in memory + + @param SourceFv Address of the Fv in memory, this firmware volume will + be modified, if SourceFfsFile exists + @param SourceFfsFile Input FFS file to replace + + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND +**/ EFI_STATUS FvBufRemoveFileNew ( IN OUT VOID *Fv, IN EFI_GUID *Name ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - SourceFv - Address of the Fv in memory, this firmware volume will - be modified, if SourceFfsFile exists - SourceFfsFile - Input FFS file to replace - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - ---*/ { EFI_STATUS Status; EFI_FFS_FILE_HEADER* FileToRm; @@ -127,30 +119,21 @@ Routine Description: return EFI_SUCCESS; } +/** + Clears out all files from the Fv buffer in memory + @param SourceFv Address of the Fv in memory, this firmware volume will + be modified, if SourceFfsFile exists + @param SourceFfsFile Input FFS file to replace + + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND +**/ EFI_STATUS FvBufRemoveFile ( IN OUT VOID *Fv, IN EFI_GUID *Name ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - SourceFv - Address of the Fv in memory, this firmware volume will - be modified, if SourceFfsFile exists - SourceFfsFile - Input FFS file to replace - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - ---*/ { EFI_STATUS Status; EFI_FFS_FILE_HEADER *NextFile; @@ -216,27 +199,18 @@ Routine Description: return EFI_SUCCESS; } +/** + Clears out all files from the Fv buffer in memory + + @param SourceFfsFile Input FFS file to update the checksum for + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND +**/ EFI_STATUS FvBufChecksumFile ( IN OUT VOID *FfsFile ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - SourceFfsFile - Input FFS file to update the checksum for - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - ---*/ { EFI_FFS_FILE_HEADER* File = (EFI_FFS_FILE_HEADER*)FfsFile; EFI_FFS_FILE_STATE StateBackup; @@ -272,29 +246,20 @@ Routine Description: return EFI_SUCCESS; } +/** + Clears out all files from the Fv buffer in memory + + @param SourceFv Address of the Fv in memory, this firmware volume will + be modified, if SourceFfsFile exists + @param SourceFfsFile Input FFS file to replace + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND +**/ EFI_STATUS FvBufChecksumHeader ( IN OUT VOID *Fv ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - SourceFv - Address of the Fv in memory, this firmware volume will - be modified, if SourceFfsFile exists - SourceFfsFile - Input FFS file to replace - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - ---*/ { EFI_FIRMWARE_VOLUME_HEADER* FvHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; @@ -308,31 +273,22 @@ Routine Description: return EFI_SUCCESS; } - -EFI_STATUS -FvBufDuplicate ( - IN VOID *SourceFv, - IN OUT VOID **DestinationFv - ) -/*++ - -Routine Description: - +/** Clears out all files from the Fv buffer in memory -Arguments: - - SourceFv - Address of the Fv in memory - DestinationFv - Output for destination Fv + @param SourceFv - Address of the Fv in memory + @param DestinationFv - Output for destination Fv DestinationFv == NULL - invalid parameter *DestinationFv == NULL - memory will be allocated *DestinationFv != NULL - this address will be the destination -Returns: - - EFI_SUCCESS - ---*/ + @retval EFI_SUCCESS +**/ +EFI_STATUS +FvBufDuplicate ( + IN VOID *SourceFv, + IN OUT VOID **DestinationFv + ) { EFI_STATUS Status; UINTN size; @@ -358,35 +314,26 @@ Routine Description: return EFI_SUCCESS; } - -EFI_STATUS -FvBufExtend ( - IN VOID **Fv, - IN UINTN Size - ) -/*++ - -Routine Description: - +/** Extends a firmware volume by the given number of bytes. BUGBUG: Does not handle the case where the firmware volume has a VTF (Volume Top File). The VTF will not be moved to the end of the extended FV. -Arguments: - - Fv - Source and destination firmware volume. - Note: The original firmware volume buffer is freed! + @param Fv Source and destination firmware volume. + Note: The original firmware volume buffer is freed! - Size - The minimum size that the firmware volume is to be extended by. - The FV may be extended more than this size. + @param Size The minimum size that the firmware volume is to be extended by. + The FV may be extended more than this size. -Returns: - - EFI_SUCCESS - ---*/ + @retval EFI_SUCCESS +**/ +EFI_STATUS +FvBufExtend ( + IN VOID **Fv, + IN UINTN Size + ) { EFI_STATUS Status; UINTN OldSize; @@ -469,27 +416,17 @@ Routine Description: } +/** + Clears out all files from the Fv buffer in memory + + @param Fv Address of the Fv in memory + @retval EFI_SUCCESS +**/ EFI_STATUS FvBufClearAllFiles ( IN OUT VOID *Fv ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - Fv - Address of the Fv in memory - -Returns: - - EFI_SUCCESS - ---*/ - { EFI_FIRMWARE_VOLUME_HEADER *hdr = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; EFI_STATUS Status; @@ -509,28 +446,18 @@ Routine Description: return EFI_SUCCESS; } +/** + Clears out all files from the Fv buffer in memory + + @param Fv Address of the Fv in memory + @retval EFI_SUCCESS +**/ EFI_STATUS FvBufGetSize ( IN VOID *Fv, OUT UINTN *Size ) -/*++ - -Routine Description: - - Clears out all files from the Fv buffer in memory - -Arguments: - - Fv - Address of the Fv in memory - -Returns: - - EFI_SUCCESS - ---*/ - { EFI_FIRMWARE_VOLUME_HEADER *hdr = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; EFI_FV_BLOCK_MAP_ENTRY *blk = hdr->BlockMap; @@ -554,28 +481,19 @@ Routine Description: return EFI_SUCCESS; } +/** + Adds a new FFS file + + @param Fv Address of the Fv in memory + @param File FFS file to add to Fv + @retval EFI_SUCCESS +**/ EFI_STATUS FvBufAddFile ( IN OUT VOID *Fv, IN VOID *File ) -/*++ - -Routine Description: - - Adds a new FFS file - -Arguments: - - Fv - Address of the Fv in memory - File - FFS file to add to Fv - -Returns: - - EFI_SUCCESS - ---*/ { EFI_FIRMWARE_VOLUME_HEADER *hdr = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; @@ -652,32 +570,23 @@ Routine Description: return EFI_SUCCESS; } +/** + Adds a new FFS file. Extends the firmware volume if needed. + + @param Fv Source and destination firmware volume. + Note: If the FV is extended, then the original firmware volume + buffer is freed! + + @param Size The minimum size that the firmware volume is to be extended by. + The FV may be extended more than this size. + @retval EFI_SUCCESS +**/ EFI_STATUS FvBufAddFileWithExtend ( IN OUT VOID **Fv, IN VOID *File ) -/*++ - -Routine Description: - - Adds a new FFS file. Extends the firmware volume if needed. - -Arguments: - - Fv - Source and destination firmware volume. - Note: If the FV is extended, then the original firmware volume - buffer is freed! - - Size - The minimum size that the firmware volume is to be extended by. - The FV may be extended more than this size. - -Returns: - - EFI_SUCCESS - ---*/ { EFI_STATUS Status; EFI_FFS_FILE_HEADER* NewFile; @@ -706,29 +615,20 @@ Routine Description: return Status; } +/** + Adds a new FFS VFT (Volume Top File) file. In other words, adds the + file to the end of the firmware volume. + + @param Fv Address of the Fv in memory + @param File FFS file to add to Fv + @retval EFI_SUCCESS +**/ EFI_STATUS FvBufAddVtfFile ( IN OUT VOID *Fv, IN VOID *File ) -/*++ - -Routine Description: - - Adds a new FFS VFT (Volume Top File) file. In other words, adds the - file to the end of the firmware volume. - -Arguments: - - Fv - Address of the Fv in memory - File - FFS file to add to Fv - -Returns: - - EFI_SUCCESS - ---*/ { EFI_STATUS Status; @@ -811,52 +711,35 @@ Routine Description: return EFI_SUCCESS; } +/** + Expands the 3 byte size commonly used in Firmware Volume data structures + + @param Size Address of the 3 byte array representing the size + @return UINT32 +**/ VOID FvBufCompact3ByteSize ( OUT VOID* SizeDest, IN UINT32 Size ) -/*++ - -Routine Description: - - Expands the 3 byte size commonly used in Firmware Volume data structures - -Arguments: - - Size - Address of the 3 byte array representing the size - -Returns: - - UINT32 - ---*/ { ((UINT8*)SizeDest)[0] = (UINT8)Size; ((UINT8*)SizeDest)[1] = (UINT8)(Size >> 8); ((UINT8*)SizeDest)[2] = (UINT8)(Size >> 16); } +/** + Get the FFS file size. + + @param Ffs Pointer to FFS header + + @return UINT32 +**/ UINT32 FvBufGetFfsFileSize ( IN EFI_FFS_FILE_HEADER *Ffs ) -/*++ - -Routine Description: - - Get the FFS file size. - -Arguments: - - Ffs - Pointer to FFS header - -Returns: - - UINT32 - ---*/ { if (Ffs == NULL) { return 0; @@ -867,25 +750,17 @@ Routine Description: return FvBufExpand3ByteSize(Ffs->Size); } +/** + Get the FFS header size. + + @param Ffs Pointer to FFS header + + @return UINT32 +**/ UINT32 FvBufGetFfsHeaderSize ( IN EFI_FFS_FILE_HEADER *Ffs ) -/*++ - -Routine Description: - - Get the FFS header size. - -Arguments: - - Ffs - Pointer to FFS header - -Returns: - - UINT32 - ---*/ { if (Ffs == NULL) { return 0; @@ -896,60 +771,44 @@ Routine Description: return sizeof(EFI_FFS_FILE_HEADER); } +/** + Expands the 3 byte size commonly used in Firmware Volume data structures + + @param Size Address of the 3 byte array representing the size + + @return UINT32 +**/ UINT32 FvBufExpand3ByteSize ( IN VOID* Size ) -/*++ - -Routine Description: - - Expands the 3 byte size commonly used in Firmware Volume data structures - -Arguments: - - Size - Address of the 3 byte array representing the size - -Returns: - - UINT32 - ---*/ { return (((UINT8*)Size)[2] << 16) + (((UINT8*)Size)[1] << 8) + ((UINT8*)Size)[0]; } +/** + Iterates through the files contained within the firmware volume + + @param Fv Address of the Fv in memory + @param Key Should be 0 to get the first file. After that, it should be + passed back in without modifying its contents to retrieve + subsequent files. + @param File Output file pointer + File == NULL - invalid parameter + otherwise - *File will be update to the location of the file + + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufFindNextFile ( IN VOID *Fv, IN OUT UINTN *Key, OUT VOID **File ) -/*++ - -Routine Description: - - Iterates through the files contained within the firmware volume - -Arguments: - - Fv - Address of the Fv in memory - Key - Should be 0 to get the first file. After that, it should be - passed back in without modifying its contents to retrieve - subsequent files. - File - Output file pointer - File == NULL - invalid parameter - otherwise - *File will be update to the location of the file - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_FIRMWARE_VOLUME_HEADER *hdr = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; @@ -1028,35 +887,26 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Searches the Fv for a file by its name + @param Fv Address of the Fv in memory + @param Name Guid filename to search for in the firmware volume + @param File Output file pointer + File == NULL - Only determine if the file exists, based on return + value from the function call. + otherwise - *File will be update to the location of the file + + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufFindFileByName ( IN VOID *Fv, IN EFI_GUID *Name, OUT VOID **File ) -/*++ - -Routine Description: - - Searches the Fv for a file by its name - -Arguments: - - Fv - Address of the Fv in memory - Name - Guid filename to search for in the firmware volume - File - Output file pointer - File == NULL - Only determine if the file exists, based on return - value from the function call. - otherwise - *File will be update to the location of the file - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_STATUS Status; UINTN Key; @@ -1080,35 +930,26 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Searches the Fv for a file by its type + + @param Fv Address of the Fv in memory + @param Type FFS FILE type to search for + @param File Output file pointer + (File == NULL) -> Only determine if the file exists, based on return + value from the function call. + otherwise -> *File will be update to the location of the file + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufFindFileByType ( IN VOID *Fv, IN EFI_FV_FILETYPE Type, OUT VOID **File ) -/*++ - -Routine Description: - - Searches the Fv for a file by its type - -Arguments: - - Fv - Address of the Fv in memory - Type - FFS FILE type to search for - File - Output file pointer - (File == NULL) -> Only determine if the file exists, based on return - value from the function call. - otherwise -> *File will be update to the location of the file - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_STATUS Status; UINTN Key; @@ -1132,34 +973,25 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Searches the requested file for raw data. + + This routine either returns all the payload of a EFI_FV_FILETYPE_RAW file, + or finds the EFI_SECTION_RAW section within the file and returns its data. + + @param FfsFile Address of the FFS file in memory + @param RawData Pointer to the raw data within the file + (This is NOT allocated. It is within the file.) + @param RawDataSize Size of the raw data within the file + @return EFI_STATUS +**/ EFI_STATUS FvBufGetFileRawData ( IN VOID* FfsFile, OUT VOID** RawData, OUT UINTN* RawDataSize ) -/*++ - -Routine Description: - - Searches the requested file for raw data. - - This routine either returns all the payload of a EFI_FV_FILETYPE_RAW file, - or finds the EFI_SECTION_RAW section within the file and returns its data. - -Arguments: - - FfsFile - Address of the FFS file in memory - RawData - Pointer to the raw data within the file - (This is NOT allocated. It is within the file.) - RawDataSize - Size of the raw data within the file - -Returns: - - EFI_STATUS - ---*/ { EFI_STATUS Status; EFI_FFS_FILE_HEADER* File; @@ -1195,7 +1027,19 @@ Routine Description: } +/** + Packages up a FFS file containing the input raw data. + + The file created will have a type of EFI_FV_FILETYPE_FREEFORM, and will + contain one EFI_FV_FILETYPE_RAW section. + + @param RawData Pointer to the raw data to be packed + @param RawDataSize Size of the raw data to be packed + @param FfsFile Address of the packaged FFS file. + Note: The called must deallocate this memory! + @return EFI_STATUS +**/ EFI_STATUS FvBufPackageFreeformRawFile ( IN EFI_GUID* Filename, @@ -1203,27 +1047,6 @@ FvBufPackageFreeformRawFile ( IN UINTN RawDataSize, OUT VOID** FfsFile ) -/*++ - -Routine Description: - - Packages up a FFS file containing the input raw data. - - The file created will have a type of EFI_FV_FILETYPE_FREEFORM, and will - contain one EFI_FV_FILETYPE_RAW section. - -Arguments: - - RawData - Pointer to the raw data to be packed - RawDataSize - Size of the raw data to be packed - FfsFile - Address of the packaged FFS file. - Note: The called must deallocate this memory! - -Returns: - - EFI_STATUS - ---*/ { EFI_FFS_FILE_HEADER* NewFile; UINT32 NewFileSize; @@ -1304,7 +1127,22 @@ Routine Description: return EFI_SUCCESS; } +/** + Iterates through the sections contained within a given array of sections + + @param SectionsStart Address of the start of the FFS sections array + @param TotalSectionsSize Total size of all the sections + @param Key Should be 0 to get the first section. After that, it should be + passed back in without modifying its contents to retrieve + subsequent files. + @param Section Output section pointer + (Section == NULL) -> invalid parameter + otherwise -> *Section will be update to the location of the file + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufFindNextSection ( IN VOID *SectionsStart, @@ -1312,30 +1150,6 @@ FvBufFindNextSection ( IN OUT UINTN *Key, OUT VOID **Section ) -/*++ - -Routine Description: - - Iterates through the sections contained within a given array of sections - -Arguments: - - SectionsStart - Address of the start of the FFS sections array - TotalSectionsSize - Total size of all the sections - Key - Should be 0 to get the first section. After that, it should be - passed back in without modifying its contents to retrieve - subsequent files. - Section - Output section pointer - (Section == NULL) -> invalid parameter - otherwise -> *Section will be update to the location of the file - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_COMMON_SECTION_HEADER *sectionHdr; UINTN sectionSize; @@ -1363,31 +1177,22 @@ Routine Description: } +/** + Searches the FFS file and counts the number of sections found. + The sections are NOT recursed. + + @param FfsFile Address of the FFS file in memory + @param Count The location to store the section count in + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufCountSections ( IN VOID* FfsFile, IN UINTN* Count ) -/*++ - -Routine Description: - - Searches the FFS file and counts the number of sections found. - The sections are NOT recursed. - -Arguments: - - FfsFile - Address of the FFS file in memory - Count - The location to store the section count in - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_STATUS Status; UINTN Key; @@ -1424,35 +1229,26 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Searches the FFS file for a section by its type + @param FfsFile Address of the FFS file in memory + @param Type FFS FILE section type to search for + @param Section Output section pointer + (Section == NULL) -> Only determine if the section exists, based on return + value from the function call. + otherwise -> *Section will be update to the location of the file + + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufFindSectionByType ( IN VOID *FfsFile, IN UINT8 Type, OUT VOID **Section ) -/*++ - -Routine Description: - - Searches the FFS file for a section by its type - -Arguments: - - FfsFile - Address of the FFS file in memory - Type - FFS FILE section type to search for - Section - Output section pointer - (Section == NULL) -> Only determine if the section exists, based on return - value from the function call. - otherwise -> *Section will be update to the location of the file - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_STATUS Status; UINTN Key; @@ -1487,30 +1283,21 @@ Routine Description: return EFI_NOT_FOUND; } - -EFI_STATUS -FvBufShrinkWrap ( - IN VOID *Fv - ) -/*++ - -Routine Description: - +/** Shrinks a firmware volume (in place) to provide a minimal FV. BUGBUG: Does not handle the case where the firmware volume has a VTF (Volume Top File). The VTF will not be moved to the end of the extended FV. -Arguments: - - Fv - Firmware volume. + @param Fv Firmware volume. -Returns: - - EFI_SUCCESS - ---*/ + @retval EFI_SUCCESS +**/ +EFI_STATUS +FvBufShrinkWrap ( + IN VOID *Fv + ) { EFI_STATUS Status; UINTN OldSize; @@ -1569,32 +1356,23 @@ Routine Description: } +/** + Searches the FFS file for a section by its type + + @param Fv Address of the Fv in memory + @param BlockSize The size of the blocks to convert the Fv to. If the total size + of the Fv is not evenly divisible by this size, then + EFI_INVALID_PARAMETER will be returned. + @retval EFI_SUCCESS + @retval EFI_NOT_FOUND + @retval EFI_VOLUME_CORRUPTED +**/ EFI_STATUS FvBufUnifyBlockSizes ( IN OUT VOID *Fv, IN UINTN BlockSize ) -/*++ - -Routine Description: - - Searches the FFS file for a section by its type - -Arguments: - - Fv - Address of the Fv in memory - BlockSize - The size of the blocks to convert the Fv to. If the total size - of the Fv is not evenly divisible by this size, then - EFI_INVALID_PARAMETER will be returned. - -Returns: - - EFI_SUCCESS - EFI_NOT_FOUND - EFI_VOLUME_CORRUPTED - ---*/ { EFI_FIRMWARE_VOLUME_HEADER *hdr = (EFI_FIRMWARE_VOLUME_HEADER*)Fv; EFI_FV_BLOCK_MAP_ENTRY *blk = hdr->BlockMap; @@ -1641,28 +1419,20 @@ Routine Description: return EFI_SUCCESS; } +/** + This function calculates the UINT16 sum for the requested region. + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + + @return The 16 bit checksum +**/ STATIC UINT16 FvBufCalculateSum16 ( IN UINT16 *Buffer, IN UINTN Size ) -/*++ - -Routine Description: - - This function calculates the UINT16 sum for the requested region. - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 16 bit checksum - ---*/ { UINTN Index; UINT16 Sum; @@ -1679,56 +1449,38 @@ Routine Description: return (UINT16) Sum; } +/** + This function calculates the value needed for a valid UINT16 checksum + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + @return The 16 bit checksum value needed. +**/ STATIC UINT16 FvBufCalculateChecksum16 ( IN UINT16 *Buffer, IN UINTN Size ) -/*++ - -Routine Description:: - - This function calculates the value needed for a valid UINT16 checksum - -Arguments: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Returns: - - The 16 bit checksum value needed. - ---*/ { return (UINT16)(0x10000 - FvBufCalculateSum16 (Buffer, Size)); } +/** + This function calculates the UINT8 sum for the requested region. + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + @return The 8 bit checksum value needed. +**/ STATIC UINT8 FvBufCalculateSum8 ( IN UINT8 *Buffer, IN UINTN Size ) -/*++ - -Description: - - This function calculates the UINT8 sum for the requested region. - -Input: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Return: - - The 8 bit checksum value needed. - ---*/ { UINTN Index; UINT8 Sum; @@ -1745,29 +1497,20 @@ FvBufCalculateSum8 ( return Sum; } +/** + This function calculates the value needed for a valid UINT8 checksum + + @param Buffer Pointer to buffer containing byte data of component. + @param Size Size of the buffer + @return The 8 bit checksum value needed. +**/ STATIC UINT8 FvBufCalculateChecksum8 ( IN UINT8 *Buffer, IN UINTN Size ) -/*++ - -Description: - - This function calculates the value needed for a valid UINT8 checksum - -Input: - - Buffer Pointer to buffer containing byte data of component. - Size Size of the buffer - -Return: - - The 8 bit checksum value needed. - ---*/ { return (UINT8)(0x100 - FvBufCalculateSum8 (Buffer, Size)); } diff --git a/BaseTools/Source/C/Common/FvLib.c b/BaseTools/Source/C/Common/FvLib.c index 82dc557bb7..37631f470f 100644 --- a/BaseTools/Source/C/Common/FvLib.c +++ b/BaseTools/Source/C/Common/FvLib.c @@ -22,29 +22,22 @@ UINT32 mFvLength = 0; // // External function implementations // -EFI_STATUS -InitializeFvLib ( - IN VOID *Fv, - IN UINT32 FvLength - ) -/*++ - -Routine Description: +/** This initializes the FV lib with a pointer to the FV and length. It does not verify the FV in any way. -Arguments: + @param Fv Buffer containing the FV. + @param FvLength Length of the FV - Fv Buffer containing the FV. - FvLength Length of the FV - -Returns: - - EFI_SUCCESS Function Completed successfully. - EFI_INVALID_PARAMETER A required parameter was NULL. - ---*/ + @retval EFI_SUCCESS Function Completed successfully. + @retval EFI_INVALID_PARAMETER A required parameter was NULL. +**/ +EFI_STATUS +InitializeFvLib ( + IN VOID *Fv, + IN UINT32 FvLength + ) { // // Verify input arguments @@ -59,29 +52,21 @@ Routine Description: return EFI_SUCCESS; } +/** + This function returns a pointer to the current FV and the size. + + @param FvHeader Pointer to the FV buffer. + @param FvLength Length of the FV + + @retval EFI_SUCCESS Function Completed successfully. + @retval EFI_INVALID_PARAMETER A required parameter was NULL. + @retvalEFI_ABORTED The library needs to be initialized. +**/ EFI_STATUS GetFvHeader ( OUT EFI_FIRMWARE_VOLUME_HEADER **FvHeader, OUT UINT32 *FvLength ) -/*++ - -Routine Description: - - This function returns a pointer to the current FV and the size. - -Arguments: - - FvHeader Pointer to the FV buffer. - FvLength Length of the FV - -Returns: - - EFI_SUCCESS Function Completed successfully. - EFI_INVALID_PARAMETER A required parameter was NULL. - EFI_ABORTED The library needs to be initialized. - ---*/ { // // Verify library has been initialized. @@ -101,31 +86,23 @@ Routine Description: return EFI_SUCCESS; } -EFI_STATUS -GetNextFile ( - IN EFI_FFS_FILE_HEADER *CurrentFile, - OUT EFI_FFS_FILE_HEADER **NextFile - ) -/*++ - -Routine Description: - +/** This function returns the next file. If the current file is NULL, it returns the first file in the FV. If the function returns EFI_SUCCESS and the file pointer is NULL, then there are no more files in the FV. -Arguments: - - CurrentFile Pointer to the current file, must be within the current FV. - NextFile Pointer to the next file in the FV. - -Returns: + @param CurrentFile Pointer to the current file, must be within the current FV. + @param NextFile Pointer to the next file in the FV. - EFI_SUCCESS Function completed successfully. - EFI_INVALID_PARAMETER A required parameter was NULL or is out of range. - EFI_ABORTED The library needs to be initialized. - ---*/ + @retval EFI_SUCCESS Function completed successfully. + @retval EFI_INVALID_PARAMETER A required parameter was NULL or is out of range. + @retval EFI_ABORTED The library needs to be initialized. +**/ +EFI_STATUS +GetNextFile ( + IN EFI_FFS_FILE_HEADER *CurrentFile, + OUT EFI_FFS_FILE_HEADER **NextFile + ) { EFI_STATUS Status; @@ -214,29 +191,21 @@ Routine Description: return EFI_SUCCESS; } +/** + Find a file by name. The function will return NULL if the file is not found. + + @param FileName The GUID file name of the file to search for. + @param File Return pointer. In the case of an error, contents are undefined. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_ABORTED An error was encountered. + @retval EFI_INVALID_PARAMETER One of the parameters was NULL. +**/ EFI_STATUS GetFileByName ( IN EFI_GUID *FileName, OUT EFI_FFS_FILE_HEADER **File ) -/*++ - -Routine Description: - - Find a file by name. The function will return NULL if the file is not found. - -Arguments: - - FileName The GUID file name of the file to search for. - File Return pointer. In the case of an error, contents are undefined. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_ABORTED An error was encountered. - EFI_INVALID_PARAMETER One of the parameters was NULL. - ---*/ { EFI_FFS_FILE_HEADER *CurrentFile; EFI_STATUS Status; @@ -295,33 +264,25 @@ Routine Description: return EFI_SUCCESS; } +/** + Find a file by type and instance. An instance of 1 is the first instance. + The function will return NULL if a matching file cannot be found. + File type EFI_FV_FILETYPE_ALL means any file type is valid. + + @param FileType Type of file to search for. + @param Instance Instance of the file type to return. + @param File Return pointer. In the case of an error, contents are undefined. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_ABORTED An error was encountered. + @retval EFI_INVALID_PARAMETER One of the parameters was NULL. +**/ EFI_STATUS GetFileByType ( IN EFI_FV_FILETYPE FileType, IN UINTN Instance, OUT EFI_FFS_FILE_HEADER **File ) -/*++ - -Routine Description: - - Find a file by type and instance. An instance of 1 is the first instance. - The function will return NULL if a matching file cannot be found. - File type EFI_FV_FILETYPE_ALL means any file type is valid. - -Arguments: - - FileType Type of file to search for. - Instance Instance of the file type to return. - File Return pointer. In the case of an error, contents are undefined. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_ABORTED An error was encountered. - EFI_INVALID_PARAMETER One of the parameters was NULL. - ---*/ { EFI_FFS_FILE_HEADER *CurrentFile; EFI_STATUS Status; @@ -383,6 +344,23 @@ Routine Description: return EFI_SUCCESS; } +/** + Helper function to search a sequence of sections from the section pointed + by FirstSection to SearchEnd for the Instance-th section of type SectionType. + The current counter is saved in StartIndex and when the section is found, it's + saved in Section. GUID-defined sections, if special processing is not required, + are searched recursively in a depth-first manner. + + @param FirstSection The first section to start searching from. + @param SearchEnd The end address to stop search. + @param SectionType The type of section to search. + @param StartIndex The current counter is saved. + @param Instance The requested n-th section number. + @param Section The found section returned. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_NOT_FOUND The section is not found. +**/ EFI_STATUS SearchSectionByType ( IN EFI_FILE_SECTION_POINTER FirstSection, @@ -392,30 +370,6 @@ SearchSectionByType ( IN UINTN Instance, OUT EFI_FILE_SECTION_POINTER *Section ) -/*++ - -Routine Description: - - Helper function to search a sequence of sections from the section pointed - by FirstSection to SearchEnd for the Instance-th section of type SectionType. - The current counter is saved in StartIndex and when the section is found, it's - saved in Section. GUID-defined sections, if special processing is not required, - are searched recursively in a depth-first manner. - -Arguments: - - FirstSection The first section to start searching from. - SearchEnd The end address to stop search. - SectionType The type of section to search. - StartIndex The current counter is saved. - Instance The requested n-th section number. - Section The found section returned. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_NOT_FOUND The section is not found. ---*/ { EFI_FILE_SECTION_POINTER CurrentSection; EFI_FILE_SECTION_POINTER InnerSection; @@ -479,6 +433,22 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Find a section in a file by type and instance. An instance of 1 is the first + instance. The function will return NULL if a matching section cannot be found. + GUID-defined sections, if special processing is not needed, are handled in a + depth-first manner. + + @param File The file to search. + @param SectionType Type of file to search for. + @param Instance Instance of the section to return. + @param Section Return pointer. In the case of an error, contents are undefined. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_ABORTED An error was encountered. + @retval EFI_INVALID_PARAMETER One of the parameters was NULL. + @retval EFI_NOT_FOUND No found. +**/ EFI_STATUS GetSectionByType ( IN EFI_FFS_FILE_HEADER *File, @@ -486,29 +456,6 @@ GetSectionByType ( IN UINTN Instance, OUT EFI_FILE_SECTION_POINTER *Section ) -/*++ - -Routine Description: - - Find a section in a file by type and instance. An instance of 1 is the first - instance. The function will return NULL if a matching section cannot be found. - GUID-defined sections, if special processing is not needed, are handled in a - depth-first manner. - -Arguments: - - File The file to search. - SectionType Type of file to search for. - Instance Instance of the section to return. - Section Return pointer. In the case of an error, contents are undefined. - -Returns: - - EFI_SUCCESS The function completed successfully. - EFI_ABORTED An error was encountered. - EFI_INVALID_PARAMETER One of the parameters was NULL. - EFI_NOT_FOUND No found. ---*/ { EFI_FILE_SECTION_POINTER CurrentSection; EFI_STATUS Status; @@ -560,31 +507,25 @@ Routine Description: return EFI_NOT_FOUND; } } + // // will not parse compressed sections // -EFI_STATUS -VerifyFv ( - IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader - ) -/*++ - -Routine Description: +/** Verify the current pointer points to a valid FV header. -Arguments: - - FvHeader Pointer to an alleged FV file. - -Returns: - - EFI_SUCCESS The FV header is valid. - EFI_VOLUME_CORRUPTED The FV header is not valid. - EFI_INVALID_PARAMETER A required parameter was NULL. - EFI_ABORTED Operation aborted. + @param FvHeader Pointer to an alleged FV file. ---*/ + @retval EFI_SUCCESS The FV header is valid. + @retval EFI_VOLUME_CORRUPTED The FV header is not valid. + @retval EFI_INVALID_PARAMETER A required parameter was NULL. + @retval EFI_ABORTED Operation aborted. +**/ +EFI_STATUS +VerifyFv ( + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader + ) { UINT16 Checksum; @@ -612,28 +553,20 @@ Routine Description: return EFI_SUCCESS; } +/** + Verify the current pointer points to a FFS file header. + + @param FfsHeader Pointer to an alleged FFS file. + + @retval EFI_SUCCESS The Ffs header is valid. + @retval EFI_NOT_FOUND This "file" is the beginning of free space. + @retval EFI_VOLUME_CORRUPTED The Ffs header is not valid. + @retval EFI_ABORTED The erase polarity is not known. +**/ EFI_STATUS VerifyFfsFile ( IN EFI_FFS_FILE_HEADER *FfsHeader ) -/*++ - -Routine Description: - - Verify the current pointer points to a FFS file header. - -Arguments: - - FfsHeader Pointer to an alleged FFS file. - -Returns: - - EFI_SUCCESS The Ffs header is valid. - EFI_NOT_FOUND This "file" is the beginning of free space. - EFI_VOLUME_CORRUPTED The Ffs header is not valid. - EFI_ABORTED The erase polarity is not known. - ---*/ { BOOLEAN ErasePolarity; EFI_STATUS Status; @@ -754,25 +687,17 @@ GetSectionHeaderLength( return sizeof(EFI_COMMON_SECTION_HEADER); } +/** + Get FFS file length including FFS header. + + @param FfsHeader Pointer to EFI_FFS_FILE_HEADER. + + @return UINT32 Length of FFS file header. +**/ UINT32 GetFfsFileLength ( EFI_FFS_FILE_HEADER *FfsHeader ) -/*++ - -Routine Description: - - Get FFS file length including FFS header. - -Arguments: - - FfsHeader Pointer to EFI_FFS_FILE_HEADER. - -Returns: - - UINT32 Length of FFS file header. - ---*/ { if (FfsHeader == NULL) { return 0; @@ -800,25 +725,17 @@ GetSectionFileLength ( return Length; } +/** + Converts a three byte length value into a UINT32. + + @param ThreeByteLength Pointer to the first of the 3 byte length. + + @return UINT32 Size of the section +**/ UINT32 GetLength ( UINT8 *ThreeByteLength ) -/*++ - -Routine Description: - - Converts a three byte length value into a UINT32. - -Arguments: - - ThreeByteLength Pointer to the first of the 3 byte length. - -Returns: - - UINT32 Size of the section - ---*/ { UINT32 Length; @@ -832,28 +749,20 @@ Routine Description: return Length; } -EFI_STATUS -GetErasePolarity ( - OUT BOOLEAN *ErasePolarity - ) -/*++ - -Routine Description: - +/** This function returns with the FV erase polarity. If the erase polarity for a bit is 1, the function return TRUE. -Arguments: - - ErasePolarity A pointer to the erase polarity. - -Returns: + @param ErasePolarity A pointer to the erase polarity. - EFI_SUCCESS The function completed successfully. - EFI_INVALID_PARAMETER One of the input parameters was invalid. - EFI_ABORTED Operation aborted. - ---*/ + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER One of the input parameters was invalid. + @retval EFI_ABORTED Operation aborted. +**/ +EFI_STATUS +GetErasePolarity ( + OUT BOOLEAN *ErasePolarity + ) { EFI_STATUS Status; @@ -886,28 +795,20 @@ Routine Description: return EFI_SUCCESS; } +/** + This function returns a the highest state bit in the FFS that is set. + It in no way validate the FFS file. + + @param ErasePolarity The erase polarity for the file state bits. + @param FfsHeader Pointer to a FFS file. + + @retval UINT8 The hightest set state of the file. +**/ UINT8 GetFileState ( IN BOOLEAN ErasePolarity, IN EFI_FFS_FILE_HEADER *FfsHeader ) -/*++ - -Routine Description: - - This function returns a the highest state bit in the FFS that is set. - It in no way validate the FFS file. - -Arguments: - - ErasePolarity The erase polarity for the file state bits. - FfsHeader Pointer to a FFS file. - -Returns: - - UINT8 The hightest set state of the file. - ---*/ { UINT8 FileState; UINT8 HighestBit; diff --git a/BaseTools/Source/C/Common/MemoryFile.c b/BaseTools/Source/C/Common/MemoryFile.c index 8154a3c990..4748132683 100644 --- a/BaseTools/Source/C/Common/MemoryFile.c +++ b/BaseTools/Source/C/Common/MemoryFile.c @@ -27,29 +27,21 @@ CheckMemoryFileState ( // Function implementations // -EFI_STATUS -GetMemoryFile ( - IN CHAR8 *InputFileName, - OUT EFI_HANDLE *OutputMemoryFile - ) -/*++ - -Routine Description: - +/** This opens a file, reads it into memory and returns a memory file object. -Arguments: - - InputFile Memory file image. - OutputMemoryFile Handle to memory file - -Returns: + @param InputFile Memory file image. + @param OutputMemoryFile Handle to memory file - EFI_STATUS + @return EFI_STATUS OutputMemoryFile is valid if !EFI_ERROR - ---*/ +**/ +EFI_STATUS +GetMemoryFile ( + IN CHAR8 *InputFileName, + OUT EFI_HANDLE *OutputMemoryFile + ) { EFI_STATUS Status; CHAR8 *InputFileImage; @@ -78,26 +70,17 @@ Routine Description: return EFI_SUCCESS; } +/** + Frees all memory associated with the input memory file. + + @param InputMemoryFile Handle to memory file + @return EFI_STATUS +**/ EFI_STATUS FreeMemoryFile ( IN EFI_HANDLE InputMemoryFile ) -/*++ - -Routine Description: - - Frees all memory associated with the input memory file. - -Arguments: - - InputMemoryFile Handle to memory file - -Returns: - - EFI_STATUS - ---*/ { MEMORY_FILE *MemoryFile; @@ -118,31 +101,22 @@ Routine Description: return EFI_SUCCESS; } - -CHAR8 * -ReadMemoryFileLine ( - IN EFI_HANDLE InputMemoryFile - ) -/*++ - -Routine Description: - +/** This function reads a line from the memory file. The newline characters are stripped and a null terminated string is returned. If the string pointer returned is non-NULL, then the caller must free the memory associated with this string. -Arguments: - - InputMemoryFile Handle to memory file - -Returns: - - NULL if error or EOF - NULL character termincated string otherwise (MUST BE FREED BY CALLER) + @param InputMemoryFile Handle to memory file ---*/ + @retval NULL if error or EOF + @retval NULL character termincated string otherwise (MUST BE FREED BY CALLER) +**/ +CHAR8 * +ReadMemoryFileLine ( + IN EFI_HANDLE InputMemoryFile + ) { CHAR8 *EndOfLine; UINTN CharsToCopy; diff --git a/BaseTools/Source/C/Common/MemoryFile.h b/BaseTools/Source/C/Common/MemoryFile.h index 58fc8bb224..c84848cf15 100644 --- a/BaseTools/Source/C/Common/MemoryFile.h +++ b/BaseTools/Source/C/Common/MemoryFile.h @@ -27,79 +27,53 @@ typedef struct { // Functions declarations // -EFI_STATUS -GetMemoryFile ( - IN CHAR8 *InputFileName, - OUT EFI_HANDLE *OutputMemoryFile - ) -; /** - -Routine Description: - This opens a file, reads it into memory and returns a memory file object. -Arguments: - - InputFile Memory file image. - OutputMemoryFile Handle to memory file + @param InputFile Memory file image. + @param OutputMemoryFile Handle to memory file -Returns: - - EFI_STATUS + @return EFI_STATUS OutputMemoryFile is valid if !EFI_ERROR - **/ - - EFI_STATUS -FreeMemoryFile ( - IN EFI_HANDLE InputMemoryFile +GetMemoryFile ( + IN CHAR8 *InputFileName, + OUT EFI_HANDLE *OutputMemoryFile ) ; -/** - -Routine Description: +/** Frees all memory associated with the input memory file. -Arguments: - - InputMemoryFile Handle to memory file - -Returns: - - EFI_STATUS + @param InputMemoryFile Handle to memory file + @return EFI_STATUS **/ - - -CHAR8 * -ReadMemoryFileLine ( - IN EFI_HANDLE InputMemoryFile +EFI_STATUS +FreeMemoryFile ( + IN EFI_HANDLE InputMemoryFile ) ; -/** - -Routine Description: +/** This function reads a line from the memory file. The newline characters are stripped and a null terminated string is returned. If the string pointer returned is non-NULL, then the caller must free the memory associated with this string. -Arguments: - - InputMemoryFile Handle to memory file - -Returns: - - NULL if error or EOF - NULL character termincated string otherwise (MUST BE FREED BY CALLER) + @param InputMemoryFile Handle to memory file + @retval NULL if error or EOF + @retval NULL character termincated string otherwise (MUST BE FREED BY CALLER) **/ +CHAR8 * +ReadMemoryFileLine ( + IN EFI_HANDLE InputMemoryFile + ) +; #endif diff --git a/BaseTools/Source/C/Common/MyAlloc.c b/BaseTools/Source/C/Common/MyAlloc.c index d104795d46..17ff5cfbbd 100644 --- a/BaseTools/Source/C/Common/MyAlloc.c +++ b/BaseTools/Source/C/Common/MyAlloc.c @@ -27,40 +27,23 @@ STATIC MY_ALLOC_STRUCT *MyAllocData = NULL; STATIC UINT32 MyAllocHeadMagik = MYALLOC_HEAD_MAGIK; STATIC UINT32 MyAllocTailMagik = MYALLOC_TAIL_MAGIK; -// -// //////////////////////////////////////////////////////////////////////////// -// -// +/** + Check for corruptions in the allocated memory chain. If a corruption + is detection program operation stops w/ an exit(1) call. + + @param Final When FALSE, MyCheck() returns if the allocated memory chain + has not been corrupted. When TRUE, MyCheck() returns if there + are no un-freed allocations. If there are un-freed allocations, + they are displayed and exit(1) is called. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. +**/ VOID MyCheck ( BOOLEAN Final, UINT8 File[], UINTN Line ) -// *++ -// Description: -// -// Check for corruptions in the allocated memory chain. If a corruption -// is detection program operation stops w/ an exit(1) call. -// -// Parameters: -// -// Final := When FALSE, MyCheck() returns if the allocated memory chain -// has not been corrupted. When TRUE, MyCheck() returns if there -// are no un-freed allocations. If there are un-freed allocations, -// they are displayed and exit(1) is called. -// -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// n/a -// -// --*/ -// { MY_ALLOC_STRUCT *Tmp; @@ -155,39 +138,26 @@ MyCheck ( } } } -// -// //////////////////////////////////////////////////////////////////////////// -// -// + +/** + Allocate a new link in the allocation chain along with enough storage + for the File[] string, requested Size and alignment overhead. If + memory cannot be allocated or the allocation chain has been corrupted, + exit(1) will be called. + + @param Size Number of bytes (UINT8) requested by the called. + Size cannot be zero. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. + + @return Pointer to the caller's buffer. +**/ VOID * MyAlloc ( UINTN Size, UINT8 File[], UINTN Line ) -// *++ -// Description: -// -// Allocate a new link in the allocation chain along with enough storage -// for the File[] string, requested Size and alignment overhead. If -// memory cannot be allocated or the allocation chain has been corrupted, -// exit(1) will be called. -// -// Parameters: -// -// Size := Number of bytes (UINT8) requested by the called. -// Size cannot be zero. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// Pointer to the caller's buffer. -// -// --*/ -// { MY_ALLOC_STRUCT *Tmp; UINTN Len; @@ -278,10 +248,19 @@ MyAlloc ( return Tmp->Buffer + sizeof (UINT32); } -// -// //////////////////////////////////////////////////////////////////////////// -// -// + +/** + This does a MyAlloc(), memcpy() and MyFree(). There is no optimization + for shrinking or expanding buffers. An invalid parameter will cause + MyRealloc() to fail with a call to exit(1). + + @param Ptr Pointer to the caller's buffer to be re-allocated. + @param Size Size of new buffer. Size cannot be zero. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. + + @return Pointer to new caller's buffer. +**/ VOID * MyRealloc ( VOID *Ptr, @@ -289,29 +268,6 @@ MyRealloc ( UINT8 File[], UINTN Line ) -// *++ -// Description: -// -// This does a MyAlloc(), memcpy() and MyFree(). There is no optimization -// for shrinking or expanding buffers. An invalid parameter will cause -// MyRealloc() to fail with a call to exit(1). -// -// Parameters: -// -// Ptr := Pointer to the caller's buffer to be re-allocated. -// -// Size := Size of new buffer. Size cannot be zero. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// Pointer to new caller's buffer. -// -// --*/ -// { MY_ALLOC_STRUCT *Tmp; VOID *Buffer; @@ -398,37 +354,22 @@ MyRealloc ( return Buffer; } -// -// //////////////////////////////////////////////////////////////////////////// -// -// + +/** + Release a previously allocated buffer. Invalid parameters will cause + MyFree() to fail with an exit(1) call. + + @param Ptr Pointer to the caller's buffer to be freed. + A NULL pointer will be ignored. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. +**/ VOID MyFree ( VOID *Ptr, UINT8 File[], UINTN Line ) -// *++ -// Description: -// -// Release a previously allocated buffer. Invalid parameters will cause -// MyFree() to fail with an exit(1) call. -// -// Parameters: -// -// Ptr := Pointer to the caller's buffer to be freed. -// A NULL pointer will be ignored. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// n/a -// -// --*/ -// { MY_ALLOC_STRUCT *Tmp; MY_ALLOC_STRUCT *Tmp2; diff --git a/BaseTools/Source/C/Common/MyAlloc.h b/BaseTools/Source/C/Common/MyAlloc.h index aff29d05ab..de3323d30d 100644 --- a/BaseTools/Source/C/Common/MyAlloc.h +++ b/BaseTools/Source/C/Common/MyAlloc.h @@ -71,6 +71,17 @@ typedef struct MyAllocStruct { #define MYALLOC_HEAD_MAGIK 0xBADFACED #define MYALLOC_TAIL_MAGIK 0xDEADBEEF +/** + Check for corruptions in the allocated memory chain. If a corruption + is detection program operation stops w/ an exit(1) call. + + @param Final When FALSE, MyCheck() returns if the allocated memory chain + has not been corrupted. When TRUE, MyCheck() returns if there + are no un-freed allocations. If there are un-freed allocations, + they are displayed and exit(1) is called. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. +**/ VOID MyCheck ( BOOLEAN Final, @@ -78,31 +89,20 @@ MyCheck ( UINTN Line ) ; -// -// *++ -// Description: -// -// Check for corruptions in the allocated memory chain. If a corruption -// is detection program operation stops w/ an exit(1) call. -// -// Parameters: -// -// Final := When FALSE, MyCheck() returns if the allocated memory chain -// has not been corrupted. When TRUE, MyCheck() returns if there -// are no un-freed allocations. If there are un-freed allocations, -// they are displayed and exit(1) is called. -// -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// n/a -// -// --*/ -// + +/** + Allocate a new link in the allocation chain along with enough storage + for the File[] string, requested Size and alignment overhead. If + memory cannot be allocated or the allocation chain has been corrupted, + exit(1) will be called. + + @param Size Number of bytes (UINT8) requested by the called. + Size cannot be zero. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. + + @return Pointer to the caller's buffer. +**/ VOID * MyAlloc ( UINTN Size, @@ -110,30 +110,20 @@ MyAlloc ( UINTN Line ) ; -// -// *++ -// Description: -// -// Allocate a new link in the allocation chain along with enough storage -// for the File[] string, requested Size and alignment overhead. If -// memory cannot be allocated or the allocation chain has been corrupted, -// exit(1) will be called. -// -// Parameters: -// -// Size := Number of bytes (UINT8) requested by the called. -// Size cannot be zero. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// Pointer to the caller's buffer. -// -// --*/ -// + +/** + This does a MyAlloc(), memcpy() and MyFree(). There is no optimization + for shrinking or expanding buffers. An invalid parameter will cause + MyRealloc() to fail with a call to exit(1). + + @param Ptr Pointer to the caller's buffer to be re-allocated. + Ptr cannot be NULL. + @param Size Size of new buffer. Size cannot be zero. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. + + @return Pointer to new caller's buffer. +**/ VOID * MyRealloc ( VOID *Ptr, @@ -142,31 +132,16 @@ MyRealloc ( UINTN Line ) ; -// -// *++ -// Description: -// -// This does a MyAlloc(), memcpy() and MyFree(). There is no optimization -// for shrinking or expanding buffers. An invalid parameter will cause -// MyRealloc() to fail with a call to exit(1). -// -// Parameters: -// -// Ptr := Pointer to the caller's buffer to be re-allocated. -// Ptr cannot be NULL. -// -// Size := Size of new buffer. Size cannot be zero. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// Pointer to new caller's buffer. -// -// --*/ -// + +/** + Release a previously allocated buffer. Invalid parameters will cause + MyFree() to fail with an exit(1) call. + + @param Ptr Pointer to the caller's buffer to be freed. + A NULL pointer will be ignored. + @param File Set to __FILE__ by macro expansion. + @param Line Set to __LINE__ by macro expansion. +**/ VOID MyFree ( VOID *Ptr, @@ -174,28 +149,7 @@ MyFree ( UINTN Line ) ; -// -// *++ -// Description: -// -// Release a previously allocated buffer. Invalid parameters will cause -// MyFree() to fail with an exit(1) call. -// -// Parameters: -// -// Ptr := Pointer to the caller's buffer to be freed. -// A NULL pointer will be ignored. -// -// File := Set to __FILE__ by macro expansion. -// -// Line := Set to __LINE__ by macro expansion. -// -// Returns: -// -// n/a -// -// --*/ -// + #else /* USE_MYALLOC */ // diff --git a/BaseTools/Source/C/Common/OsPath.c b/BaseTools/Source/C/Common/OsPath.c index 35ca54761f..9901f686c9 100644 --- a/BaseTools/Source/C/Common/OsPath.c +++ b/BaseTools/Source/C/Common/OsPath.c @@ -20,14 +20,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // BUGBUG: Not fully implemented yet. // -CHAR8* -OsPathDirName ( - IN CHAR8 *FilePath - ) -/*++ - -Routine Description: +/** This function returns the directory path which contains the particular path. Some examples: "a/b/c" -> "a/b" @@ -40,15 +34,15 @@ Routine Description: The caller must free the string returned. -Arguments: - - FilePath Path name of file to get the parent directory for. - -Returns: + @param FilePath Path name of file to get the parent directory for. - NULL if error + @return NULL if error +**/ +CHAR8* +OsPathDirName ( + IN CHAR8 *FilePath + ) ---*/ { CHAR8 *Return; CHAR8 *Pos; @@ -97,14 +91,8 @@ Routine Description: // // BUGBUG: Not fully implemented yet. // -VOID -OsPathNormPathInPlace ( - IN CHAR8 *Path - ) -/*++ - -Routine Description: +/** This function returns the directory path which contains the particular path. Some examples: "a/b/../c" -> "a/c" @@ -113,15 +101,14 @@ Routine Description: This function does not check for the existence of the file. -Arguments: - - Path Path name of file to normalize + @param Path Path name of file to normalize -Returns: - - The string is altered in place. - ---*/ + @return The string is altered in place. +**/ +VOID +OsPathNormPathInPlace ( + IN CHAR8 *Path + ) { CHAR8 *Pos; INTN Offset; @@ -200,16 +187,7 @@ Routine Description: } #endif - -CHAR8* -OsPathPeerFilePath ( - IN CHAR8 *OldPath, - IN CHAR8 *Peer - ) -/*++ - -Routine Description: - +/** This function replaces the final portion of a path with an alternative 'peer' filename. For example: "a/b/../c", "peer" -> "a/b/../peer" @@ -219,16 +197,16 @@ Routine Description: This function does not check for the existence of the file. -Arguments: - - OldPath Path name of replace the final segment - Peer The new path name to concatenate to become the peer path + @param OldPath Path name of replace the final segment + @param Peer The new path name to concatenate to become the peer path -Returns: - - A CHAR8* string, which must be freed by the caller - ---*/ + @return A CHAR8* string, which must be freed by the caller +**/ +CHAR8* +OsPathPeerFilePath ( + IN CHAR8 *OldPath, + IN CHAR8 *Peer + ) { CHAR8 *Result; INTN Offset; @@ -259,27 +237,18 @@ Routine Description: return Result; } +/** + Checks if a file exists + + @param InputFileName The name of the file to check for existence + @retval TRUE The file exists + @retval FALSE The file does not exist +**/ BOOLEAN OsPathExists ( IN CHAR8 *InputFileName ) -/*++ - -Routine Description: - - Checks if a file exists - -Arguments: - - InputFileName The name of the file to check for existence - -Returns: - - TRUE The file exists - FALSE The file does not exist - ---*/ { FILE *InputFile; InputFile = fopen (LongFilePath (InputFileName), "rb"); diff --git a/BaseTools/Source/C/Common/OsPath.h b/BaseTools/Source/C/Common/OsPath.h index 1868103e7f..b1881c4a1e 100644 --- a/BaseTools/Source/C/Common/OsPath.h +++ b/BaseTools/Source/C/Common/OsPath.h @@ -16,15 +16,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Functions declarations // -CHAR8* -OsPathDirName ( - IN CHAR8 *FilePath - ) -; /** - -Routine Description: - This function returns the directory path which contains the particular path. Some examples: "a/b/c" -> "a/b" @@ -37,26 +29,17 @@ Routine Description: The caller must free the string returned. -Arguments: - - FilePath Path name of file to get the parent directory for. - -Returns: - - NULL if error + @param FilePath Path name of file to get the parent directory for. + @return NULL if error **/ - - -VOID -OsPathNormPathInPlace ( - IN CHAR8 *Path +CHAR8* +OsPathDirName ( + IN CHAR8 *FilePath ) ; -/** - -Routine Description: +/** This function returns the directory path which contains the particular path. Some examples: "a/b/../c" -> "a/c" @@ -65,27 +48,17 @@ Routine Description: This function does not check for the existence of the file. -Arguments: - - Path Path name of file to normalize - -Returns: - - The string is altered in place. + @param Path Path name of file to normalize + @return The string is altered in place. **/ - - -CHAR8* -OsPathPeerFilePath ( - IN CHAR8 *OldPath, - IN CHAR8 *Peer +VOID +OsPathNormPathInPlace ( + IN CHAR8 *Path ) ; -/** - -Routine Description: +/** This function replaces the final portion of a path with an alternative 'peer' filename. For example: "a/b/../c", "peer" -> "a/b/../peer" @@ -95,39 +68,30 @@ Routine Description: This function does not check for the existence of the file. -Arguments: + @param OldPath Path name of replace the final segment + @param Peer The new path name to concatenate to become the peer path - OldPath Path name of replace the final segment - Peer The new path name to concatenate to become the peer path + @return A CHAR8* string, which must be freed by the caller +**/ +CHAR8* +OsPathPeerFilePath ( + IN CHAR8 *OldPath, + IN CHAR8 *Peer + ) +; -Returns: +/** + Checks if a file exists - A CHAR8* string, which must be freed by the caller + @param InputFileName The name of the file to check for existence + @retval TRUE The file exists + @retval FALSE The file does not exist **/ - - BOOLEAN OsPathExists ( IN CHAR8 *InputFileName ) ; -/** - -Routine Description: - - Checks if a file exists - -Arguments: - - InputFileName The name of the file to check for existence - -Returns: - - TRUE The file exists - FALSE The file does not exist - -**/ - #endif diff --git a/BaseTools/Source/C/Common/ParseGuidedSectionTools.c b/BaseTools/Source/C/Common/ParseGuidedSectionTools.c index a34581ecb6..e1e9a97e7b 100644 --- a/BaseTools/Source/C/Common/ParseGuidedSectionTools.c +++ b/BaseTools/Source/C/Common/ParseGuidedSectionTools.c @@ -33,30 +33,22 @@ typedef struct _GUID_SEC_TOOL_ENTRY { // Function Implementation // -EFI_HANDLE -ParseGuidedSectionToolsFile ( - IN CHAR8 *InputFile - ) -/*++ - -Routine Description: - +/** This function parses the tools_def.txt file. It returns a EFI_HANDLE object which can be used for the other library functions and should be passed to FreeParsedGuidedSectionToolsHandle to free resources when the tools_def.txt information is no longer needed. -Arguments: + @param InputFile Path name of file to read - InputFile Path name of file to read - -Returns: - - NULL if error parsing - A non-NULL EFI_HANDLE otherwise - ---*/ + @retval NULL if error parsing + @retval A non-NULL EFI_HANDLE otherwise +**/ +EFI_HANDLE +ParseGuidedSectionToolsFile ( + IN CHAR8 *InputFile + ) { EFI_STATUS Status; EFI_HANDLE MemoryFile; @@ -74,31 +66,22 @@ Routine Description: return ParsedGuidedSectionTools; } - -EFI_HANDLE -ParseGuidedSectionToolsMemoryFile ( - IN EFI_HANDLE InputFile - ) -/*++ - -Routine Description: - +/** This function parses the tools_def.txt file. It returns a EFI_HANDLE object which can be used for the other library functions and should be passed to FreeParsedGuidedSectionToolsHandle to free resources when the tools_def.txt information is no longer needed. -Arguments: - - InputFile Memory file image. + @param InputFile Memory file image. -Returns: - - NULL if error or EOF - InputBuffer otherwise - ---*/ + @retval NULL if error or EOF + @retval InputBuffer otherwise +**/ +EFI_HANDLE +ParseGuidedSectionToolsMemoryFile ( + IN EFI_HANDLE InputFile + ) { EFI_STATUS Status; CHAR8 *NextLine; @@ -160,31 +143,22 @@ Routine Description: return FirstGuidTool; } +/** + This function looks up the appropriate tool to use for extracting + a GUID defined FV section. + @param ParsedGuidedSectionToolsHandle A parsed GUID section tools handle. + @param SectionGuid The GUID for the section. + + @retval NULL if no tool is found or there is another error + @retval Non-NULL The tool to use to access the section contents. (The caller + must free the memory associated with this string.) +**/ CHAR8* LookupGuidedSectionToolPath ( IN EFI_HANDLE ParsedGuidedSectionToolsHandle, IN EFI_GUID *SectionGuid ) -/*++ - -Routine Description: - - This function looks up the appropriate tool to use for extracting - a GUID defined FV section. - -Arguments: - - ParsedGuidedSectionToolsHandle A parsed GUID section tools handle. - SectionGuid The GUID for the section. - -Returns: - - NULL - if no tool is found or there is another error - Non-NULL - The tool to use to access the section contents. (The caller - must free the memory associated with this string.) - ---*/ { GUID_SEC_TOOL_ENTRY *GuidTool; diff --git a/BaseTools/Source/C/Common/ParseGuidedSectionTools.h b/BaseTools/Source/C/Common/ParseGuidedSectionTools.h index 2714b8ce82..2180bbd074 100644 --- a/BaseTools/Source/C/Common/ParseGuidedSectionTools.h +++ b/BaseTools/Source/C/Common/ParseGuidedSectionTools.h @@ -15,106 +15,73 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Functions declarations // -EFI_HANDLE -ParseGuidedSectionToolsFile ( - IN CHAR8 *InputFile - ) -; /** - -Routine Description: - This function parses the tools_def.txt file. It returns a EFI_HANDLE object which can be used for the other library functions and should be passed to FreeParsedToolsDefHandle to free resources when the tools_def.txt information is no longer needed. -Arguments: - - InputFile Path name of file to read - -Returns: - - NULL if error parsing - A non-NULL EFI_HANDLE otherwise + @param InputFile Path name of file to read + @retval NULL if error parsing + @retval A non-NULL EFI_HANDLE otherwise **/ - - EFI_HANDLE -ParseGuidedSectionToolsMemoryFile ( - IN EFI_HANDLE InputFile +ParseGuidedSectionToolsFile ( + IN CHAR8 *InputFile ) ; -/** - -Routine Description: +/** This function parses the tools_def.txt file. It returns a EFI_HANDLE object which can be used for the other library functions and should be passed to FreeParsedToolsDefHandle to free resources when the tools_def.txt information is no longer needed. -Arguments: - - InputFile Memory file image. - -Returns: - - NULL if error parsing - A non-NULL EFI_HANDLE otherwise + @param InputFile Memory file image. + @retval NULL if error parsing + @retval A non-NULL EFI_HANDLE otherwise **/ - -CHAR8* -LookupGuidedSectionToolPath ( - IN EFI_HANDLE ParsedGuidedSectionToolsHandle, - IN EFI_GUID *SectionGuid +EFI_HANDLE +ParseGuidedSectionToolsMemoryFile ( + IN EFI_HANDLE InputFile ) ; -/** - -Routine Description: +/** This function looks up the appropriate tool to use for extracting a GUID defined FV section. -Arguments: - - ParsedGuidedSectionToolsHandle A parsed GUID section tools handle. - SectionGuid The GUID for the section. - -Returns: + @param ParsedGuidedSectionToolsHandle A parsed GUID section tools handle. + @param SectionGuid The GUID for the section. - NULL - if no tool is found or there is another error - Non-NULL - The tool to use to access the section contents. (The caller + @retval NULL if no tool is found or there is another error + @retval Non-NULL The tool to use to access the section contents. (The caller must free the memory associated with this string.) - **/ - -EFI_STATUS -FreeParsedGuidedSectionToolsHandle ( - IN EFI_HANDLE ParsedGuidedSectionToolsHandle +CHAR8* +LookupGuidedSectionToolPath ( + IN EFI_HANDLE ParsedGuidedSectionToolsHandle, + IN EFI_GUID *SectionGuid ) ; -/** - -Routine Description: +/** Frees resources that were allocated by ParseGuidedSectionToolsFile. After freeing these resources, the information that was parsed is no longer accessible. -Arguments: - - ParsedToolDefHandle Handle returned from ParseGuidedSectionToolsFile - -Returns: - - EFI_STATUS + @param ParsedToolDefHandle Handle returned from ParseGuidedSectionToolsFile + @return EFI_STATUS **/ +EFI_STATUS +FreeParsedGuidedSectionToolsHandle ( + IN EFI_HANDLE ParsedGuidedSectionToolsHandle + ) +; #endif diff --git a/BaseTools/Source/C/Common/ParseInf.c b/BaseTools/Source/C/Common/ParseInf.c index 5ef8f1306d..63da3d647c 100644 --- a/BaseTools/Source/C/Common/ParseInf.c +++ b/BaseTools/Source/C/Common/ParseInf.c @@ -14,16 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "ParseInf.h" #include "CommonLib.h" -CHAR8 * -ReadLine ( - IN MEMORY_FILE *InputFile, - IN OUT CHAR8 *InputBuffer, - IN UINTN MaxLength - ) -/*++ - -Routine Description: - +/** This function reads a line, stripping any comments. The function reads a string from the input stream argument and stores it in the input string. ReadLine reads characters from the current file position @@ -31,18 +22,20 @@ Routine Description: until the number of characters read is equal to MaxLength - 1, whichever comes first. The newline character, if read, is replaced with a \0. -Arguments: - - InputFile Memory file image. - InputBuffer Buffer to read into, must be MaxLength size. - MaxLength The maximum size of the input buffer. - -Returns: + @param InputFile Memory file image. + @param InputBuffer Buffer to read into, must be MaxLength size. + @param MaxLength The maximum size of the input buffer. - NULL if error or EOF - InputBuffer otherwise + @retval NULL if error or EOF + @retval InputBuffer otherwise +**/ +CHAR8 * +ReadLine ( + IN MEMORY_FILE *InputFile, + IN OUT CHAR8 *InputBuffer, + IN UINTN MaxLength + ) ---*/ { CHAR8 *CharPtr; CHAR8 *EndOfLine; @@ -129,29 +122,21 @@ Routine Description: return InputBuffer; } +/** + This function parses a file from the beginning to find a section. + The section string may be anywhere within a line. + + @param InputFile Memory file image. + @param Section Section to search for + + @retval FALSE if error or EOF + @retval TRUE if section found +**/ BOOLEAN FindSection ( IN MEMORY_FILE *InputFile, IN CHAR8 *Section ) -/*++ - -Routine Description: - - This function parses a file from the beginning to find a section. - The section string may be anywhere within a line. - -Arguments: - - InputFile Memory file image. - Section Section to search for - -Returns: - - FALSE if error or EOF - TRUE if section found - ---*/ { CHAR8 InputBuffer[MAX_LONG_FILE_PATH]; CHAR8 *CurrentToken; @@ -190,6 +175,21 @@ Routine Description: return FALSE; } +/** + Finds a token value given the section and token to search for. + + @param InputFile Memory file image. + @param Section The section to search for, a string within []. + @param Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file. + @param Instance The instance of the token to search for. Zero is the first instance. + @param Value The string that holds the value following the =. Must be MAX_LONG_FILE_PATH in size. + + @retval EFI_SUCCESS Value found. + @retval EFI_ABORTED Format error detected in INF file. + @retval EFI_INVALID_PARAMETER Input argument was null. + @retval EFI_LOAD_ERROR Error reading from the file. + @retval EFI_NOT_FOUND Section/Token/Value not found. +**/ EFI_STATUS FindToken ( IN MEMORY_FILE *InputFile, @@ -198,29 +198,6 @@ FindToken ( IN UINTN Instance, OUT CHAR8 *Value ) -/*++ - -Routine Description: - - Finds a token value given the section and token to search for. - -Arguments: - - InputFile Memory file image. - Section The section to search for, a string within []. - Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file. - Instance The instance of the token to search for. Zero is the first instance. - Value The string that holds the value following the =. Must be MAX_LONG_FILE_PATH in size. - -Returns: - - EFI_SUCCESS Value found. - EFI_ABORTED Format error detected in INF file. - EFI_INVALID_PARAMETER Input argument was null. - EFI_LOAD_ERROR Error reading from the file. - EFI_NOT_FOUND Section/Token/Value not found. - ---*/ { CHAR8 InputBuffer[MAX_LONG_FILE_PATH]; CHAR8 *CurrentToken; @@ -359,30 +336,22 @@ Routine Description: return EFI_NOT_FOUND; } +/** + Converts a string to an EFI_GUID. The string must be in the + xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format. + + @param AsciiGuidBuffer pointer to ascii string + @param GuidBuffer pointer to destination Guid + + @retval EFI_ABORTED Could not convert the string + @retval EFI_SUCCESS The string was successfully converted + @retval EFI_INVALID_PARAMETER Input parameter is invalid. +**/ EFI_STATUS StringToGuid ( IN CHAR8 *AsciiGuidBuffer, OUT EFI_GUID *GuidBuffer ) -/*++ - -Routine Description: - - Converts a string to an EFI_GUID. The string must be in the - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format. - -Arguments: - - AsciiGuidBuffer - pointer to ascii string - GuidBuffer - pointer to destination Guid - -Returns: - - EFI_ABORTED Could not convert the string - EFI_SUCCESS The string was successfully converted - EFI_INVALID_PARAMETER Input parameter is invalid. - ---*/ { INT32 Index; int Data1; @@ -461,33 +430,25 @@ Routine Description: return EFI_SUCCESS; } -EFI_STATUS -AsciiStringToUint64 ( - IN CONST CHAR8 *AsciiString, - IN BOOLEAN IsHex, - OUT UINT64 *ReturnValue - ) -/*++ - -Routine Description: - +/** Converts a null terminated ascii string that represents a number into a UINT64 value. A hex number may be preceded by a 0x, but may not be succeeded by an h. A number without 0x or 0X is considered to be base 10 unless the IsHex input is true. -Arguments: - - AsciiString The string to convert. - IsHex Force the string to be treated as a hex number. - ReturnValue The return value. + @param AsciiString The string to convert. + @param IsHex Force the string to be treated as a hex number. + @param ReturnValue The return value. -Returns: - - EFI_SUCCESS Number successfully converted. - EFI_ABORTED Invalid character encountered. - ---*/ + @retval EFI_SUCCESS Number successfully converted. + @retval EFI_ABORTED Invalid character encountered. +**/ +EFI_STATUS +AsciiStringToUint64 ( + IN CONST CHAR8 *AsciiString, + IN BOOLEAN IsHex, + OUT UINT64 *ReturnValue + ) { UINT8 Index; UINT64 Value; @@ -577,29 +538,21 @@ Routine Description: return EFI_SUCCESS; } +/** + This function reads a line, stripping any comments. + // BUGBUG: This is obsolete once genmake goes away... + + @param InputFile Stream pointer. + @param InputBuffer Buffer to read into, must be MAX_LONG_FILE_PATH size. + + @retval NULL if error or EOF + @retval InputBuffer otherwise +**/ CHAR8 * ReadLineInStream ( IN FILE *InputFile, IN OUT CHAR8 *InputBuffer ) -/*++ - -Routine Description: - - This function reads a line, stripping any comments. - // BUGBUG: This is obsolete once genmake goes away... - -Arguments: - - InputFile Stream pointer. - InputBuffer Buffer to read into, must be MAX_LONG_FILE_PATH size. - -Returns: - - NULL if error or EOF - InputBuffer otherwise - ---*/ { CHAR8 *CharPtr; @@ -633,30 +586,22 @@ Routine Description: return InputBuffer; } -BOOLEAN -FindSectionInStream ( - IN FILE *InputFile, - IN CHAR8 *Section - ) -/*++ - -Routine Description: - +/** This function parses a stream file from the beginning to find a section. The section string may be anywhere within a line. // BUGBUG: This is obsolete once genmake goes away... -Arguments: - - InputFile Stream pointer. - Section Section to search for - -Returns: - - FALSE if error or EOF - TRUE if section found + @param InputFile Stream pointer. + @param Section Section to search for ---*/ + @retval FALSE if error or EOF + @retval TRUE if section found +**/ +BOOLEAN +FindSectionInStream ( + IN FILE *InputFile, + IN CHAR8 *Section + ) { CHAR8 InputBuffer[MAX_LONG_FILE_PATH]; CHAR8 *CurrentToken; diff --git a/BaseTools/Source/C/Common/ParseInf.h b/BaseTools/Source/C/Common/ParseInf.h index 596cb3aa3b..a0881a5c9e 100644 --- a/BaseTools/Source/C/Common/ParseInf.h +++ b/BaseTools/Source/C/Common/ParseInf.h @@ -20,18 +20,8 @@ extern "C" { // // Functions declarations // -CHAR8 * -ReadLine ( - IN MEMORY_FILE *InputFile, - IN OUT CHAR8 *InputBuffer, - IN UINTN MaxLength - ) -; - -/*++ - -Routine Description: +/** This function reads a line, stripping any comments. The function reads a string from the input stream argument and stores it in the input string. ReadLine reads characters from the current file position @@ -39,18 +29,31 @@ Routine Description: until the number of characters read is equal to MaxLength - 1, whichever comes first. The newline character, if read, is replaced with a \0. -Arguments: + @param InputFile Memory file image. + @param InputBuffer Buffer to read into, must be MaxLength size. + @param MaxLength The maximum size of the input buffer. - InputFile Memory file image. - InputBuffer Buffer to read into, must be MaxLength size. - MaxLength The maximum size of the input buffer. + @retval NULL if error or EOF + @retval InputBuffer otherwise +**/ +CHAR8 * +ReadLine ( + IN MEMORY_FILE *InputFile, + IN OUT CHAR8 *InputBuffer, + IN UINTN MaxLength + ) +; -Returns: +/** + This function parses a file from the beginning to find a section. + The section string may be anywhere within a line. - NULL if error or EOF - InputBuffer otherwise + @param InputFile Memory file image. + @param Section Section to search for ---*/ + @retval FALSE if error or EOF + @retval TRUE if section found +**/ BOOLEAN FindSection ( IN MEMORY_FILE *InputFile, @@ -58,24 +61,21 @@ FindSection ( ) ; -/*++ - -Routine Description: - - This function parses a file from the beginning to find a section. - The section string may be anywhere within a line. - -Arguments: - - InputFile Memory file image. - Section Section to search for - -Returns: - - FALSE if error or EOF - TRUE if section found +/** + Finds a token value given the section and token to search for. ---*/ + @param InputFile Memory file image. + @param Section The section to search for, a string within []. + @param Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file. + @param Instance The instance of the token to search for. Zero is the first instance. + @param Value The string that holds the value following the =. Must be MAX_LONG_FILE_PATH in size. + + @retval EFI_SUCCESS Value found. + @retval EFI_ABORTED Format error detected in INF file. + @retval EFI_INVALID_PARAMETER Input argument was null. + @retval EFI_LOAD_ERROR Error reading from the file. + @retval EFI_NOT_FOUND Section/Token/Value not found. +**/ EFI_STATUS FindToken ( IN MEMORY_FILE *InputFile, @@ -86,29 +86,16 @@ FindToken ( ) ; -/*++ - -Routine Description: - - Finds a token value given the section and token to search for. - -Arguments: - - InputFile Memory file image. - Section The section to search for, a string within []. - Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file. - Instance The instance of the token to search for. Zero is the first instance. - Value The string that holds the value following the =. Must be MAX_LONG_FILE_PATH in size. - -Returns: +/** + Converts a string to an EFI_GUID. The string must be in the + xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format. - EFI_SUCCESS Value found. - EFI_ABORTED Format error detected in INF file. - EFI_INVALID_PARAMETER Input argument was null. - EFI_LOAD_ERROR Error reading from the file. - EFI_NOT_FOUND Section/Token/Value not found. + @param GuidBuffer pointer to destination Guid + @param AsciiGuidBuffer pointer to ascii string ---*/ + @retval EFI_ABORTED Could not convert the string + @retval EFI_SUCCESS The string was successfully converted +**/ EFI_STATUS StringToGuid ( IN CHAR8 *AsciiGuidBuffer, @@ -116,24 +103,19 @@ StringToGuid ( ) ; -/*++ - -Routine Description: - - Converts a string to an EFI_GUID. The string must be in the - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format. - -Arguments: - - GuidBuffer - pointer to destination Guid - AsciiGuidBuffer - pointer to ascii string - -Returns: +/** + Converts a null terminated ascii string that represents a number into a + UINT64 value. A hex number may be preceded by a 0x, but may not be + succeeded by an h. A number without 0x or 0X is considered to be base 10 + unless the IsHex input is true. - EFI_ABORTED Could not convert the string - EFI_SUCCESS The string was successfully converted + @param AsciiString The string to convert. + @param IsHex Force the string to be treated as a hex number. + @param ReturnValue The return value. ---*/ + @retval EFI_SUCCESS Number successfully converted. + @retval EFI_ABORTED Invalid character encountered. +**/ EFI_STATUS AsciiStringToUint64 ( IN CONST CHAR8 *AsciiString, @@ -142,27 +124,15 @@ AsciiStringToUint64 ( ) ; -/*++ - -Routine Description: - - Converts a null terminated ascii string that represents a number into a - UINT64 value. A hex number may be preceded by a 0x, but may not be - succeeded by an h. A number without 0x or 0X is considered to be base 10 - unless the IsHex input is true. - -Arguments: - - AsciiString The string to convert. - IsHex Force the string to be treated as a hex number. - ReturnValue The return value. - -Returns: +/** + This function reads a line, stripping any comments. - EFI_SUCCESS Number successfully converted. - EFI_ABORTED Invalid character encountered. + @param InputFile Stream pointer. + @param InputBuffer Buffer to read into, must be MAX_LONG_FILE_PATH size. ---*/ + @retval NULL if error or EOF + @retval InputBuffer otherwise +**/ CHAR8 * ReadLineInStream ( IN FILE *InputFile, @@ -170,23 +140,16 @@ ReadLineInStream ( ) ; -/*++ - -Routine Description: - - This function reads a line, stripping any comments. - -Arguments: - - InputFile Stream pointer. - InputBuffer Buffer to read into, must be MAX_LONG_FILE_PATH size. - -Returns: +/** + This function parses a stream file from the beginning to find a section. + The section string may be anywhere within a line. - NULL if error or EOF - InputBuffer otherwise + @param InputFile Stream pointer. + @param Section Section to search for ---*/ + @retval FALSE if error or EOF + @retval TRUE if section found +**/ BOOLEAN FindSectionInStream ( IN FILE *InputFile, @@ -194,25 +157,6 @@ FindSectionInStream ( ) ; -/*++ - -Routine Description: - - This function parses a stream file from the beginning to find a section. - The section string may be anywhere within a line. - -Arguments: - - InputFile Stream pointer. - Section Section to search for - -Returns: - - FALSE if error or EOF - TRUE if section found - ---*/ - #ifdef __cplusplus } #endif diff --git a/BaseTools/Source/C/Common/PcdValueCommon.c b/BaseTools/Source/C/Common/PcdValueCommon.c index 98023e8786..f17a357b7c 100644 --- a/BaseTools/Source/C/Common/PcdValueCommon.c +++ b/BaseTools/Source/C/Common/PcdValueCommon.c @@ -35,6 +35,15 @@ typedef struct { PCD_ENTRY *PcdList; UINT32 PcdListLength; +/** + Record new token information + + @param FileBuffer File Buffer to be record + @param PcdIndex Index of PCD in database + @param TokenIndex Index of Token + @param TokenStart Start of Token + @param TokenEnd End of Token +**/ VOID STATIC RecordToken ( @@ -44,24 +53,7 @@ RecordToken ( UINT32 TokenStart, UINT32 TokenEnd ) -/*++ - -Routine Description: - - Record new token information - -Arguments: - - FileBuffer File Buffer to be record - PcdIndex Index of PCD in database - TokenIndex Index of Token - TokenStart Start of Token - TokenEnd End of Token -Returns: - - None ---*/ { CHAR8 *Token; @@ -109,6 +101,16 @@ Routine Description: } } +/** + Get PCD index in Pcd database + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + + @return Index of PCD in Pcd database +**/ int STATIC LookupPcdIndex ( @@ -117,23 +119,6 @@ LookupPcdIndex ( CHAR8 *TokenSpaceGuidName, CHAR8 *TokenName ) -/*++ - -Routine Description: - - Get PCD index in Pcd database - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - -Returns: - - Index of PCD in Pcd database ---*/ { UINT32 Index; @@ -161,6 +146,16 @@ Routine Description: return -1; } +/** + Get PCD value + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + + @return PCD value +**/ UINT64 __PcdGet ( CHAR8 *SkuName OPTIONAL, @@ -168,23 +163,6 @@ __PcdGet ( CHAR8 *TokenSpaceGuidName, CHAR8 *TokenName ) -/*++ - -Routine Description: - - Get PCD value - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - -Returns: - - PCD value ---*/ { int Index; CHAR8 *End; @@ -212,6 +190,15 @@ Routine Description: return 0; } +/** + Set PCD value + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Value PCD value to be set +**/ VOID __PcdSet ( CHAR8 *SkuName OPTIONAL, @@ -220,24 +207,6 @@ __PcdSet ( CHAR8 *TokenName, UINT64 Value ) -/*++ - -Routine Description: - - Set PCD value - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Value PCD value to be set - -Returns: - - None ---*/ { int Index; @@ -275,6 +244,17 @@ Routine Description: } } +/** + Get PCD value buffer + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Size Size of PCD value buffer + + @return PCD value buffer +**/ VOID * __PcdGetPtr ( CHAR8 *SkuName OPTIONAL, @@ -283,24 +263,6 @@ __PcdGetPtr ( CHAR8 *TokenName, UINT32 *Size ) -/*++ - -Routine Description: - - Get PCD value buffer - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Size Size of PCD value buffer - -Returns: - - PCD value buffer ---*/ { int Index; CHAR8 *Value; @@ -341,6 +303,16 @@ Routine Description: return 0; } +/** + Set PCD value buffer + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Size Size of PCD value + @param Value Pointer to the updated PCD value buffer +**/ VOID __PcdSetPtr ( CHAR8 *SkuName OPTIONAL, @@ -350,25 +322,6 @@ __PcdSetPtr ( UINT32 Size, UINT8 *Value ) -/*++ - -Routine Description: - - Set PCD value buffer - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Size Size of PCD value - Value Pointer to the updated PCD value buffer - -Returns: - - None ---*/ { int Index; UINT32 ValueIndex; @@ -400,6 +353,13 @@ Routine Description: } } +/** + Read the file buffer from the input file. + + @param InputFileName Point to the input file name. + @param FileBuffer Point to the input file buffer. + @param FileSize Size of the file buffer. +**/ VOID STATIC ReadInputFile ( @@ -407,22 +367,6 @@ ReadInputFile ( UINT8 **FileBuffer, UINT32 *FileSize ) -/*++ - -Routine Description: - - Read the file buffer from the input file. - -Arguments: - - InputFileName Point to the input file name. - FileBuffer Point to the input file buffer. - FileSize Size of the file buffer. - -Returns: - - None ---*/ { FILE *InputFile; UINT32 BytesRead; @@ -492,27 +436,18 @@ Routine Description: fclose (InputFile); } +/** + Read the initial PCD value from the input file buffer. + + @param FileBuffer Point to the input file buffer. + @param FileSize Size of the file buffer. +**/ VOID STATIC ParseFile ( UINT8 *FileBuffer, UINT32 FileSize ) -/*++ - -Routine Description: - - Read the initial PCD value from the input file buffer. - -Arguments: - - FileBuffer Point to the input file buffer. - FileSize Size of the file buffer. - -Returns: - - None ---*/ { UINT32 Index; UINT32 NumLines; @@ -552,25 +487,16 @@ Routine Description: } } +/** + Write the updated PCD value into the output file name. + + @param OutputFileName Point to the output file name. +**/ VOID STATIC WriteOutputFile ( CHAR8 *OutputFileName ) -/*++ - -Routine Description: - - Write the updated PCD value into the output file name. - -Arguments: - - OutputFileName Point to the output file name. - -Returns: - - None ---*/ { FILE *OutputFile; UINT32 Index; @@ -605,26 +531,14 @@ Routine Description: } } +/** + Displays the utility usage syntax to STDOUT +**/ VOID STATIC Usage ( VOID ) -/*++ - -Routine Description: - - Displays the utility usage syntax to STDOUT - -Arguments: - - None - -Returns: - - None - ---*/ { fprintf (stdout, "Usage: -i -o \n\n"); fprintf (stdout, "optional arguments:\n"); @@ -635,6 +549,14 @@ Routine Description: PCD Database Output file name\n"); } +/** + Parse the input parameters to get the input/output file name. + + @param argc Number of command line parameters. + @param argv Array of pointers to parameter strings. + @param InputFileName Point to the input file name. + @param OutputFileName Point to the output file name. +**/ VOID STATIC ParseArguments ( @@ -643,23 +565,6 @@ ParseArguments ( CHAR8 **InputFileName, CHAR8 **OutputFileName ) -/*++ - -Routine Description: - - Parse the input parameters to get the input/output file name. - -Arguments: - - argc Number of command line parameters. - argv Array of pointers to parameter strings. - InputFileName Point to the input file name. - OutputFileName Point to the output file name. - -Returns: - - None ---*/ { if (argc == 1) { fprintf (stderr, "Missing options\n"); @@ -722,25 +627,19 @@ Routine Description: } } +/** + Main function updates PCD values. + + @param argc Number of command line parameters. + @param argv Array of pointers to parameter strings. + + @retval EXIT_SUCCESS +**/ int PcdValueMain ( int argc, char *argv[] ) -/*++ - -Routine Description: - - Main function updates PCD values. - -Arguments: - - argc Number of command line parameters. - argv Array of pointers to parameter strings. - -Returns: - EXIT_SUCCESS ---*/ { CHAR8 *InputFileName; CHAR8 *OutputFileName; diff --git a/BaseTools/Source/C/Common/PcdValueCommon.h b/BaseTools/Source/C/Common/PcdValueCommon.h index 1652bd5430..02ef803be4 100644 --- a/BaseTools/Source/C/Common/PcdValueCommon.h +++ b/BaseTools/Source/C/Common/PcdValueCommon.h @@ -24,46 +24,40 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define __STATIC_ASSERT _Static_assert #endif +/** + Main function updates PCD values. It is auto generated by Build +**/ VOID PcdEntryPoint ( VOID ) -/*++ -Routine Description: - - Main function updates PCD values. It is auto generated by Build +; -Arguments: +/** + Main function updates PCD values. - None - -Returns: - None ---*/ -; + @param argc Number of command line parameters. + @param argv Array of pointers to parameter strings. + @retval EXIT_SUCCESS +**/ int PcdValueMain ( int argc, char *argv[] ) -/*++ - -Routine Description: - - Main function updates PCD values. - -Arguments: - - argc Number of command line parameters. - argv Array of pointers to parameter strings. - -Returns: - EXIT_SUCCESS ---*/ ; +/** + Set PCD value + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Value PCD value to be set +**/ VOID __PcdSet ( CHAR8 *SkuName OPTIONAL, @@ -72,25 +66,18 @@ __PcdSet ( CHAR8 *TokenName, UINT64 Value ) -/*++ - -Routine Description: +; +/** Get PCD value -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - -Returns: - - PCD value ---*/ -; + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @return PCD value +**/ VOID __PcdSet ( CHAR8 *SkuName OPTIONAL, @@ -99,26 +86,19 @@ __PcdSet ( CHAR8 *TokenName, UINT64 Value ) -/*++ - -Routine Description: - - Set PCD value - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Value PCD value to be set +; -Returns: +/** + Get PCD value buffer - None ---*/ -; + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Size Size of PCD value buffer + @return PCD value buffer +**/ VOID * __PcdGetPtr ( CHAR8 *SkuName OPTIONAL, @@ -127,26 +107,18 @@ __PcdGetPtr ( CHAR8 *TokenName, UINT32 *Size ) -/*++ - -Routine Description: - - Get PCD value buffer - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Size Size of PCD value buffer - -Returns: - - PCD value buffer ---*/ ; +/** + Set PCD value buffer + + @param SkuName SkuName String + @param DefaultValueName DefaultValueName String + @param TokenSpaceGuidName TokenSpaceGuidName String + @param TokenName TokenName String + @param Size Size of PCD value + @param Value Pointer to the updated PCD value buffer +**/ VOID __PcdSetPtr ( CHAR8 *SkuName OPTIONAL, @@ -156,25 +128,6 @@ __PcdSetPtr ( UINT32 Size, UINT8 *Value ) -/*++ - -Routine Description: - - Set PCD value buffer - -Arguments: - - SkuName SkuName String - DefaultValueName DefaultValueName String - TokenSpaceGuidName TokenSpaceGuidName String - TokenName TokenName String - Size Size of PCD value - Value Pointer to the updated PCD value buffer - -Returns: - - None ---*/ ; #define PcdGet(A, B, C, D) __PcdGet(#A, #B, #C, #D) diff --git a/BaseTools/Source/C/Common/PeCoffLoaderEx.c b/BaseTools/Source/C/Common/PeCoffLoaderEx.c index 2cc428d733..181192035e 100644 --- a/BaseTools/Source/C/Common/PeCoffLoaderEx.c +++ b/BaseTools/Source/C/Common/PeCoffLoaderEx.c @@ -65,6 +65,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent UINT32 *RiscVHi20Fixup = NULL; +/** + Performs an IA-32 specific relocation fixup + + @param Reloc Pointer to the relocation record + @param Fixup Pointer to the address to fix up + @param FixupData Pointer to a buffer to log the fixups + @param Adjust The offset to adjust the fixup + + @retval EFI_UNSUPPORTED - Unsupported now +**/ RETURN_STATUS PeCoffLoaderRelocateIa32Image ( IN UINT16 *Reloc, @@ -72,52 +82,20 @@ PeCoffLoaderRelocateIa32Image ( IN OUT CHAR8 **FixupData, IN UINT64 Adjust ) -/*++ - -Routine Description: - - Performs an IA-32 specific relocation fixup - -Arguments: - - Reloc - Pointer to the relocation record - - Fixup - Pointer to the address to fix up - - FixupData - Pointer to a buffer to log the fixups - - Adjust - The offset to adjust the fixup - -Returns: - - EFI_UNSUPPORTED - Unsupported now - ---*/ { return RETURN_UNSUPPORTED; } -/*++ - -Routine Description: - +/** Performs an RISC-V specific relocation fixup -Arguments: - - Reloc - Pointer to the relocation record + @param Reloc Pointer to the relocation record + @param Fixup Pointer to the address to fix up + @param FixupData Pointer to a buffer to log the fixups + @param Adjust The offset to adjust the fixup - Fixup - Pointer to the address to fix up - - FixupData - Pointer to a buffer to log the fixups - - Adjust - The offset to adjust the fixup - -Returns: - - Status code - ---*/ + @return Status code +**/ RETURN_STATUS PeCoffLoaderRelocateRiscVImage ( IN UINT16 *Reloc, diff --git a/BaseTools/Source/C/Common/SimpleFileParsing.c b/BaseTools/Source/C/Common/SimpleFileParsing.c index eb6abea1be..382cd406cb 100644 --- a/BaseTools/Source/C/Common/SimpleFileParsing.c +++ b/BaseTools/Source/C/Common/SimpleFileParsing.c @@ -152,65 +152,43 @@ SetFilePosition ( FILE_POSITION *Fpos ); +/** + @retval STATUS_SUCCESS always +**/ STATUS SFPInit ( VOID ) -/*++ - -Routine Description: - -Arguments: - None. - -Returns: - STATUS_SUCCESS always - ---*/ { memset ((VOID *) &mGlobals, 0, sizeof (mGlobals)); return STATUS_SUCCESS; } +/** + Return the line number of the file we're parsing. Used + for error reporting purposes. + + @return The line number, or 0 if no file is being processed +**/ UINTN SFPGetLineNumber ( VOID ) -/*++ - -Routine Description: - Return the line number of the file we're parsing. Used - for error reporting purposes. - -Arguments: - None. - -Returns: - The line number, or 0 if no file is being processed - ---*/ { return mGlobals.SourceFile.LineNum; } -CHAR8 * -SFPGetFileName ( - VOID - ) -/*++ - -Routine Description: +/** Return the name of the file we're parsing. Used for error reporting purposes. -Arguments: - None. - -Returns: - A pointer to the file name. Null if no file is being + @return A pointer to the file name. Null if no file is being processed. - ---*/ +**/ +CHAR8 * +SFPGetFileName ( + VOID + ) { if (mGlobals.SourceFile.FileName[0]) { return mGlobals.SourceFile.FileName; @@ -219,22 +197,15 @@ Routine Description: return NULL; } +/** + Open a file for parsing. + + @param FileName name of the file to parse +**/ STATUS SFPOpenFile ( CHAR8 *FileName ) -/*++ - -Routine Description: - Open a file for parsing. - -Arguments: - FileName - name of the file to parse - -Returns: - - ---*/ { STATUS Status; t_strcpy (mGlobals.SourceFile.FileName, FileName); @@ -242,31 +213,26 @@ Routine Description: return Status; } -BOOLEAN -SFPIsToken ( - CHAR8 *Str - ) -/*++ - -Routine Description: +/** Check to see if the specified token is found at the current position in the input file. -Arguments: - Str - the token to look for - -Returns: - TRUE - the token is next - FALSE - the token is not next + @note: + We do a simple string comparison on this function. It is + the responsibility of the caller to ensure that the token + is not a subset of some other token. -Notes: - We do a simple string comparison on this function. It is - the responsibility of the caller to ensure that the token - is not a subset of some other token. + The file pointer is advanced past the token in the input file. - The file pointer is advanced past the token in the input file. + @param Str the token to look for ---*/ + @retval TRUE the token is next + @retval FALSE the token is not next +**/ +BOOLEAN +SFPIsToken ( + CHAR8 *Str + ) { UINTN Len; SkipWhiteSpace (&mGlobals.SourceFile); @@ -286,28 +252,23 @@ Routine Description: return FALSE; } -BOOLEAN -SFPIsKeyword ( - CHAR8 *Str - ) -/*++ - -Routine Description: +/** Check to see if the specified keyword is found at the current position in the input file. -Arguments: - Str - keyword to look for - -Returns: - TRUE - the keyword is next - FALSE - the keyword is not next + @note: + A keyword is defined as a "special" string that has a non-alphanumeric + character following it. -Notes: - A keyword is defined as a "special" string that has a non-alphanumeric - character following it. + @param Str keyword to look for ---*/ + @retval TRUE the keyword is next + @retval FALSE the keyword is not next +**/ +BOOLEAN +SFPIsKeyword ( + CHAR8 *Str + ) { UINTN Len; SkipWhiteSpace (&mGlobals.SourceFile); @@ -331,30 +292,25 @@ Routine Description: return FALSE; } +/** + Get the next token from the input stream. + + @note: + Preceding white space is ignored. + The parser's buffer pointer is advanced past the end of the + token. + + @param Str pointer to a copy of the next token + @param Len size of buffer pointed to by Str + + @retval TRUE next token successfully returned + @retval FALSE otherwise +**/ BOOLEAN SFPGetNextToken ( CHAR8 *Str, UINTN Len ) -/*++ - -Routine Description: - Get the next token from the input stream. - -Arguments: - Str - pointer to a copy of the next token - Len - size of buffer pointed to by Str - -Returns: - TRUE - next token successfully returned - FALSE - otherwise - -Notes: - Preceding white space is ignored. - The parser's buffer pointer is advanced past the end of the - token. - ---*/ { UINTN Index; CHAR8 TempChar; @@ -436,25 +392,20 @@ Routine Description: return FALSE; } +/** + Parse a GUID from the input stream. Stop when you discover white space. + + @param Str pointer to a copy of the next token + @param Len size of buffer pointed to by Str + + @retval TRUE GUID string returned successfully + @retval FALSE otherwise +**/ BOOLEAN SFPGetGuidToken ( CHAR8 *Str, UINT32 Len ) -/*++ - -Routine Description: - Parse a GUID from the input stream. Stop when you discover white space. - -Arguments: - Str - pointer to a copy of the next token - Len - size of buffer pointed to by Str - -Returns: - TRUE - GUID string returned successfully - FALSE - otherwise - ---*/ { UINT32 Index; SkipWhiteSpace (&mGlobals.SourceFile); @@ -505,24 +456,19 @@ SFPSkipToToken ( return FALSE; } -BOOLEAN -SFPGetNumber ( - UINTN *Value - ) -/*++ - -Routine Description: +/** Check the token at the current file position for a numeric value. May be either decimal or hex. -Arguments: - Value - pointer where to store the value - -Returns: - FALSE - current token is not a number - TRUE - current token is a number + @param Value pointer where to store the value ---*/ + @retval FALSE current token is not a number + @retval TRUE current token is a number +**/ +BOOLEAN +SFPGetNumber ( + UINTN *Value + ) { int Val; @@ -561,23 +507,16 @@ Routine Description: } } +/** + Close the file being parsed. + + @retval STATUS_SUCCESS the file was closed + @retval STATUS_ERROR no file is currently open +**/ STATUS SFPCloseFile ( VOID ) -/*++ - -Routine Description: - Close the file being parsed. - -Arguments: - None. - -Returns: - STATUS_SUCCESS - the file was closed - STATUS_ERROR - no file is currently open - ---*/ { if (mGlobals.SourceFile.FileBuffer != NULL) { free (mGlobals.SourceFile.FileBuffer); @@ -588,28 +527,20 @@ Routine Description: return STATUS_ERROR; } +/** + Given a source file, open the file and parse it + + @param SourceFile name of file to parse + @param ParentSourceFile for error reporting purposes, the file that #included SourceFile. + + @return Standard status. +**/ STATIC STATUS ProcessIncludeFile ( SOURCE_FILE *SourceFile, SOURCE_FILE *ParentSourceFile ) -/*++ - -Routine Description: - - Given a source file, open the file and parse it - -Arguments: - - SourceFile - name of file to parse - ParentSourceFile - for error reporting purposes, the file that #included SourceFile. - -Returns: - - Standard status. - ---*/ { STATIC UINTN NestDepth = 0; CHAR8 FoundFileName[MAX_PATH]; @@ -657,27 +588,19 @@ Routine Description: return Status; } +/** + Given a source file that's been opened, read the contents into an internal + buffer and pre-process it to remove comments. + + @param SourceFile structure containing info on the file to process + + @return Standard status. +**/ STATIC STATUS ProcessFile ( SOURCE_FILE *SourceFile ) -/*++ - -Routine Description: - - Given a source file that's been opened, read the contents into an internal - buffer and pre-process it to remove comments. - -Arguments: - - SourceFile - structure containing info on the file to process - -Returns: - - Standard status. - ---*/ { // // Get the file size, and then read the entire thing into memory. @@ -706,24 +629,17 @@ Routine Description: return STATUS_SUCCESS; } +/** + Preprocess a file to replace all carriage returns with NULLs so + we can print lines (as part of error messages) from the file to the screen. + + @param SourceFile structure that we use to keep track of an input file. +**/ STATIC VOID PreprocessFile ( SOURCE_FILE *SourceFile ) -/*++ - -Routine Description: - Preprocess a file to replace all carriage returns with NULLs so - we can print lines (as part of error messages) from the file to the screen. - -Arguments: - SourceFile - structure that we use to keep track of an input file. - -Returns: - Nothing. - ---*/ { BOOLEAN InComment; BOOLEAN SlashSlashComment; @@ -812,26 +728,21 @@ Routine Description: } } +/** + Retrieve a quoted-string from the input file. + + @param Str pointer to a copy of the quoted string parsed + @param Length size of buffer pointed to by Str + + @retval TRUE next token in input stream was a quoted string, and + the string value was returned in Str + @retval FALSE otherwise +**/ BOOLEAN SFPGetQuotedString ( CHAR8 *Str, INTN Length ) -/*++ - -Routine Description: - Retrieve a quoted-string from the input file. - -Arguments: - Str - pointer to a copy of the quoted string parsed - Length - size of buffer pointed to by Str - -Returns: - TRUE - next token in input stream was a quoted string, and - the string value was returned in Str - FALSE - otherwise - ---*/ { SkipWhiteSpace (&mGlobals.SourceFile); if (EndOfFile (&mGlobals.SourceFile)) { @@ -866,24 +777,17 @@ Routine Description: return FALSE; } +/** + Return TRUE of FALSE to indicate whether or not we've reached the end of the + file we're parsing. + + @retval TRUE EOF reached + @retval FALSE otherwise +**/ BOOLEAN SFPIsEOF ( VOID ) -/*++ - -Routine Description: - Return TRUE of FALSE to indicate whether or not we've reached the end of the - file we're parsing. - -Arguments: - NA - -Returns: - TRUE - EOF reached - FALSE - otherwise - ---*/ { SkipWhiteSpace (&mGlobals.SourceFile); return EndOfFile (&mGlobals.SourceFile); @@ -1112,27 +1016,22 @@ SkipWhiteSpace ( return Count; } +/** + Compare two strings for equality. The string pointed to by 'Buffer' may or may not be null-terminated, + so only compare up to the length of Str. + + @param Buffer pointer to first (possibly not null-terminated) string + @param Str pointer to null-terminated string to compare to Buffer + + @retval Number of bytes matched if exact match + @retval 0 if Buffer does not start with Str +**/ STATIC UINTN t_strcmp ( CHAR8 *Buffer, CHAR8 *Str ) -/*++ - -Routine Description: - Compare two strings for equality. The string pointed to by 'Buffer' may or may not be null-terminated, - so only compare up to the length of Str. - -Arguments: - Buffer - pointer to first (possibly not null-terminated) string - Str - pointer to null-terminated string to compare to Buffer - -Returns: - Number of bytes matched if exact match - 0 if Buffer does not start with Str - ---*/ { UINTN Len; @@ -1245,28 +1144,23 @@ GetHexChars ( return Len; } +/** + Parse a GUID from the input stream. Stop when you discover white space. + + GUID styles + Style[0] 12345678-1234-5678-AAAA-BBBBCCCCDDDD + + @param GuidStyle Style of the following GUID token + @param Value pointer to EFI_GUID struct for output + + @retval TRUE GUID string parsed successfully + @retval FALSE otherwise +**/ BOOLEAN SFPGetGuid ( INTN GuidStyle, EFI_GUID *Value ) -/*++ - -Routine Description: - Parse a GUID from the input stream. Stop when you discover white space. - -Arguments: - GuidStyle - Style of the following GUID token - Value - pointer to EFI_GUID struct for output - -Returns: - TRUE - GUID string parsed successfully - FALSE - otherwise - - GUID styles - Style[0] 12345678-1234-5678-AAAA-BBBBCCCCDDDD - ---*/ { INT32 Value32; UINT32 Index; diff --git a/BaseTools/Source/C/Common/StringFuncs.c b/BaseTools/Source/C/Common/StringFuncs.c index 50573fdf09..53e44365e9 100644 --- a/BaseTools/Source/C/Common/StringFuncs.c +++ b/BaseTools/Source/C/Common/StringFuncs.c @@ -14,25 +14,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Functions implementations // +/** + Allocates a new string and copies 'String' to clone it + + @param String The string to clone + + @return CHAR8* - NULL if there are not enough resources +**/ CHAR8* CloneString ( IN CHAR8 *String ) -/*++ - -Routine Description: - - Allocates a new string and copies 'String' to clone it - -Arguments: - - String The string to clone - -Returns: - - CHAR8* - NULL if there are not enough resources - ---*/ { CHAR8* NewString; @@ -44,26 +36,17 @@ Routine Description: return NewString; } +/** + Remove all comments, leading and trailing whitespace from the string. + + @param String The string to 'strip' + @return EFI_STATUS +**/ EFI_STATUS StripInfDscStringInPlace ( IN CHAR8 *String ) -/*++ - -Routine Description: - - Remove all comments, leading and trailing whitespace from the string. - -Arguments: - - String The string to 'strip' - -Returns: - - EFI_STATUS - ---*/ { CHAR8 *Pos; @@ -110,27 +93,18 @@ Routine Description: return EFI_SUCCESS; } +/** + Creates and returns a 'split' STRING_LIST by splitting the string + on whitespace boundaries. + @param String The string to 'split' + + @return EFI_STATUS +**/ STRING_LIST* SplitStringByWhitespace ( IN CHAR8 *String ) -/*++ - -Routine Description: - - Creates and returns a 'split' STRING_LIST by splitting the string - on whitespace boundaries. - -Arguments: - - String The string to 'split' - -Returns: - - EFI_STATUS - ---*/ { CHAR8 *Pos; CHAR8 *EndOfSubString; @@ -172,21 +146,14 @@ Routine Description: return Output; } +/** + Creates a new STRING_LIST with 0 strings. + @return STRING_LIST* - Null if there is not enough resources to create the object. +**/ STRING_LIST* NewStringList ( ) -/*++ - -Routine Description: - - Creates a new STRING_LIST with 0 strings. - -Returns: - - STRING_LIST* - Null if there is not enough resources to create the object. - ---*/ { STRING_LIST *NewList; NewList = AllocateStringListStruct (0); @@ -196,24 +163,17 @@ Routine Description: return NewList; } +/** + Adds String to StringList. A new copy of String is made before it is + added to StringList. + @return EFI_STATUS +**/ EFI_STATUS AppendCopyOfStringToList ( IN OUT STRING_LIST **StringList, IN CHAR8 *String ) -/*++ - -Routine Description: - - Adds String to StringList. A new copy of String is made before it is - added to StringList. - -Returns: - - EFI_STATUS - ---*/ { STRING_LIST *OldList; STRING_LIST *NewList; @@ -245,27 +205,18 @@ Routine Description: return EFI_SUCCESS; } +/** + Removes the last string from StringList and frees the memory associated + with it. + @param StringList The string list to remove the string from + + @return EFI_STATUS +**/ EFI_STATUS RemoveLastStringFromList ( IN STRING_LIST *StringList ) -/*++ - -Routine Description: - - Removes the last string from StringList and frees the memory associated - with it. - -Arguments: - - StringList The string list to remove the string from - -Returns: - - EFI_STATUS - ---*/ { if (StringList->Count == 0) { return EFI_INVALID_PARAMETER; @@ -276,49 +227,30 @@ Routine Description: return EFI_SUCCESS; } +/** + Allocates a STRING_LIST structure that can store StringCount strings. + + @param StringCount The number of strings that need to be stored + @return EFI_STATUS +**/ STRING_LIST* AllocateStringListStruct ( IN UINTN StringCount ) -/*++ - -Routine Description: - - Allocates a STRING_LIST structure that can store StringCount strings. - -Arguments: - - StringCount The number of strings that need to be stored - -Returns: - - EFI_STATUS - ---*/ { return malloc (OFFSET_OF(STRING_LIST, Strings[StringCount + 1])); } +/** + Frees all memory associated with StringList. + @param StringList The string list to free +**/ VOID FreeStringList ( IN STRING_LIST *StringList ) -/*++ - -Routine Description: - - Frees all memory associated with StringList. - -Arguments: - - StringList The string list to free - -Returns: - - VOID ---*/ { while (StringList->Count > 0) { RemoveLastStringFromList (StringList); @@ -327,27 +259,18 @@ Routine Description: free (StringList); } +/** + Generates a string that represents the STRING_LIST + @param StringList The string list to convert to a string + + @return CHAR8* - The string list represented with a single string. The returned + string must be freed by the caller. +**/ CHAR8* StringListToString ( IN STRING_LIST *StringList ) -/*++ - -Routine Description: - - Generates a string that represents the STRING_LIST - -Arguments: - - StringList The string list to convert to a string - -Returns: - - CHAR8* - The string list represented with a single string. The returned - string must be freed by the caller. - ---*/ { UINTN Count; UINTN Length; @@ -381,26 +304,17 @@ Routine Description: return NewString; } +/** + Prints out the string list + + @param StringList The string list to print + @return EFI_STATUS +**/ VOID PrintStringList ( IN STRING_LIST *StringList ) -/*++ - -Routine Description: - - Prints out the string list - -Arguments: - - StringList The string list to print - -Returns: - - EFI_STATUS - ---*/ { CHAR8* String; String = StringListToString (StringList); diff --git a/BaseTools/Source/C/Common/StringFuncs.h b/BaseTools/Source/C/Common/StringFuncs.h index 8fc616de80..23dce27244 100644 --- a/BaseTools/Source/C/Common/StringFuncs.h +++ b/BaseTools/Source/C/Common/StringFuncs.h @@ -29,216 +29,139 @@ typedef struct { // Functions declarations // +/** + Allocates a new string and copies 'String' to clone it + + @param String The string to clone + + @return CHAR8* - NULL if there are not enough resources +**/ CHAR8* CloneString ( IN CHAR8 *String ) ; -/** - -Routine Description: - Allocates a new string and copies 'String' to clone it - -Arguments: - - String The string to clone - -Returns: +/** + Remove all comments, leading and trailing whitespace from the string. - CHAR8* - NULL if there are not enough resources + @param String The string to 'strip' + @return EFI_STATUS **/ - - EFI_STATUS StripInfDscStringInPlace ( IN CHAR8 *String ) ; -/** - -Routine Description: - - Remove all comments, leading and trailing whitespace from the string. - -Arguments: - String The string to 'strip' - -Returns: +/** + Creates and returns a 'split' STRING_LIST by splitting the string + on whitespace boundaries. - EFI_STATUS + @param String The string to 'split' + @return EFI_STATUS **/ - - STRING_LIST* SplitStringByWhitespace ( IN CHAR8 *String ) ; -/** - -Routine Description: - - Creates and returns a 'split' STRING_LIST by splitting the string - on whitespace boundaries. - -Arguments: - - String The string to 'split' -Returns: - - EFI_STATUS +/** + Creates a new STRING_LIST with 0 strings. + @return STRING_LIST* - Null if there is not enough resources to create the object. **/ - - STRING_LIST* NewStringList ( ) ; -/** -Routine Description: - Creates a new STRING_LIST with 0 strings. - -Returns: - - STRING_LIST* - Null if there is not enough resources to create the object. +/** + Adds String to StringList. A new copy of String is made before it is + added to StringList. + @return EFI_STATUS **/ - - EFI_STATUS AppendCopyOfStringToList ( IN OUT STRING_LIST **StringList, IN CHAR8 *String ) ; -/** - -Routine Description: - - Adds String to StringList. A new copy of String is made before it is - added to StringList. -Returns: +/** + Removes the last string from StringList and frees the memory associated + with it. - EFI_STATUS + @param StringList The string list to remove the string from + @return EFI_STATUS **/ - - EFI_STATUS RemoveLastStringFromList ( IN STRING_LIST *StringList ) ; -/** -Routine Description: - Removes the last string from StringList and frees the memory associated - with it. - -Arguments: - - StringList The string list to remove the string from - -Returns: +/** + Allocates a STRING_LIST structure that can store StringCount strings. - EFI_STATUS + @param StringCount The number of strings that need to be stored + @return EFI_STATUS **/ - - STRING_LIST* AllocateStringListStruct ( IN UINTN StringCount ) ; -/** - -Routine Description: - - Allocates a STRING_LIST structure that can store StringCount strings. - -Arguments: - StringCount The number of strings that need to be stored -Returns: +/** + Frees all memory associated with StringList. - EFI_STATUS + @param StringList The string list to free + @return EFI_STATUS **/ - - VOID FreeStringList ( IN STRING_LIST *StringList ) ; -/** - -Routine Description: - Frees all memory associated with StringList. - -Arguments: - StringList The string list to free - -Returns: +/** + Generates a string that represents the STRING_LIST - EFI_STATUS + @param StringList The string list to convert to a string + @return CHAR8* The string list represented with a single string. The returned + string must be freed by the caller. **/ - - CHAR8* StringListToString ( IN STRING_LIST *StringList ) ; -/** - -Routine Description: - - Generates a string that represents the STRING_LIST - -Arguments: - StringList The string list to convert to a string -Returns: - - CHAR8* - The string list represented with a single string. The returned - string must be freed by the caller. +/** + Prints out the string list + @param StringList The string list to print **/ - - VOID PrintStringList ( IN STRING_LIST *StringList ) ; -/** -Routine Description: - - Prints out the string list - -Arguments: - - StringList The string list to print - -**/ #endif diff --git a/BaseTools/Source/C/Common/TianoCompress.c b/BaseTools/Source/C/Common/TianoCompress.c index 030cdca025..6d23259720 100644 --- a/BaseTools/Source/C/Common/TianoCompress.c +++ b/BaseTools/Source/C/Common/TianoCompress.c @@ -256,6 +256,25 @@ STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NU // // functions // + +/** + The internal implementation of [Efi/Tiano]Compress(). + + @param SrcBuffer The buffer storing the source data + @param SrcSize The size of source data + @param DstBuffer The buffer to store the compressed data + @param DstSize On input, the size of DstBuffer; On output, + the size of the actual compressed data. + @param Version The version of de/compression algorithm. + Version 1 for UEFI 2.0 de/compression algorithm. + Version 2 for Tiano de/compression algorithm. + + @retval EFI_BUFFER_TOO_SMALL The DstBuffer is too small. In this case, + DstSize contains the size needed. + @retval EFI_SUCCESS Compression is successful. + @retval EFI_OUT_OF_RESOURCES No resource to complete function. + @retval EFI_INVALID_PARAMETER Parameter supplied is wrong. +**/ EFI_STATUS TianoCompress ( IN UINT8 *SrcBuffer, @@ -263,32 +282,6 @@ TianoCompress ( IN UINT8 *DstBuffer, IN OUT UINT32 *DstSize ) -/*++ - -Routine Description: - - The internal implementation of [Efi/Tiano]Compress(). - -Arguments: - - SrcBuffer - The buffer storing the source data - SrcSize - The size of source data - DstBuffer - The buffer to store the compressed data - DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. - Version - The version of de/compression algorithm. - Version 1 for UEFI 2.0 de/compression algorithm. - Version 2 for Tiano de/compression algorithm. - -Returns: - - EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case, - DstSize contains the size needed. - EFI_SUCCESS - Compression is successful. - EFI_OUT_OF_RESOURCES - No resource to complete function. - EFI_INVALID_PARAMETER - Parameter supplied is wrong. - ---*/ { EFI_STATUS Status; @@ -351,24 +344,16 @@ Routine Description: } +/** + Put a dword to output stream + + @param Data the dword to put +**/ STATIC VOID PutDword ( IN UINT32 Data ) -/*++ - -Routine Description: - - Put a dword to output stream - -Arguments: - - Data - the dword to put - -Returns: (VOID) - ---*/ { if (mDst < mDstUpperLimit) { *mDst++ = (UINT8) (((UINT8) (Data)) & 0xff); @@ -387,26 +372,17 @@ Returns: (VOID) } } +/** + Allocate memory spaces for data structures used in compression process + + @retval EFI_SUCCESS Memory is allocated successfully + @retval EFI_OUT_OF_RESOURCES Allocation fails +**/ STATIC EFI_STATUS AllocateMemory ( VOID ) -/*++ - -Routine Description: - - Allocate memory spaces for data structures used in compression process - -Arguments: - VOID - -Returns: - - EFI_SUCCESS - Memory is allocated successfully - EFI_OUT_OF_RESOURCES - Allocation fails - ---*/ { UINT32 Index; @@ -445,21 +421,13 @@ Routine Description: return EFI_SUCCESS; } +/** + Called when compression is completed to free memory previously allocated. +**/ VOID FreeMemory ( VOID ) -/*++ - -Routine Description: - - Called when compression is completed to free memory previously allocated. - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { if (mText != NULL) { free (mText); @@ -496,22 +464,14 @@ Returns: (VOID) return ; } +/** + Initialize String Info Log data structures +**/ STATIC VOID InitSlide ( VOID ) -/*++ - -Routine Description: - - Initialize String Info Log data structures - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE Index; @@ -535,28 +495,20 @@ Returns: (VOID) } } +/** + Find child node given the parent node and the edge character + + @param NodeQ the parent node + @param CharC the edge character + + @return The child node (NIL if not found) +**/ STATIC NODE Child ( IN NODE NodeQ, IN UINT8 CharC ) -/*++ - -Routine Description: - - Find child node given the parent node and the edge character - -Arguments: - - NodeQ - the parent node - CharC - the edge character - -Returns: - - The child node (NIL if not found) - ---*/ { NODE NodeR; @@ -572,6 +524,13 @@ Routine Description: return NodeR; } +/** + Create a new child for a given parent node. + + @param Parent the parent node + @param CharC the edge character + @param Child the child node +**/ STATIC VOID MakeChild ( @@ -579,21 +538,6 @@ MakeChild ( IN UINT8 CharC, IN NODE Child ) -/*++ - -Routine Description: - - Create a new child for a given parent node. - -Arguments: - - Parent - the parent node - CharC - the edge character - Child - the child node - -Returns: (VOID) - ---*/ { NODE Node1; NODE Node2; @@ -608,24 +552,16 @@ Returns: (VOID) mChildCount[Parent]++; } +/** + Split a node. + + @param Old the node to split +**/ STATIC VOID Split ( NODE Old ) -/*++ - -Routine Description: - - Split a node. - -Arguments: - - Old - the node to split - -Returns: (VOID) - ---*/ { NODE New; NODE TempNode; @@ -646,22 +582,14 @@ Returns: (VOID) MakeChild (New, mText[mPos + mMatchLen], mPos); } +/** + Insert string info for current position into the String Info Log +**/ STATIC VOID InsertNode ( VOID ) -/*++ - -Routine Description: - - Insert string info for current position into the String Info Log - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE NodeQ; NODE NodeR; @@ -778,23 +706,15 @@ Returns: (VOID) } +/** + Delete outdated string info. (The Usage of PERC_FLAG + ensures a clean deletion) +**/ STATIC VOID DeleteNode ( VOID ) -/*++ - -Routine Description: - - Delete outdated string info. (The Usage of PERC_FLAG - ensures a clean deletion) - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { NODE NodeQ; NODE NodeR; @@ -873,23 +793,15 @@ Returns: (VOID) mAvail = NodeR; } +/** + Advance the current position (read in new data if needed). + Delete outdated string info. Find a match string for current position. +**/ STATIC VOID GetNextMatch ( VOID ) -/*++ - -Routine Description: - - Advance the current position (read in new data if needed). - Delete outdated string info. Find a match string for current position. - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 Number; @@ -906,25 +818,17 @@ Returns: (VOID) InsertNode (); } +/** + The main controlling routine for compression process. + + @retval EFI_SUCCESS The compression is successful + @retval EFI_OUT_0F_RESOURCES Not enough memory for compression process +**/ STATIC EFI_STATUS Encode ( VOID ) -/*++ - -Routine Description: - - The main controlling routine for compression process. - -Arguments: (VOID) - -Returns: - - EFI_SUCCESS - The compression is successful - EFI_OUT_0F_RESOURCES - Not enough memory for compression process - ---*/ { EFI_STATUS Status; INT32 LastMatchLen; @@ -996,22 +900,14 @@ Arguments: (VOID) return EFI_SUCCESS; } +/** + Count the frequencies for the Extra Set +**/ STATIC VOID CountTFreq ( VOID ) -/*++ - -Routine Description: - - Count the frequencies for the Extra Set - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 Index; INT32 Index3; @@ -1053,6 +949,13 @@ Returns: (VOID) } } +/** + Outputs the code length array for the Extra Set or the Position Set. + + @param Number the number of symbols + @param nbit the number of bits needed to represent 'n' + @param Special the special symbol that needs to be take care of +**/ STATIC VOID WritePTLen ( @@ -1060,21 +963,6 @@ WritePTLen ( IN INT32 nbit, IN INT32 Special ) -/*++ - -Routine Description: - - Outputs the code length array for the Extra Set or the Position Set. - -Arguments: - - Number - the number of symbols - nbit - the number of bits needed to represent 'n' - Special - the special symbol that needs to be take care of - -Returns: (VOID) - ---*/ { INT32 Index; INT32 Index3; @@ -1103,22 +991,14 @@ Returns: (VOID) } } +/** + Outputs the code length array for Char&Length Set +**/ STATIC VOID WriteCLen ( VOID ) -/*++ - -Routine Description: - - Outputs the code length array for Char&Length Set - -Arguments: (VOID) - -Returns: (VOID) - ---*/ { INT32 Index; INT32 Index3; @@ -1193,24 +1073,14 @@ EncodeP ( } } +/** + Huffman code the block and output it. +**/ STATIC VOID SendBlock ( VOID ) -/*++ - -Routine Description: - - Huffman code the block and output it. - -Arguments: - (VOID) - -Returns: - (VOID) - ---*/ { UINT32 Index; UINT32 Index2; @@ -1281,26 +1151,18 @@ Routine Description: } } +/** + Outputs an Original Character or a Pointer + + @param CharC The original character or the 'String Length' element of a Pointer + @param Pos The 'Position' field of a Pointer +**/ STATIC VOID Output ( IN UINT32 CharC, IN UINT32 Pos ) -/*++ - -Routine Description: - - Outputs an Original Character or a Pointer - -Arguments: - - CharC - The original character or the 'String Length' element of a Pointer - Pos - The 'Position' field of a Pointer - -Returns: (VOID) - ---*/ { STATIC UINT32 CPos; @@ -1399,26 +1261,18 @@ MakeCrcTable ( } } +/** + Outputs rightmost n bits of x + + @param Number the rightmost n bits of the data is used + @param x the data +**/ STATIC VOID PutBits ( IN INT32 Number, IN UINT32 Value ) -/*++ - -Routine Description: - - Outputs rightmost n bits of x - -Arguments: - - Number - the rightmost n bits of the data is used - x - the data - -Returns: (VOID) - ---*/ { UINT8 Temp; @@ -1439,28 +1293,20 @@ Returns: (VOID) mSubBitBuf |= Value << (mBitCount -= Number); } +/** + Read in source data + + @param Pointer - the buffer to hold the data + @param Number - number of bytes to read + + @return number of bytes actually read +**/ STATIC INT32 FreadCrc ( OUT UINT8 *Pointer, IN INT32 Number ) -/*++ - -Routine Description: - - Read in source data - -Arguments: - - Pointer - the buffer to hold the data - Number - number of bytes to read - -Returns: - - number of bytes actually read - ---*/ { INT32 Index; @@ -1491,24 +1337,16 @@ InitPutBits ( mSubBitBuf = 0; } +/** + Count the number of each code length for a Huffman tree. + + @param Index the top node +**/ STATIC VOID CountLen ( IN INT32 Index ) -/*++ - -Routine Description: - - Count the number of each code length for a Huffman tree. - -Arguments: - - Index - the top node - -Returns: (VOID) - ---*/ { STATIC INT32 Depth = 0; @@ -1522,26 +1360,16 @@ Returns: (VOID) } } +/** + Create code length array for a Huffman tree + + @param Root the root of the tree +**/ STATIC VOID MakeLen ( IN INT32 Root ) -/*++ - -Routine Description: - - Create code length array for a Huffman tree - -Arguments: - - Root - the root of the tree - -Returns: - - VOID - ---*/ { INT32 Index; INT32 Index3; @@ -1616,6 +1444,13 @@ DownHeap ( mHeap[Index] = (INT16) Index3; } +/** + Assign code to each symbol based on the code length array + + @param Number number of symbols + @param Len the code length array + @param Code stores codes for each symbol +**/ STATIC VOID MakeCode ( @@ -1623,21 +1458,6 @@ MakeCode ( IN UINT8 Len[ ], OUT UINT16 Code[] ) -/*++ - -Routine Description: - - Assign code to each symbol based on the code length array - -Arguments: - - Number - number of symbols - Len - the code length array - Code - stores codes for each symbol - -Returns: (VOID) - ---*/ { INT32 Index; UINT16 Start[18]; @@ -1652,6 +1472,16 @@ Returns: (VOID) } } +/** + Generates Huffman codes given a frequency distribution of symbols + + @param NParm number of symbols + @param FreqParm frequency of each symbol + @param LenParm code length for each symbol + @param CodeParm code for each symbol + + @return Root of the Huffman tree. +**/ STATIC INT32 MakeTree ( @@ -1660,24 +1490,6 @@ MakeTree ( OUT UINT8 LenParm[ ], OUT UINT16 CodeParm[] ) -/*++ - -Routine Description: - - Generates Huffman codes given a frequency distribution of symbols - -Arguments: - - NParm - number of symbols - FreqParm - frequency of each symbol - LenParm - code length for each symbol - CodeParm - code for each symbol - -Returns: - - Root of the Huffman tree. - ---*/ { INT32 Index; INT32 Index2; From 7bb6c7d3dc11e72544b05b5f1983d9e33629ffaa Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Sun, 19 Feb 2023 23:22:59 -0700 Subject: [PATCH 0715/1529] BaseTools: Replace duplicate __PcdSet prototype with __PcdGet Replace the duplicate __PcdSet prototype in PcdValueCommon.h with the prototype for __PcdGet. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/Common/PcdValueCommon.h | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/BaseTools/Source/C/Common/PcdValueCommon.h b/BaseTools/Source/C/Common/PcdValueCommon.h index 02ef803be4..7dac5bd92d 100644 --- a/BaseTools/Source/C/Common/PcdValueCommon.h +++ b/BaseTools/Source/C/Common/PcdValueCommon.h @@ -78,13 +78,12 @@ __PcdSet ( @return PCD value **/ -VOID -__PcdSet ( - CHAR8 *SkuName OPTIONAL, - CHAR8 *DefaultValueName OPTIONAL, - CHAR8 *TokenSpaceGuidName, - CHAR8 *TokenName, - UINT64 Value +UINT64 +__PcdGet ( + CHAR8 *SkuName OPTIONAL, + CHAR8 *DefaultValueName OPTIONAL, + CHAR8 *TokenSpaceGuidName, + CHAR8 *TokenName ) ; From 8c745ad67cf1d53ad0b9b33c0cba63bc94843528 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Thu, 16 Mar 2023 23:37:40 -0700 Subject: [PATCH 0716/1529] IntelFsp2Pkg: Fix NASM X64 build warnings. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4377 Fix below warnings generated by NASM X64 build: /X64/FspHelper.iii:26: warning: signed dword value exceeds bounds /X64/FspHelper.iii:35: warning: signed dword value exceeds bounds /X64/FspApiEntryT.iii:320: warning: dword data exceeds bounds Also replaced "cmp reg, 0" with "test reg, reg" per optimization suggestion. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm | 18 +++++++++--------- IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm | 2 -- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm index cdebe90fab..b32fa32a89 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm @@ -135,9 +135,9 @@ ASM_PFX(LoadMicrocodeDefault): ; LOAD_RBP - cmp rsp, 0 + test rsp, rsp jz ParamError - cmp rcx, 0 + test rcx, rcx jz ParamError mov rsp, rcx @@ -151,13 +151,13 @@ ASM_PFX(LoadMicrocodeDefault): ; UPD structure is compliant with FSP spec 2.4 mov rax, qword [rsp + LoadMicrocodeParamsFsp24.MicrocodeCodeSize] - cmp rax, 0 + test rax, rax jz Exit2 cmp rax, 0800h jl ParamError mov rsi, qword [rsp + LoadMicrocodeParamsFsp24.MicrocodeCodeAddr] - cmp rsi, 0 + test rsi, rsi jnz CheckMainHeader ParamError: @@ -315,9 +315,9 @@ Done: mov ecx, MSR_IA32_BIOS_SIGN_ID rdmsr ; Get current microcode signature xor eax, eax - cmp edx, 0 + test edx, edx jnz Exit2 - mov eax, 0800000000000000Eh + mov rax, 0800000000000000Eh Exit2: jmp rbp @@ -464,7 +464,7 @@ ParamValid: ; Sec Platform Init ; CALL_YMM ASM_PFX(SecPlatformInit) - cmp eax, 0 + test rax, rax jnz TempRamInitExit ; Load microcode @@ -476,12 +476,12 @@ ParamValid: ; Call Sec CAR Init LOAD_RCX CALL_YMM ASM_PFX(SecCarInit) - cmp rax, 0 + test rax, rax jnz TempRamInitExit LOAD_RCX CALL_YMM ASM_PFX(EstablishStackFsp) - cmp rax, 0 + test rax, rax jnz TempRamInitExit LOAD_UCODE_STATUS rax ; Restore microcode status if no CAR init error from SLOT 0 in YMM9 (upper 128bits). diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm index 71624a3aad..32a60270b8 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspHelper.nasm @@ -23,7 +23,6 @@ ASM_PFX(AsmGetFspInfoHeader): global ASM_PFX(FspInfoHeaderRelativeOff) ASM_PFX(FspInfoHeaderRelativeOff): DD 0x12345678 ; This value must be patched by the build script - and rax, 0xffffffff ret global ASM_PFX(AsmGetFspInfoHeaderNoStack) @@ -32,5 +31,4 @@ ASM_PFX(AsmGetFspInfoHeaderNoStack): lea rcx, [ASM_PFX(FspInfoHeaderRelativeOff)] mov ecx, [rcx] sub rax, rcx - and rax, 0xffffffff jmp rdi From 23c2841eb34f2de6d8bce4e40aa7c872e9db1438 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Po=C5=82awski?= Date: Fri, 24 Mar 2023 07:36:59 -0700 Subject: [PATCH 0717/1529] MdePkg/Include/Ppi: Remove Itanium leftover data structure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Itanium support has been removed from EDK2 around 2019. ITANIUM_HANDOFF_STATUS data structure looks to be some leftover from that process. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1560 GitHub: https://github.com/tianocore/edk2/commit/4e1daa60f5372c22a11503961061ffa569eaf873 There is also positive side effect of this data structure removal. Due to HOB allocation type used in PEI stage there is a limit how much data about virtual CPU can be hold. This limit result in only 1024 vCPU can be used by VM. With Itanium related data structure removed more allocated space can be used for vCPU data and with current allocation limit will change from 1024 to around 8k vCPUs. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Paweł Poławski Reviewed-by: Michael D Kinney --- MdePkg/Include/Ppi/SecPlatformInformation.h | 51 ++------------------- 1 file changed, 5 insertions(+), 46 deletions(-) diff --git a/MdePkg/Include/Ppi/SecPlatformInformation.h b/MdePkg/Include/Ppi/SecPlatformInformation.h index 02b0711f18..c66183eb16 100644 --- a/MdePkg/Include/Ppi/SecPlatformInformation.h +++ b/MdePkg/Include/Ppi/SecPlatformInformation.h @@ -84,57 +84,16 @@ typedef union { typedef EFI_HEALTH_FLAGS X64_HANDOFF_STATUS; typedef EFI_HEALTH_FLAGS IA32_HANDOFF_STATUS; -/// -/// The hand-off status structure for Itanium architecture. -/// -typedef struct { - /// - /// SALE_ENTRY state : 3 = Recovery_Check - /// and 0 = RESET or Normal_Boot phase. - /// - UINT8 BootPhase; - /// - /// Firmware status on entry to SALE. - /// - UINT8 FWStatus; - UINT16 Reserved1; - UINT32 Reserved2; - /// - /// Geographically significant unique processor ID assigned by PAL. - /// - UINT16 ProcId; - UINT16 Reserved3; - UINT8 IdMask; - UINT8 EidMask; - UINT16 Reserved4; - /// - /// Address to make PAL calls. - /// - UINT64 PalCallAddress; - /// - /// If the entry state is RECOVERY_CHECK, this contains the PAL_RESET - /// return address, and if entry state is RESET, this contains - /// address for PAL_authentication call. - /// - UINT64 PalSpecialAddress; - /// - /// GR35 from PALE_EXIT state. - /// - UINT64 SelfTestStatus; - /// - /// GR37 from PALE_EXIT state. - /// - UINT64 SelfTestControl; - UINT64 MemoryBufferRequired; -} ITANIUM_HANDOFF_STATUS; /// /// EFI_SEC_PLATFORM_INFORMATION_RECORD. +/// ItaniumHealthFlags has been removed from this union due to Itanium support +/// being deprecated. The union has now diverged from the definition +/// in the PI Specification. /// typedef union { - IA32_HANDOFF_STATUS IA32HealthFlags; - X64_HANDOFF_STATUS x64HealthFlags; - ITANIUM_HANDOFF_STATUS ItaniumHealthFlags; + IA32_HANDOFF_STATUS IA32HealthFlags; + X64_HANDOFF_STATUS x64HealthFlags; } EFI_SEC_PLATFORM_INFORMATION_RECORD; /** From 4099988f299f039b3739abbd54e2cd3542bf0627 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 3 Mar 2023 11:22:54 +0800 Subject: [PATCH 0718/1529] MdePkg/Include: Add DMTF MCTP definitions BZ #4355 This change adds definitions for DMTF MCTP base specification. Spec ref: https://www.dmtf.org/sites/default/files/standards/documents/DSP0236_1.3.1.pdf Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Abdul Lateef Attar Acked-by: Isaac Oram Reviewed-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Mctp.h | 139 +++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/Mctp.h diff --git a/MdePkg/Include/IndustryStandard/Mctp.h b/MdePkg/Include/IndustryStandard/Mctp.h new file mode 100644 index 0000000000..5e603b9cf6 --- /dev/null +++ b/MdePkg/Include/IndustryStandard/Mctp.h @@ -0,0 +1,139 @@ +/** @file + + The definitions of DMTF Management Component Transport Protocol (MCTP) + Base Specification. + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Revision Reference: + DMTF Management Component Transport Protocol (MCTP) Base Specification + Version 1.3.1 + https://www.dmtf.org/sites/default/files/standards/documents/DSP0236_1.3.1.pdf +**/ + +#ifndef MCTP_H_ +#define MCTP_H_ + +/// +/// Definitions of endpoint ID +/// +#define MCTP_NULL_DESTINATION_ENDPOINT_ID 0 +#define MCTP_NULL_SOURCE_ENDPOINT_ID 0 +#define MCTP_RESERVED_ENDPOINT_START_ID 1 +#define MCTP_RESERVED_ENDPOINT_END_ID 7 +#define MCTP_BROADCAST_ENDPOINT_ID 0xFF + +/// +/// MCTP Control Commands +/// +#define MCTP_CONTROL_RESERVED 0x00 +#define MCTP_CONTROL_SET_ENDPOINT_ID 0x01 +#define MCTP_CONTROL_GET_ENDPOINT_ID 0x02 +#define MCTP_CONTROL_GET_ENDPOINT_UUID 0x03 +#define MCTP_CONTROL_GET_MCTP_VERSION_SUPPORT 0x04 +#define MCTP_CONTROL_GET_MESSAGE_TYPE_SUPPORT 0x05 +#define MCTP_CONTROL_GET_VENDOR_DEFINED_MESSAGE_SUPPORT 0x06 +#define MCTP_CONTROL_RESOLVE_ENDPOINT_ID 0x07 +#define MCTP_CONTROL_ALLOCATE_ENDPOINT_IDS 0x08 +#define MCTP_CONTROL_ROUTING_INFORMATION_UPDATE 0x09 +#define MCTP_CONTROL_GET_ROUTINE_TABLE_ENTRIES 0x0A +#define MCTP_CONTROL_PREPARE_FOR_ENDPOINT_DISCOVERY 0x0B +#define MCTP_CONTROL_ENDPOINT_DISCOVERY 0x0C +#define MCTP_CONTROL_DISCOVERY_NOTIFY 0x0D +#define MCTP_CONTROL_GET_NETWORK_ID 0x0E +#define MCTP_CONTROL_QUERY_HOP 0x0F +#define MCTP_CONTROL_RESOLVE_UUID 0x10 +#define MCTP_CONTROL_QUERY_RATE_LIMIT 0x11 +#define MCTP_CONTROL_REQUEST_TX_RATE_LIMIT 0x12 +#define MCTP_CONTROL_UPDATE_RATE_LIMIT 0x13 +#define MCTP_CONTROL_QUERY_SUPPORTED_INTERFACES 0x14 +#define MCTP_CONTROL_TRANSPORT_SPECIFIC_START 0xF0 +#define MCTP_CONTROL_TRANSPORT_SPECIFIC_END 0xFF + +/// +/// MCTP Control Message Completion Codes +/// +#define MCTP_CONTROL_COMPLETION_CODES_SUCCESS 0x00 +#define MCTP_CONTROL_COMPLETION_CODES_ERROR 0x01 +#define MCTP_CONTROL_COMPLETION_CODES_ERROR_INVALID_DATA 0x02 +#define MCTP_CONTROL_COMPLETION_CODES_ERROR_INVALID_LENGTH 0x03 +#define MCTP_CONTROL_COMPLETION_CODES_ERROR_NOT_READY 0x04 +#define MCTP_CONTROL_COMPLETION_CODES_ERROR_UNSUPPORTED_CMD 0x05 +#define MCTP_CONTROL_COMPLETION_CODES_COMMAND_SPECIFIC_START 0x80 +#define MCTP_CONTROL_COMPLETION_CODES_COMMAND_SPECIFIC_END 0xFF + +/// +/// MCTP Control Message Types +/// +#define MCTP_MESSAGE_TYPE_CONTROL 0x00 +#define MCTP_MESSAGE_TYPE_PLDM 0x01 +#define MCTP_MESSAGE_TYPE_NCSI 0x02 +#define MCTP_MESSAGE_TYPE_ETHERNET 0x03 +#define MCTP_MESSAGE_TYPE_NVME 0x04 +#define MCTP_MESSAGE_TYPE_SPDM 0x05 +#define MCTP_MESSAGE_TYPE_SECURE_MESSAGE 0x06 +#define MCTP_MESSAGE_TYPE_CXL_FM_API 0x07 +#define MCTP_MESSAGE_TYPE_CXL_CCI 0x08 +#define MCTP_MESSAGE_TYPE_VENDOR_DEFINED_PCI 0x7E +#define MCTP_MESSAGE_TYPE_VENDOR_DEFINED_IANA 0x7F + +#define MCTP_ENDPOINT_ID_NULL 0 +#define MCTP_ENDPOINT_ID_RESERVED_START 1 +#define MCTP_ENDPOINT_ID_RESERVED_END 7 +#define MCTP_ENDPOINT_ID_BROADCAST 0xff +/// +/// MCTP Control Message Format +/// +typedef union { + struct { + UINT32 MessageType : 7; ///< Message type. + UINT32 IntegrityCheck : 1; ///< Message integrity check. + UINT32 InstanceId : 5; ///< Instance ID. + UINT32 Reserved : 1; ///< Reserved bit. + UINT32 DatagramBit : 1; ///< Datagram bit. + UINT32 RequestBit : 1; ///< Request bit. + UINT32 CommandCode : 8; ///< Command code of request message. + UINT32 CompletionCode : 8; ///< Completion code in response message. + } Bits; + UINT32 BodyHeader; +} MCTP_CONTROL_MESSAGE; + +/// Minimum transmission size is 64 bytes. +/// The value of 64 is defined in MCTP Base Specification. +#define MCTP_BASELINE_MINIMUM_UNIT_TRANSMISSION_SIZE 0x40 + +/// +/// The 32-bit Header of MCTP packet. +/// +typedef union { + struct { + UINT32 HeaderVersion : 4; ///< The version of header. + UINT32 Reserved : 4; ///< Reserved for future definitions. + UINT32 DestinationEndpointId : 8; ///< Destination endpoint Id (EID). + UINT32 SourceEndpointIdId : 8; ///< Source endpoint Id (EID) + UINT32 MessageTag : 3; ///< Check the MCTP Base specification for the + ///< usages. + UINT32 TagOwner : 1; ///< Tag owner identifies the message was + ///< originated by the source EID or + ///< destination EID. + UINT32 PacketSequence : 2; ///< Sequence number increments Modulo 4 on + ///< each packet. + UINT32 EndOfMessage : 1; ///< Indicates the last packet of message. + UINT32 StartOfMessage : 1; ///< Indicates the first packet of message. + } Bits; + UINT32 Header; +} MCTP_TRANSPORT_HEADER; + +/// +/// The 8-bit Message Header of MCTP packet. +/// +typedef union { + struct { + UINT8 MessageType : 7; + UINT8 IntegrityCheck : 1; + } Bits; + UINT8 MessageHeader; +} MCTP_MESSAGE_HEADER; + +#endif From f4c3fac2a96e798d2d6065793af0bd71554da434 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Fri, 3 Mar 2023 09:34:46 +0800 Subject: [PATCH 0719/1529] MdePkg/Include: Add IPMI KCS definitions BZ #4354 This change adds definitions for IPMI KCS. Spec ref: https://www.intel.com/content/www/us/en/products/docs/servers/ipmi/ipmi-second-gen-interface-spec-v2-rev1-1.html Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Abdul Lateef Attar Acked-by: Isaac Oram Reviewed-by: Michael D Kinney Reviewed-by: Tinh Nguyen --- MdePkg/Include/IndustryStandard/IpmiKcs.h | 76 +++++++++++++++++++++++ MdePkg/MdePkg.dec | 6 ++ 2 files changed, 82 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/IpmiKcs.h diff --git a/MdePkg/Include/IndustryStandard/IpmiKcs.h b/MdePkg/Include/IndustryStandard/IpmiKcs.h new file mode 100644 index 0000000000..b4f9b51f5c --- /dev/null +++ b/MdePkg/Include/IndustryStandard/IpmiKcs.h @@ -0,0 +1,76 @@ +/** @file + IPMI KCS Register Definitions + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Revision Reference: + IPMI Specification + Version 2.0, Rev. 1.1 + https://www.intel.com/content/www/us/en/products/docs/servers/ipmi/ipmi-second-gen-interface-spec-v2-rev1-1.html +**/ + +#ifndef IPMI_KCS_H_ +#define IPMI_KCS_H_ + +#define IPMI_KCS_STATUS_REGISTER_OFFSET 1 +#define IPMI_KCS_COMMAND_REGISTER_OFFSET 1 +#define IPMI_KCS_DATA_OUT_REGISTER_OFFSET 0 +#define IPMI_KCS_DATA_IN_REGISTER_OFFSET 0 + +/// +/// IPMI KCS Interface Status Bits +/// +#define IPMI_KCS_OBF BIT0 +#define IPMI_KCS_IBF BIT1 +#define IPMI_KCS_SMS_ATN BIT2 +#define IPMI_KCS_COMMAND_DATA BIT3 +#define IPMI_KCS_OEM1 BIT4 +#define IPMI_KCS_OEM2 BIT5 +#define IPMI_KCS_S0 BIT6 +#define IPMI_KCS_S1 BIT7 + +/// +/// IPMI KCS Interface Control Codes +/// +#define IPMI_KCS_CONTROL_CODE_GET_STATUS_ABORT 0x60 +#define IPMI_KCS_CONTROL_CODE_WRITE_START 0x61 +#define IPMI_KCS_CONTROL_CODE_WRITE_END 0x62 +#define IPMI_KCS_CONTROL_CODE_READ 0x68 + +/// +/// Status Codes +/// +#define IPMI_KCS_STATUS_NO_ERROR 0x00 +#define IPMI_KCS_STATUS_ABORT 0x01 +#define IPMI_KCS_STATUS_ILLEGAL 0x02 +#define IPMI_KCS_STATUS_LENGTH_ERROR 0x06 +#define IPMI_KCS_STATUS_UNSPECIFIED 0xFF + +/// +/// KCS Interface State Bit +/// +typedef enum { + IpmiKcsIdleState = 0, + IpmiKcsReadState, + IpmiKcsWriteState, + IpmiKcsErrorState +} IPMI_KCS_STATE; + +/// +/// IPMI KCS Interface Request Format +/// +typedef struct { + UINT8 NetFunc; + UINT8 Command; + UINT8 Data[]; +} IPMI_KCS_REQUEST_HEADER; + +/// +/// IPMI KCS Interface Response Format +/// +typedef struct { + UINT8 NetFunc; + UINT8 Command; +} IPMI_KCS_RESPONSE_HEADER; +#endif diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 2d643bede1..5cf04bc0cb 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -9,6 +9,7 @@ # (C) Copyright 2016 - 2021 Hewlett Packard Enterprise Development LP
# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights reserved.
# Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.
+# Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -2342,6 +2343,11 @@ # @Prompt Memory Address of GuidedExtractHandler Table. gEfiMdePkgTokenSpaceGuid.PcdGuidedExtractHandlerTableAddress|0x1000000|UINT64|0x30001015 + ## This value is the IPMI KCS Interface I/O base address used to transmit IPMI commands. + # The value of 0xca2 is the default I/O base address defined in IPMI specification. + # @Prompt IPMI KCS Interface I/O Base Address + gEfiMdePkgTokenSpaceGuid.PcdIpmiKcsIoBaseAddress|0xca2|UINT16|0x00000031 + [PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx] ## This value is used to set the base address of PCI express hierarchy. # @Prompt PCI Express Base Address. From 01046b61eb3e50a3749810cdb43559fc954a8667 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Fri, 24 Mar 2023 14:55:13 +0800 Subject: [PATCH 0720/1529] UefiPayloadPkg: Add gUefiAcpiBoardInfoGuid support if system both exist gUefiAcpiBoardInfoGuid and rsdp, we may need to use gUefiAcpiBoardInfoGuid as final config to have backward support. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Reviewed-by: James Lu Signed-off-by: Gua Guo --- UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c index 46ee27c905..f8939efe70 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c +++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.c @@ -422,9 +422,12 @@ BuildHobs ( // GuidHob = GetFirstGuidHob (&gUniversalPayloadAcpiTableGuid); if (GuidHob != NULL) { - AcpiTable = (UNIVERSAL_PAYLOAD_ACPI_TABLE *)GET_GUID_HOB_DATA (GuidHob); - AcpiBoardInfo = BuildHobFromAcpi ((UINT64)AcpiTable->Rsdp); - ASSERT (AcpiBoardInfo != NULL); + AcpiTable = (UNIVERSAL_PAYLOAD_ACPI_TABLE *)GET_GUID_HOB_DATA (GuidHob); + GuidHob = GetFirstGuidHob (&gUefiAcpiBoardInfoGuid); + if (GuidHob == NULL) { + AcpiBoardInfo = BuildHobFromAcpi ((UINT64)AcpiTable->Rsdp); + ASSERT (AcpiBoardInfo != NULL); + } } // From d8d02bb93d5e512d3b6317bcac6fc0b701a6dd0d Mon Sep 17 00:00:00 2001 From: "Xie, Yuanhao" Date: Tue, 21 Mar 2023 15:29:59 +0800 Subject: [PATCH 0721/1529] UefiCpuPkg: Solve that stack top address is not mapped in pagetable For the case CPU logic index is 0, RSP points to the very top of all AP stacks. That address is not mapped in page table. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Signed-off-by: Ted Kuo Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm | 1 + 1 file changed, 1 insertion(+) diff --git a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm index 9ebe31795b..5bcdf7726b 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm +++ b/UefiCpuPkg/Library/MpInitLib/X64/MpFuncs.nasm @@ -315,6 +315,7 @@ MwaitCheckGeneric: MwaitLoopGeneric: cli mov rax, rsp ; Set Monitor Address + sub eax, 8 ; To ensure the monitor address is in the page table xor ecx, ecx ; ecx = 0 xor edx, edx ; edx = 0 monitor From e5469996bcea102bde7fc80eff0fe757855629db Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 25 Mar 2023 19:41:38 -0700 Subject: [PATCH 0722/1529] PcAtChipsetPkg: Add PCD for RTC default year Add PcdRtcDefaultYear to specify the default year to use when the RTC is in an invalid state. Make sure PcdRtcDefaultYear is >= PcdMinimalValidYear and <= PcdMaximalValidYear. Set the default value for this PCD to PcdMinimalValidYear to preserve the existing behavior. A platform DSC file can override this default value setting. Cc: Ray Ni Signed-off-by: Michael D Kinney Reviewed-by: Ray Ni --- PcAtChipsetPkg/PcAtChipsetPkg.dec | 6 ++++++ PcAtChipsetPkg/PcAtChipsetPkg.uni | 4 ++++ PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c | 4 ++-- .../PcatRealTimeClockRuntimeDxe.inf | 1 + 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/PcAtChipsetPkg/PcAtChipsetPkg.dec b/PcAtChipsetPkg/PcAtChipsetPkg.dec index a53ca777e8..0db385fb90 100644 --- a/PcAtChipsetPkg/PcAtChipsetPkg.dec +++ b/PcAtChipsetPkg/PcAtChipsetPkg.dec @@ -76,6 +76,12 @@ # @Expression 0x80000001 | gPcAtChipsetPkgTokenSpaceGuid.PcdMaximalValidYear < gPcAtChipsetPkgTokenSpaceGuid.PcdMinimalValidYear + 100 gPcAtChipsetPkgTokenSpaceGuid.PcdMaximalValidYear|2097|UINT16|0x0000000E + ## This PCD specifies the RTC default year when the RTC is in an invalid state. + # @Prompt Default year in RTC. + # @Expression 0x80000001 | gPcAtChipsetPkgTokenSpaceGuid.PcdRtcDefaultYear >= gPcAtChipsetPkgTokenSpaceGuid.PcdMinimalValidYear + # @Expression 0x80000001 | gPcAtChipsetPkgTokenSpaceGuid.PcdRtcDefaultYear <= gPcAtChipsetPkgTokenSpaceGuid.PcdMaximalValidYear + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcDefaultYear|gPcAtChipsetPkgTokenSpaceGuid.PcdMinimalValidYear|UINT16|0x0000000F + ## Specifies RTC Index Register address in MMIO space. # @Prompt RTC Index Register address gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister64|0x0|UINT64|0x00000022 diff --git a/PcAtChipsetPkg/PcAtChipsetPkg.uni b/PcAtChipsetPkg/PcAtChipsetPkg.uni index d290dcf165..8eb7970c58 100644 --- a/PcAtChipsetPkg/PcAtChipsetPkg.uni +++ b/PcAtChipsetPkg/PcAtChipsetPkg.uni @@ -79,6 +79,10 @@ #string STR_gPcAtChipsetPkgTokenSpaceGuid_PcdMaximalValidYear_HELP #language en-US "This PCD specifies the maximal valid year in RTC." +#string STR_gPcAtChipsetPkgTokenSpaceGuid_PcdRtcDefaultYear_PROMPT #language en-US "Default year in RTC" + +#string STR_gPcAtChipsetPkgTokenSpaceGuid_PcdRtcDefaultYear_HELP #language en-US "This PCD specifies the RTC default year when the RTC is in an invalid state." + #string STR_gPcAtChipsetPkgTokenSpaceGuid_PcdAcpiIoPortBaseAddressMask_PROMPT #language en-US "ACPI IO Port Base Address Mask" #string STR_gPcAtChipsetPkgTokenSpaceGuid_PcdAcpiIoPortBaseAddressMask_HELP #language en-US "Defines the bit mask to retrieve ACPI IO Port Base Address." diff --git a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c index 9242a2e826..b059e92f02 100644 --- a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c +++ b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c @@ -317,7 +317,7 @@ PcRtcInit ( Time.Hour = RTC_INIT_HOUR; Time.Day = RTC_INIT_DAY; Time.Month = RTC_INIT_MONTH; - Time.Year = PcdGet16 (PcdMinimalValidYear); + Time.Year = PcdGet16 (PcdRtcDefaultYear); Time.Nanosecond = 0; Time.TimeZone = EFI_UNSPECIFIED_TIMEZONE; Time.Daylight = 0; @@ -357,7 +357,7 @@ PcRtcInit ( Time.Hour = RTC_INIT_HOUR; Time.Day = RTC_INIT_DAY; Time.Month = RTC_INIT_MONTH; - Time.Year = PcdGet16 (PcdMinimalValidYear); + Time.Year = PcdGet16 (PcdRtcDefaultYear); Time.Nanosecond = 0; Time.TimeZone = Global->SavedTimeZone; Time.Daylight = Global->Daylight; diff --git a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf index 0d8eca28b6..c344b05987 100644 --- a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf +++ b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf @@ -76,6 +76,7 @@ gPcAtChipsetPkgTokenSpaceGuid.PcdRealTimeClockUpdateTimeout ## CONSUMES gPcAtChipsetPkgTokenSpaceGuid.PcdMinimalValidYear ## CONSUMES gPcAtChipsetPkgTokenSpaceGuid.PcdMaximalValidYear ## CONSUMES + gPcAtChipsetPkgTokenSpaceGuid.PcdRtcDefaultYear ## CONSUMES gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister ## CONSUMES gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister ## CONSUMES gPcAtChipsetPkgTokenSpaceGuid.PcdRtcIndexRegister64 ## CONSUMES From 846e7e24554541ed0cd75982f0bfcfbb81981352 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 3 Mar 2023 15:39:41 +0800 Subject: [PATCH 0723/1529] UefiCpuPkg/CpuPageTableLib: Remove unneeded 'if' condition Remove unneeded 'if' condition in CpuPageTableLib code. The deleted code is in the code branch for present non-leaf parent entry. So the 'if' check for (ParentPagingEntry->Pnle.Bits.Present == 0) is always FALSE. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 37713ec659..52535e5a8d 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -1,7 +1,7 @@ /** @file This library implements CpuPageTableLib that are generic for IA32 family CPU. - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -375,15 +375,6 @@ PageTableLibMapInLevel ( // we need to change PDPTE[0].ReadWrite = 1 and let all PDE[0-255].ReadWrite = 0 in this step. // when PDPTE[0].Nx = 1 but caller wants to map [0-2MB] as Nx = 0 (PDT[0].Nx = 0) // we need to change PDPTE[0].Nx = 0 and let all PDE[0-255].Nx = 1 in this step. - if ((ParentPagingEntry->Pnle.Bits.Present == 0) && (Mask->Bits.Present == 1) && (Attribute->Bits.Present == 1)) { - if (Modify) { - ParentPagingEntry->Pnle.Bits.Present = 1; - } - - ChildAttribute.Bits.Present = 0; - ChildMask.Bits.Present = 1; - } - if ((ParentPagingEntry->Pnle.Bits.ReadWrite == 0) && (Mask->Bits.ReadWrite == 1) && (Attribute->Bits.ReadWrite == 1)) { if (Modify) { ParentPagingEntry->Pnle.Bits.ReadWrite = 1; From 86d6fbeff2bda4fdc4b3bad1666b57a5e62c4ca1 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 7 Mar 2023 11:51:32 +0800 Subject: [PATCH 0724/1529] UefiCpuPkg/CpuPageTableLib: Add check for input Length Add check for input Length in PageTableMap (). Return RETURN_SUCCESS when input Length is 0. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Include/Library/CpuPageTableLib.h | 4 ++-- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/UefiCpuPkg/Include/Library/CpuPageTableLib.h b/UefiCpuPkg/Include/Library/CpuPageTableLib.h index 2dc9b7d18e..5f44ece548 100644 --- a/UefiCpuPkg/Include/Library/CpuPageTableLib.h +++ b/UefiCpuPkg/Include/Library/CpuPageTableLib.h @@ -1,7 +1,7 @@ /** @file Public include file for PageTableLib library. - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -81,7 +81,7 @@ typedef enum { @retval RETURN_BUFFER_TOO_SMALL The buffer is too small for page table creation/updating. BufferSize is updated to indicate the expected buffer size. Caller may still get RETURN_BUFFER_TOO_SMALL with the new BufferSize. - @retval RETURN_SUCCESS PageTable is created/updated successfully. + @retval RETURN_SUCCESS PageTable is created/updated successfully or the input Length is 0. **/ RETURN_STATUS EFIAPI diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 52535e5a8d..218068a3e1 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -544,7 +544,7 @@ PageTableLibMapInLevel ( @retval RETURN_BUFFER_TOO_SMALL The buffer is too small for page table creation/updating. BufferSize is updated to indicate the expected buffer size. Caller may still get RETURN_BUFFER_TOO_SMALL with the new BufferSize. - @retval RETURN_SUCCESS PageTable is created/updated successfully. + @retval RETURN_SUCCESS PageTable is created/updated successfully or the input Length is 0. **/ RETURN_STATUS EFIAPI @@ -567,6 +567,10 @@ PageTableMap ( IA32_PAGE_LEVEL MaxLeafLevel; IA32_MAP_ATTRIBUTE ParentAttribute; + if (Length == 0) { + return RETURN_SUCCESS; + } + if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. From 20f8748c1dcbb697623c378fe18743741b30a2b4 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 16 Mar 2023 10:30:53 +0800 Subject: [PATCH 0725/1529] UefiCpuPkg/CpuPageTableLib:Initialize some LocalVariable at beginning Move some local variable initialization to the beginning of the function. Also delete duplicated calculation for RegionLength. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../Library/CpuPageTableLib/CpuPageTableMap.c | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 218068a3e1..127b65183f 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -258,6 +258,7 @@ PageTableLibMapInLevel ( UINTN BitStart; UINTN Index; IA32_PAGING_ENTRY *PagingEntry; + UINTN PagingEntryIndex; IA32_PAGING_ENTRY *CurrentPagingEntry; UINT64 RegionLength; UINT64 SubLength; @@ -288,6 +289,14 @@ PageTableLibMapInLevel ( LocalParentAttribute.Uint64 = ParentAttribute->Uint64; ParentAttribute = &LocalParentAttribute; + // + // RegionLength: 256T (1 << 48) 512G (1 << 39), 1G (1 << 30), 2M (1 << 21) or 4K (1 << 12). + // + BitStart = 12 + (Level - 1) * 9; + PagingEntryIndex = (UINTN)BitFieldRead64 (LinearAddress + Offset, BitStart, BitStart + 9 - 1); + RegionLength = REGION_LENGTH (Level); + RegionMask = RegionLength - 1; + // // ParentPagingEntry ONLY is deferenced for checking Present and MustBeOne bits // when Modify is FALSE. @@ -353,8 +362,7 @@ PageTableLibMapInLevel ( // PageTableLibSetPnle (&ParentPagingEntry->Pnle, &NopAttribute, &AllOneMask); - RegionLength = REGION_LENGTH (Level); - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&ParentPagingEntry->Pnle); + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&ParentPagingEntry->Pnle); for (SubOffset = 0, Index = 0; Index < 512; Index++) { PagingEntry[Index].Uint64 = OneOfPagingEntry.Uint64 + SubOffset; SubOffset += RegionLength; @@ -425,15 +433,10 @@ PageTableLibMapInLevel ( } // - // RegionLength: 256T (1 << 48) 512G (1 << 39), 1G (1 << 30), 2M (1 << 21) or 4K (1 << 12). // RegionStart: points to the linear address that's aligned on RegionLength and lower than (LinearAddress + Offset). // - BitStart = 12 + (Level - 1) * 9; - Index = (UINTN)BitFieldRead64 (LinearAddress + Offset, BitStart, BitStart + 9 - 1); - RegionLength = LShiftU64 (1, BitStart); - RegionMask = RegionLength - 1; - RegionStart = (LinearAddress + Offset) & ~RegionMask; - + Index = PagingEntryIndex; + RegionStart = (LinearAddress + Offset) & ~RegionMask; ParentAttribute->Uint64 = PageTableLibGetPnleMapAttribute (&ParentPagingEntry->Pnle, ParentAttribute); // From fa5e02c2129fef8132e49f17ca7ac1ad628501c4 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 16 Mar 2023 10:34:40 +0800 Subject: [PATCH 0726/1529] UefiCpuPkg/CpuPageTableLib: Fix the non-1:1 mapping issue In previous code logic, when splitting a leaf parent entry to smaller granularity child page table, if the parent entry Attribute&Mask(without PageTableBaseAddress field) is equal to the input attribute&mask(without PageTableBaseAddress field), the split process won't happen. This may lead to failure in non-1:1 mapping. For example, there is a page table in which [0, 1G] is mapped(Lv4[0] ,Lv3[0,0], a non-leaf level4 entry and a leaf level3 entry). And we want to remap [0, 2M] linear address range to [1G, 1G + 2M] with the same attibute. The expected behaviour should be: split Lv3[0,0] entry into 512 level2 entries and remap the first level2 entry to cover [0, 2M]. But the split won't happen in previous code since PageTableBaseAddress of input Attribute is not checked. So, when checking if a leaf parent entry needs to be splitted, we should also check if PageTableBaseAddress calculated by parent entry is equal to the value caculated by input attribute. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 127b65183f..b94ef07c56 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -274,6 +274,8 @@ PageTableLibMapInLevel ( IA32_MAP_ATTRIBUTE ChildMask; IA32_MAP_ATTRIBUTE CurrentMask; IA32_MAP_ATTRIBUTE LocalParentAttribute; + UINT64 PhysicalAddrInEntry; + UINT64 PhysicalAddrInAttr; ASSERT (Level != 0); ASSERT ((Attribute != NULL) && (Mask != NULL)); @@ -341,7 +343,15 @@ PageTableLibMapInLevel ( // This function is called when the memory length is less than the region length of the parent level. // No need to split the page when the attributes equal. // - return RETURN_SUCCESS; + if (Mask->Bits.PageTableBaseAddress == 0) { + return RETURN_SUCCESS; + } + + PhysicalAddrInEntry = IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&PleBAttribute) + MultU64x32 (RegionLength, (UINT32)PagingEntryIndex); + PhysicalAddrInAttr = (IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (Attribute) + Offset) & (~RegionMask); + if (PhysicalAddrInEntry == PhysicalAddrInAttr) { + return RETURN_SUCCESS; + } } ASSERT (Buffer == NULL || *BufferSize >= SIZE_4KB); From 9f478cfa18db5d3861d125cdaad51809cbd9756e Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Mon, 20 Mar 2023 09:40:01 +0800 Subject: [PATCH 0727/1529] UefiCpuPkg/CpuPageTableLib:Clear PageSize bit(Bit7) for non-leaf Clear PageSize bit(Bit7) for non-leaf entry in PageTableLibSetPnle. This function is used to set non-leaf entry attributes so it should make sure that the PageSize bit of the entry should be 0. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index b94ef07c56..57f1db203b 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -202,7 +202,8 @@ PageTableLibSetPnle ( Pnle->Bits.Nx = Attribute->Bits.Nx; } - Pnle->Bits.Accessed = 0; + Pnle->Bits.Accessed = 0; + Pnle->Bits.MustBeZero = 0; // // Set the attributes (WT, CD, A) to 0. From 763ad32b4096571976b51de636ef7e5716bbc88c Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 9 Dec 2022 10:34:43 +0800 Subject: [PATCH 0728/1529] UefiCpuPkg/CpuPageTableLib: Fix issue when splitting leaf entry When splitting leaf parent entry to smaller granularity, create child page table before modifing parent entry. In previous code logic, when splitting a leaf parent entry, parent entry will point to a null 4k memory before child page table is created in this 4k memory. When the page table to be modified is the page table in CR3, if the executed CpuPageTableLib code is in the range mapped by the modified leaf parent entry, then issue will happen. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../Library/CpuPageTableLib/CpuPageTableMap.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 57f1db203b..f09bb63ad1 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -363,21 +363,24 @@ PageTableLibMapInLevel ( // // Create 512 child-level entries that map to 2M/4K. // - ParentPagingEntry->Uintn = (UINTN)Buffer + *BufferSize; - ZeroMem ((VOID *)ParentPagingEntry->Uintn, SIZE_4KB); + PagingEntry = (IA32_PAGING_ENTRY *)((UINTN)Buffer + *BufferSize); + ZeroMem (PagingEntry, SIZE_4KB); + + for (SubOffset = 0, Index = 0; Index < 512; Index++) { + PagingEntry[Index].Uint64 = OneOfPagingEntry.Uint64 + SubOffset; + SubOffset += RegionLength; + } // // Set NOP attributes // Note: Should NOT inherit the attributes from the original entry because a zero RW bit // will make the entire region read-only even the child entries set the RW bit. // + // Non-leaf entry doesn't have PAT bit. So use ~IA32_PE_BASE_ADDRESS_MASK_40 is to make sure PAT bit + // (bit12) in original big-leaf entry is not assigned to PageTableBaseAddress field of non-leaf entry. + // PageTableLibSetPnle (&ParentPagingEntry->Pnle, &NopAttribute, &AllOneMask); - - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&ParentPagingEntry->Pnle); - for (SubOffset = 0, Index = 0; Index < 512; Index++) { - PagingEntry[Index].Uint64 = OneOfPagingEntry.Uint64 + SubOffset; - SubOffset += RegionLength; - } + ParentPagingEntry->Uint64 = ((UINTN)(VOID *)PagingEntry) | (ParentPagingEntry->Uint64 & (~IA32_PE_BASE_ADDRESS_MASK_40)); } } else { // From 8f49a524d5cbd0b7471f0bd415119612a78e4988 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 17 Mar 2023 15:43:26 +0800 Subject: [PATCH 0729/1529] UefiCpuPkg/MpInitLib: Add code to initialize MapMask In function CreatePageTable(), add code to initialize MapMask to MAX_UINT64. When creating new page table or map non-present range to present, all attributes should be provided. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c index 7cf91ed9c4..f20068152b 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c @@ -36,10 +36,7 @@ CreatePageTable ( MapAttribute.Uint64 = Address; MapAttribute.Bits.Present = 1; MapAttribute.Bits.ReadWrite = 1; - - MapMask.Bits.PageTableBaseAddress = 1; - MapMask.Bits.Present = 1; - MapMask.Bits.ReadWrite = 1; + MapMask.Uint64 = MAX_UINT64; PageTable = 0; PageTableBufferSize = 0; From 1f7cedd2d2f600c694fb383b2231e13eac486c7f Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 Feb 2023 15:05:08 +0800 Subject: [PATCH 0730/1529] UefiCpuPkg/CpuPageTableLib:Add check for Mask and Attr For different usage, check if the combination for Mask and Attr is valid when creating or updating page table. 1.For non-present range 1.1Mask.Present is 0 but some other attributes is provided. This case is invalid. 1.2Mask.Present is 1 and Attr.Present is 0. In this case,all other attributes should not be provided. 1.3Mask.Present is 1 and Attr.Present is 1. In this case,all attributes should be provided to intialize the attribute. 2.For present range 2.1Mask.Present is 1 and Attr.Present is 0.In this case, all other attributes should not be provided. All other usage for present range is permitted. In the mentioned cases, 1.2 and 2.1 can be merged into 1 check. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Include/Library/CpuPageTableLib.h | 4 + .../Library/CpuPageTableLib/CpuPageTableMap.c | 83 ++++++++++++++++++- 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Include/Library/CpuPageTableLib.h b/UefiCpuPkg/Include/Library/CpuPageTableLib.h index 5f44ece548..4ef4a8b6af 100644 --- a/UefiCpuPkg/Include/Library/CpuPageTableLib.h +++ b/UefiCpuPkg/Include/Library/CpuPageTableLib.h @@ -77,6 +77,10 @@ typedef enum { @retval RETURN_UNSUPPORTED PagingMode is not supported. @retval RETURN_INVALID_PARAMETER PageTable, BufferSize, Attribute or Mask is NULL. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 1 but some other attributes are not provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 0 but some other attributes are provided. @retval RETURN_INVALID_PARAMETER *BufferSize is not multiple of 4KB. @retval RETURN_BUFFER_TOO_SMALL The buffer is too small for page table creation/updating. BufferSize is updated to indicate the expected buffer size. diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index f09bb63ad1..76c3719cdf 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -215,6 +215,44 @@ PageTableLibSetPnle ( Pnle->Bits.CacheDisabled = 0; } +/** + Check if the combination for Attribute and Mask is valid for non-present entry. + 1.Mask.Present is 0 but some other attributes is provided. This case should be invalid. + 2.Map non-present range to present. In this case, all attributes should be provided. + + @param[in] Attribute The attribute of the linear address range. + @param[in] Mask The mask used for attribute to check. + + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 1 but some other attributes are not provided. + @retval RETURN_SUCCESS The combination for Attribute and Mask is valid. +**/ +RETURN_STATUS +IsAttributesAndMaskValidForNonPresentEntry ( + IN IA32_MAP_ATTRIBUTE *Attribute, + IN IA32_MAP_ATTRIBUTE *Mask + ) +{ + if ((Mask->Bits.Present == 1) && (Attribute->Bits.Present == 1)) { + // + // Creating new page table or remapping non-present range to present. + // + if ((Mask->Bits.ReadWrite == 0) || (Mask->Bits.UserSupervisor == 0) || (Mask->Bits.WriteThrough == 0) || (Mask->Bits.CacheDisabled == 0) || + (Mask->Bits.Accessed == 0) || (Mask->Bits.Dirty == 0) || (Mask->Bits.Pat == 0) || (Mask->Bits.Global == 0) || + (Mask->Bits.PageTableBaseAddress == 0) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) + { + return RETURN_INVALID_PARAMETER; + } + } else if ((Mask->Bits.Present == 0) && (Mask->Uint64 > 1)) { + // + // Only change other attributes for non-present range is not permitted. + // + return RETURN_INVALID_PARAMETER; + } + + return RETURN_SUCCESS; +} + /** Update page table to map [LinearAddress, LinearAddress + Length) with specified attribute in the specified level. @@ -237,6 +275,8 @@ PageTableLibSetPnle ( when a new physical base address is set. @param[in] Mask The mask used for attribute. The corresponding field in Attribute is ignored if that in Mask is 0. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 1 but some other attributes are not provided. @retval RETURN_SUCCESS PageTable is created/updated successfully. **/ RETURN_STATUS @@ -260,6 +300,7 @@ PageTableLibMapInLevel ( UINTN Index; IA32_PAGING_ENTRY *PagingEntry; UINTN PagingEntryIndex; + UINTN PagingEntryIndexEnd; IA32_PAGING_ENTRY *CurrentPagingEntry; UINT64 RegionLength; UINT64 SubLength; @@ -306,6 +347,14 @@ PageTableLibMapInLevel ( // if (ParentPagingEntry->Pce.Present == 0) { + // + // [LinearAddress, LinearAddress + Length] contains non-present range. + // + Status = IsAttributesAndMaskValidForNonPresentEntry (Attribute, Mask); + if (RETURN_ERROR (Status)) { + return Status; + } + // // The parent entry is CR3 or PML5E/PML4E/PDPTE/PDE. // It does NOT point to an existing page directory. @@ -383,6 +432,27 @@ PageTableLibMapInLevel ( ParentPagingEntry->Uint64 = ((UINTN)(VOID *)PagingEntry) | (ParentPagingEntry->Uint64 & (~IA32_PE_BASE_ADDRESS_MASK_40)); } } else { + // + // If (LinearAddress + Length - 1) is not in the same ParentPagingEntry with (LinearAddress + Offset), then the remaining child PagingEntry + // starting from PagingEntryIndex of ParentPagingEntry is all covered by [LinearAddress + Offset, LinearAddress + Length - 1]. + // + PagingEntryIndexEnd = (BitFieldRead64 (LinearAddress + Length - 1, BitStart + 9, 63) != BitFieldRead64 (LinearAddress + Offset, BitStart + 9, 63)) ? 511 : + (UINTN)BitFieldRead64 (LinearAddress + Length - 1, BitStart, BitStart + 9 - 1); + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&ParentPagingEntry->Pnle); + for (Index = PagingEntryIndex; Index <= PagingEntryIndexEnd; Index++) { + if (PagingEntry[Index].Pce.Present == 0) { + // + // [LinearAddress, LinearAddress + Length] contains non-present range. + // + Status = IsAttributesAndMaskValidForNonPresentEntry (Attribute, Mask); + if (RETURN_ERROR (Status)) { + return Status; + } + + break; + } + } + // // It's a non-leaf entry // @@ -430,7 +500,6 @@ PageTableLibMapInLevel ( // Update child entries to use restrictive attribute inherited from parent. // e.g.: Set PDE[0-255].ReadWrite = 0 // - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&ParentPagingEntry->Pnle); for (Index = 0; Index < 512; Index++) { if (PagingEntry[Index].Pce.Present == 0) { continue; @@ -557,6 +626,10 @@ PageTableLibMapInLevel ( @retval RETURN_UNSUPPORTED PagingMode is not supported. @retval RETURN_INVALID_PARAMETER PageTable, BufferSize, Attribute or Mask is NULL. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 1 but some other attributes are not provided. + @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 0 but some other attributes are provided. + @retval RETURN_INVALID_PARAMETER For present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 0 but some other attributes are provided. @retval RETURN_INVALID_PARAMETER *BufferSize is not multiple of 4KB. @retval RETURN_BUFFER_TOO_SMALL The buffer is too small for page table creation/updating. BufferSize is updated to indicate the expected buffer size. @@ -618,6 +691,14 @@ PageTableMap ( return RETURN_INVALID_PARAMETER; } + // + // If to map [LinearAddress, LinearAddress + Length] as non-present, + // all attributes except Present should not be provided. + // + if ((Attribute->Bits.Present == 0) && (Mask->Bits.Present == 1) && (Mask->Uint64 > 1)) { + return RETURN_INVALID_PARAMETER; + } + MaxLeafLevel = (IA32_PAGE_LEVEL)(UINT8)PagingMode; MaxLevel = (IA32_PAGE_LEVEL)(UINT8)(PagingMode >> 8); MaxLinearAddress = LShiftU64 (1, 12 + MaxLevel * 9); From 67cfbc3bbc65ff3966b86022146f36e996a46ac3 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 Feb 2023 15:25:09 +0800 Subject: [PATCH 0731/1529] UefiCpuPkg/CpuPageTableLib: Add manual test to check Mask and Attr Add manual test case to check input Mask and Attribute. The check steps are: 1.Create Page table to cover [0, 2G]. All fields of MapMask should be set. 2.Update Page table to set [2G - 8K,2G] from present to non-present. All fields of MapMask except present should not be set. 3.Still set [2G - 8K, 2G] as not present, this case is permitted. But set [2G - 8K, 2G] as RW is not permitted. 4.Update Page table to set [2G - 8K, 2G] as present and RW. All fields of MapMask should be set. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 129 +++++++++++++++++- 1 file changed, 127 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index 3014a03243..52fae1864a 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -1,7 +1,7 @@ /** @file Unit tests of the CpuPageTableLib instance of the CpuPageTableLib class - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -697,6 +697,131 @@ TestCaseManualChangeNx ( return UNIT_TEST_PASSED; } +/** + Check if the input Mask and Attribute is as expected when creating new page table or + updating existing page table. + + @param[in] Context [Optional] An optional parameter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +TestCaseToCheckMapMaskAndAttr ( + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN PageTable; + PAGING_MODE PagingMode; + VOID *Buffer; + UINTN PageTableBufferSize; + IA32_MAP_ATTRIBUTE MapAttribute; + IA32_MAP_ATTRIBUTE ExpectedMapAttribute; + IA32_MAP_ATTRIBUTE MapMask; + RETURN_STATUS Status; + IA32_MAP_ENTRY *Map; + UINTN MapCount; + + PagingMode = Paging4Level; + PageTableBufferSize = 0; + PageTable = 0; + Buffer = NULL; + MapAttribute.Uint64 = 0; + MapAttribute.Bits.Present = 1; + MapMask.Uint64 = 0; + MapMask.Bits.Present = 1; + // + // Create Page table to cover [0, 2G]. All fields of MapMask should be set. + // + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + MapMask.Uint64 = MAX_UINT64; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); + Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); + + // + // Update Page table to set [2G - 8K, 2G] from present to non-present. All fields of MapMask except present should not be set. + // + PageTableBufferSize = 0; + MapAttribute.Uint64 = SIZE_2GB - SIZE_8KB; + MapMask.Uint64 = 0; + MapMask.Bits.Present = 1; + MapMask.Bits.ReadWrite = 1; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + MapMask.Bits.ReadWrite = 0; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); + Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); + + // + // Still set [2G - 8K, 2G] as not present, this case is permitted. But set [2G - 8K, 2G] as RW is not permitted. + // + PageTableBufferSize = 0; + MapAttribute.Uint64 = 0; + MapMask.Uint64 = 0; + MapMask.Bits.Present = 1; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); + MapAttribute.Bits.ReadWrite = 1; + MapMask.Bits.ReadWrite = 1; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + + // + // Update Page table to set [2G - 8K, 2G] as present and RW. All fields of MapMask should be set. + // + PageTableBufferSize = 0; + MapAttribute.Uint64 = SIZE_2GB - SIZE_8KB; + MapAttribute.Bits.ReadWrite = 1; + MapAttribute.Bits.Present = 1; + MapMask.Uint64 = 0; + MapMask.Bits.ReadWrite = 1; + MapMask.Bits.Present = 1; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + MapMask.Uint64 = MAX_UINT64; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); + + MapCount = 0; + Status = PageTableParse (PageTable, PagingMode, NULL, &MapCount); + UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); + Map = AllocatePages (EFI_SIZE_TO_PAGES (MapCount* sizeof (IA32_MAP_ENTRY))); + Status = PageTableParse (PageTable, PagingMode, Map, &MapCount); + UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); + + // + // There should be two ranges [0, 2G-8k] with RW = 0 and [2G-8k, 2G] with RW = 1 + // + UT_ASSERT_EQUAL (MapCount, 2); + UT_ASSERT_EQUAL (Map[0].LinearAddress, 0); + UT_ASSERT_EQUAL (Map[0].Length, SIZE_2GB - SIZE_8KB); + ExpectedMapAttribute.Uint64 = 0; + ExpectedMapAttribute.Bits.Present = 1; + UT_ASSERT_EQUAL (Map[0].Attribute.Uint64, ExpectedMapAttribute.Uint64); + UT_ASSERT_EQUAL (Map[1].LinearAddress, SIZE_2GB - SIZE_8KB); + UT_ASSERT_EQUAL (Map[1].Length, SIZE_8KB); + ExpectedMapAttribute.Uint64 = SIZE_2GB - SIZE_8KB; + ExpectedMapAttribute.Bits.Present = 1; + ExpectedMapAttribute.Bits.ReadWrite = 1; + UT_ASSERT_EQUAL (Map[1].Attribute.Uint64, ExpectedMapAttribute.Uint64); + return UNIT_TEST_PASSED; +} + /** Initialize the unit test framework, suite, and unit tests for the sample unit tests and run the unit tests. @@ -746,7 +871,7 @@ UefiTestMain ( AddTestCase (ManualTestCase, "Check if the parent entry has different ReadWrite attribute", "Manual Test Case5", TestCaseManualChangeReadWrite, NULL, NULL, NULL); AddTestCase (ManualTestCase, "Check if the parent entry has different Nx attribute", "Manual Test Case6", TestCaseManualChangeNx, NULL, NULL, NULL); AddTestCase (ManualTestCase, "Check if the needed size is expected", "Manual Test Case7", TestCaseManualSizeNotMatch, NULL, NULL, NULL); - + AddTestCase (ManualTestCase, "Check MapMask when creating new page table or mapping not-present range", "Manual Test Case8", TestCaseToCheckMapMaskAndAttr, NULL, NULL, NULL); // // Populate the Random Test Cases. // From 2db77ff3d368729c3f7407b01e6f32f57794c9fd Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 17 Mar 2023 12:09:50 +0800 Subject: [PATCH 0732/1529] UefiCpuPkg/CpuPageTableLib:Modify RandomBoolean() in RandomTest Add an input parameter to control the probability of returning true. Change RandomBoolean() in RandomTest from 50% chance returning true to returning true with the percentage of input Probability. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../CpuPageTableLib/UnitTest/RandomTest.c | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index 97a388ca1c..52eb9daa10 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -1,7 +1,7 @@ /** @file Random test case for Unit tests of the CpuPageTableLib instance of the CpuPageTableLib class - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -81,22 +81,6 @@ LocalRandomBytes ( } } -/** - Return a random boolean. - - @return boolean -**/ -BOOLEAN -RandomBoolean ( - VOID - ) -{ - BOOLEAN Value; - - LocalRandomBytes ((UINT8 *)&Value, sizeof (BOOLEAN)); - return Value%2; -} - /** Return a 32bit random number. @@ -139,6 +123,21 @@ Random64 ( return (UINT64)(Value % (Limit - Start + 1)) + Start; } +/** + Returns true with the percentage of input Probability. + + @param[in] Probability The percentage to return true. + + @return boolean +**/ +BOOLEAN +RandomBoolean ( + UINT8 Probability + ) +{ + return ((Probability > ((UINT8)Random64 (0, 100))) ? TRUE : FALSE); +} + /** Check if the Page table entry is valid @@ -178,7 +177,7 @@ ValidateAndRandomeModifyPageTablePageTableEntry ( UT_ASSERT_EQUAL ((PagingEntry->Uint64 & mValidMaskLeaf[Level].Uint64), PagingEntry->Uint64); } - if ((RandomNumber < 100) && RandomBoolean ()) { + if ((RandomNumber < 100) && RandomBoolean (50)) { RandomNumber++; if (Level == 1) { TempPhysicalBase = PagingEntry->Pte4K.Bits.PageTableBaseAddress; @@ -211,7 +210,7 @@ ValidateAndRandomeModifyPageTablePageTableEntry ( UT_ASSERT_EQUAL ((PagingEntry->Uint64 & mValidMaskNoLeaf[Level].Uint64), PagingEntry->Uint64); } - if ((RandomNumber < 100) && RandomBoolean ()) { + if ((RandomNumber < 100) && RandomBoolean (50)) { RandomNumber++; TempPhysicalBase = PagingEntry->Pnle.Bits.PageTableBaseAddress; @@ -299,7 +298,7 @@ GenerateSingleRandomMapEntry ( // // use AlignedTable to avoid that a random number can be very hard to be 1G or 2M aligned // - if ((MapsIndex != 0) && (RandomBoolean ())) { + if ((MapsIndex != 0) && (RandomBoolean (50))) { FormerLinearAddress = MapEntrys->Maps[Random32 (0, (UINT32)MapsIndex-1)].LinearAddress; if (FormerLinearAddress < 2 * (UINT64)SIZE_1GB) { FormerLinearAddressBottom = 0; @@ -323,7 +322,7 @@ GenerateSingleRandomMapEntry ( // MapEntrys->Maps[MapsIndex].Length = Random64 (0, MIN (MaxAddress - MapEntrys->Maps[MapsIndex].LinearAddress, 10 * (UINT64)SIZE_1GB)) & AlignedTable[Random32 (0, ARRAY_SIZE (AlignedTable) -1)]; - if ((MapsIndex != 0) && (RandomBoolean ())) { + if ((MapsIndex != 0) && (RandomBoolean (50))) { MapEntrys->Maps[MapsIndex].Attribute.Uint64 = MapEntrys->Maps[Random32 (0, (UINT32)MapsIndex-1)].Attribute.Uint64; MapEntrys->Maps[MapsIndex].Mask.Uint64 = MapEntrys->Maps[Random32 (0, (UINT32)MapsIndex-1)].Mask.Uint64; } else { @@ -344,7 +343,7 @@ GenerateSingleRandomMapEntry ( // Need to avoid such case when remove the Random option ONLY_ONE_ONE_MAPPING // MapEntrys->Maps[MapsIndex].Attribute.Bits.PageTableBaseAddress = (Random64 (0, (((UINT64)1)<<52) - 1) & AlignedTable[Random32 (0, ARRAY_SIZE (AlignedTable) -1)])>> 12; - if (RandomBoolean ()) { + if (RandomBoolean (50)) { MapEntrys->Maps[MapsIndex].Mask.Bits.PageTableBaseAddress = 0; } } From ed9a979f3541173d42b0bb009cbb76cb823ceacb Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 Mar 2023 12:12:44 +0800 Subject: [PATCH 0733/1529] UefiCpuPkg/CpuPageTableLib: Add LastMapEntry pointer Add LastMapEntry pointer to replace MapEntrys->Maps[MapsIndex] in SingleMapEntryTest () of RandomTest. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann --- .../CpuPageTableLib/UnitTest/RandomTest.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index 52eb9daa10..612fddcee0 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -621,10 +621,12 @@ SingleMapEntryTest ( UINTN Level; UINT64 Value; UNIT_TEST_STATUS TestStatus; + MAP_ENTRY *LastMapEntry; MapsIndex = MapEntrys->Count; GenerateSingleRandomMapEntry (MaxAddress, MapEntrys); + LastMapEntry = &MapEntrys->Maps[MapsIndex]; PageTableBufferSize = 0; Status = PageTableMap ( @@ -632,10 +634,10 @@ SingleMapEntryTest ( PagingMode, NULL, &PageTableBufferSize, - MapEntrys->Maps[MapsIndex].LinearAddress, - MapEntrys->Maps[MapsIndex].Length, - &MapEntrys->Maps[MapsIndex].Attribute, - &MapEntrys->Maps[MapsIndex].Mask + LastMapEntry->LinearAddress, + LastMapEntry->Length, + &LastMapEntry->Attribute, + &LastMapEntry->Mask ); if (PageTableBufferSize != 0) { UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); @@ -651,10 +653,10 @@ SingleMapEntryTest ( PagingMode, Buffer, &PageTableBufferSize, - MapEntrys->Maps[MapsIndex].LinearAddress, - MapEntrys->Maps[MapsIndex].Length, - &MapEntrys->Maps[MapsIndex].Attribute, - &MapEntrys->Maps[MapsIndex].Mask + LastMapEntry->LinearAddress, + LastMapEntry->Length, + &LastMapEntry->Attribute, + &LastMapEntry->Mask ); } From 356d77ce0e2879602160e50120f81cd4072d0c8e Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 17 Mar 2023 15:06:48 +0800 Subject: [PATCH 0734/1529] UefiCpuPkg/CpuPageTableLib:Modify RandomTest to check Mask/Attr Modify RandomTest to check invalid input. When creating new page table or updating exsiting page table: 1.If set [LinearAddress, LinearAddress+Length] to non-present, all other attributes should not be provided. 2.If [LinearAddress, LinearAddress+Length] contain non-present range, the Returnstatus of PageTableMap() should be InvalidParameter when: 2.1Some of attributes are not provided when mapping non-present range to present. 2.2Set any other attribute without setting the non-present range to Present. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann Cc: Zhiguang Liu --- .../CpuPageTableLib/UnitTest/RandomTest.c | 153 +++++++++++++++--- .../CpuPageTableLib/UnitTest/TestHelper.c | 6 +- 2 files changed, 133 insertions(+), 26 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index 612fddcee0..121cc4f2b2 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -273,6 +273,27 @@ ValidateAndRandomeModifyPageTable ( return Status; } +/** + Remove the last MAP_ENTRY in MapEntrys. + + @param MapEntrys Pointer to MapEntrys buffer +**/ +VOID +RemoveLastMapEntry ( + IN OUT MAP_ENTRYS *MapEntrys + ) +{ + UINTN MapsIndex; + + if (MapEntrys->Count == 0) { + return; + } + + MapsIndex = MapEntrys->Count - 1; + ZeroMem (&(MapEntrys->Maps[MapsIndex]), sizeof (MAP_ENTRY)); + MapEntrys->Count = MapsIndex; +} + /** Generate single random map entry. The map entry can be the input of function PageTableMap @@ -327,7 +348,16 @@ GenerateSingleRandomMapEntry ( MapEntrys->Maps[MapsIndex].Mask.Uint64 = MapEntrys->Maps[Random32 (0, (UINT32)MapsIndex-1)].Mask.Uint64; } else { MapEntrys->Maps[MapsIndex].Attribute.Uint64 = Random64 (0, MAX_UINT64) & mSupportedBit.Uint64; - MapEntrys->Maps[MapsIndex].Mask.Uint64 = Random64 (0, MAX_UINT64) & mSupportedBit.Uint64; + if (RandomBoolean (5)) { + // + // The probability to get random Mask should be small since all bits of a random number + // have a high probability of containing 0, which may be a invalid input. + // + MapEntrys->Maps[MapsIndex].Mask.Uint64 = Random64 (0, MAX_UINT64) & mSupportedBit.Uint64; + } else { + MapEntrys->Maps[MapsIndex].Mask.Uint64 = MAX_UINT64; + } + if (MapEntrys->Maps[MapsIndex].Mask.Bits.ProtectionKey != 0) { MapEntrys->Maps[MapsIndex].Mask.Bits.ProtectionKey = 0xF; } @@ -337,15 +367,7 @@ GenerateSingleRandomMapEntry ( MapEntrys->Maps[MapsIndex].Attribute.Bits.PageTableBaseAddress = MapEntrys->Maps[MapsIndex].LinearAddress >> 12; MapEntrys->Maps[MapsIndex].Mask.Bits.PageTableBaseAddress = 0xFFFFFFFFFF; } else { - // - // Todo: If the mask bit for base address is zero, when dump the pagetable, every entry mapping to physical address zeor. - // This means the map count will be a large number, and impossible to finish in proper time. - // Need to avoid such case when remove the Random option ONLY_ONE_ONE_MAPPING - // MapEntrys->Maps[MapsIndex].Attribute.Bits.PageTableBaseAddress = (Random64 (0, (((UINT64)1)<<52) - 1) & AlignedTable[Random32 (0, ARRAY_SIZE (AlignedTable) -1)])>> 12; - if (RandomBoolean (50)) { - MapEntrys->Maps[MapsIndex].Mask.Bits.PageTableBaseAddress = 0; - } } MapEntrys->Count += 1; @@ -608,25 +630,65 @@ SingleMapEntryTest ( IN UINTN InitMapCount ) { - UINTN MapsIndex; - RETURN_STATUS Status; - UINTN PageTableBufferSize; - VOID *Buffer; - IA32_MAP_ENTRY *Map; - UINTN MapCount; - UINTN Index; - UINTN KeyPointCount; - UINTN NewKeyPointCount; - UINT64 *KeyPointBuffer; - UINTN Level; - UINT64 Value; - UNIT_TEST_STATUS TestStatus; - MAP_ENTRY *LastMapEntry; - - MapsIndex = MapEntrys->Count; + UINTN MapsIndex; + RETURN_STATUS Status; + UINTN PageTableBufferSize; + VOID *Buffer; + IA32_MAP_ENTRY *Map; + UINTN MapCount; + UINTN Index; + UINTN KeyPointCount; + UINTN NewKeyPointCount; + UINT64 *KeyPointBuffer; + UINTN Level; + UINT64 Value; + UNIT_TEST_STATUS TestStatus; + MAP_ENTRY *LastMapEntry; + IA32_MAP_ATTRIBUTE *Mask; + IA32_MAP_ATTRIBUTE *Attribute; + UINT64 LastNotPresentRegionStart; + BOOLEAN IsNotPresent; + + MapsIndex = MapEntrys->Count; + MapCount = 0; + LastNotPresentRegionStart = 0; + IsNotPresent = FALSE; GenerateSingleRandomMapEntry (MaxAddress, MapEntrys); LastMapEntry = &MapEntrys->Maps[MapsIndex]; + Status = PageTableParse (*PageTable, PagingMode, NULL, &MapCount); + + if (MapCount != 0) { + UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); + Map = AllocatePages (EFI_SIZE_TO_PAGES (MapCount * sizeof (IA32_MAP_ENTRY))); + ASSERT (Map != NULL); + Status = PageTableParse (*PageTable, PagingMode, Map, &MapCount); + } + + // + // Check if the generated MapEntrys->Maps[MapsIndex] contains not-present range. + // + if (LastMapEntry->Length > 0) { + for (Index = 0; Index < MapCount; Index++) { + if ((LastNotPresentRegionStart < Map[Index].LinearAddress) && + (LastMapEntry->LinearAddress < Map[Index].LinearAddress) && (LastMapEntry->LinearAddress + LastMapEntry->Length > LastNotPresentRegionStart)) + { + // + // MapEntrys->Maps[MapsIndex] contains not-present range in exsiting page table. + // + break; + } + + LastNotPresentRegionStart = Map[Index].LinearAddress + Map[Index].Length; + } + + // + // Either LastMapEntry overlaps with the not-present region in the very end + // Or it overlaps with one in the middle + if (LastNotPresentRegionStart < LastMapEntry->LinearAddress + LastMapEntry->Length) { + IsNotPresent = TRUE; + } + } PageTableBufferSize = 0; Status = PageTableMap ( @@ -639,6 +701,47 @@ SingleMapEntryTest ( &LastMapEntry->Attribute, &LastMapEntry->Mask ); + + Attribute = &LastMapEntry->Attribute; + Mask = &LastMapEntry->Mask; + // + // If set [LinearAddress, LinearAddress+Attribute] to not preset, all + // other attributes should not be provided. + // + if ((LastMapEntry->Length > 0) && (Attribute->Bits.Present == 0) && (Mask->Bits.Present == 1) && (Mask->Uint64 > 1)) { + RemoveLastMapEntry (MapEntrys); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + return UNIT_TEST_PASSED; + } + + // + // Return Status for non-present range also should be InvalidParameter when: + // 1. Some of attributes are not provided when mapping non-present range to present. + // 2. Set any other attribute without setting the non-present range to Present. + // + if (IsNotPresent) { + if ((Mask->Bits.Present == 1) && (Attribute->Bits.Present == 1)) { + // + // Creating new page table or remapping non-present range to present. + // + if ((Mask->Bits.ReadWrite == 0) || (Mask->Bits.UserSupervisor == 0) || (Mask->Bits.WriteThrough == 0) || (Mask->Bits.CacheDisabled == 0) || + (Mask->Bits.Accessed == 0) || (Mask->Bits.Dirty == 0) || (Mask->Bits.Pat == 0) || (Mask->Bits.Global == 0) || + (Mask->Bits.PageTableBaseAddress == 0) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) + { + RemoveLastMapEntry (MapEntrys); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + return UNIT_TEST_PASSED; + } + } else if ((Mask->Bits.Present == 0) && (Mask->Uint64 > 1)) { + // + // Only change other attributes for non-present range is not permitted. + // + RemoveLastMapEntry (MapEntrys); + UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); + return UNIT_TEST_PASSED; + } + } + if (PageTableBufferSize != 0) { UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c index 5bd70c0f65..10fdee2f94 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c @@ -1,7 +1,7 @@ /** @file helper file for Unit tests of the CpuPageTableLib instance of the CpuPageTableLib class - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -171,6 +171,10 @@ IsPageTableValid ( UNIT_TEST_STATUS Status; IA32_PAGING_ENTRY *PagingEntry; + if (PageTable == 0) { + return UNIT_TEST_PASSED; + } + if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. From b5505159e45224899f14f48f6e67da06483cce34 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 3 Mar 2023 15:30:46 +0800 Subject: [PATCH 0735/1529] UefiCpuPkg/CpuPageTableLib: Enable non-1:1 mapping in random test Enable non-1:1 mapping in random test. In previous test, non-1:1 test will fail due to the non-1:1 mapping issue in CpuPageTableLib and invalid Input Mask when creating new page table or mapping not-present range. Now these issue have been fixed. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index 52fae1864a..c682d4ea04 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -9,10 +9,10 @@ #include "CpuPageTableLibUnitTest.h" // ----------------------------------------------------------------------- PageMode--TestCount-TestRangeCount---RandomOptions -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 100, 20, ONLY_ONE_ONE_MAPPING|USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 100, 20, ONLY_ONE_ONE_MAPPING|USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 100, 20, ONLY_ONE_ONE_MAPPING|USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 100, 20, ONLY_ONE_ONE_MAPPING|USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 100, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 100, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 100, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 100, 20, USE_RANDOM_ARRAY }; /** Check if the input parameters are not supported. From d292ab82465e2020a40d6db6b71fd065d799d8f6 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 9 Dec 2022 10:36:37 +0800 Subject: [PATCH 0736/1529] UefiCpuPkg/CpuPageTableLib: Add OUTPUT IsModified parameter. Add OUTPUT IsModified parameter in PageTableMap() to indicate if page table has been modified. With this parameter, caller can know if need to call FlushTlb when the page table is in CR3. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Include/Library/CpuPageTableLib.h | 4 +- .../Library/CpuPageTableLib/CpuPageTableMap.c | 46 ++++++++++-- .../UnitTest/CpuPageTableLibUnitTestHost.c | 72 +++++++++---------- .../CpuPageTableLib/UnitTest/RandomTest.c | 6 +- .../Library/MpInitLib/X64/CreatePageTable.c | 6 +- 5 files changed, 88 insertions(+), 46 deletions(-) diff --git a/UefiCpuPkg/Include/Library/CpuPageTableLib.h b/UefiCpuPkg/Include/Library/CpuPageTableLib.h index 4ef4a8b6af..352b6df6c6 100644 --- a/UefiCpuPkg/Include/Library/CpuPageTableLib.h +++ b/UefiCpuPkg/Include/Library/CpuPageTableLib.h @@ -74,6 +74,7 @@ typedef enum { Page table entries that map the linear address range are reset to 0 before set to the new attribute when a new physical base address is set. @param[in] Mask The mask used for attribute. The corresponding field in Attribute is ignored if that in Mask is 0. + @param[out] IsModified TRUE means page table is modified. FALSE means page table is not modified. @retval RETURN_UNSUPPORTED PagingMode is not supported. @retval RETURN_INVALID_PARAMETER PageTable, BufferSize, Attribute or Mask is NULL. @@ -97,7 +98,8 @@ PageTableMap ( IN UINT64 LinearAddress, IN UINT64 Length, IN IA32_MAP_ATTRIBUTE *Attribute, - IN IA32_MAP_ATTRIBUTE *Mask + IN IA32_MAP_ATTRIBUTE *Mask, + OUT BOOLEAN *IsModified OPTIONAL ); typedef struct { diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 76c3719cdf..64383cc522 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -274,6 +274,7 @@ IsAttributesAndMaskValidForNonPresentEntry ( Page table entries that map the linear address range are reset to 0 before set to the new attribute when a new physical base address is set. @param[in] Mask The mask used for attribute. The corresponding field in Attribute is ignored if that in Mask is 0. + @param[out] IsModified TRUE means page table is modified. FALSE means page table is not modified. @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 0 but some other attributes are provided. @retval RETURN_INVALID_PARAMETER For non-present range, Mask->Bits.Present is 1, Attribute->Bits.Present is 1 but some other attributes are not provided. @@ -292,7 +293,8 @@ PageTableLibMapInLevel ( IN UINT64 Length, IN UINT64 Offset, IN IA32_MAP_ATTRIBUTE *Attribute, - IN IA32_MAP_ATTRIBUTE *Mask + IN IA32_MAP_ATTRIBUTE *Mask, + OUT BOOLEAN *IsModified ) { RETURN_STATUS Status; @@ -318,6 +320,8 @@ PageTableLibMapInLevel ( IA32_MAP_ATTRIBUTE LocalParentAttribute; UINT64 PhysicalAddrInEntry; UINT64 PhysicalAddrInAttr; + IA32_PAGING_ENTRY OriginalParentPagingEntry; + IA32_PAGING_ENTRY OriginalCurrentPagingEntry; ASSERT (Level != 0); ASSERT ((Attribute != NULL) && (Mask != NULL)); @@ -333,6 +337,8 @@ PageTableLibMapInLevel ( LocalParentAttribute.Uint64 = ParentAttribute->Uint64; ParentAttribute = &LocalParentAttribute; + OriginalParentPagingEntry.Uint64 = ParentPagingEntry->Uint64; + // // RegionLength: 256T (1 << 48) 512G (1 << 39), 1G (1 << 30), 2M (1 << 21) or 4K (1 << 12). // @@ -568,7 +574,15 @@ PageTableLibMapInLevel ( ASSERT (CreateNew || (Mask->Bits.Nx == 0) || (Attribute->Bits.Nx == 1)); } + // + // Check if any leaf PagingEntry is modified. + // + OriginalCurrentPagingEntry.Uint64 = CurrentPagingEntry->Uint64; PageTableLibSetPle (Level, CurrentPagingEntry, Offset, Attribute, &CurrentMask); + + if (OriginalCurrentPagingEntry.Uint64 != CurrentPagingEntry->Uint64) { + *IsModified = TRUE; + } } } else { // @@ -591,7 +605,8 @@ PageTableLibMapInLevel ( Length, Offset, Attribute, - Mask + Mask, + IsModified ); if (RETURN_ERROR (Status)) { return Status; @@ -603,6 +618,14 @@ PageTableLibMapInLevel ( Index++; } + // + // Check if ParentPagingEntry entry is modified here is enough. Except the changes happen in leaf PagingEntry during + // the while loop, if there is any other change happens in page table, the ParentPagingEntry must has been modified. + // + if (OriginalParentPagingEntry.Uint64 != ParentPagingEntry->Uint64) { + *IsModified = TRUE; + } + return RETURN_SUCCESS; } @@ -623,6 +646,7 @@ PageTableLibMapInLevel ( Page table entries that map the linear address range are reset to 0 before set to the new attribute when a new physical base address is set. @param[in] Mask The mask used for attribute. The corresponding field in Attribute is ignored if that in Mask is 0. + @param[out] IsModified TRUE means page table is modified. FALSE means page table is not modified. @retval RETURN_UNSUPPORTED PagingMode is not supported. @retval RETURN_INVALID_PARAMETER PageTable, BufferSize, Attribute or Mask is NULL. @@ -646,7 +670,8 @@ PageTableMap ( IN UINT64 LinearAddress, IN UINT64 Length, IN IA32_MAP_ATTRIBUTE *Attribute, - IN IA32_MAP_ATTRIBUTE *Mask + IN IA32_MAP_ATTRIBUTE *Mask, + OUT BOOLEAN *IsModified OPTIONAL ) { RETURN_STATUS Status; @@ -656,6 +681,7 @@ PageTableMap ( IA32_PAGE_LEVEL MaxLevel; IA32_PAGE_LEVEL MaxLeafLevel; IA32_MAP_ATTRIBUTE ParentAttribute; + BOOLEAN LocalIsModified; if (Length == 0) { return RETURN_SUCCESS; @@ -718,6 +744,12 @@ PageTableMap ( TopPagingEntry.Pce.Nx = 0; } + if (IsModified == NULL) { + IsModified = &LocalIsModified; + } + + *IsModified = FALSE; + ParentAttribute.Uint64 = 0; ParentAttribute.Bits.PageTableBaseAddress = 1; ParentAttribute.Bits.Present = 1; @@ -741,8 +773,10 @@ PageTableMap ( Length, 0, Attribute, - Mask + Mask, + IsModified ); + ASSERT (*IsModified == FALSE); if (RETURN_ERROR (Status)) { return Status; } @@ -773,8 +807,10 @@ PageTableMap ( Length, 0, Attribute, - Mask + Mask, + IsModified ); + if (!RETURN_ERROR (Status)) { *PageTable = (UINTN)(TopPagingEntry.Uintn & IA32_PE_BASE_ADDRESS_MASK_40); } diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index c682d4ea04..759da09271 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -51,26 +51,26 @@ TestCaseForParameter ( // // If the input linear address is not 4K align, it should return invalid parameter // - UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, &MapMask), RETURN_INVALID_PARAMETER); + UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, &MapMask, NULL), RETURN_INVALID_PARAMETER); // // If the input PageTableBufferSize is not 4K align, it should return invalid parameter // PageTableBufferSize = 10; - UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 0, SIZE_4KB, &MapAttribute, &MapMask), RETURN_INVALID_PARAMETER); + UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 0, SIZE_4KB, &MapAttribute, &MapMask, NULL), RETURN_INVALID_PARAMETER); // // If the input PagingMode is Paging32bit, it should return invalid parameter // PageTableBufferSize = 0; PagingMode = Paging32bit; - UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, &MapMask), RETURN_UNSUPPORTED); + UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, &MapMask, NULL), RETURN_UNSUPPORTED); // // If the input MapMask is NULL, it should return invalid parameter // PagingMode = Paging5Level1GB; - UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, NULL), RETURN_INVALID_PARAMETER); + UT_ASSERT_EQUAL (PageTableMap (&PageTable, PagingMode, &Buffer, &PageTableBufferSize, 1, SIZE_4KB, &MapAttribute, NULL, NULL), RETURN_INVALID_PARAMETER); return UNIT_TEST_PASSED; } @@ -119,10 +119,10 @@ TestCaseWhichNoNeedExtraSize ( // // Create page table to cover [0, 10M], it should have 5 PTE // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_2MB * 5, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_2MB * 5, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_2MB * 5, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_2MB * 5, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); if (TestStatus != UNIT_TEST_PASSED) { @@ -134,7 +134,7 @@ TestCaseWhichNoNeedExtraSize ( // We assume the fucntion doesn't need to change page table, return success and output BufferSize is 0 // Buffer = NULL; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_4KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, (UINT64)SIZE_4KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (PageTableBufferSize, 0); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); @@ -148,7 +148,7 @@ TestCaseWhichNoNeedExtraSize ( // MapMask.Bits.Nx = 0; PageTableBufferSize = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, (UINT64)SIZE_4KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, (UINT64)SIZE_4KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); UT_ASSERT_EQUAL (PageTableBufferSize, 0); TestStatus = IsPageTableValid (PageTable, PagingMode); @@ -164,7 +164,7 @@ TestCaseWhichNoNeedExtraSize ( MapAttribute.Bits.Accessed = 1; MapMask.Bits.Accessed = 1; PageTableBufferSize = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)SIZE_2MB, (UINT64)SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)SIZE_2MB, (UINT64)SIZE_2MB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); UT_ASSERT_EQUAL (PageTableBufferSize, 0); TestStatus = IsPageTableValid (PageTable, PagingMode); @@ -217,10 +217,10 @@ TestCase1Gmapto4K ( MapAttribute.Bits.Present = 1; MapMask.Bits.Present = 1; MapMask.Uint64 = MAX_UINT64; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); // @@ -281,11 +281,11 @@ TestCaseManualChangeReadWrite ( // // Create Page table to cover [0,2G], with ReadWrite = 1 // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); BackupPageTableBufferSize = PageTableBufferSize; Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); IsPageTableValid (PageTable, PagingMode); @@ -331,7 +331,7 @@ TestCaseManualChangeReadWrite ( // Call library to change ReadWrite to 0 for [0,2M] // MapAttribute.Bits.ReadWrite = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, SIZE_2MB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); IsPageTableValid (PageTable, PagingMode); MapCount = 0; @@ -360,7 +360,7 @@ TestCaseManualChangeReadWrite ( // MapAttribute.Bits.ReadWrite = 1; PageTableBufferSize = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, 0, SIZE_2MB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); IsPageTableValid (PageTable, PagingMode); MapCount = 0; @@ -434,10 +434,10 @@ TestCaseManualSizeNotMatch ( // // Create Page table to cover [2M-4K, 4M], with ReadWrite = 1 // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB + SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB + SIZE_2MB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB + SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB + SIZE_2MB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); IsPageTableValid (PageTable, PagingMode); @@ -493,7 +493,7 @@ TestCaseManualSizeNotMatch ( MapAttribute.Bits.ReadWrite = 1; PageTableBufferSize = 0; MapAttribute.Bits.PageTableBaseAddress = (SIZE_2MB - SIZE_4KB) >> 12; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB * 2, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); return UNIT_TEST_PASSED; } @@ -540,10 +540,10 @@ TestCaseManualNotMergeEntry ( // // Create Page table to cover [0,4M], and [4M, 1G] is not present // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB * 2, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB * 2, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); if (TestStatus != UNIT_TEST_PASSED) { @@ -555,7 +555,7 @@ TestCaseManualNotMergeEntry ( // It looks like the chioce is not bad, but sometime, we need to keep some small entry // PageTableBufferSize = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); if (TestStatus != UNIT_TEST_PASSED) { @@ -564,7 +564,7 @@ TestCaseManualNotMergeEntry ( MapAttribute.Bits.Accessed = 1; PageTableBufferSize = 0; - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_2MB, &MapAttribute, &MapMask, NULL); // // If it didn't use a big 1G entry to cover whole range, only change [0,2M] for some attribute won't need extra memory // @@ -619,10 +619,10 @@ TestCaseManualChangeNx ( // // Create Page table to cover [0,2G], with Nx = 0 // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB * 2, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB * 2, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); if (TestStatus != UNIT_TEST_PASSED) { @@ -666,7 +666,7 @@ TestCaseManualChangeNx ( // // Call library to change Nx to 0 for [0,1G] // - Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, NULL, &PageTableBufferSize, (UINT64)0, (UINT64)SIZE_1GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); TestStatus = IsPageTableValid (PageTable, PagingMode); if (TestStatus != UNIT_TEST_PASSED) { @@ -741,30 +741,30 @@ TestCaseToCheckMapMaskAndAttr ( // // Create Page table to cover [0, 2G]. All fields of MapMask should be set. // - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); MapMask.Uint64 = MAX_UINT64; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); // // Update Page table to set [2G - 8K, 2G] from present to non-present. All fields of MapMask except present should not be set. // PageTableBufferSize = 0; - MapAttribute.Uint64 = SIZE_2GB - SIZE_8KB; + MapAttribute.Uint64 = 0; MapMask.Uint64 = 0; MapMask.Bits.Present = 1; MapMask.Bits.ReadWrite = 1; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); MapMask.Bits.ReadWrite = 0; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); Buffer = AllocatePages (EFI_SIZE_TO_PAGES (PageTableBufferSize)); - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, 0, SIZE_2GB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); // @@ -774,11 +774,11 @@ TestCaseToCheckMapMaskAndAttr ( MapAttribute.Uint64 = 0; MapMask.Uint64 = 0; MapMask.Bits.Present = 1; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); MapAttribute.Bits.ReadWrite = 1; MapMask.Bits.ReadWrite = 1; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); // @@ -791,10 +791,10 @@ TestCaseToCheckMapMaskAndAttr ( MapMask.Uint64 = 0; MapMask.Bits.ReadWrite = 1; MapMask.Bits.Present = 1; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); MapMask.Uint64 = MAX_UINT64; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask); + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2GB - SIZE_8KB, SIZE_8KB, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); MapCount = 0; diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index 121cc4f2b2..e603dba269 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -699,7 +699,8 @@ SingleMapEntryTest ( LastMapEntry->LinearAddress, LastMapEntry->Length, &LastMapEntry->Attribute, - &LastMapEntry->Mask + &LastMapEntry->Mask, + NULL ); Attribute = &LastMapEntry->Attribute; @@ -759,7 +760,8 @@ SingleMapEntryTest ( LastMapEntry->LinearAddress, LastMapEntry->Length, &LastMapEntry->Attribute, - &LastMapEntry->Mask + &LastMapEntry->Mask, + NULL ); } diff --git a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c index f20068152b..da8729e752 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/CreatePageTable.c @@ -57,7 +57,8 @@ CreatePageTable ( Address, Length, &MapAttribute, - &MapMask + &MapMask, + NULL ); ASSERT (Status == EFI_BUFFER_TOO_SMALL); DEBUG ((DEBUG_INFO, "AP Page Table Buffer Size = %x\n", PageTableBufferSize)); @@ -72,7 +73,8 @@ CreatePageTable ( Address, Length, &MapAttribute, - &MapMask + &MapMask, + NULL ); ASSERT_EFI_ERROR (Status); return PageTable; From 5af5b36a81b9dee1f5cb7677c5c4f0c68d76ab28 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 7 Mar 2023 15:25:27 +0800 Subject: [PATCH 0737/1529] UefiCpuPkg/CpuPageTableLib: Modify RandomTest to check IsModified Modify RandomTest to check if parameter IsModified of PageTableMap() correctlly indicates whether input page table is modified or not. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann Cc: Zhiguang Liu --- .../CpuPageTableLib/UnitTest/RandomTest.c | 45 ++++++++++++++----- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index e603dba269..bffd95c898 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -636,6 +636,8 @@ SingleMapEntryTest ( VOID *Buffer; IA32_MAP_ENTRY *Map; UINTN MapCount; + IA32_MAP_ENTRY *Map2; + UINTN MapCount2; UINTN Index; UINTN KeyPointCount; UINTN NewKeyPointCount; @@ -648,11 +650,13 @@ SingleMapEntryTest ( IA32_MAP_ATTRIBUTE *Attribute; UINT64 LastNotPresentRegionStart; BOOLEAN IsNotPresent; + BOOLEAN IsModified; MapsIndex = MapEntrys->Count; MapCount = 0; LastNotPresentRegionStart = 0; IsNotPresent = FALSE; + IsModified = FALSE; GenerateSingleRandomMapEntry (MaxAddress, MapEntrys); LastMapEntry = &MapEntrys->Maps[MapsIndex]; @@ -700,7 +704,7 @@ SingleMapEntryTest ( LastMapEntry->Length, &LastMapEntry->Attribute, &LastMapEntry->Mask, - NULL + &IsModified ); Attribute = &LastMapEntry->Attribute; @@ -761,7 +765,7 @@ SingleMapEntryTest ( LastMapEntry->Length, &LastMapEntry->Attribute, &LastMapEntry->Mask, - NULL + &IsModified ); } @@ -775,18 +779,31 @@ SingleMapEntryTest ( return TestStatus; } - MapCount = 0; - Status = PageTableParse (*PageTable, PagingMode, NULL, &MapCount); - if (MapCount != 0) { + MapCount2 = 0; + Status = PageTableParse (*PageTable, PagingMode, NULL, &MapCount2); + if (MapCount2 != 0) { UT_ASSERT_EQUAL (Status, RETURN_BUFFER_TOO_SMALL); // - // Allocate memory for Maps + // Allocate memory for Map2 // Note the memory is only used in this one Single MapEntry Test // - Map = AllocatePages (EFI_SIZE_TO_PAGES (MapCount * sizeof (IA32_MAP_ENTRY))); - ASSERT (Map != NULL); - Status = PageTableParse (*PageTable, PagingMode, Map, &MapCount); + Map2 = AllocatePages (EFI_SIZE_TO_PAGES (MapCount2 * sizeof (IA32_MAP_ENTRY))); + ASSERT (Map2 != NULL); + Status = PageTableParse (*PageTable, PagingMode, Map2, &MapCount2); + } + + // + // Check if PageTable has been modified. + // + if (MapCount2 != MapCount) { + UT_ASSERT_EQUAL (IsModified, TRUE); + } else { + if (CompareMem (Map, Map2, MapCount2 * sizeof (IA32_MAP_ENTRY)) != 0) { + UT_ASSERT_EQUAL (IsModified, TRUE); + } else { + UT_ASSERT_EQUAL (IsModified, FALSE); + } } UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); @@ -796,17 +813,17 @@ SingleMapEntryTest ( // Note the memory is only used in this one Single MapEntry Test // KeyPointCount = 0; - GetKeyPointList (MapEntrys, Map, MapCount, NULL, &KeyPointCount); + GetKeyPointList (MapEntrys, Map2, MapCount2, NULL, &KeyPointCount); KeyPointBuffer = AllocatePages (EFI_SIZE_TO_PAGES (KeyPointCount * sizeof (UINT64))); ASSERT (KeyPointBuffer != NULL); NewKeyPointCount = 0; - GetKeyPointList (MapEntrys, Map, MapCount, KeyPointBuffer, &NewKeyPointCount); + GetKeyPointList (MapEntrys, Map2, MapCount2, KeyPointBuffer, &NewKeyPointCount); // // Compare all key point's attribute // for (Index = 0; Index < NewKeyPointCount; Index++) { - if (!CompareEntrysforOnePoint (KeyPointBuffer[Index], MapEntrys, Map, MapCount, InitMap, InitMapCount)) { + if (!CompareEntrysforOnePoint (KeyPointBuffer[Index], MapEntrys, Map2, MapCount2, InitMap, InitMapCount)) { DEBUG ((DEBUG_INFO, "Error happens at below key point\n")); DEBUG ((DEBUG_INFO, "Index = %d KeyPointBuffer[Index] = 0x%lx\n", Index, KeyPointBuffer[Index])); Value = GetEntryFromPageTable (*PageTable, PagingMode, KeyPointBuffer[Index], &Level); @@ -820,6 +837,10 @@ SingleMapEntryTest ( FreePages (Map, EFI_SIZE_TO_PAGES (MapCount * sizeof (IA32_MAP_ENTRY))); } + if (MapCount2 != 0) { + FreePages (Map2, EFI_SIZE_TO_PAGES (MapCount2 * sizeof (IA32_MAP_ENTRY))); + } + return UNIT_TEST_PASSED; } From 124bf22b16a234334d20d67d07b9d2f471b8c3c4 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Tue, 7 Mar 2023 13:55:43 +0800 Subject: [PATCH 0738/1529] UefiCpuPkg: Fix IA32 build failure in CpuPageTableLib.inf The definition of IA32_MAP_ATTRIBUTE has 64 bits, and one of the bit field PageTableBaseAddress is from bit 12 to bit 52. This means if the compiler treats the 64bits value as two UINT32 value, the field PageTableBaseAddress spans two UINT32 value. That's why when building in NOOPT mode in IA32, the below issue is noticed: unresolved external symbol __allshl This patch fix the build failure by seperate field PageTableBaseAddress into two fields, make sure no field spans two UINT32 value. Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann Signed-off-by: Zhiguang Liu Signed-off-by: Ray Ni --- UefiCpuPkg/Include/Library/CpuPageTableLib.h | 32 ++--- .../Library/CpuPageTableLib/CpuPageTable.h | 125 +++++++++--------- .../Library/CpuPageTableLib/CpuPageTableMap.c | 22 +-- 3 files changed, 90 insertions(+), 89 deletions(-) diff --git a/UefiCpuPkg/Include/Library/CpuPageTableLib.h b/UefiCpuPkg/Include/Library/CpuPageTableLib.h index 352b6df6c6..78aa83b8de 100644 --- a/UefiCpuPkg/Include/Library/CpuPageTableLib.h +++ b/UefiCpuPkg/Include/Library/CpuPageTableLib.h @@ -11,22 +11,22 @@ typedef union { struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User - UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) - UINT64 Pat : 1; // PAT - - UINT64 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) - UINT64 Reserved1 : 3; // Ignored - - UINT64 PageTableBaseAddress : 40; // Page Table Base Address - UINT64 Reserved2 : 7; // Ignored - UINT64 ProtectionKey : 4; // Protection key - UINT64 Nx : 1; // No Execute bit + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT32 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT32 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT32 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT32 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT32 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) + UINT32 Pat : 1; // PAT + UINT32 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) + UINT32 Reserved1 : 3; // Ignored + UINT32 PageTableBaseAddressLow : 20; // Page Table Base Address Low + + UINT32 PageTableBaseAddressHigh : 20; // Page Table Base Address High + UINT32 Reserved2 : 7; // Ignored + UINT32 ProtectionKey : 4; // Protection key + UINT32 Nx : 1; // No Execute bit } Bits; UINT64 Uint64; } IA32_MAP_ATTRIBUTE; diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h index 8d856d7c7e..2c67ecb469 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h @@ -29,11 +29,12 @@ typedef enum { } IA32_PAGE_LEVEL; typedef struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User - UINT64 Reserved : 58; - UINT64 Nx : 1; // No Execute bit + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT32 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT32 Reserved0 : 29; + UINT32 Reserved1 : 31; + UINT32 Nx : 1; // No Execute bit } IA32_PAGE_COMMON_ENTRY; /// @@ -41,20 +42,20 @@ typedef struct { /// typedef union { struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User - UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Available0 : 1; // Ignored - UINT64 MustBeZero : 1; // Must Be Zero - - UINT64 Available2 : 4; // Ignored - - UINT64 PageTableBaseAddress : 40; // Page Table Base Address - UINT64 Available3 : 11; // Ignored - UINT64 Nx : 1; // No Execute bit + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT32 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT32 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT32 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT32 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT32 Available0 : 1; // Ignored + UINT32 MustBeZero : 1; // Must Be Zero + UINT32 Available2 : 4; // Ignored + UINT32 PageTableBaseAddressLow : 20; // Page Table Base Address Low + + UINT32 PageTableBaseAddressHigh : 20; // Page Table Base Address High + UINT32 Available3 : 11; // Ignored + UINT32 Nx : 1; // No Execute bit } Bits; UINT64 Uint64; } IA32_PAGE_NON_LEAF_ENTRY; @@ -86,23 +87,23 @@ typedef IA32_PAGE_NON_LEAF_ENTRY IA32_PDE; /// typedef union { struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User - UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) - UINT64 MustBeOne : 1; // Page Size. Must Be One - - UINT64 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) - UINT64 Available1 : 3; // Ignored - UINT64 Pat : 1; // PAT - - UINT64 PageTableBaseAddress : 39; // Page Table Base Address - UINT64 Available3 : 7; // Ignored - UINT64 ProtectionKey : 4; // Protection key - UINT64 Nx : 1; // No Execute bit + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT32 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT32 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT32 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT32 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT32 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) + UINT32 MustBeOne : 1; // Page Size. Must Be One + UINT32 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) + UINT32 Available1 : 3; // Ignored + UINT32 Pat : 1; // PAT + UINT32 PageTableBaseAddressLow : 19; // Page Table Base Address Low + + UINT32 PageTableBaseAddressHigh : 20; // Page Table Base Address High + UINT32 Available3 : 7; // Ignored + UINT32 ProtectionKey : 4; // Protection key + UINT32 Nx : 1; // No Execute bit } Bits; UINT64 Uint64; } IA32_PAGE_LEAF_ENTRY_BIG_PAGESIZE; @@ -123,22 +124,22 @@ typedef IA32_PAGE_LEAF_ENTRY_BIG_PAGESIZE IA32_PDPTE_1G; /// typedef union { struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User - UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) - UINT64 Pat : 1; // PAT - - UINT64 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) - UINT64 Available1 : 3; // Ignored - - UINT64 PageTableBaseAddress : 40; // Page Table Base Address - UINT64 Available3 : 7; // Ignored - UINT64 ProtectionKey : 4; // Protection key - UINT64 Nx : 1; // No Execute bit + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT32 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT32 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT32 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT32 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT32 Dirty : 1; // 0 = Not dirty, 1 = Dirty (set by CPU) + UINT32 Pat : 1; // PAT + UINT32 Global : 1; // 0 = Not global, 1 = Global (if CR4.PGE = 1) + UINT32 Available1 : 3; // Ignored + UINT32 PageTableBaseAddressLow : 20; // Page Table Base Address Low + + UINT32 PageTableBaseAddressHigh : 20; // Page Table Base Address High + UINT32 Available3 : 7; // Ignored + UINT32 ProtectionKey : 4; // Protection key + UINT32 Nx : 1; // No Execute bit } Bits; UINT64 Uint64; } IA32_PTE_4K; @@ -149,16 +150,16 @@ typedef union { /// typedef union { struct { - UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory - UINT64 MustBeZero : 2; // Must Be Zero - UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached - UINT64 MustBeZero2 : 4; // Must Be Zero - - UINT64 Available : 3; // Ignored - - UINT64 PageTableBaseAddress : 40; // Page Table Base Address - UINT64 MustBeZero3 : 12; // Must Be Zero + UINT32 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT32 MustBeZero : 2; // Must Be Zero + UINT32 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT32 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT32 MustBeZero2 : 4; // Must Be Zero + UINT32 Available : 3; // Ignored + UINT32 PageTableBaseAddressLow : 20; // Page Table Base Address Low + + UINT32 PageTableBaseAddressHigh : 20; // Page Table Base Address High + UINT32 MustBeZero3 : 12; // Must Be Zero } Bits; UINT64 Uint64; } IA32_PDPTE_PAE; diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 64383cc522..7936333e01 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -26,7 +26,7 @@ PageTableLibSetPte4K ( IN IA32_MAP_ATTRIBUTE *Mask ) { - if (Mask->Bits.PageTableBaseAddress) { + if (Mask->Bits.PageTableBaseAddressLow || Mask->Bits.PageTableBaseAddressHigh) { Pte4K->Uint64 = (IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (Attribute) + Offset) | (Pte4K->Uint64 & ~IA32_PE_BASE_ADDRESS_MASK_40); } @@ -93,7 +93,7 @@ PageTableLibSetPleB ( IN IA32_MAP_ATTRIBUTE *Mask ) { - if (Mask->Bits.PageTableBaseAddress) { + if (Mask->Bits.PageTableBaseAddressLow || Mask->Bits.PageTableBaseAddressHigh) { PleB->Uint64 = (IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (Attribute) + Offset) | (PleB->Uint64 & ~IA32_PE_BASE_ADDRESS_MASK_39); } @@ -239,7 +239,7 @@ IsAttributesAndMaskValidForNonPresentEntry ( // if ((Mask->Bits.ReadWrite == 0) || (Mask->Bits.UserSupervisor == 0) || (Mask->Bits.WriteThrough == 0) || (Mask->Bits.CacheDisabled == 0) || (Mask->Bits.Accessed == 0) || (Mask->Bits.Dirty == 0) || (Mask->Bits.Pat == 0) || (Mask->Bits.Global == 0) || - (Mask->Bits.PageTableBaseAddress == 0) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) + ((Mask->Bits.PageTableBaseAddressLow == 0) && (Mask->Bits.PageTableBaseAddressHigh == 0)) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) { return RETURN_INVALID_PARAMETER; } @@ -399,7 +399,7 @@ PageTableLibMapInLevel ( // This function is called when the memory length is less than the region length of the parent level. // No need to split the page when the attributes equal. // - if (Mask->Bits.PageTableBaseAddress == 0) { + if ((Mask->Bits.PageTableBaseAddressLow == 0) && (Mask->Bits.PageTableBaseAddressHigh == 0)) { return RETURN_SUCCESS; } @@ -706,7 +706,7 @@ PageTableMap ( return RETURN_INVALID_PARAMETER; } - if ((LinearAddress % SIZE_4KB != 0) || (Length % SIZE_4KB != 0)) { + if (((UINTN)LinearAddress % SIZE_4KB != 0) || ((UINTN)Length % SIZE_4KB != 0)) { // // LinearAddress and Length should be multiple of 4K. // @@ -750,12 +750,12 @@ PageTableMap ( *IsModified = FALSE; - ParentAttribute.Uint64 = 0; - ParentAttribute.Bits.PageTableBaseAddress = 1; - ParentAttribute.Bits.Present = 1; - ParentAttribute.Bits.ReadWrite = 1; - ParentAttribute.Bits.UserSupervisor = 1; - ParentAttribute.Bits.Nx = 0; + ParentAttribute.Uint64 = 0; + ParentAttribute.Bits.PageTableBaseAddressLow = 1; + ParentAttribute.Bits.Present = 1; + ParentAttribute.Bits.ReadWrite = 1; + ParentAttribute.Bits.UserSupervisor = 1; + ParentAttribute.Bits.Nx = 0; // // Query the required buffer size without modifying the page table. From a5bded161cb05646eadd787871f2a206199d2b69 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Tue, 7 Mar 2023 14:21:54 +0800 Subject: [PATCH 0739/1529] UefiCpuPkg: Modify UnitTest code since tested API is changed Last commit changed the CpuPageTableLib API PageTableMap, unit test code should also be modified. Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann Signed-off-by: Zhiguang Liu --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 38 ++++----- .../CpuPageTableLib/UnitTest/RandomTest.c | 84 +++++++++++-------- .../CpuPageTableLib/UnitTest/TestHelper.c | 4 +- 3 files changed, 67 insertions(+), 59 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index 759da09271..4303095579 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -422,15 +422,14 @@ TestCaseManualSizeNotMatch ( UINTN MapCount; IA32_PAGING_ENTRY *PagingEntry; - PagingMode = Paging4Level; - PageTableBufferSize = 0; - PageTable = 0; - Buffer = NULL; - MapAttribute.Uint64 = 0; - MapMask.Uint64 = MAX_UINT64; - MapAttribute.Bits.Present = 1; - MapAttribute.Bits.ReadWrite = 1; - MapAttribute.Bits.PageTableBaseAddress = (SIZE_2MB - SIZE_4KB) >> 12; + PagingMode = Paging4Level; + PageTableBufferSize = 0; + PageTable = 0; + Buffer = NULL; + MapMask.Uint64 = MAX_UINT64; + MapAttribute.Uint64 = (SIZE_2MB - SIZE_4KB); + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; // // Create Page table to cover [2M-4K, 4M], with ReadWrite = 1 // @@ -460,9 +459,9 @@ TestCaseManualSizeNotMatch ( // [2M-4K,2M], R/W = 0 // [2M ,4M], R/W = 1 // - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)PageTable; // Get 4 level entry - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)(PagingEntry->Pnle.Bits.PageTableBaseAddress << 12); // Get 3 level entry - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)(PagingEntry->Pnle.Bits.PageTableBaseAddress << 12); // Get 2 level entry + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)PageTable; // Get 4 level entry + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (PagingEntry); // Get 3 level entry + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (PagingEntry); // Get 2 level entry PagingEntry->Uint64 = PagingEntry->Uint64 & (~(UINT64)0x2); MapCount = 0; Status = PageTableParse (PageTable, PagingMode, NULL, &MapCount); @@ -480,20 +479,19 @@ TestCaseManualSizeNotMatch ( UT_ASSERT_EQUAL (Map[1].LinearAddress, SIZE_2MB); UT_ASSERT_EQUAL (Map[1].Length, SIZE_2MB); - ExpectedMapAttribute.Uint64 = MapAttribute.Uint64; - ExpectedMapAttribute.Bits.ReadWrite = 1; - ExpectedMapAttribute.Bits.PageTableBaseAddress = SIZE_2MB >> 12; + ExpectedMapAttribute.Uint64 = MapAttribute.Uint64 + SIZE_4KB; + ExpectedMapAttribute.Bits.ReadWrite = 1; UT_ASSERT_EQUAL (Map[1].Attribute.Uint64, ExpectedMapAttribute.Uint64); // // Set Page table [2M-4K, 2M+4K]'s ReadWrite = 1, [2M,2M+4K]'s ReadWrite is already 1 // Just need to set [2M-4K,2M], won't need extra size, so the status should be success // - MapAttribute.Bits.Present = 1; - MapAttribute.Bits.ReadWrite = 1; - PageTableBufferSize = 0; - MapAttribute.Bits.PageTableBaseAddress = (SIZE_2MB - SIZE_4KB) >> 12; - Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB * 2, &MapAttribute, &MapMask, NULL); + MapAttribute.Uint64 = SIZE_2MB - SIZE_4KB; + MapAttribute.Bits.Present = 1; + MapAttribute.Bits.ReadWrite = 1; + PageTableBufferSize = 0; + Status = PageTableMap (&PageTable, PagingMode, Buffer, &PageTableBufferSize, SIZE_2MB - SIZE_4KB, SIZE_4KB * 2, &MapAttribute, &MapMask, NULL); UT_ASSERT_EQUAL (Status, RETURN_SUCCESS); return UNIT_TEST_PASSED; } diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index bffd95c898..2db49f7de7 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -157,7 +157,8 @@ ValidateAndRandomeModifyPageTablePageTableEntry ( ) { UINT64 Index; - UINT64 TempPhysicalBase; + UINT32 PageTableBaseAddressLow; + UINT32 PageTableBaseAddressHigh; IA32_PAGING_ENTRY *ChildPageEntry; UNIT_TEST_STATUS Status; @@ -180,17 +181,21 @@ ValidateAndRandomeModifyPageTablePageTableEntry ( if ((RandomNumber < 100) && RandomBoolean (50)) { RandomNumber++; if (Level == 1) { - TempPhysicalBase = PagingEntry->Pte4K.Bits.PageTableBaseAddress; + PageTableBaseAddressLow = PagingEntry->Pte4K.Bits.PageTableBaseAddressLow; + PageTableBaseAddressHigh = PagingEntry->Pte4K.Bits.PageTableBaseAddressHigh; } else { - TempPhysicalBase = PagingEntry->PleB.Bits.PageTableBaseAddress; + PageTableBaseAddressLow = PagingEntry->PleB.Bits.PageTableBaseAddressLow; + PageTableBaseAddressHigh = PagingEntry->PleB.Bits.PageTableBaseAddressHigh; } PagingEntry->Uint64 = (Random64 (0, MAX_UINT64) & mValidMaskLeaf[Level].Uint64) | mValidMaskLeafFlag[Level].Uint64; PagingEntry->Pte4K.Bits.Present = 1; if (Level == 1) { - PagingEntry->Pte4K.Bits.PageTableBaseAddress = TempPhysicalBase; + PagingEntry->Pte4K.Bits.PageTableBaseAddressLow = PageTableBaseAddressLow; + PagingEntry->Pte4K.Bits.PageTableBaseAddressHigh = PageTableBaseAddressHigh; } else { - PagingEntry->PleB.Bits.PageTableBaseAddress = TempPhysicalBase; + PagingEntry->PleB.Bits.PageTableBaseAddressLow = PageTableBaseAddressLow; + PagingEntry->PleB.Bits.PageTableBaseAddressHigh = PageTableBaseAddressHigh; } if ((PagingEntry->Uint64 & mValidMaskLeaf[Level].Uint64) != PagingEntry->Uint64) { @@ -212,15 +217,17 @@ ValidateAndRandomeModifyPageTablePageTableEntry ( if ((RandomNumber < 100) && RandomBoolean (50)) { RandomNumber++; - TempPhysicalBase = PagingEntry->Pnle.Bits.PageTableBaseAddress; + PageTableBaseAddressLow = PagingEntry->PleB.Bits.PageTableBaseAddressLow; + PageTableBaseAddressHigh = PagingEntry->PleB.Bits.PageTableBaseAddressHigh; - PagingEntry->Uint64 = Random64 (0, MAX_UINT64) & mValidMaskNoLeaf[Level].Uint64; - PagingEntry->Pnle.Bits.Present = 1; - PagingEntry->Pnle.Bits.PageTableBaseAddress = TempPhysicalBase; + PagingEntry->Uint64 = Random64 (0, MAX_UINT64) & mValidMaskNoLeaf[Level].Uint64; + PagingEntry->Pnle.Bits.Present = 1; + PagingEntry->PleB.Bits.PageTableBaseAddressLow = PageTableBaseAddressLow; + PagingEntry->PleB.Bits.PageTableBaseAddressHigh = PageTableBaseAddressHigh; ASSERT ((PagingEntry->Uint64 & mValidMaskLeafFlag[Level].Uint64) != mValidMaskLeafFlag[Level].Uint64); } - ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)((PagingEntry->Pnle.Bits.PageTableBaseAddress) << 12); + ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)(IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&PagingEntry->Pnle)); for (Index = 0; Index < 512; Index++) { Status = ValidateAndRandomeModifyPageTablePageTableEntry (&ChildPageEntry[Index], Level-1, MaxLeafLevel, Address + (Index<<(9*(Level-1) + 3))); if (Status != UNIT_TEST_PASSED) { @@ -364,10 +371,12 @@ GenerateSingleRandomMapEntry ( } if (mRandomOption & ONLY_ONE_ONE_MAPPING) { - MapEntrys->Maps[MapsIndex].Attribute.Bits.PageTableBaseAddress = MapEntrys->Maps[MapsIndex].LinearAddress >> 12; - MapEntrys->Maps[MapsIndex].Mask.Bits.PageTableBaseAddress = 0xFFFFFFFFFF; + MapEntrys->Maps[MapsIndex].Attribute.Uint64 &= (~IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK); + MapEntrys->Maps[MapsIndex].Attribute.Uint64 |= MapEntrys->Maps[MapsIndex].LinearAddress; + MapEntrys->Maps[MapsIndex].Mask.Uint64 |= IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK; } else { - MapEntrys->Maps[MapsIndex].Attribute.Bits.PageTableBaseAddress = (Random64 (0, (((UINT64)1)<<52) - 1) & AlignedTable[Random32 (0, ARRAY_SIZE (AlignedTable) -1)])>> 12; + MapEntrys->Maps[MapsIndex].Attribute.Uint64 &= (~IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK); + MapEntrys->Maps[MapsIndex].Attribute.Uint64 |= (Random64 (0, (((UINT64)1)<<52) - 1) & AlignedTable[Random32 (0, ARRAY_SIZE (AlignedTable) -1)]); } MapEntrys->Count += 1; @@ -414,8 +423,9 @@ CompareEntrysforOnePoint ( // for (Index = 0; Index < MapCount; Index++) { if ((Address >= Map[Index].LinearAddress) && (Address < (Map[Index].LinearAddress + Map[Index].Length))) { - AttributeInMap.Uint64 = (Map[Index].Attribute.Uint64 & mSupportedBit.Uint64); - AttributeInMap.Bits.PageTableBaseAddress = ((Address - Map[Index].LinearAddress) >> 12) + Map[Index].Attribute.Bits.PageTableBaseAddress; + AttributeInMap.Uint64 = (Map[Index].Attribute.Uint64 & mSupportedBit.Uint64); + AttributeInMap.Uint64 &= (~IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK); + AttributeInMap.Uint64 |= (Address - Map[Index].LinearAddress + IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&Map[Index].Attribute)) & IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK; break; } } @@ -425,8 +435,10 @@ CompareEntrysforOnePoint ( // for (Index = 0; Index < InitMapCount; Index++) { if ((Address >= InitMap[Index].LinearAddress) && (Address < (InitMap[Index].LinearAddress + InitMap[Index].Length))) { - AttributeInInitMap.Uint64 = (InitMap[Index].Attribute.Uint64 & mSupportedBit.Uint64); - AttributeInInitMap.Bits.PageTableBaseAddress = ((Address - InitMap[Index].LinearAddress) >> 12) + InitMap[Index].Attribute.Bits.PageTableBaseAddress; + AttributeInInitMap.Uint64 = (InitMap[Index].Attribute.Uint64 & mSupportedBit.Uint64); + AttributeInInitMap.Uint64 &= (~IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK); + AttributeInInitMap.Uint64 |= (Address - InitMap[Index].LinearAddress + IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&InitMap[Index].Attribute)) & IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK; + break; } } @@ -443,8 +455,9 @@ CompareEntrysforOnePoint ( MaskInMapEntrys.Uint64 |= MapEntrys->Maps[Index].Mask.Uint64; AttributeInMapEntrys.Uint64 &= (~MapEntrys->Maps[Index].Mask.Uint64); AttributeInMapEntrys.Uint64 |= (MapEntrys->Maps[Index].Attribute.Uint64 & MapEntrys->Maps[Index].Mask.Uint64); - if (MapEntrys->Maps[Index].Mask.Bits.PageTableBaseAddress != 0) { - AttributeInMapEntrys.Bits.PageTableBaseAddress = ((Address - MapEntrys->Maps[Index].LinearAddress) >> 12) + MapEntrys->Maps[Index].Attribute.Bits.PageTableBaseAddress; + if (IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&MapEntrys->Maps[Index].Mask) != 0) { + AttributeInMapEntrys.Uint64 &= (~IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK); + AttributeInMapEntrys.Uint64 |= (Address - MapEntrys->Maps[Index].LinearAddress + IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&MapEntrys->Maps[Index].Attribute)) & IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS_MASK; } } } @@ -458,8 +471,8 @@ CompareEntrysforOnePoint ( if ((AttributeInMap.Uint64 & MaskInMapEntrys.Uint64) != (AttributeInMapEntrys.Uint64 & MaskInMapEntrys.Uint64)) { DEBUG ((DEBUG_INFO, "======detailed information begin=====\n")); DEBUG ((DEBUG_INFO, "\nError: Detect different attribute on a point with linear address: 0x%lx\n", Address)); - DEBUG ((DEBUG_INFO, "By parsing page table, the point has Attribute 0x%lx, and map to physical address 0x%lx\n", IA32_MAP_ATTRIBUTE_ATTRIBUTES (&AttributeInMap) & MaskInMapEntrys.Uint64, AttributeInMap.Bits.PageTableBaseAddress)); - DEBUG ((DEBUG_INFO, "While according to inputs, the point should Attribute 0x%lx, and should map to physical address 0x%lx\n", IA32_MAP_ATTRIBUTE_ATTRIBUTES (&AttributeInMapEntrys) & MaskInMapEntrys.Uint64, AttributeInMapEntrys.Bits.PageTableBaseAddress)); + DEBUG ((DEBUG_INFO, "By parsing page table, the point has Attribute 0x%lx, and map to physical address 0x%lx\n", IA32_MAP_ATTRIBUTE_ATTRIBUTES (&AttributeInMap) & MaskInMapEntrys.Uint64, IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&AttributeInMap))); + DEBUG ((DEBUG_INFO, "While according to inputs, the point should Attribute 0x%lx, and should map to physical address 0x%lx\n", IA32_MAP_ATTRIBUTE_ATTRIBUTES (&AttributeInMapEntrys) & MaskInMapEntrys.Uint64, IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&AttributeInMapEntrys))); DEBUG ((DEBUG_INFO, "The total Mask is 0x%lx\n", MaskInMapEntrys.Uint64)); if (MapEntrys->InitCount != 0) { @@ -731,7 +744,7 @@ SingleMapEntryTest ( // if ((Mask->Bits.ReadWrite == 0) || (Mask->Bits.UserSupervisor == 0) || (Mask->Bits.WriteThrough == 0) || (Mask->Bits.CacheDisabled == 0) || (Mask->Bits.Accessed == 0) || (Mask->Bits.Dirty == 0) || (Mask->Bits.Pat == 0) || (Mask->Bits.Global == 0) || - (Mask->Bits.PageTableBaseAddress == 0) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) + ((Mask->Bits.PageTableBaseAddressLow == 0) && (Mask->Bits.PageTableBaseAddressHigh == 0)) || (Mask->Bits.ProtectionKey == 0) || (Mask->Bits.Nx == 0)) { RemoveLastMapEntry (MapEntrys); UT_ASSERT_EQUAL (Status, RETURN_INVALID_PARAMETER); @@ -1016,21 +1029,18 @@ TestCaseforRandomTest ( UT_ASSERT_EQUAL (Random64 (100, 100), 100); UT_ASSERT_TRUE ((Random32 (9, 10) >= 9) & (Random32 (9, 10) <= 10)); UT_ASSERT_TRUE ((Random64 (9, 10) >= 9) & (Random64 (9, 10) <= 10)); - - mSupportedBit.Bits.Present = 1; - mSupportedBit.Bits.ReadWrite = 1; - mSupportedBit.Bits.UserSupervisor = 1; - mSupportedBit.Bits.WriteThrough = 1; - mSupportedBit.Bits.CacheDisabled = 1; - mSupportedBit.Bits.Accessed = 1; - mSupportedBit.Bits.Dirty = 1; - mSupportedBit.Bits.Pat = 1; - mSupportedBit.Bits.Global = 1; - mSupportedBit.Bits.Reserved1 = 0; - mSupportedBit.Bits.PageTableBaseAddress = 0; - mSupportedBit.Bits.Reserved2 = 0; - mSupportedBit.Bits.ProtectionKey = 0xF; - mSupportedBit.Bits.Nx = 1; + mSupportedBit.Uint64 = 0; + mSupportedBit.Bits.Present = 1; + mSupportedBit.Bits.ReadWrite = 1; + mSupportedBit.Bits.UserSupervisor = 1; + mSupportedBit.Bits.WriteThrough = 1; + mSupportedBit.Bits.CacheDisabled = 1; + mSupportedBit.Bits.Accessed = 1; + mSupportedBit.Bits.Dirty = 1; + mSupportedBit.Bits.Pat = 1; + mSupportedBit.Bits.Global = 1; + mSupportedBit.Bits.ProtectionKey = 0xF; + mSupportedBit.Bits.Nx = 1; mRandomOption = ((CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT *)Context)->RandomOption; mNumberIndex = 0; diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c index 10fdee2f94..22f179c21f 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c @@ -140,7 +140,7 @@ IsPageTableEntryValid ( UT_ASSERT_EQUAL ((PagingEntry->Uint64 & mValidMaskNoLeaf[Level].Uint64), PagingEntry->Uint64); } - ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)(((UINTN)(PagingEntry->Pnle.Bits.PageTableBaseAddress)) << 12); + ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)(IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&PagingEntry->Pnle)); for (Index = 0; Index < 512; Index++) { Status = IsPageTableEntryValid (&ChildPageEntry[Index], Level-1, MaxLeafLevel, Address + (Index<<(9*(Level-1) + 3))); if (Status != UNIT_TEST_PASSED) { @@ -233,7 +233,7 @@ GetEntryFromSubPageTable ( // // Not a leaf // - ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)(((UINTN)(PagingEntry->Pnle.Bits.PageTableBaseAddress)) << 12); + ChildPageEntry = (IA32_PAGING_ENTRY *)(UINTN)(IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&PagingEntry->Pnle)); *Level = *Level -1; Index = Address >> (*Level * 9 + 3); ASSERT (Index == (Index & ((1<< 9) - 1))); From 2ba5104574a379419e993d7a165acee4ee870910 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Mon, 20 Mar 2023 12:24:17 +0800 Subject: [PATCH 0740/1529] UefiCpuPkg/CpuPageTableLib: Add check for page table creation Add code to compare ParentPagingEntry Attribute&Mask and input Attribute&Mask to decide if new next level page table is needed in non-present ParentPagingEntry condition. This can help avoid unneccessary page table creation. For example, there is a page table in which [0, 1G] is mapped(Lv4[0] ,Lv3[0,0], a non-leaf level4 entry and a leaf level3 entry).And we only want to map [1G, 1G+2M] linear address still as non-present. The expected behaviour should be nothing happens in the process. However, previous code logic doesn't check if ParentPagingEntry Attribute&Mask and input Attribute&Mask are the same in non-present ParentPagingEntry condition. Then a new 4K memory is allocated for Lv2 since 1G+2M is not 1G-aligned. So when ParentPagingEntry is non-present, before allocate 4K memory for next level paging, we also check if ParentPagingEntry Attribute& Mask and input Attribute&Mask are the same. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 7936333e01..11cca8ccbc 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -361,6 +361,16 @@ PageTableLibMapInLevel ( return Status; } + // + // Check the attribute in ParentPagingEntry is equal to attribute calculated by input Attribue and Mask. + // + PleBAttribute.Uint64 = PageTableLibGetPleBMapAttribute (&ParentPagingEntry->PleB, ParentAttribute); + if ((IA32_MAP_ATTRIBUTE_ATTRIBUTES (&PleBAttribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask)) + == (IA32_MAP_ATTRIBUTE_ATTRIBUTES (Attribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask))) + { + return RETURN_SUCCESS; + } + // // The parent entry is CR3 or PML5E/PML4E/PDPTE/PDE. // It does NOT point to an existing page directory. From 589981c0db38aef9828e64596a59a95f5032d913 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 23 Mar 2023 15:16:20 +0800 Subject: [PATCH 0741/1529] UefiCpuPkg: Combine branch for non-present and leaf ParentEntry Combine 'if' condition branch for non-present and leaf Parent Entry in PageTableLibMapInLevel. Most steps of these two condition are the same. This commit doesn't change any functionality. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../Library/CpuPageTableLib/CpuPageTableMap.c | 85 +++++++------------ 1 file changed, 32 insertions(+), 53 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 11cca8ccbc..0d576ce39a 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -351,68 +351,45 @@ PageTableLibMapInLevel ( // ParentPagingEntry ONLY is deferenced for checking Present and MustBeOne bits // when Modify is FALSE. // - - if (ParentPagingEntry->Pce.Present == 0) { - // - // [LinearAddress, LinearAddress + Length] contains non-present range. - // - Status = IsAttributesAndMaskValidForNonPresentEntry (Attribute, Mask); - if (RETURN_ERROR (Status)) { - return Status; - } - - // - // Check the attribute in ParentPagingEntry is equal to attribute calculated by input Attribue and Mask. - // - PleBAttribute.Uint64 = PageTableLibGetPleBMapAttribute (&ParentPagingEntry->PleB, ParentAttribute); - if ((IA32_MAP_ATTRIBUTE_ATTRIBUTES (&PleBAttribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask)) - == (IA32_MAP_ATTRIBUTE_ATTRIBUTES (Attribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask))) - { - return RETURN_SUCCESS; - } - + if ((ParentPagingEntry->Pce.Present == 0) || IsPle (ParentPagingEntry, Level + 1)) { // - // The parent entry is CR3 or PML5E/PML4E/PDPTE/PDE. + // When ParentPagingEntry is non-present, parent entry is CR3 or PML5E/PML4E/PDPTE/PDE. // It does NOT point to an existing page directory. + // When ParentPagingEntry is present, parent entry is leaf PDPTE_1G or PDE_2M. Split to 2M or 4K pages. + // Note: it's impossible the parent entry is a PTE_4K. // - ASSERT (Buffer == NULL || *BufferSize >= SIZE_4KB); - CreateNew = TRUE; - *BufferSize -= SIZE_4KB; - - if (Modify) { - ParentPagingEntry->Uintn = (UINTN)Buffer + *BufferSize; - ZeroMem ((VOID *)ParentPagingEntry->Uintn, SIZE_4KB); - // - // Set default attribute bits for PML5E/PML4E/PDPTE/PDE. - // - PageTableLibSetPnle (&ParentPagingEntry->Pnle, &NopAttribute, &AllOneMask); - } else { + PleBAttribute.Uint64 = PageTableLibGetPleBMapAttribute (&ParentPagingEntry->PleB, ParentAttribute); + if (ParentPagingEntry->Pce.Present == 0) { // - // Just make sure Present and MustBeZero (PageSize) bits are accurate. + // [LinearAddress, LinearAddress + Length] contains non-present range. // + Status = IsAttributesAndMaskValidForNonPresentEntry (Attribute, Mask); + if (RETURN_ERROR (Status)) { + return Status; + } + OneOfPagingEntry.Pnle.Uint64 = 0; + } else { + PageTableLibSetPle (Level, &OneOfPagingEntry, 0, &PleBAttribute, &AllOneMask); } - } else if (IsPle (ParentPagingEntry, Level + 1)) { - // - // The parent entry is a PDPTE_1G or PDE_2M. Split to 2M or 4K pages. - // Note: it's impossible the parent entry is a PTE_4K. - // + // - // Use NOP attributes as the attribute of grand-parents because CPU will consider - // the actual attributes of grand-parents when determing the memory type. + // Check if the attribute, the physical address calculated by ParentPagingEntry is equal to + // the attribute, the physical address calculated by input Attribue and Mask. // - PleBAttribute.Uint64 = PageTableLibGetPleBMapAttribute (&ParentPagingEntry->PleB, ParentAttribute); if ((IA32_MAP_ATTRIBUTE_ATTRIBUTES (&PleBAttribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask)) == (IA32_MAP_ATTRIBUTE_ATTRIBUTES (Attribute) & IA32_MAP_ATTRIBUTE_ATTRIBUTES (Mask))) { - // - // This function is called when the memory length is less than the region length of the parent level. - // No need to split the page when the attributes equal. - // if ((Mask->Bits.PageTableBaseAddressLow == 0) && (Mask->Bits.PageTableBaseAddressHigh == 0)) { return RETURN_SUCCESS; } + // + // Non-present entry won't reach there since: + // 1.When map non-present entry to present, the attribute must be different. + // 2.When still map non-present entry to non-present, PageTableBaseAddressLow and High in Mask must be 0. + // + ASSERT (ParentPagingEntry->Pce.Present == 1); PhysicalAddrInEntry = IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (&PleBAttribute) + MultU64x32 (RegionLength, (UINT32)PagingEntryIndex); PhysicalAddrInAttr = (IA32_MAP_ATTRIBUTE_PAGE_TABLE_BASE_ADDRESS (Attribute) + Offset) & (~RegionMask); if (PhysicalAddrInEntry == PhysicalAddrInAttr) { @@ -423,17 +400,19 @@ PageTableLibMapInLevel ( ASSERT (Buffer == NULL || *BufferSize >= SIZE_4KB); CreateNew = TRUE; *BufferSize -= SIZE_4KB; - PageTableLibSetPle (Level, &OneOfPagingEntry, 0, &PleBAttribute, &AllOneMask); + if (Modify) { - // - // Create 512 child-level entries that map to 2M/4K. - // PagingEntry = (IA32_PAGING_ENTRY *)((UINTN)Buffer + *BufferSize); ZeroMem (PagingEntry, SIZE_4KB); - for (SubOffset = 0, Index = 0; Index < 512; Index++) { - PagingEntry[Index].Uint64 = OneOfPagingEntry.Uint64 + SubOffset; - SubOffset += RegionLength; + if (ParentPagingEntry->Pce.Present) { + // + // Create 512 child-level entries that map to 2M/4K. + // + for (SubOffset = 0, Index = 0; Index < 512; Index++) { + PagingEntry[Index].Uint64 = OneOfPagingEntry.Uint64 + SubOffset; + SubOffset += RegionLength; + } } // From 6e7db5b0965fadaab094cf1a3c8e5df57d3676b7 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Wed, 22 Mar 2023 15:20:20 +0800 Subject: [PATCH 0742/1529] UefiCpuPkg/CpuPageTableLib: Enable PAE paging Modify CpuPageTableLib code to enable PAE paging. In PageTableMap() API: When creating new PAE page table, after creating page table, set all MustBeZero fields of 4 PDPTE to 0. The MustBeZero fields are treated as RW and other attributes by the common map logic. So they might be set to 1. When updating exsiting PAE page table, the special steps are: 1.Prepare 4K-aligned 32bytes memory in stack for 4 temp PDPTE. 2.Copy original 4 PDPTE to the 4 temp PDPTE and set the RW, UserSupervisor to 1 and set Nx of 4 temp PDPTE to 0. 4.After updating the page table, set the MustBeZero fields of 4 temp PDPTE to 0. 5.Copy the temp PDPTE to original PDPTE. In PageTableParse() API, also create 4 temp PDPTE in stack. Copy original 4 PDPTE to the 4 temp PDPTE. Then set the RW, UserSupervisor to 1 and set Nx of 4 temp PDPTE to 0. Finally use the address of temp PDPTE as the page table address. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../Library/CpuPageTableLib/CpuPageTable.h | 4 +- .../Library/CpuPageTableLib/CpuPageTableMap.c | 53 +++++++++++++++++-- .../CpuPageTableLib/CpuPageTableParse.c | 27 ++++++++-- 3 files changed, 73 insertions(+), 11 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h index 2c67ecb469..24da0ffb30 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTable.h @@ -1,7 +1,7 @@ /** @file Internal header for CpuPageTableLib. - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -20,6 +20,8 @@ #define REGION_LENGTH(l) LShiftU64 (1, (l) * 9 + 3) +#define MAX_PAE_PDPTE_NUM 4 + typedef enum { Pte = 1, Pde = 2, diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c index 0d576ce39a..eff02619fa 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableMap.c @@ -671,15 +671,17 @@ PageTableMap ( IA32_PAGE_LEVEL MaxLeafLevel; IA32_MAP_ATTRIBUTE ParentAttribute; BOOLEAN LocalIsModified; + UINTN Index; + IA32_PAGING_ENTRY *PagingEntry; + UINT8 BufferInStack[SIZE_4KB - 1 + MAX_PAE_PDPTE_NUM * sizeof (IA32_PAGING_ENTRY)]; if (Length == 0) { return RETURN_SUCCESS; } - if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { + if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. - // PAE paging will be supported later. // return RETURN_UNSUPPORTED; } @@ -716,17 +718,32 @@ PageTableMap ( MaxLeafLevel = (IA32_PAGE_LEVEL)(UINT8)PagingMode; MaxLevel = (IA32_PAGE_LEVEL)(UINT8)(PagingMode >> 8); - MaxLinearAddress = LShiftU64 (1, 12 + MaxLevel * 9); + MaxLinearAddress = (PagingMode == PagingPae) ? LShiftU64 (1, 32) : LShiftU64 (1, 12 + MaxLevel * 9); if ((LinearAddress > MaxLinearAddress) || (Length > MaxLinearAddress - LinearAddress)) { // - // Maximum linear address is (1 << 48) or (1 << 57) + // Maximum linear address is (1 << 32), (1 << 48) or (1 << 57) // return RETURN_INVALID_PARAMETER; } TopPagingEntry.Uintn = *PageTable; if (TopPagingEntry.Uintn != 0) { + if (PagingMode == PagingPae) { + // + // Create 4 temporary PDPTE at a 4k-aligned address. + // Copy the original PDPTE content and set ReadWrite, UserSupervisor to 1, set Nx to 0. + // + TopPagingEntry.Uintn = ALIGN_VALUE ((UINTN)BufferInStack, BASE_4KB); + PagingEntry = (IA32_PAGING_ENTRY *)(TopPagingEntry.Uintn); + CopyMem (PagingEntry, (VOID *)(*PageTable), MAX_PAE_PDPTE_NUM * sizeof (IA32_PAGING_ENTRY)); + for (Index = 0; Index < MAX_PAE_PDPTE_NUM; Index++) { + PagingEntry[Index].Pnle.Bits.ReadWrite = 1; + PagingEntry[Index].Pnle.Bits.UserSupervisor = 1; + PagingEntry[Index].Pnle.Bits.Nx = 0; + } + } + TopPagingEntry.Pce.Present = 1; TopPagingEntry.Pce.ReadWrite = 1; TopPagingEntry.Pce.UserSupervisor = 1; @@ -801,7 +818,33 @@ PageTableMap ( ); if (!RETURN_ERROR (Status)) { - *PageTable = (UINTN)(TopPagingEntry.Uintn & IA32_PE_BASE_ADDRESS_MASK_40); + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)(TopPagingEntry.Uintn & IA32_PE_BASE_ADDRESS_MASK_40); + + if (PagingMode == PagingPae) { + // + // These MustBeZero fields are treated as RW and other attributes by the common map logic. So they might be set to 1. + // + for (Index = 0; Index < MAX_PAE_PDPTE_NUM; Index++) { + PagingEntry[Index].PdptePae.Bits.MustBeZero = 0; + PagingEntry[Index].PdptePae.Bits.MustBeZero2 = 0; + PagingEntry[Index].PdptePae.Bits.MustBeZero3 = 0; + } + + if (*PageTable != 0) { + // + // Copy temp PDPTE to original PDPTE. + // + CopyMem ((VOID *)(*PageTable), PagingEntry, MAX_PAE_PDPTE_NUM * sizeof (IA32_PAGING_ENTRY)); + } + } + + if (*PageTable == 0) { + // + // Do not assign the *PageTable when it's an existing page table. + // If it's an existing PAE page table, PagingEntry is the temp buffer in stack. + // + *PageTable = (UINTN)PagingEntry; + } } return Status; diff --git a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c index 65490751ab..37466e4e10 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableParse.c @@ -1,7 +1,7 @@ /** @file This library implements CpuPageTableLib that are generic for IA32 family CPU. - Copyright (c) 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2022 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -158,6 +158,7 @@ VOID PageTableLibParsePnle ( IN UINT64 PageTableBaseAddress, IN UINTN Level, + IN UINTN MaxLevel, IN UINT64 RegionStart, IN IA32_MAP_ATTRIBUTE *ParentMapAttribute, IN OUT IA32_MAP_ENTRY *Map, @@ -171,13 +172,15 @@ PageTableLibParsePnle ( UINTN Index; IA32_MAP_ATTRIBUTE MapAttribute; UINT64 RegionLength; + UINTN PagingEntryNumber; ASSERT (OneEntry != NULL); - PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)PageTableBaseAddress; - RegionLength = REGION_LENGTH (Level); + PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)PageTableBaseAddress; + RegionLength = REGION_LENGTH (Level); + PagingEntryNumber = ((MaxLevel == 3) && (Level == 3)) ? MAX_PAE_PDPTE_NUM : 512; - for (Index = 0; Index < 512; Index++, RegionStart += RegionLength) { + for (Index = 0; Index < PagingEntryNumber; Index++, RegionStart += RegionLength) { if (PagingEntry[Index].Pce.Present == 0) { continue; } @@ -228,6 +231,7 @@ PageTableLibParsePnle ( PageTableLibParsePnle ( IA32_PNLE_PAGE_TABLE_BASE_ADDRESS (&PagingEntry[Index].Pnle), Level - 1, + MaxLevel, RegionStart, &MapAttribute, Map, @@ -269,6 +273,8 @@ PageTableParse ( IA32_MAP_ENTRY *LastEntry; IA32_MAP_ENTRY OneEntry; UINTN MaxLevel; + UINTN Index; + IA32_PAGING_ENTRY BufferInStack[MAX_PAE_PDPTE_NUM]; if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // @@ -290,6 +296,17 @@ PageTableParse ( return RETURN_SUCCESS; } + if (PagingMode == PagingPae) { + CopyMem (BufferInStack, (VOID *)PageTable, sizeof (BufferInStack)); + for (Index = 0; Index < MAX_PAE_PDPTE_NUM; Index++) { + BufferInStack[Index].Pnle.Bits.ReadWrite = 1; + BufferInStack[Index].Pnle.Bits.UserSupervisor = 1; + BufferInStack[Index].Pnle.Bits.Nx = 0; + } + + PageTable = (UINTN)BufferInStack; + } + // // Page table layout is as below: // @@ -319,7 +336,7 @@ PageTableParse ( MapCapacity = *MapCount; *MapCount = 0; LastEntry = NULL; - PageTableLibParsePnle ((UINT64)PageTable, MaxLevel, 0, &NopAttribute, Map, MapCount, MapCapacity, &LastEntry, &OneEntry); + PageTableLibParsePnle ((UINT64)PageTable, MaxLevel, MaxLevel, 0, &NopAttribute, Map, MapCount, MapCapacity, &LastEntry, &OneEntry); if (*MapCount > MapCapacity) { return RETURN_BUFFER_TOO_SMALL; From 43692d4d303b1d946c2348f2829bde7af0524411 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Wed, 22 Mar 2023 12:14:30 +0800 Subject: [PATCH 0743/1529] UefiCpuPkg/CpuPageTableLib: Add RandomTest for PAE paging Add RandomTest for PAE paging. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 2 ++ .../Library/CpuPageTableLib/UnitTest/RandomTest.c | 3 +-- .../Library/CpuPageTableLib/UnitTest/TestHelper.c | 12 ++++++++---- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index 4303095579..b0be2c5a73 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -13,6 +13,7 @@ static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { P static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 100, 20, USE_RANDOM_ARRAY }; static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 100, 20, USE_RANDOM_ARRAY }; static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 100, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPagingPae = { PagingPae, 100, 20, USE_RANDOM_ARRAY }; /** Check if the input parameters are not supported. @@ -884,6 +885,7 @@ UefiTestMain ( AddTestCase (RandomTestCase, "Random Test for Paging4Level1G", "Random Test Case2", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging4Level1GB); AddTestCase (RandomTestCase, "Random Test for Paging5Level", "Random Test Case3", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level); AddTestCase (RandomTestCase, "Random Test for Paging5Level1G", "Random Test Case4", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level1GB); + AddTestCase (RandomTestCase, "Random Test for PagingPae", "Random Test Case5", TestCaseforRandomTest, NULL, NULL, &mTestContextPagingPae); // // Execute the tests. diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c index 2db49f7de7..f7a77d00e7 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/RandomTest.c @@ -258,10 +258,9 @@ ValidateAndRandomeModifyPageTable ( UNIT_TEST_STATUS Status; IA32_PAGING_ENTRY *PagingEntry; - if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { + if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. - // PAE paging will be supported later. // return UNIT_TEST_ERROR_TEST_FAILED; } diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c index 22f179c21f..67776255c2 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/TestHelper.c @@ -175,10 +175,9 @@ IsPageTableValid ( return UNIT_TEST_PASSED; } - if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { + if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. - // PAE paging will be supported later. // return UNIT_TEST_ERROR_TEST_FAILED; } @@ -187,7 +186,12 @@ IsPageTableValid ( MaxLevel = (UINT8)(PagingMode >> 8); PagingEntry = (IA32_PAGING_ENTRY *)(UINTN)PageTable; - for (Index = 0; Index < 512; Index++) { + for (Index = 0; Index < ((PagingMode == PagingPae) ? 4 : 512); Index++) { + if (PagingMode == PagingPae) { + UT_ASSERT_EQUAL (PagingEntry[Index].PdptePae.Bits.MustBeZero, 0); + UT_ASSERT_EQUAL (PagingEntry[Index].PdptePae.Bits.MustBeZero2, 0); + } + Status = IsPageTableEntryValid (&PagingEntry[Index], MaxLevel, MaxLeafLevel, Index << (9 * MaxLevel + 3)); if (Status != UNIT_TEST_PASSED) { return Status; @@ -264,7 +268,7 @@ GetEntryFromPageTable ( UINT64 Index; IA32_PAGING_ENTRY *PagingEntry; - if ((PagingMode == Paging32bit) || (PagingMode == PagingPae) || (PagingMode >= PagingModeMax)) { + if ((PagingMode == Paging32bit) || (PagingMode >= PagingModeMax)) { // // 32bit paging is never supported. // PAE paging will be supported later. From d9b50c8a30152bdb3827195e363915528619d0e3 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Wed, 22 Mar 2023 16:28:55 +0800 Subject: [PATCH 0744/1529] UefiCpuPkg/CpuPageTableLib: Reduce the number of random tests Reduce the number of random tests. In previous patch, non-1:1 mapping is enbaled and it may need more than an hour and a half for the CI test, which may lead to CI timeout. Reduce the number of random test count to pass the CI. Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Tested-by: Gerd Hoffmann Acked-by: Gerd Hoffmann --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index b0be2c5a73..547f6c2e50 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -9,11 +9,11 @@ #include "CpuPageTableLibUnitTest.h" // ----------------------------------------------------------------------- PageMode--TestCount-TestRangeCount---RandomOptions -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 100, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 100, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 100, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 100, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPagingPae = { PagingPae, 100, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 30, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 30, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 30, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 30, 20, USE_RANDOM_ARRAY }; +static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPagingPae = { PagingPae, 30, 20, USE_RANDOM_ARRAY }; /** Check if the input parameters are not supported. From b2d0c18828c70016570b0109c0ea582f7bc1d882 Mon Sep 17 00:00:00 2001 From: Umang Patel Date: Fri, 13 Jan 2023 03:01:14 -0800 Subject: [PATCH 0745/1529] MdeModulePkg/Include/Ppi: Add FirmwareVolumeShadowPpi Add FirmwareVolumeShadow PPI to shadow an FV to memory. Cc: Jian J Wang Cc: Liming Gao Signed-off-by: Patel Umang Reviewed-by: Jian J Wang --- .../Include/Ppi/FirmwareVolumeShadowPpi.h | 61 +++++++++++++++++++ MdeModulePkg/MdeModulePkg.dec | 3 + 2 files changed, 64 insertions(+) create mode 100644 MdeModulePkg/Include/Ppi/FirmwareVolumeShadowPpi.h diff --git a/MdeModulePkg/Include/Ppi/FirmwareVolumeShadowPpi.h b/MdeModulePkg/Include/Ppi/FirmwareVolumeShadowPpi.h new file mode 100644 index 0000000000..a2756cb0ab --- /dev/null +++ b/MdeModulePkg/Include/Ppi/FirmwareVolumeShadowPpi.h @@ -0,0 +1,61 @@ +/** @file + Define PPI to shadow Firmware Volume from flash to Permanent Memory. + +Copyright (c) 2023, Intel Corporation. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef PEI_FIRMWARE_VOLUME_SHADOW_PPI_H_ +#define PEI_FIRMWARE_VOLUME_SHADOW_PPI_H_ + +// +// Firmware Volume Shadow PPI GUID value +// +#define EDKII_FIRMWARE_VOLUME_SHADOW_PPI_GUID \ + { \ + 0x7dfe756c, 0xed8d, 0x4d77, { 0x9e, 0xc4, 0x39, 0x9a, 0x8a, 0x81, 0x51, 0x16 } \ + } + +/** + Copy FV to Destination. Length of copy is FV length from FV Header. + + @param[in] FirmwareVolumeBase Base address of FV to shadow. Length of FV + is in FV Header. + @param[in] Destination Pointer to the Buffer in system memory to + shadow FV. + @param[in] DestinationLength Size of Destination buffer in bytes. + + @retval EFI_SUCCESS Shadow complete + @retval EFI_INVALID_PARAMETER Destination is NULL + @retval EFI_INVALID_PARAMETER DestinationLength = 0. + @retval EFI_INVALID_PARAMETER FV does not have valid FV Header. + @retval EFI_INVALID_PARAMETER FV overlaps Destination. + @retval EFI_INVALID_PARAMETER Destination + DestinationLength rolls over 4GB + for 32-bit or 64-bit rollover. + @retval EFI_BUFFER_TOO_SMALL DestinationLength less than FV length from FV + Header. + @retval EFI_UNSUPPORTED FirmwareVolumeBase to FVBase + FVLength does + not support shadow. Caller should fallback to + CopyMem(). + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_PEI_FIRMWARE_VOLUME_SHADOW)( + IN EFI_PHYSICAL_ADDRESS FirmwareVolumeBase, + IN VOID *Destination, + IN UINTN DestinationLength + ); + +/// +/// This PPI provides a service to shadow a FV from one location to another +/// +typedef struct { + EDKII_PEI_FIRMWARE_VOLUME_SHADOW FirmwareVolumeShadow; +} EDKII_PEI_FIRMWARE_VOLUME_SHADOW_PPI; + +extern EFI_GUID gEdkiiPeiFirmwareVolumeShadowPpiGuid; + +#endif diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index e8058c8bfa..3eb4a79bf7 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -442,6 +442,9 @@ gBootDiscoveryPolicyMgrFormsetGuid = { 0x5b6f7107, 0xbb3c, 0x4660, { 0x92, 0xcd, 0x54, 0x26, 0x90, 0x28, 0x0b, 0xbd } } [Ppis] + ## Include/Ppi/FirmwareVolumeShadowPpi.h + gEdkiiPeiFirmwareVolumeShadowPpiGuid = { 0x7dfe756c, 0xed8d, 0x4d77, {0x9e, 0xc4, 0x39, 0x9a, 0x8a, 0x81, 0x51, 0x16 } } + ## Include/Ppi/AtaController.h gPeiAtaControllerPpiGuid = { 0xa45e60d1, 0xc719, 0x44aa, { 0xb0, 0x7a, 0xaa, 0x77, 0x7f, 0x85, 0x90, 0x6d }} From 12ad7445be8ea9c5c76165116886210d88078fbd Mon Sep 17 00:00:00 2001 From: Umang Patel Date: Tue, 21 Mar 2023 17:02:34 -0700 Subject: [PATCH 0746/1529] SecurityPkg/FvReportPei: Use FirmwareVolumeShadowPpi If FirmwareVolumeShadow PPI is available, then use it to shadow FVs to memory. Otherwise fallback to CopyMem(). Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Patel Umang Reviewed-by: Jian J Wang --- SecurityPkg/FvReportPei/FvReportPei.c | 37 ++++++++++++++++++++----- SecurityPkg/FvReportPei/FvReportPei.h | 1 + SecurityPkg/FvReportPei/FvReportPei.inf | 1 + 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/SecurityPkg/FvReportPei/FvReportPei.c b/SecurityPkg/FvReportPei/FvReportPei.c index 846605cda1..6288dde16b 100644 --- a/SecurityPkg/FvReportPei/FvReportPei.c +++ b/SecurityPkg/FvReportPei/FvReportPei.c @@ -114,12 +114,13 @@ VerifyHashedFv ( IN EFI_BOOT_MODE BootMode ) { - UINTN FvIndex; - CONST HASH_ALG_INFO *AlgInfo; - UINT8 *HashValue; - UINT8 *FvHashValue; - VOID *FvBuffer; - EFI_STATUS Status; + UINTN FvIndex; + CONST HASH_ALG_INFO *AlgInfo; + UINT8 *HashValue; + UINT8 *FvHashValue; + VOID *FvBuffer; + EDKII_PEI_FIRMWARE_VOLUME_SHADOW_PPI *FvShadowPpi; + EFI_STATUS Status; if ((HashInfo == NULL) || (HashInfo->HashSize == 0) || @@ -191,8 +192,30 @@ VerifyHashedFv ( // Copy FV to permanent memory to avoid potential TOC/TOU. // FvBuffer = AllocatePages (EFI_SIZE_TO_PAGES ((UINTN)FvInfo[FvIndex].Length)); + ASSERT (FvBuffer != NULL); - CopyMem (FvBuffer, (CONST VOID *)(UINTN)FvInfo[FvIndex].Base, (UINTN)FvInfo[FvIndex].Length); + Status = PeiServicesLocatePpi ( + &gEdkiiPeiFirmwareVolumeShadowPpiGuid, + 0, + NULL, + (VOID **)&FvShadowPpi + ); + + if (!EFI_ERROR (Status)) { + Status = FvShadowPpi->FirmwareVolumeShadow ( + (EFI_PHYSICAL_ADDRESS)FvInfo[FvIndex].Base, + FvBuffer, + (UINTN)FvInfo[FvIndex].Length + ); + } + + if (EFI_ERROR (Status)) { + CopyMem ( + FvBuffer, + (CONST VOID *)(UINTN)FvInfo[FvIndex].Base, + (UINTN)FvInfo[FvIndex].Length + ); + } if (!AlgInfo->HashAll (FvBuffer, (UINTN)FvInfo[FvIndex].Length, FvHashValue)) { Status = EFI_ABORTED; diff --git a/SecurityPkg/FvReportPei/FvReportPei.h b/SecurityPkg/FvReportPei/FvReportPei.h index 92504a3c51..07ffb2f576 100644 --- a/SecurityPkg/FvReportPei/FvReportPei.h +++ b/SecurityPkg/FvReportPei/FvReportPei.h @@ -14,6 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include +#include #include #include diff --git a/SecurityPkg/FvReportPei/FvReportPei.inf b/SecurityPkg/FvReportPei/FvReportPei.inf index 4084068897..4246fb75eb 100644 --- a/SecurityPkg/FvReportPei/FvReportPei.inf +++ b/SecurityPkg/FvReportPei/FvReportPei.inf @@ -46,6 +46,7 @@ [Ppis] gEdkiiPeiFirmwareVolumeInfoPrehashedFvPpiGuid ## PRODUCES gEdkiiPeiFirmwareVolumeInfoStoredHashFvPpiGuid ## CONSUMES + gEdkiiPeiFirmwareVolumeShadowPpiGuid ## CONSUMES [Pcd] gEfiSecurityPkgTokenSpaceGuid.PcdStatusCodeFvVerificationPass From 7a9c3ab2fb7d0cea0e2c506c21c52baeb6c2f373 Mon Sep 17 00:00:00 2001 From: Sunil V L Date: Sat, 18 Mar 2023 23:15:11 +0530 Subject: [PATCH 0747/1529] OvmfPkg/RiscVVirt: Support multiple reserved memory ranges M-mode firmware ranges should not be used by EDK2/OS. Currently, we search for mmode_resv0 node in FDT and mark it as the reserved memory in EFI memory map. However, if there are multiple M-mode firmware ranges, then this will miss those extra ranges allowing the OS to access the memory and hit a fault. This issue is exposed since recent opensbi started creating two ranges for text and data. Fix this by searching for all reserved memory nodes and marking them as reserved in the EFI memory map. Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: Andrei Warkentin Signed-off-by: Sunil V L Reviewed-by: Andrei Warkentin --- OvmfPkg/RiscVVirt/Sec/Memory.c | 226 ++++++++++++++++++++++----------- 1 file changed, 149 insertions(+), 77 deletions(-) diff --git a/OvmfPkg/RiscVVirt/Sec/Memory.c b/OvmfPkg/RiscVVirt/Sec/Memory.c index 70935b07b5..f7a72c7bb4 100644 --- a/OvmfPkg/RiscVVirt/Sec/Memory.c +++ b/OvmfPkg/RiscVVirt/Sec/Memory.c @@ -38,31 +38,6 @@ BuildMemoryTypeInformationHob ( VOID ); -/** - Build reserved memory range resource HOB. - - @param MemoryBase Reserved memory range base address. - @param MemorySize Reserved memory range size. - -**/ -STATIC -VOID -AddReservedMemoryBaseSizeHob ( - EFI_PHYSICAL_ADDRESS MemoryBase, - UINT64 MemorySize - ) -{ - BuildResourceDescriptorHob ( - EFI_RESOURCE_MEMORY_RESERVED, - EFI_RESOURCE_ATTRIBUTE_PRESENT | - EFI_RESOURCE_ATTRIBUTE_INITIALIZED | - EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | - EFI_RESOURCE_ATTRIBUTE_TESTED, - MemoryBase, - MemorySize - ); -} - /** Create memory range resource HOB using the memory base address and size. @@ -74,8 +49,8 @@ AddReservedMemoryBaseSizeHob ( STATIC VOID AddMemoryBaseSizeHob ( - EFI_PHYSICAL_ADDRESS MemoryBase, - UINT64 MemorySize + IN EFI_PHYSICAL_ADDRESS MemoryBase, + IN UINT64 MemorySize ) { BuildResourceDescriptorHob ( @@ -103,8 +78,8 @@ AddMemoryBaseSizeHob ( STATIC VOID AddMemoryRangeHob ( - EFI_PHYSICAL_ADDRESS MemoryBase, - EFI_PHYSICAL_ADDRESS MemoryLimit + IN EFI_PHYSICAL_ADDRESS MemoryBase, + IN EFI_PHYSICAL_ADDRESS MemoryLimit ) { AddMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase)); @@ -132,39 +107,152 @@ InitMmu ( STATIC VOID InitializeRamRegions ( - EFI_PHYSICAL_ADDRESS SystemMemoryBase, - UINT64 SystemMemorySize, - EFI_PHYSICAL_ADDRESS MmodeResvBase, - UINT64 MmodeResvSize + IN EFI_PHYSICAL_ADDRESS SystemMemoryBase, + IN UINT64 SystemMemorySize ) { - /* - * M-mode FW can be loaded anywhere in memory but should not overlap - * with the EDK2. This can happen if some other boot code loads the - * M-mode firmware. - * - * The M-mode firmware memory should be marked as reserved memory - * so that OS doesn't use it. - */ - DEBUG (( - DEBUG_INFO, - "%a: M-mode FW Memory Start:0x%lx End:0x%lx\n", - __FUNCTION__, - MmodeResvBase, - MmodeResvBase + MmodeResvSize - )); - AddReservedMemoryBaseSizeHob (MmodeResvBase, MmodeResvSize); - - if (MmodeResvBase > SystemMemoryBase) { - AddMemoryRangeHob (SystemMemoryBase, MmodeResvBase); - } - AddMemoryRangeHob ( - MmodeResvBase + MmodeResvSize, + SystemMemoryBase, SystemMemoryBase + SystemMemorySize ); } +/** Get the number of cells for a given property + + @param[in] Fdt Pointer to Device Tree (DTB) + @param[in] Node Node + @param[in] Name Name of the property + + @return Number of cells. +**/ +STATIC +INT32 +GetNumCells ( + IN VOID *Fdt, + IN INT32 Node, + IN CONST CHAR8 *Name + ) +{ + CONST INT32 *Prop; + INT32 Len; + UINT32 Val; + + Prop = fdt_getprop (Fdt, Node, Name, &Len); + if (Prop == NULL) { + return Len; + } + + if (Len != sizeof (*Prop)) { + return -FDT_ERR_BADNCELLS; + } + + Val = fdt32_to_cpu (*Prop); + if (Val > FDT_MAX_NCELLS) { + return -FDT_ERR_BADNCELLS; + } + + return (INT32)Val; +} + +/** Mark reserved memory ranges in the EFI memory map + + The M-mode firmware ranges should not be used by the + EDK2/OS. These ranges are passed via device tree using reserved + memory nodes. Parse the DT and mark those ranges as of + type EfiReservedMemoryType. + + NOTE: Device Tree spec section 3.5.4 says reserved memory regions + without no-map property should be installed as EfiBootServicesData. + As per UEFI spec, memory of type EfiBootServicesData can be used + by the OS after ExitBootServices(). + This is not an issue for DT since OS can parse the DT also along + with EFI memory map and avoid using these ranges. But with ACPI, + there is no such mechanisms possible. + Since EDK2 needs to support both DT and ACPI, we are deviating + from the DT spec and marking all reserved memory ranges as + EfiReservedMemoryType itself irrespective of no-map. + + @param FdtPointer Pointer to FDT + +**/ +STATIC +VOID +AddReservedMemoryMap ( + IN VOID *FdtPointer + ) +{ + CONST INT32 *RegProp; + INT32 Node; + INT32 SubNode; + INT32 Len; + EFI_PHYSICAL_ADDRESS Addr; + UINT64 Size; + INTN NumRsv, i; + INT32 NumAddrCells, NumSizeCells; + + NumRsv = fdt_num_mem_rsv (FdtPointer); + + /* Look for an existing entry and add it to the efi mem map. */ + for (i = 0; i < NumRsv; i++) { + if (fdt_get_mem_rsv (FdtPointer, i, &Addr, &Size) != 0) { + continue; + } + + BuildMemoryAllocationHob ( + Addr, + Size, + EfiReservedMemoryType + ); + } + + /* process reserved-memory */ + Node = fdt_subnode_offset (FdtPointer, 0, "reserved-memory"); + if (Node >= 0) { + NumAddrCells = GetNumCells (FdtPointer, Node, "#address-cells"); + if (NumAddrCells <= 0) { + return; + } + + NumSizeCells = GetNumCells (FdtPointer, Node, "#size-cells"); + if (NumSizeCells <= 0) { + return; + } + + fdt_for_each_subnode (SubNode, FdtPointer, Node) { + RegProp = fdt_getprop (FdtPointer, SubNode, "reg", &Len); + + if ((RegProp != 0) && (Len == ((NumAddrCells + NumSizeCells) * sizeof (INT32)))) { + Addr = fdt32_to_cpu (RegProp[0]); + + if (NumAddrCells > 1) { + Addr = (Addr << 32) | fdt32_to_cpu (RegProp[1]); + } + + RegProp += NumAddrCells; + Size = fdt32_to_cpu (RegProp[0]); + + if (NumSizeCells > 1) { + Size = (Size << 32) | fdt32_to_cpu (RegProp[1]); + } + + DEBUG (( + DEBUG_INFO, + "%a: Adding Reserved Memory Addr = 0x%llx, Size = 0x%llx\n", + __func__, + Addr, + Size + )); + + BuildMemoryAllocationHob ( + Addr, + Size, + EfiReservedMemoryType + ); + } + } + } +} + /** Initialize memory hob based on the DTB information. @@ -183,8 +271,6 @@ MemoryPeimInitialization ( INT32 Node, Prev; INT32 Len; VOID *FdtPointer; - EFI_PHYSICAL_ADDRESS MmodeResvBase; - UINT64 MmodeResvSize; FirmwareContext = NULL; GetFirmwareContextPointer (&FirmwareContext); @@ -200,16 +286,6 @@ MemoryPeimInitialization ( return EFI_UNSUPPORTED; } - /* try to locate the reserved memory opensbi node */ - Node = fdt_path_offset (FdtPointer, "/reserved-memory/mmode_resv0"); - if (Node >= 0) { - RegProp = fdt_getprop (FdtPointer, Node, "reg", &Len); - if ((RegProp != 0) && (Len == (2 * sizeof (UINT64)))) { - MmodeResvBase = fdt64_to_cpu (ReadUnaligned64 (RegProp)); - MmodeResvSize = fdt64_to_cpu (ReadUnaligned64 (RegProp + 1)); - } - } - // Look for the lowest memory node for (Prev = 0; ; Prev = Node) { Node = fdt_next_node (FdtPointer, Prev, NULL); @@ -235,16 +311,10 @@ MemoryPeimInitialization ( CurBase + CurSize - 1 )); - if ((MmodeResvBase >= CurBase) && ((MmodeResvBase + MmodeResvSize) <= (CurBase + CurSize))) { - InitializeRamRegions ( - CurBase, - CurSize, - MmodeResvBase, - MmodeResvSize - ); - } else { - AddMemoryBaseSizeHob (CurBase, CurSize); - } + InitializeRamRegions ( + CurBase, + CurSize + ); } else { DEBUG (( DEBUG_ERROR, @@ -255,6 +325,8 @@ MemoryPeimInitialization ( } } + AddReservedMemoryMap (FdtPointer); + InitMmu (); BuildMemoryTypeInformationHob (); From 7aa9714a0b8dd3295819519a1af9f01d5b7c4041 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 28 Mar 2023 09:34:00 +0200 Subject: [PATCH 0748/1529] OvmfPkg/PlatformInitLib: update address space layout comment Move the commment up so it is placed just before the address space calculations start. Also add q35 memory layout. Signed-off-by: Gerd Hoffmann Reviewed-by: Anthony PERARD --- OvmfPkg/Library/PlatformInitLib/Platform.c | 28 ++++++++++++---------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 9fee6e4810..678e8e3290 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -152,6 +152,21 @@ PlatformMemMapInitialization ( return; } + // + // address purpose size + // ------------ -------- ------------------------- + // max(top, 2g) PCI MMIO 0xFC000000 - max(top, 2g) (pc) + // 0xB0000000 MMCONFIG 256 MB (q35) + // 0xC0000000 PCI MMIO 960 MB (q35) + // 0xFC000000 gap 44 MB + // 0xFEC00000 IO-APIC 4 KB + // 0xFEC01000 gap 1020 KB + // 0xFED00000 HPET 1 KB + // 0xFED00400 gap 111 KB + // 0xFED1C000 gap (PIIX4) / RCRB (ICH9) 16 KB + // 0xFED20000 gap 896 KB + // 0xFEE00000 LAPIC 1 MB + // PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); PciExBarBase = 0; if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { @@ -168,19 +183,6 @@ PlatformMemMapInitialization ( PciBase = PlatformInfoHob->Uc32Base; } - // - // address purpose size - // ------------ -------- ------------------------- - // max(top, 2g) PCI MMIO 0xFC000000 - max(top, 2g) - // 0xFC000000 gap 44 MB - // 0xFEC00000 IO-APIC 4 KB - // 0xFEC01000 gap 1020 KB - // 0xFED00000 HPET 1 KB - // 0xFED00400 gap 111 KB - // 0xFED1C000 gap (PIIX4) / RCRB (ICH9) 16 KB - // 0xFED20000 gap 896 KB - // 0xFEE00000 LAPIC 1 MB - // PciSize = 0xFC000000 - PciBase; PlatformAddIoMemoryBaseSizeHob (PciBase, PciSize); From 4f4088272dcc3c935f35ab86e4f4bb2bd2249a7e Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 28 Mar 2023 09:34:01 +0200 Subject: [PATCH 0749/1529] OvmfPkg/PlatformInitLib: move mmconfig to 0xe0000000 Also swap the ordering of 32bit PCI MMIO window on q35, i.e. use the room between end of low memory and the start of the mmconfig bar. With a typical configuration on modern qemu with gigabyte-aligned memory the MMIO window start at 0x8000000, sized 1532 MB. In case there is memory present above 0x80000000 the window will start at 0xc0000000 instead, with 512 MB size. This depends on qemu commit 4a4418369d6d ("q35: fix mmconfig and PCI0._CRS"), so it raises the bar for the lowest supported version to qemu 4.1 (released Aug 2019). Signed-off-by: Gerd Hoffmann Reviewed-by: Anthony PERARD --- OvmfPkg/AmdSev/AmdSevX64.dsc | 2 +- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 2 +- OvmfPkg/Library/PlatformInitLib/Platform.c | 10 +++++----- OvmfPkg/OvmfPkgIa32.dsc | 2 +- OvmfPkg/OvmfPkgIa32X64.dsc | 2 +- OvmfPkg/OvmfPkgX64.dsc | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index 654c3af092..c005e474dd 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -443,7 +443,7 @@ # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2816 MB. - gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000 + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 !if $(SOURCE_DEBUG_ENABLE) == TRUE gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2 diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index e6d85286e0..5c56858d06 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -448,7 +448,7 @@ # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2816 MB. - gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000 + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 # # The NumberOfPages values below are ad-hoc. They are updated sporadically at diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 678e8e3290..5cf8af825a 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -156,8 +156,8 @@ PlatformMemMapInitialization ( // address purpose size // ------------ -------- ------------------------- // max(top, 2g) PCI MMIO 0xFC000000 - max(top, 2g) (pc) - // 0xB0000000 MMCONFIG 256 MB (q35) - // 0xC0000000 PCI MMIO 960 MB (q35) + // max(top, 2g) PCI MMIO 0xE0000000 - max(top, 2g) (q35) + // 0xE0000000 MMCONFIG 256 MB (q35) // 0xFC000000 gap 44 MB // 0xFEC00000 IO-APIC 4 KB // 0xFEC01000 gap 1020 KB @@ -168,6 +168,7 @@ PlatformMemMapInitialization ( // 0xFEE00000 LAPIC 1 MB // PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); + PciBase = PlatformInfoHob->Uc32Base; PciExBarBase = 0; if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { // @@ -177,13 +178,12 @@ PlatformMemMapInitialization ( PciExBarBase = PcdGet64 (PcdPciExpressBaseAddress); ASSERT (PlatformInfoHob->LowMemory <= PciExBarBase); ASSERT (PciExBarBase <= MAX_UINT32 - SIZE_256MB); - PciBase = (UINT32)(PciExBarBase + SIZE_256MB); + PciSize = (UINT32)(PciExBarBase - PciBase); } else { ASSERT (PlatformInfoHob->LowMemory <= PlatformInfoHob->Uc32Base); - PciBase = PlatformInfoHob->Uc32Base; + PciSize = 0xFC000000 - PciBase; } - PciSize = 0xFC000000 - PciBase; PlatformAddIoMemoryBaseSizeHob (PciBase, PciSize); PlatformInfoHob->PcdPciMmio32Base = PciBase; diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 9e4705f29b..a6db902f54 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -559,7 +559,7 @@ # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2816 MB. - gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000 + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 !if $(SOURCE_DEBUG_ENABLE) == TRUE gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2 diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 86940e9af5..076fc0353d 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -565,7 +565,7 @@ # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2816 MB. - gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000 + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 !if $(SOURCE_DEBUG_ENABLE) == TRUE gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2 diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 00f7005fca..4a276e1ec0 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -586,7 +586,7 @@ # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2816 MB. - gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000 + gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 !if $(SOURCE_DEBUG_ENABLE) == TRUE gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2 From abfe822f53cc49164e8f7d6bb898d616a42c3cf2 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 28 Mar 2023 09:34:02 +0200 Subject: [PATCH 0750/1529] OvmfPkg/PlatformInitLib: simplify mtrr setup With the new mmconfig location at 0xe0000000 above the 32-bit PCI MMIO window we don't have to special-case the mmconfig xbar any more. We'll just add a mtrr uncachable entry starting at MMIO window base and ending at 4GB. Update comments to match reality. Signed-off-by: Gerd Hoffmann Reviewed-by: Anthony PERARD --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 36 +++++++++------------ 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 38cece9173..f85a63ac51 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -61,33 +61,20 @@ PlatformQemuUc32BaseInitialization ( return; } + ASSERT ( + PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID || + PlatformInfoHob->HostBridgeDevId == INTEL_82441_DEVICE_ID + ); + PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob); if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { ASSERT (PcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32); ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= PlatformInfoHob->LowMemory); - - if (PlatformInfoHob->LowMemory <= BASE_2GB) { - // Newer qemu with gigabyte aligned memory, - // 32-bit pci mmio window is 2G -> 4G then. - PlatformInfoHob->Uc32Base = BASE_2GB; - } else { - // - // On q35, the 32-bit area that we'll mark as UC, through variable MTRRs, - // starts at PcdPciExpressBaseAddress. The platform DSC is responsible for - // setting PcdPciExpressBaseAddress such that describing the - // [PcdPciExpressBaseAddress, 4GB) range require a very small number of - // variable MTRRs (preferably 1 or 2). - // - PlatformInfoHob->Uc32Base = (UINT32)PcdGet64 (PcdPciExpressBaseAddress); - } - - return; } - ASSERT (PlatformInfoHob->HostBridgeDevId == INTEL_82441_DEVICE_ID); // - // On i440fx, start with the [LowerMemorySize, 4GB) range. Make sure one + // Start with the [LowerMemorySize, 4GB) range. Make sure one // variable MTRR suffices by truncating the size to a whole power of two, // while keeping the end affixed to 4GB. This will round the base up. // @@ -1027,6 +1014,13 @@ PlatformQemuInitializeRam ( // practically any alignment, and we may not have enough variable MTRRs to // cover it exactly. // + // Because of that PlatformQemuUc32BaseInitialization() will round + // up PlatformInfoHob->LowMemory to make sure a single mtrr register + // is enough. The the result will be stored in + // PlatformInfoHob->Uc32Base. On a typical qemu configuration with + // gigabyte-alignment being used LowMemory will be 2 or 3 GB and no + // rounding is needed, so LowMemory and Uc32Base will be identical. + // if (IsMtrrSupported () && (PlatformInfoHob->HostBridgeDevId != CLOUDHV_DEVICE_ID)) { MtrrGetAllMtrrs (&MtrrSettings); @@ -1056,8 +1050,8 @@ PlatformQemuInitializeRam ( ASSERT_EFI_ERROR (Status); // - // Set the memory range from the start of the 32-bit MMIO area (32-bit PCI - // MMIO aperture on i440fx, PCIEXBAR on q35) to 4GB as uncacheable. + // Set the memory range from the start of the 32-bit PCI MMIO + // aperture to 4GB as uncacheable. // Status = MtrrSetMemoryAttribute ( PlatformInfoHob->Uc32Base, From e6bc9c5c480bb5f1483e9f637d6ebdf04700511b Mon Sep 17 00:00:00 2001 From: Tinh Nguyen Date: Mon, 27 Mar 2023 01:35:43 +0700 Subject: [PATCH 0751/1529] ArmPkg/SmbiosMiscDxe: Adjust the priority of getting firmware version The BIOS Firmware Version in the SMBIOS Type 0 can be fetched from the fixed PcdFirmwareVersionString or platform specific OemMiscLib. In fact, the support from OemMiscLib comes into play when the firmware version may be modified at boot time for extended information. Therefore, the priority of getting the version from OemMiscLib should be higher. In case there is no modification in the OemMiscLib, we have to keep HII string STR_MISC_BIOS_VERSION empty or 'Not Specified' to indicate that the firmware version should be fetched from the PcdFirmwareVersionString. Signed-off-by: Tinh Nguyen Reviewed-by: Rebecca Cran Reviewed-by: Oliver Smith-Denny Reviewed-by: Leif Lindholm --- .../Type00/MiscBiosVendorFunction.c | 62 ++++++++++++------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c index 66ead22a6e..c9f25b7502 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c @@ -1,6 +1,6 @@ /** @file - Copyright (c) 2022, Ampere Computing LLC. All rights reserved.
+ Copyright (c) 2022 - 2023, Ampere Computing LLC. All rights reserved.
Copyright (c) 2021, NUVIA Inc. All rights reserved.
Copyright (c) 2009, Intel Corporation. All rights reserved.
Copyright (c) 2015, Hisilicon Limited. All rights reserved.
@@ -124,22 +124,47 @@ GetBiosReleaseDate ( return ReleaseDate; } -/** - Fetches the firmware ('BIOS') version from the - FirmwareVersionInfo HOB. +/** Fetches the Firmware version string for SMBIOS type 0 + + This function first acquires the firmware version string from OemMiscLib; + if it is invalid, PcdFirmwareVersionString is used as a fallback, + and then sets it in SMBIOS type 0. - @return The version as a UTF-16 string **/ -CHAR16 * -GetBiosVersion ( +VOID +SetBiosVersion ( VOID ) { - CHAR16 *ReleaseString; - - ReleaseString = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareVersionString); - - return ReleaseString; + CHAR16 *DefaultVersionString; + CHAR16 *Version; + EFI_STRING_ID TokenToUpdate; + + DefaultVersionString = HiiGetString ( + mSmbiosMiscHiiHandle, + STRING_TOKEN (STR_MISC_BIOS_VERSION), + NULL + ); + + OemUpdateSmbiosInfo ( + mSmbiosMiscHiiHandle, + STRING_TOKEN (STR_MISC_BIOS_VERSION), + BiosVersionType00 + ); + + Version = HiiGetString ( + mSmbiosMiscHiiHandle, + STRING_TOKEN (STR_MISC_BIOS_VERSION), + NULL + ); + + if (((StrCmp (Version, DefaultVersionString) == 0) || (StrLen (Version) == 0))) { + Version = (CHAR16 *)FixedPcdGetPtr (PcdFirmwareVersionString); + if (StrLen (Version) > 0) { + TokenToUpdate = STRING_TOKEN (STR_MISC_BIOS_VERSION); + HiiSetString (mSmbiosMiscHiiHandle, TokenToUpdate, Version, NULL); + } + } } /** @@ -187,18 +212,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBiosVendor) { HiiSetString (mSmbiosMiscHiiHandle, TokenToUpdate, Vendor, NULL); } - Version = GetBiosVersion (); - - if (StrLen (Version) > 0) { - TokenToUpdate = STRING_TOKEN (STR_MISC_BIOS_VERSION); - HiiSetString (mSmbiosMiscHiiHandle, TokenToUpdate, Version, NULL); - } else { - OemUpdateSmbiosInfo ( - mSmbiosMiscHiiHandle, - STRING_TOKEN (STR_MISC_BIOS_VERSION), - BiosVersionType00 - ); - } + SetBiosVersion (); Char16String = GetBiosReleaseDate (); if (StrLen (Char16String) > 0) { From d7af7325daad2c1683d16968f1b229ccddbe1920 Mon Sep 17 00:00:00 2001 From: Jianyong Wu Date: Tue, 28 Mar 2023 17:11:00 +0800 Subject: [PATCH 0752/1529] ArmVirtPkg: can't find gUefiOvmfPkgTokenSpaceGuid commit f13264b34 introduces a bug for CloudHv as OvmfPkg/OvmfPkg.dec is missing in CloudHvHasAcpiDtDxe.inf which leads to gUefiOvmfPkgTokenSpaceGuid found nowhere when build. Reviewed-by: Ard Biesheuvel Reviewed-by: Sunil V L Reviewed-by: Sami Mujawar Signed-off-by: Jianyong Wu --- ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf | 1 + 1 file changed, 1 insertion(+) diff --git a/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf b/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf index 7cad40e11f..6ff80b24d0 100644 --- a/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf +++ b/ArmVirtPkg/CloudHvPlatformHasAcpiDtDxe/CloudHvHasAcpiDtDxe.inf @@ -23,6 +23,7 @@ EmbeddedPkg/EmbeddedPkg.dec MdeModulePkg/MdeModulePkg.dec MdePkg/MdePkg.dec + OvmfPkg/OvmfPkg.dec [LibraryClasses] BaseLib From 025143225bbc29f97e86eafb367c34be61e9cf99 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Mon, 27 Mar 2023 22:09:00 +0800 Subject: [PATCH 0753/1529] RedfishPkg/JsonLib: address coverity issue Fix implicit conversion issue in JsonLib. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang --- RedfishPkg/Library/JsonLib/JsonLib.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/RedfishPkg/Library/JsonLib/JsonLib.c b/RedfishPkg/Library/JsonLib/JsonLib.c index 5d75882004..69f2455c00 100644 --- a/RedfishPkg/Library/JsonLib/JsonLib.c +++ b/RedfishPkg/Library/JsonLib/JsonLib.c @@ -7,6 +7,7 @@ Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -1112,5 +1113,5 @@ JsonGetType ( IN EDKII_JSON_VALUE JsonValue ) { - return ((json_t *)JsonValue)->type; + return (EDKII_JSON_TYPE)(((json_t *)JsonValue)->type); } From 3f104e084704c1d5369b9e29e55968938cd8088e Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Mon, 27 Mar 2023 22:28:58 +0800 Subject: [PATCH 0754/1529] RedfishPkg: Redfish discover driver improvement Bug fix: - function stack fault - properly handle "SubnetAddrInfoIPv6" when there is no IPv6 support - copy-n-paste error in RedfishGetHostInterfaceProtocolData() - fix typo Enhancement: - Redfish discover driver now can configure host IP address based on the information from SMBIOS type 42 record. This saves the effort of configuring host IP address in setup menu. - Performance improvement to driver binding process. Redfish discover driver will wait until all required drivers are ready and do driver binding start(). - Use CopyGuid() to copy GUID instead of intrinsic function. - Error handling when SMBIOS data is corrupted. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang --- .../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 144 ++++++++++++------ .../RedfishDiscoverInternal.h | 20 ++- .../RedfishSmbiosHostInterface.c | 13 +- 3 files changed, 120 insertions(+), 57 deletions(-) diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c index 042d6d5fd5..f64c79088f 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c @@ -1,9 +1,10 @@ /** @file - The implementation of EFI Redfidh Discover Protocol. + The implementation of EFI Redfish Discover Protocol. (C) Copyright 2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2022, AMD Incorporated. All rights reserved. + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -270,10 +271,13 @@ Tcp6GetSubnetInfo ( if (IpModedata.AddressCount == 0) { DEBUG ((DEBUG_INFO, "%a: No IPv6 address configured.\n", __FUNCTION__)); + Instance->SubnetAddrInfoIPv6Number = 0; + return EFI_SUCCESS; } if (Instance->SubnetAddrInfoIPv6 != NULL) { FreePool (Instance->SubnetAddrInfoIPv6); + Instance->SubnetAddrInfoIPv6 = NULL; } Instance->SubnetAddrInfoIPv6 = AllocateZeroPool (IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)); @@ -447,7 +451,7 @@ NumberOfNetworkInterface ( /** This function checks the IP version supported on this - netwoek interface. + network interface. @param[in] ThisNetworkInterface EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL @@ -472,7 +476,7 @@ CheckIsIpVersion6 ( @param[in] Instance EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE @retval EFI_SUCCESS Redfish service is discovered through SMBIOS Host interface. - @retval Others Fail to discover Redfish service throught SMBIOS host interface + @retval Others Fail to discover Redfish service through SMBIOS host interface **/ EFI_STATUS @@ -487,7 +491,7 @@ DiscoverRedfishHostInterface ( CHAR16 Ipv6Str[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" + 1]; CHAR8 RedfishServiceLocateStr[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" + 1]; UINTN StrSize; - UINTN MacCompareStstus; + UINTN MacCompareStatus; BOOLEAN IsHttps; Data = NULL; @@ -503,24 +507,52 @@ DiscoverRedfishHostInterface ( Status = RedfishGetHostInterfaceProtocolData (mSmbios, &DeviceDescriptor, &Data); // Search for SMBIOS type 42h if (!EFI_ERROR (Status) && (Data != NULL) && (DeviceDescriptor != NULL)) { // - // Chceck if we can reach out Redfish service using this network interface. - // Check with MAC address using Device Descroptor Data Device Type 04 and Type 05. + // Check if we can reach out Redfish service using this network interface. + // Check with MAC address using Device Descriptor Data Device Type 04 and Type 05. // Those two types of Redfish host interface device has MAC information. // if (DeviceDescriptor->DeviceType == REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2) { - MacCompareStstus = CompareMem (&Instance->NetworkInterface->MacAddress, &DeviceDescriptor->DeviceDescriptor.PciPcieDeviceV2.MacAddress, 6); + MacCompareStatus = CompareMem (&Instance->NetworkInterface->MacAddress, &DeviceDescriptor->DeviceDescriptor.PciPcieDeviceV2.MacAddress, 6); } else if (DeviceDescriptor->DeviceType == REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2) { - MacCompareStstus = CompareMem (&Instance->NetworkInterface->MacAddress, &DeviceDescriptor->DeviceDescriptor.UsbDeviceV2.MacAddress, 6); + MacCompareStatus = CompareMem (&Instance->NetworkInterface->MacAddress, &DeviceDescriptor->DeviceDescriptor.UsbDeviceV2.MacAddress, 6); } else { return EFI_UNSUPPORTED; } - if (MacCompareStstus != 0) { + if (MacCompareStatus != 0) { return EFI_UNSUPPORTED; } - if (Data->RedfishServiceIpAddressFormat == 1) { + Instance->HostAddrFormat = Data->HostIpAddressFormat; + if (Data->HostIpAddressFormat == REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4) { + IP4_COPY_ADDRESS ((VOID *)&Instance->HostIpAddress.v4, (VOID *)Data->HostIpAddress); + IP4_COPY_ADDRESS ((VOID *)&Instance->HostSubnetMask.v4, (VOID *)Data->HostIpMask); + + if (EFI_IP4_EQUAL (&Instance->HostIpAddress.v4, &mZeroIp4Addr)) { + DEBUG ((DEBUG_ERROR, "%a: invalid host IP address: zero address\n", __FUNCTION__)); + // + // Invalid IP address detected. Change address format to Unknown and use system default address. + // + Instance->HostAddrFormat = REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_UNKNOWN; + } + + if (!IP4_IS_VALID_NETMASK (EFI_IP4 (Instance->HostSubnetMask.v4))) { + DEBUG ((DEBUG_ERROR, "%a: invalid subnet mask address\n", __FUNCTION__)); + // + // Invalid subnet mast address detected. Change address format to Unknown and use system default address. + // + Instance->HostAddrFormat = REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_UNKNOWN; + } + } else if (Data->HostIpAddressFormat == REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP6) { + IP6_COPY_ADDRESS ((VOID *)&Instance->HostIpAddress.v6, (VOID *)Data->HostIpAddress); + } + + if (Data->RedfishServiceIpAddressFormat == REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4) { IP4_COPY_ADDRESS ((VOID *)&Instance->TargetIpAddress.v4, (VOID *)Data->RedfishServiceIpAddress); + + if (EFI_IP4_EQUAL (&Instance->TargetIpAddress.v4, &mZeroIp4Addr)) { + DEBUG ((DEBUG_ERROR, "%a: invalid service IP address: zero address\n", __FUNCTION__)); + } } else { IP6_COPY_ADDRESS ((VOID *)&Instance->TargetIpAddress.v6, (VOID *)Data->RedfishServiceIpAddress); } @@ -530,7 +562,7 @@ DiscoverRedfishHostInterface ( Status = EFI_UNSUPPORTED; } else { // - // Add this istance to list without detial information of Redfish + // Add this instance to list without detail information of Redfish // service. // IsHttps = FALSE; @@ -614,7 +646,7 @@ DiscoverRedfishHostInterface ( @param[in] Os OS string. @param[in] OsVer OS version string. @param[in] Product Product string. - @param[in] ProductVer Product verison string. + @param[in] ProductVer Product version string. @param[in] UseHttps Redfish service requires secured connection. @retval EFI_SUCCESS Redfish service is added to list successfully. @@ -671,7 +703,7 @@ AddAndSignalNewRedfishService ( do { if ((Char16Uuid == NULL) || (DiscoveredList->Instance->Information.Uuid == NULL)) { // - // Check if this Redfish instance already found using IP addrress. + // Check if this Redfish instance already found using IP address. // if (!CheckIsIpVersion6 (NetworkInterface)) { if (CompareMem ( @@ -849,6 +881,10 @@ AddAndSignalNewRedfishService ( Status = EFI_OUT_OF_RESOURCES; goto EXIT_FREE_CONFIG_DATA; } + + if (Instance->HostAddrFormat == REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP6) { + IP6_COPY_ADDRESS (&RestExHttpConfigData->HttpConfigData.AccessPoint.IPv6Node->LocalAddress, &Instance->HostIpAddress.v6); + } } else { RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node = AllocateZeroPool (sizeof (EFI_HTTPv4_ACCESS_POINT)); if (RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node == NULL) { @@ -856,7 +892,13 @@ AddAndSignalNewRedfishService ( goto EXIT_FREE_CONFIG_DATA; } - RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node->UseDefaultAddress = TRUE; + if (Instance->HostAddrFormat == REDFISH_HOST_INTERFACE_HOST_IP_ADDRESS_FORMAT_IP4) { + RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node->UseDefaultAddress = FALSE; + IP4_COPY_ADDRESS (&RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node->LocalAddress, &Instance->HostIpAddress.v4); + IP4_COPY_ADDRESS (&RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node->LocalSubnet, &Instance->HostSubnetMask.v4); + } else { + RestExHttpConfigData->HttpConfigData.AccessPoint.IPv4Node->UseDefaultAddress = TRUE; + } } Status = RestEx->Configure ( @@ -955,7 +997,7 @@ NetworkInterfaceGetSubnetInfo ( Instance ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:Faile to get Subnet infomation.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Failed to get Subnet infomation.\n", __FUNCTION__)); return Status; } else { DEBUG ((DEBUG_INFO, "%a:MAC address: %s\n", __FUNCTION__, Instance->StrMacAddr)); @@ -982,7 +1024,7 @@ NetworkInterfaceGetSubnetInfo ( ThisSubnetAddrInfoIPv6++; for (IPv6InfoIndex = 0; IPv6InfoIndex < Instance->SubnetAddrInfoIPv6Number - 1; IPv6InfoIndex++) { // - // Build up addtional EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL instances. + // Build up additional EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL instances. // NewNetworkInterface = (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *)AllocateZeroPool (sizeof (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL)); if (NewNetworkInterface != NULL) { @@ -1103,9 +1145,9 @@ RedfishServiceGetNetworkInterface ( /** This function acquires Redfish services by discovering static Redfish setting according to Redfish Host Interface or through SSDP. Returns a list of EFI - handles in EFI_REDFISH_DISCOVERED_LIST. Each of EFI handle has cooresponding - EFI REST EX instance installed on it. Each REST EX isntance is a child instance which - created through EFI REST EX serivce protoocl for communicating with specific + handles in EFI_REDFISH_DISCOVERED_LIST. Each of EFI handle has corresponding + EFI REST EX instance installed on it. Each REST EX instance is a child instance which + created through EFI REST EX service protocol for communicating with specific Redfish service. @param[in] This EFI_REDFISH_DISCOVER_PROTOCOL instance. @@ -1255,7 +1297,7 @@ RedfishServiceAbortAcquire ( ) { // This function is used to abort Redfish service discovery through SSDP - // on the network interface. SSDP is optionally supprted by EFI_REDFISH_DISCOVER_PROTOCOL, + // on the network interface. SSDP is optionally suppoted by EFI_REDFISH_DISCOVER_PROTOCOL, // we dont have implementation for SSDP now. return EFI_UNSUPPORTED; @@ -1425,7 +1467,7 @@ CreateRedfishDiscoverNetworkInterface ( } /** - This function destory network interface + This function destroy network interface @param[in] ThisNetworkInterface EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL instance. @@ -1433,7 +1475,7 @@ CreateRedfishDiscoverNetworkInterface ( @retval EFI_STATUS **/ EFI_STATUS -DestroyRedfishNetwrokInterface ( +DestroyRedfishNetworkInterface ( IN EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *ThisNetworkInterface ) { @@ -1467,11 +1509,13 @@ TestForRequiredProtocols ( IN EFI_HANDLE ControllerHandle ) { - UINT32 Id; + UINT32 *Id; UINTN Index; EFI_STATUS Status; + UINTN ListCount; - for (Index = 0; Index < (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL)); Index++) { + ListCount = (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL)); + for (Index = 0; Index < ListCount; Index++) { Status = gBS->OpenProtocol ( ControllerHandle, gRequiredProtocol[Index].RequiredServiceBindingProtocolGuid, @@ -1490,8 +1534,10 @@ TestForRequiredProtocols ( EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %s is found on this controller handle.\n", __FUNCTION__, gRequiredProtocol[Index].ProtocolName)); - return EFI_SUCCESS; + if (Index == ListCount - 1) { + DEBUG ((DEBUG_ERROR, "%a: all required protocols are found on this controller handle: %p.\n", __FUNCTION__, ControllerHandle)); + return EFI_SUCCESS; + } } } } @@ -1517,7 +1563,7 @@ BuildupNetworkInterface ( IN EFI_HANDLE ControllerHandle ) { - UINT32 Id; + UINT32 *Id; UINT32 Index; EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *NetworkInterface; BOOLEAN IsNew; @@ -1578,13 +1624,11 @@ BuildupNetworkInterface ( return Status; } - NetworkInterface->NetworkProtocolType = gRequiredProtocol[Index].ProtocolType; - NetworkInterface->OpenDriverAgentHandle = This->DriverBindingHandle; - NetworkInterface->OpenDriverControllerHandle = ControllerHandle; - NetworkInterface->NetworkInterfaceProtocolInfo.ProtocolGuid = \ - *gRequiredProtocol[Index].RequiredProtocolGuid; - NetworkInterface->NetworkInterfaceProtocolInfo.ProtocolServiceGuid = \ - *gRequiredProtocol[Index].RequiredServiceBindingProtocolGuid; + NetworkInterface->NetworkProtocolType = gRequiredProtocol[Index].ProtocolType; + NetworkInterface->OpenDriverAgentHandle = This->DriverBindingHandle; + NetworkInterface->OpenDriverControllerHandle = ControllerHandle; + CopyGuid (&NetworkInterface->NetworkInterfaceProtocolInfo.ProtocolGuid, gRequiredProtocol[Index].RequiredProtocolGuid); + CopyGuid (&NetworkInterface->NetworkInterfaceProtocolInfo.ProtocolServiceGuid, gRequiredProtocol[Index].RequiredServiceBindingProtocolGuid); ProtocolDiscoverIdPtr = &NetworkInterface->NetworkInterfaceProtocolInfo.ProtocolDiscoverId; OpenDriverAgentHandle = NetworkInterface->OpenDriverAgentHandle; OpenDriverControllerHandle = NetworkInterface->OpenDriverControllerHandle; @@ -1598,7 +1642,7 @@ BuildupNetworkInterface ( gBS->RestoreTPL (OldTpl); } else { - // Record REST_EX instance. REST_EX is created when clinet asks for Redfish service discovery. + // Record REST_EX instance. REST_EX is created when client asks for Redfish service discovery. // Redfish Service Discover protocol will match REST EX to the corresponding EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL // when discovery. @@ -1655,9 +1699,9 @@ BuildupNetworkInterface ( ); if (!EFI_ERROR (Status)) { if ((gRequiredProtocol[Index].ProtocolType == ProtocolTypeRestEx)) { - // Install Redfish Discover Protocol when EFI REST EX protcol is discovered. + // Install Redfish Discover Protocol when EFI REST EX protocol is discovered. // This ensures EFI REST EX is ready while the consumer of EFI_REDFISH_DISCOVER_PROTOCOL - // acquires Redfish serivce over network interface. + // acquires Redfish service over network interface. if (!NewNetworkInterfaceInstalled) { NetworkInterface = GetTargetNetworkInterfaceInternalByController (ControllerHandle); @@ -1678,6 +1722,14 @@ BuildupNetworkInterface ( if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI_REDFISH_DISCOVER_PROTOCOL\n", __FUNCTION__)); } + } else { + DEBUG ((DEBUG_INFO, "%a: Not REST EX, continue with next\n", __FUNCTION__)); + Index++; + if (Index == (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL))) { + break; + } + + continue; } } @@ -1692,11 +1744,11 @@ BuildupNetworkInterface ( } } while (Index < (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL))); - return EFI_UNSUPPORTED; + return EFI_DEVICE_ERROR; } /** - Close the protocol opened for Redfish discovery. This function also destories + Close the protocol opened for Redfish discovery. This function also destroy the network services. @param[in] ThisBindingProtocol A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance. @@ -1707,8 +1759,8 @@ BuildupNetworkInterface ( @param[in] DriverAgentHandle Driver agent handle which used to open protocol earlier. @param[in] DriverControllerHandle Driver controller handle which used to open protocol earlier. - @retval EFI_SUCCESS Prorocol is closed successfully. - @retval Others Prorocol is closed unsuccessfully. + @retval EFI_SUCCESS Protocol is closed successfully. + @retval Others Protocol is closed unsuccessfully. **/ EFI_STATUS @@ -1748,7 +1800,7 @@ CloseProtocolService ( must support a protocol interface that supplies an I/O abstraction to the driver. @retval EFI_SUCCESS One of required protocol is found. - @retval Others Faile to stop the services on network interface. + @retval Others Failed to stop the services on network interface. **/ EFI_STATUS StopServiceOnNetworkInterface ( @@ -1792,14 +1844,14 @@ StopServiceOnNetworkInterface ( ThisNetworkInterface->OpenDriverControllerHandle ); if (!EFI_ERROR (Status)) { - Status = DestroyRedfishNetwrokInterface (ThisNetworkInterface); + Status = DestroyRedfishNetworkInterface (ThisNetworkInterface); } gBS->RestoreTPL (OldTpl); // // Disconnect EFI Redfish discover driver controller to notify the - // clinet which uses .EFI Redfish discover protocol. + // client which uses .EFI Redfish discover protocol. // if (DiscoverProtocolHandle != NULL) { gBS->DisconnectController (DiscoverProtocolHandle, NULL, NULL); @@ -1945,7 +1997,7 @@ RedfishDiscoverDriverBindingSupported ( @retval EFI_SUCCESS The device was started. @retval EFI_DEVICE_ERROR The device could not be started due to a device error.Currently not implemented. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. - @retval Others The driver failded to start the device. + @retval Others The driver failed to start the device. **/ EFI_STATUS @@ -2030,7 +2082,7 @@ RedfishDiscoverEntryPoint ( InitializeListHead (&mEfiRedfishDiscoverNetworkInterface); InitializeListHead (&mEfiRedfishDiscoverRestExInstance); // - // Install binding protoocl to obtain UDP and REST EX protocol. + // Install binding protocol to obtain UDP and REST EX protocol. // Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h index 04fa09e1cc..2704cd955d 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h @@ -3,6 +3,7 @@ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2022, AMD Incorporated. All rights reserved. + Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -102,7 +103,7 @@ typedef struct { UINT32 SubnetAddrInfoIPv6Number; ///< IPv6 address info number. EFI_IP6_ADDRESS_INFO *SubnetAddrInfoIPv6; ///< IPv6 address info. // - // Network interface protocol and REST EX infor. + // Network interface protocol and REST EX info. // UINT32 NetworkProtocolType; ///< Network protocol type. Refer to ///< NETWORK_INTERFACE_PROTOCOL_TYPE. @@ -112,7 +113,7 @@ typedef struct { // EFI_REDFISH_DISCOVER_PROTOCOL instance installed // on this network interface. // - EFI_HANDLE EfiRedfishDiscoverProtocolHandle; ///< EFI_REDFISH_DISCOVER_PROTOTOCOL instance installed + EFI_HANDLE EfiRedfishDiscoverProtocolHandle; ///< EFI_REDFISH_DISCOVER_PROTOCOL instance installed ///< on this network interface. } EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL; @@ -123,7 +124,7 @@ typedef struct { LIST_ENTRY Entry; ///< Link list entry. EFI_HANDLE OpenDriverAgentHandle; ///< The agent to open network protocol. EFI_HANDLE OpenDriverControllerHandle; ///< The controller handle to open network protocol. - EFI_HANDLE RestExChildHandle; ///< The child handle created throught REST EX Service Protocol. + EFI_HANDLE RestExChildHandle; ///< The child handle created through REST EX Service Protocol. EFI_HANDLE RestExControllerHandle; ///< The controller handle which provide REST EX protocol. EFI_REST_EX_PROTOCOL *RestExProtocolInterface; ///< Pointer to EFI_REST_EX_PROTOCOL. UINT32 RestExId; ///< The identifier installed on REST EX controller handle. @@ -178,15 +179,18 @@ typedef struct { EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *NetworkInterface; ///< EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL ///< instance used to discover Redfish service. // - // Below for Host insterface discovery. + // Below for Host interface discovery. // BOOLEAN HostIntfValidation; ///< Indicates whether to validate Redfish Host interface. EFI_IP_ADDRESS TargetIpAddress; ///< Target IP address reported in Redfish Host interface. + UINT8 HostAddrFormat; ///< Unknown=00h, Ipv4=01h, Ipv6=02h. + EFI_IP_ADDRESS HostIpAddress; ///< Host IP address reported in Redfish Host interface. + EFI_IP_ADDRESS HostSubnetMask; ///< Host subnet mask address reported in Redfish Host interface. } EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE; /** - The function adds a new foudn Redfish service to internal list and - notify clinet. + The function adds a new found Redfish service to internal list and + notify client. It simply frees the packet. @@ -197,7 +201,7 @@ typedef struct { @param[in] Os OS string. @param[in] OsVer OS version string. @param[in] Product Product string. - @param[in] ProductVer Product verison string. + @param[in] ProductVer Product version string. @param[in] UseHttps Redfish service requires secured connection. @retval EFI_SUCCESS Redfish service is added to list successfully. @@ -224,7 +228,7 @@ AddAndSignalNewRedfishService ( @param[out] DeviceDescriptor Pointer to REDFISH_INTERFACE_DATA. @param[out] ProtocolData Pointer to REDFISH_OVER_IP_PROTOCOL_DATA. - @retval EFI_SUCCESS Get host interface succesfully. + @retval EFI_SUCCESS Get host interface successfully. @retval Otherwise Fail to tet host interface. **/ diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishSmbiosHostInterface.c b/RedfishPkg/RedfishDiscoverDxe/RedfishSmbiosHostInterface.c index 88cec1f416..0d6edc7dc3 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishSmbiosHostInterface.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishSmbiosHostInterface.c @@ -4,6 +4,7 @@ Discover Redfish SMBIOS Host Interface. (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -22,7 +23,7 @@ SMBIOS_TABLE_TYPE42 *mType42Record; @param[out] DeviceDescriptor Pointer to REDFISH_INTERFACE_DATA. @param[out] ProtocolData Pointer to REDFISH_OVER_IP_PROTOCOL_DATA. - @retval EFI_SUCCESS Get host interface succesfully. + @retval EFI_SUCCESS Get host interface successfully. @retval Otherwise Fail to tet host interface. **/ @@ -69,9 +70,15 @@ RedfishGetHostInterfaceProtocolData ( // if ((*RecordTmp == REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2) || (*RecordTmp == REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2)) { if (*RecordTmp == REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2) { - ASSERT (SpecificDataLen == sizeof (PCI_OR_PCIE_INTERFACE_DEVICE_DESCRIPTOR_V2) + 1); + if (SpecificDataLen != sizeof (PCI_OR_PCIE_INTERFACE_DEVICE_DESCRIPTOR_V2) + 1) { + ASSERT (SpecificDataLen == sizeof (PCI_OR_PCIE_INTERFACE_DEVICE_DESCRIPTOR_V2) + 1); + return EFI_VOLUME_CORRUPTED; + } } else { - ASSERT (SpecificDataLen > sizeof (REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2) + 1); + if (SpecificDataLen != sizeof (USB_INTERFACE_DEVICE_DESCRIPTOR_V2) + 1) { + ASSERT (SpecificDataLen == sizeof (USB_INTERFACE_DEVICE_DESCRIPTOR_V2) + 1); + return EFI_VOLUME_CORRUPTED; + } } *DeviceDescriptor = (REDFISH_INTERFACE_DATA *)RecordTmp; From 2691a51f18b61dd8786bc91e30baf67cbd2ea944 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Mon, 27 Mar 2023 22:34:43 +0800 Subject: [PATCH 0755/1529] RedfishPkg: fix config handler driver issues Bug fix: - function stack fault - config handler driver requires the dependency of Redfish Credential Protocol - incorrect caller id installation when failed to perform init() - fix typo Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang --- .../RedfishConfigHandler/RedfishConfigHandlerCommon.c | 10 ++++++---- .../RedfishConfigHandlerDriver.inf | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c index c3a7efd796..96aac125ee 100644 --- a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c +++ b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c @@ -2,6 +2,7 @@ The common code of EDKII Redfish Configuration Handler driver. (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -9,7 +10,7 @@ #include "RedfishConfigHandlerCommon.h" -REDFISH_CONFIG_DRIVER_DATA gRedfishConfigData; // Only one Redfish service supproted +REDFISH_CONFIG_DRIVER_DATA gRedfishConfigData; // Only one Redfish service supported // on platform for the BIOS // Redfish configuration. EFI_EVENT gEndOfDxeEvent = NULL; @@ -34,7 +35,7 @@ RedfishConfigOnEndOfDxe ( Status = gCredential->StopService (gCredential, ServiceStopTypeSecureBootDisabled); if (EFI_ERROR (Status) && (Status != EFI_UNSUPPORTED)) { - DEBUG ((DEBUG_ERROR, "Redfish credential protocol faied to stop service on EndOfDxe: %r", Status)); + DEBUG ((DEBUG_ERROR, "Redfish credential protocol failed to stop service on EndOfDxe: %r", Status)); } // @@ -62,7 +63,7 @@ RedfishConfigOnExitBootService ( Status = gCredential->StopService (gCredential, ServiceStopTypeExitBootService); if (EFI_ERROR (Status) && (Status != EFI_UNSUPPORTED)) { - DEBUG ((DEBUG_ERROR, "Redfish credential protocol faied to stop service on ExitBootService: %r", Status)); + DEBUG ((DEBUG_ERROR, "Redfish credential protocol failed to stop service on ExitBootService: %r", Status)); } } @@ -225,7 +226,7 @@ RedfishConfigHandlerInitialization ( UINTN NumberOfHandles; EDKII_REDFISH_CONFIG_HANDLER_PROTOCOL *ConfigHandler; UINTN Index; - UINT32 Id; + UINT32 *Id; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -257,6 +258,7 @@ RedfishConfigHandlerInitialization ( Status = ConfigHandler->Init (ConfigHandler, &gRedfishConfigData.RedfishServiceInfo); if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { DEBUG ((DEBUG_ERROR, "ERROR: Failed to init Redfish config handler %p.\n", ConfigHandler)); + continue; } // diff --git a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.inf b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.inf index def91c7531..b167c6e1ee 100644 --- a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.inf +++ b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.inf @@ -4,6 +4,7 @@ # # Copyright (c) 2019, Intel Corporation. All rights reserved.
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -56,5 +57,4 @@ gEfiEndOfDxeEventGroupGuid ## CONSUMES ## Event [Depex] - TRUE - + gEdkIIRedfishCredentialProtocolGuid From e2639fec0fba791b8fac14ea063534db2d9c44d8 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 28 Mar 2023 11:30:59 -0600 Subject: [PATCH 0756/1529] OvmfPkg: Replace static struct initialization with ZeroMem call Replace the static struct initialization with a call to ZeroMem to avoid generating a call to memset in certain build configurations. Signed-off-by: Rebecca Cran Reviewed-by: Gerd Hoffmann Reviewed-by: Oliver Smith-Denny Reviewed-by: Jiewen Yao Reviewed-by: Michael D Kinney --- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index f85a63ac51..aced8535e6 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -595,10 +595,12 @@ PlatformAddressWidthFromCpuid ( { UINT32 RegEax, RegEbx, RegEcx, RegEdx, Max; UINT8 PhysBits; - CHAR8 Signature[13] = { 0 }; + CHAR8 Signature[13]; BOOLEAN Valid = FALSE; BOOLEAN Page1GSupport = FALSE; + ZeroMem (Signature, sizeof (Signature)); + AsmCpuid (0x80000000, &RegEax, &RegEbx, &RegEcx, &RegEdx); *(UINT32 *)(Signature + 0) = RegEbx; *(UINT32 *)(Signature + 4) = RegEdx; From 3440dc31e77801739ce2cdabaada3c212c683058 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 28 Mar 2023 11:31:08 -0600 Subject: [PATCH 0757/1529] OvmfPkg: Use Xcode5 version of CpuExceptionHandlerLib for CLANGDWARF The CLANGDWARF toolchain has the same problem as XCODE5 linking CpuExceptionHandlerLib. So, use the Xcode5SecPeiCpuExceptionHandlerLib.inf when building with the CLANGDWARF toolchain. Since the difference is that the non-Xcode5 version uses `mov` while the Xcode5 version uses `lea`, they can be merged in future with the single version using `lea`. [ardb: the main difference is that the 'mov' instructions result in absolute symbol references, which are necessary because the code in question is copied in memory independently from the code that carries the symbols it refers to. The Xcode5 version has additional runtime handling to fix up the copied code with the correct absolute references.] Signed-off-by: Rebecca Cran Acked-by: Ard Biesheuvel --- OvmfPkg/OvmfPkgX64.dsc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 4a276e1ec0..b2f3d14cd9 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -297,7 +297,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" +!if $(TOOL_CHAIN_TAG) == "XCODE5" || $(TOOL_CHAIN_TAG) == "CLANGDWARF" CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf !else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf From 014c84bffd56ba145d499294d1504a7109992778 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Wed, 25 May 2022 18:56:25 +0100 Subject: [PATCH 0758/1529] DynamicTablesPkg: Reduce log output from TableHelperLib Reduce the log output from Configuration Manager Object Parser in TableHelperLib by enabling the logs only if DEBUG_INFO is enabled. Reviewed-by: Pierre Gondois Signed-off-by: Sami Mujawar --- .../ConfigurationManagerObjectParser.c | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c index 5e4b88e8cc..99d6032510 100644 --- a/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c +++ b/DynamicTablesPkg/Library/Common/TableHelperLib/ConfigurationManagerObjectParser.c @@ -1,7 +1,7 @@ /** @file Configuration Manager Object parser. - Copyright (c) 2021 - 2022, ARM Limited. All rights reserved.
+ Copyright (c) 2021 - 2023, ARM Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -787,7 +787,7 @@ PrintOemId ( ) { DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, (Format != NULL) ? Format : "%C%C%C%C%C%C", Ptr[0], Ptr[1], @@ -855,7 +855,7 @@ PrintCmObjDesc ( *RemainingSize -= Parser[Index].Length; if (*RemainingSize < 0) { DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, "\nERROR: %a: Buffer overrun\n", Parser[Index].NameStr )); @@ -865,11 +865,11 @@ PrintCmObjDesc ( // Indentation for (IndentIndex = 0; IndentIndex < IndentLevel; IndentIndex++) { - DEBUG ((DEBUG_ERROR, " ")); + DEBUG ((DEBUG_INFO, " ")); } DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, "%-*a :", OUTPUT_FIELD_COLUMN_WIDTH - 2 * IndentLevel, Parser[Index].NameStr @@ -879,20 +879,20 @@ PrintCmObjDesc ( } else if (Parser[Index].Format != NULL) { switch (Parser[Index].Length) { case 1: - DEBUG ((DEBUG_ERROR, Parser[Index].Format, *(UINT8 *)Data)); + DEBUG ((DEBUG_INFO, Parser[Index].Format, *(UINT8 *)Data)); break; case 2: - DEBUG ((DEBUG_ERROR, Parser[Index].Format, *(UINT16 *)Data)); + DEBUG ((DEBUG_INFO, Parser[Index].Format, *(UINT16 *)Data)); break; case 4: - DEBUG ((DEBUG_ERROR, Parser[Index].Format, *(UINT32 *)Data)); + DEBUG ((DEBUG_INFO, Parser[Index].Format, *(UINT32 *)Data)); break; case 8: - DEBUG ((DEBUG_ERROR, Parser[Index].Format, ReadUnaligned64 (Data))); + DEBUG ((DEBUG_INFO, Parser[Index].Format, ReadUnaligned64 (Data))); break; default: DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, "\nERROR: %a: CANNOT PARSE THIS FIELD, Field Length = %d\n", Parser[Index].NameStr, Parser[Index].Length @@ -901,7 +901,7 @@ PrintCmObjDesc ( } else if (Parser[Index].SubObjParser != NULL) { SubStructSize = Parser[Index].Length; - DEBUG ((DEBUG_ERROR, "\n")); + DEBUG ((DEBUG_INFO, "\n")); PrintCmObjDesc ( Data, Parser[Index].SubObjParser, @@ -912,14 +912,14 @@ PrintCmObjDesc ( } else { ASSERT (0); DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, "\nERROR: %a: CANNOT PARSE THIS FIELD, Field Length = %d\n", Parser[Index].NameStr, Parser[Index].Length )); } - DEBUG ((DEBUG_ERROR, "\n")); + DEBUG ((DEBUG_INFO, "\n")); Data = (UINT8 *)Data + Parser[Index].Length; } // for } @@ -978,7 +978,7 @@ ParseCmObjDesc ( for (ObjIndex = 0; ObjIndex < ObjectCount; ObjIndex++) { DEBUG (( - DEBUG_ERROR, + DEBUG_INFO, "\n%-*a [%d/%d]:\n", OUTPUT_FIELD_COLUMN_WIDTH, ParserArray->ObjectName, From 9486fbb41b55f0c2562683ac06389b7b4d37f3af Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Mon, 12 Dec 2022 10:51:03 +0000 Subject: [PATCH 0759/1529] DynamicTablesPkg: Fix parsing of serial port node When scanning for the Serial Port in the device tree, the length and value parameters to ScanMem8() are not in the right order. This results in the serial port not being detected if the chosen node in the device tree has additional elements. Therefore, pass the parameters to ScanMem8() in the correct order to fix this issue. Reviewed-by: Pierre Gondois Signed-off-by: Sami Mujawar --- .../Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c index cfd032df4d..732b482eeb 100644 --- a/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c +++ b/DynamicTablesPkg/Library/FdtHwInfoParserLib/Serial/ArmSerialPortParser.c @@ -1,7 +1,7 @@ /** @file Arm Serial Port Parser. - Copyright (c) 2021, ARM Limited. All rights reserved.
+ Copyright (c) 2021 - 2023, Arm Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): @@ -290,7 +290,7 @@ GetSerialConsoleNode ( } // Determine the actual path length, as a colon terminates the path. - Path = ScanMem8 (Prop, ':', PropSize); + Path = ScanMem8 (Prop, PropSize, ':'); if (Path == NULL) { PathLen = (UINT32)AsciiStrLen (Prop); } else { From 45d8bab65736925543d75ee7c5241bb840a8976c Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Mon, 12 Dec 2022 10:40:52 +0000 Subject: [PATCH 0760/1529] ArmVirtPkg: Fix parsing of serial port node When scanning for the Serial Port in the device tree, the length and value parameters to ScanMem8() are not in the right order. This results in the serial port not being detected if the chosen node in the device tree has additional elements. Therefore, pass the parameters to ScanMem8() in the correct order to fix this issue. Reviewed-by: Ard Biesheuvel Reviewed-by: Pierre Gondois Signed-off-by: Sami Mujawar --- .../EarlyFdt16550SerialPortHookLib.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.c b/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.c index fb1daf3276..c1b8192021 100644 --- a/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.c +++ b/ArmVirtPkg/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.c @@ -1,7 +1,7 @@ /** @file Early Platform Hook Library instance for 16550 Uart. - Copyright (c) 2020, ARM Ltd. All rights reserved.
+ Copyright (c) 2020 - 2023, Arm Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -67,7 +67,7 @@ GetSerialConsolePortAddress ( } // Determine the actual path length, as a colon terminates the path. - Path = ScanMem8 (Prop, ':', PropSize); + Path = ScanMem8 (Prop, PropSize, ':'); if (Path == NULL) { PathLen = AsciiStrLen (Prop); } else { From 58b84788e0d97c9914ea33b059183b2bd6dfc0d8 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Tue, 1 Mar 2022 17:29:51 +0000 Subject: [PATCH 0761/1529] ArmVirtPkg: Fix depex in kvmtool guest Rtc library The Rtc library for the kvmtool guest firmware configures the RTC controller address range as runtime memory by calling the gDS->SetMemorySpaceAttributes(). The SetMemorySpaceAttributes() function has a dependency on the CPU Arch Protocol. If the CPU Arch Protocol is not installed the call to set the memory attributes fails with error code EFI_NOT_AVAILABLE_YET. Therefore, set the library dependency on the CPU Arch protocol. Reviewed-by: Ard Biesheuvel Reviewed-by: Pierre Gondois Signed-off-by: Sami Mujawar --- .../Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.inf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.inf b/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.inf index f0a7c19ca5..c10a6737a0 100644 --- a/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.inf +++ b/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.inf @@ -1,7 +1,7 @@ ## @file # FDT client library for motorola,mc146818 RTC driver # -# Copyright (c) 2020, ARM Limited. All rights reserved.
+# Copyright (c) 2020 - 2023, ARM Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -40,4 +40,4 @@ gPcAtChipsetPkgTokenSpaceGuid.PcdRtcTargetRegister64 [Depex] - gFdtClientProtocolGuid + gFdtClientProtocolGuid AND gEfiCpuArchProtocolGuid From 11a7c12eaa18b28b9d53f0d2613edeeec205e26a Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Mon, 27 Mar 2023 17:01:38 +0200 Subject: [PATCH 0762/1529] OvmfPkg/CI: Boot OVMF in SMP mode. Increase the chance that CI finds bugs in MP changes. Signed-off-by: Gerd Hoffmann --- OvmfPkg/PlatformCI/PlatformBuildLib.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OvmfPkg/PlatformCI/PlatformBuildLib.py b/OvmfPkg/PlatformCI/PlatformBuildLib.py index 58dc1189a2..1ff85fdc24 100644 --- a/OvmfPkg/PlatformCI/PlatformBuildLib.py +++ b/OvmfPkg/PlatformCI/PlatformBuildLib.py @@ -196,6 +196,7 @@ def FlashRomImage(self): args = "-debugcon stdio" # write messages to stdio args += " -global isa-debugcon.iobase=0x402" # debug messages out thru virtual io port args += " -net none" # turn off network + args += " -smp 4" args += f" -drive file=fat:rw:{VirtualDrive},format=raw,media=disk" # Mount disk with startup.nsh if (self.env.GetValue("QEMU_HEADLESS").upper() == "TRUE"): @@ -204,7 +205,6 @@ def FlashRomImage(self): if (self.env.GetBuildValue("SMM_REQUIRE") == "1"): args += " -machine q35,smm=on" #,accel=(tcg|kvm)" #args += " -m ..." - #args += " -smp ..." args += " -global driver=cfi.pflash01,property=secure,value=on" args += " -drive if=pflash,format=raw,unit=0,file=" + os.path.join(OutputPath_FV, "OVMF_CODE.fd") + ",readonly=on" args += " -drive if=pflash,format=raw,unit=1,file=" + os.path.join(OutputPath_FV, "OVMF_VARS.fd") From be5dc1e21442cc9b4df7487eba25790cbb96f209 Mon Sep 17 00:00:00 2001 From: Linus Wu Date: Wed, 29 Mar 2023 10:26:00 +0800 Subject: [PATCH 0763/1529] UefiPayloadPkg: Support more input parameter REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4386 Add additional input parameter support --SpecRevision: user input spec version --Revision: user input revision --ProducerId: producer company name 1. UniversalPayloadBuild.py 2. Downgrade spec revision from 0.9 to 0.7 Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Reviewed-by: Gua Guo Signed-off-by: Linus Wu --- UefiPayloadPkg/UniversalPayloadBuild.py | 45 ++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 522855eba4..7cd04fdceb 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -31,11 +31,48 @@ class UPLD_INFO_HEADER(LittleEndianStructure): def __init__(self): self.Identifier = b'PLDH' self.HeaderLength = sizeof(UPLD_INFO_HEADER) - self.SpecRevision = 0x0009 + self.SpecRevision = 0x0070 self.Revision = 0x0000010105 self.ImageId = b'UEFI' self.ProducerId = b'INTEL' +def GenSpecRevision (Argument): + try: + (MajorStr, MinorStr) = Argument.split('.') + except: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + # + # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version. + # + if len(MinorStr) > 0 and len(MinorStr) < 3: + try: + Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4) + except: + raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + if len(MajorStr) > 0 and len(MajorStr) < 3: + try: + Major = int(MajorStr, 16) + except: + raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0) + +def Validate32BitInteger (Argument): + try: + Value = int (Argument, 0) + except: + raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument)) + if Value < 0: + raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument)) + if Value > 0xffffffff: + raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument)) + return Value + def RunCommand(cmd): print(cmd) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE']) @@ -111,6 +148,9 @@ def BuildUniversalPayload(Args, MacroList): # Buid Universal Payload Information Section ".upld_info" # upld_info_hdr = UPLD_INFO_HEADER() + upld_info_hdr.SpecRevision = Args.SpecRevision + upld_info_hdr.Revision = Args.Revision + upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16] upld_info_hdr.ImageId = Args.ImageId.encode()[:16] upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0 fp = open(UpldInfoFile, 'wb') @@ -156,6 +196,9 @@ def main(): parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI') parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.') parser.add_argument("-p", "--pcd", action="append") + parser.add_argument("-s", "--SpecRevision", type=GenSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') + parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build') + parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).') MacroList = {} args = parser.parse_args() if args.Macro is not None: From 5f2e2347c9559b86510c363a67d8d5cff593c6b9 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:32:15 +0100 Subject: [PATCH 0764/1529] MdePkg/ProcessorBind AARCH64: Add asm macro to emit GNU BTI note Implement a CPP macro that can be called from .S files to emit the .note section carrying the annotation that informs the linker that the object file is compatible with BTI control flow integrity checks. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Include/AArch64/ProcessorBind.h | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/MdePkg/Include/AArch64/ProcessorBind.h b/MdePkg/Include/AArch64/ProcessorBind.h index abe2571245..c03594d924 100644 --- a/MdePkg/Include/AArch64/ProcessorBind.h +++ b/MdePkg/Include/AArch64/ProcessorBind.h @@ -186,6 +186,40 @@ typedef INT64 INTN; #define GCC_ASM_IMPORT(func__) \ .extern _CONCATENATE (__USER_LABEL_PREFIX__, func__) + #if defined (__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1 +#define AARCH64_BTI_NOTE() \ + .ifndef .Lgnu_bti_notesize ;\ + .pushsection .note.gnu.property, "a" ;\ + .set NT_GNU_PROPERTY_TYPE_0, 0x5 ;\ + .set GNU_PROPERTY_AARCH64_FEATURE_1_AND, 0xc0000000 ;\ + .set GNU_PROPERTY_AARCH64_FEATURE_1_BTI, 0x1 ;\ + .align 3 ;\ + .long .Lnamesize ;\ + .long .Lgnu_bti_notesize ;\ + .long NT_GNU_PROPERTY_TYPE_0 ;\ +0: .asciz "GNU" ;\ + .set .Lnamesize, . - 0b ;\ + .align 3 ;\ +1: .long GNU_PROPERTY_AARCH64_FEATURE_1_AND ;\ + .long .Lvalsize ;\ +2: .long GNU_PROPERTY_AARCH64_FEATURE_1_BTI ;\ + .set .Lvalsize, . - 2b ;\ + .align 3 ;\ + .set .Lgnu_bti_notesize, . - 1b ;\ + .popsection ;\ + .endif + +#define AARCH64_BTI(__type) \ + AARCH64_BTI_NOTE() ;\ + bti __type + + #endif + +#endif + +#ifndef AARCH64_BTI +#define AARCH64_BTI_NOTE() +#define AARCH64_BTI(__type) #endif /** From 6e43881e821ff771dcd6c7a5ce207487eae0abcd Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:34:58 +0100 Subject: [PATCH 0765/1529] MdePkg/BaseCpuLib AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseCpuLib/AArch64/CpuFlushTlb.S | 1 + MdePkg/Library/BaseCpuLib/AArch64/CpuSleep.S | 1 + 2 files changed, 2 insertions(+) diff --git a/MdePkg/Library/BaseCpuLib/AArch64/CpuFlushTlb.S b/MdePkg/Library/BaseCpuLib/AArch64/CpuFlushTlb.S index 82a7232268..12c2421b6d 100644 --- a/MdePkg/Library/BaseCpuLib/AArch64/CpuFlushTlb.S +++ b/MdePkg/Library/BaseCpuLib/AArch64/CpuFlushTlb.S @@ -26,6 +26,7 @@ GCC_ASM_EXPORT(CpuFlushTlb) # )# # ASM_PFX(CpuFlushTlb): + AARCH64_BTI(c) tlbi vmalle1 // Invalidate Inst TLB and Data TLB dsb sy isb diff --git a/MdePkg/Library/BaseCpuLib/AArch64/CpuSleep.S b/MdePkg/Library/BaseCpuLib/AArch64/CpuSleep.S index 410a271565..6853e0c56e 100644 --- a/MdePkg/Library/BaseCpuLib/AArch64/CpuSleep.S +++ b/MdePkg/Library/BaseCpuLib/AArch64/CpuSleep.S @@ -29,5 +29,6 @@ GCC_ASM_EXPORT(CpuSleep) # ASM_PFX(CpuSleep): + AARCH64_BTI(c) wfi ret From b2e810573da4423bb2e190bc63dd1bd59bee4739 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:36:28 +0100 Subject: [PATCH 0766/1529] MdePkg/BaseIoLibIntrinsic AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseIoLibIntrinsic/AArch64/ArmVirtMmio.S | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/MdePkg/Library/BaseIoLibIntrinsic/AArch64/ArmVirtMmio.S b/MdePkg/Library/BaseIoLibIntrinsic/AArch64/ArmVirtMmio.S index 00f1abec15..77f562697e 100644 --- a/MdePkg/Library/BaseIoLibIntrinsic/AArch64/ArmVirtMmio.S +++ b/MdePkg/Library/BaseIoLibIntrinsic/AArch64/ArmVirtMmio.S @@ -29,6 +29,7 @@ GCC_ASM_EXPORT(MmioWrite64Internal) // @return The value read. // ASM_PFX(MmioRead8Internal): + AARCH64_BTI(c) ldrb w0, [x0] dmb ld ret @@ -44,6 +45,7 @@ ASM_PFX(MmioRead8Internal): // @param Value The value to write to the MMIO register. // ASM_PFX(MmioWrite8Internal): + AARCH64_BTI(c) dmb st strb w1, [x0] ret @@ -60,6 +62,7 @@ ASM_PFX(MmioWrite8Internal): // @return The value read. // ASM_PFX(MmioRead16Internal): + AARCH64_BTI(c) ldrh w0, [x0] dmb ld ret @@ -75,6 +78,7 @@ ASM_PFX(MmioRead16Internal): // @param Value The value to write to the MMIO register. // ASM_PFX(MmioWrite16Internal): + AARCH64_BTI(c) dmb st strh w1, [x0] ret @@ -91,6 +95,7 @@ ASM_PFX(MmioWrite16Internal): // @return The value read. // ASM_PFX(MmioRead32Internal): + AARCH64_BTI(c) ldr w0, [x0] dmb ld ret @@ -106,6 +111,7 @@ ASM_PFX(MmioRead32Internal): // @param Value The value to write to the MMIO register. // ASM_PFX(MmioWrite32Internal): + AARCH64_BTI(c) dmb st str w1, [x0] ret @@ -122,6 +128,7 @@ ASM_PFX(MmioWrite32Internal): // @return The value read. // ASM_PFX(MmioRead64Internal): + AARCH64_BTI(c) ldr x0, [x0] dmb ld ret @@ -137,6 +144,7 @@ ASM_PFX(MmioRead64Internal): // @param Value The value to write to the MMIO register. // ASM_PFX(MmioWrite64Internal): + AARCH64_BTI(c) dmb st str x1, [x0] ret From 969b91e3645959bddd094c6015d9c429b2fc8699 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 27 Mar 2023 12:32:42 +0200 Subject: [PATCH 0767/1529] MdePkg/BaseLib AARCH64: Make LongJump() BTI compatible Currently, the AArch64 implementation of LongJump() avoids using the RET instruction to perform the jump, even though the target address is held in the link register X30, as the nature of a long jump implies that the ordinary return address prediction machinery will not be able to make a correct prediction. However, LongJump() is rarely used, and the return stack will be out of sync in any case, so this optimization has little value in practice, and given that indirect calls other than function returns require a BTI landing pad at the call site, this optimization is not compatible with BTI. So let's just use RET instead. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S b/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S index deefdf526b..1d5cfbf644 100644 --- a/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S +++ b/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S @@ -85,7 +85,6 @@ ASM_PFX(InternalLongJump): cmp w1, #0 mov w0, #1 csel w0, w1, w0, ne - // use br not ret, as ret is guaranteed to mispredict - br x30 + ret ASM_FUNCTION_REMOVE_IF_UNREFERENCED From 7838a5b610613e8eba77559ba252bf1c395fb1f4 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:37:10 +0100 Subject: [PATCH 0768/1529] MdePkg/BaseLib AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseLib/AArch64/CpuBreakpoint.S | 1 + MdePkg/Library/BaseLib/AArch64/DisableInterrupts.S | 1 + MdePkg/Library/BaseLib/AArch64/EnableInterrupts.S | 1 + MdePkg/Library/BaseLib/AArch64/GetInterruptsState.S | 1 + MdePkg/Library/BaseLib/AArch64/MemoryFence.S | 1 + MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S | 2 ++ MdePkg/Library/BaseLib/AArch64/SpeculationBarrier.S | 1 + MdePkg/Library/BaseLib/AArch64/SwitchStack.S | 2 ++ 8 files changed, 10 insertions(+) diff --git a/MdePkg/Library/BaseLib/AArch64/CpuBreakpoint.S b/MdePkg/Library/BaseLib/AArch64/CpuBreakpoint.S index 7524fb1882..24a1ac3718 100644 --- a/MdePkg/Library/BaseLib/AArch64/CpuBreakpoint.S +++ b/MdePkg/Library/BaseLib/AArch64/CpuBreakpoint.S @@ -27,5 +27,6 @@ GCC_ASM_EXPORT(CpuBreakpoint) # ); # ASM_PFX(CpuBreakpoint): + AARCH64_BTI(c) svc 0xdbdb // Superviser exception. Takes 16bit arg -> Armv7 had 'swi' here. ret diff --git a/MdePkg/Library/BaseLib/AArch64/DisableInterrupts.S b/MdePkg/Library/BaseLib/AArch64/DisableInterrupts.S index f0faf16b06..3f56246161 100644 --- a/MdePkg/Library/BaseLib/AArch64/DisableInterrupts.S +++ b/MdePkg/Library/BaseLib/AArch64/DisableInterrupts.S @@ -26,5 +26,6 @@ GCC_ASM_EXPORT(DisableInterrupts) # ); # ASM_PFX(DisableInterrupts): + AARCH64_BTI(c) msr daifset, #DAIF_WR_IRQ_BIT ret diff --git a/MdePkg/Library/BaseLib/AArch64/EnableInterrupts.S b/MdePkg/Library/BaseLib/AArch64/EnableInterrupts.S index 97eeb13fbe..0f1377f51c 100644 --- a/MdePkg/Library/BaseLib/AArch64/EnableInterrupts.S +++ b/MdePkg/Library/BaseLib/AArch64/EnableInterrupts.S @@ -26,5 +26,6 @@ GCC_ASM_EXPORT(EnableInterrupts) # ); # ASM_PFX(EnableInterrupts): + AARCH64_BTI(c) msr daifclr, #DAIF_WR_IRQ_BIT ret diff --git a/MdePkg/Library/BaseLib/AArch64/GetInterruptsState.S b/MdePkg/Library/BaseLib/AArch64/GetInterruptsState.S index bf8b829bb2..26787a5b9b 100644 --- a/MdePkg/Library/BaseLib/AArch64/GetInterruptsState.S +++ b/MdePkg/Library/BaseLib/AArch64/GetInterruptsState.S @@ -33,6 +33,7 @@ GCC_ASM_EXPORT(GetInterruptState) # ); # ASM_PFX(GetInterruptState): + AARCH64_BTI(c) mrs x0, daif tst x0, #DAIF_RD_IRQ_BIT // Check IRQ mask; set Z=1 if clear/unmasked cset w0, eq // if Z=1 (eq) return 1, else 0 diff --git a/MdePkg/Library/BaseLib/AArch64/MemoryFence.S b/MdePkg/Library/BaseLib/AArch64/MemoryFence.S index e553bd2dc9..ad5b92a9a7 100644 --- a/MdePkg/Library/BaseLib/AArch64/MemoryFence.S +++ b/MdePkg/Library/BaseLib/AArch64/MemoryFence.S @@ -28,6 +28,7 @@ GCC_ASM_EXPORT(MemoryFence) # ); # ASM_PFX(MemoryFence): + AARCH64_BTI(c) // System wide Data Memory Barrier. dmb sy ret diff --git a/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S b/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S index 1d5cfbf644..0d902d94d3 100644 --- a/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S +++ b/MdePkg/Library/BaseLib/AArch64/SetJumpLongJump.S @@ -46,6 +46,7 @@ GCC_ASM_EXPORT(InternalLongJump) # ); # ASM_PFX(SetJump): + AARCH64_BTI(c) mov x16, sp // use IP0 so save SP #define REG_PAIR(REG1, REG2, OFFS) stp REG1, REG2, [x0, OFFS] #define REG_ONE(REG1, OFFS) str REG1, [x0, OFFS] @@ -75,6 +76,7 @@ ASM_PFX(SetJump): # ); # ASM_PFX(InternalLongJump): + AARCH64_BTI(c) #define REG_PAIR(REG1, REG2, OFFS) ldp REG1, REG2, [x0, OFFS] #define REG_ONE(REG1, OFFS) ldr REG1, [x0, OFFS] GPR_LAYOUT diff --git a/MdePkg/Library/BaseLib/AArch64/SpeculationBarrier.S b/MdePkg/Library/BaseLib/AArch64/SpeculationBarrier.S index a20d6aed0c..248ee01e52 100644 --- a/MdePkg/Library/BaseLib/AArch64/SpeculationBarrier.S +++ b/MdePkg/Library/BaseLib/AArch64/SpeculationBarrier.S @@ -28,6 +28,7 @@ GCC_ASM_EXPORT(SpeculationBarrier) # ); # ASM_PFX(SpeculationBarrier): + AARCH64_BTI(c) dsb sy isb ret diff --git a/MdePkg/Library/BaseLib/AArch64/SwitchStack.S b/MdePkg/Library/BaseLib/AArch64/SwitchStack.S index f3bce6a09b..837c65b45e 100644 --- a/MdePkg/Library/BaseLib/AArch64/SwitchStack.S +++ b/MdePkg/Library/BaseLib/AArch64/SwitchStack.S @@ -35,6 +35,7 @@ GCC_ASM_EXPORT(CpuPause) # ); # ASM_PFX(InternalSwitchStackAsm): + AARCH64_BTI(c) mov x29, #0 mov x30, x0 mov sp, x3 @@ -57,6 +58,7 @@ ASM_PFX(InternalSwitchStackAsm): # ) # ASM_PFX(CpuPause): + AARCH64_BTI(c) nop nop nop From 6dbb6c6cd541f6c516bccfa81d70e3cc7eede768 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:37:30 +0100 Subject: [PATCH 0769/1529] MdePkg/BaseMemoryLibOptDxe AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareGuid.S | 1 + MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareMem.S | 1 + MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CopyMem.S | 1 + MdePkg/Library/BaseMemoryLibOptDxe/AArch64/ScanMem.S | 1 + MdePkg/Library/BaseMemoryLibOptDxe/AArch64/SetMem.S | 5 +++++ 5 files changed, 9 insertions(+) diff --git a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareGuid.S b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareGuid.S index b7a566fdaf..7f058e94b3 100644 --- a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareGuid.S +++ b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareGuid.S @@ -8,6 +8,7 @@ .align 5 ASM_GLOBAL ASM_PFX(InternalMemCompareGuid) ASM_PFX(InternalMemCompareGuid): + AARCH64_BTI(c) mov x2, xzr ldp x3, x4, [x0] cbz x1, 0f diff --git a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareMem.S b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareMem.S index ffe4b7a0b0..707e06b050 100644 --- a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareMem.S +++ b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CompareMem.S @@ -32,6 +32,7 @@ .p2align 6 ASM_GLOBAL ASM_PFX(InternalMemCompareMem) ASM_PFX(InternalMemCompareMem): + AARCH64_BTI(c) eor tmp1, src1, src2 tst tmp1, #7 b.ne .Lmisaligned8 diff --git a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CopyMem.S b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CopyMem.S index 9fad6d1f26..59a6593d96 100644 --- a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CopyMem.S +++ b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/CopyMem.S @@ -178,6 +178,7 @@ L(copy_long): ASM_GLOBAL ASM_PFX(InternalMemCopyMem) ASM_PFX(InternalMemCopyMem): + AARCH64_BTI(c) sub tmp2, dstin, src cmp count, 96 ccmp tmp2, count, 2, hi diff --git a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/ScanMem.S b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/ScanMem.S index 8673b76eca..55aaf89f56 100644 --- a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/ScanMem.S +++ b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/ScanMem.S @@ -45,6 +45,7 @@ ASM_GLOBAL ASM_PFX(InternalMemScanMem8) ASM_PFX(InternalMemScanMem8): + AARCH64_BTI(c) // Do not dereference srcin if no bytes to compare. cbz cntin, .Lzero_length // diff --git a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/SetMem.S b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/SetMem.S index f974840559..b5618bf09d 100644 --- a/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/SetMem.S +++ b/MdePkg/Library/BaseMemoryLibOptDxe/AArch64/SetMem.S @@ -29,29 +29,34 @@ ASM_GLOBAL ASM_PFX(InternalMemSetMem16) ASM_PFX(InternalMemSetMem16): + AARCH64_BTI(c) dup v0.8H, valw lsl count, count, #1 b 0f ASM_GLOBAL ASM_PFX(InternalMemSetMem32) ASM_PFX(InternalMemSetMem32): + AARCH64_BTI(c) dup v0.4S, valw lsl count, count, #2 b 0f ASM_GLOBAL ASM_PFX(InternalMemSetMem64) ASM_PFX(InternalMemSetMem64): + AARCH64_BTI(c) dup v0.2D, val lsl count, count, #3 b 0f ASM_GLOBAL ASM_PFX(InternalMemZeroMem) ASM_PFX(InternalMemZeroMem): + AARCH64_BTI(c) movi v0.16B, #0 b 0f ASM_GLOBAL ASM_PFX(InternalMemSetMem) ASM_PFX(InternalMemSetMem): + AARCH64_BTI(c) dup v0.16B, valw 0: add dstend, dstin, count mov val, v0.D[0] From 6514186b9ca046d6e44848c46d99eadb235b08ee Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 17:37:55 +0100 Subject: [PATCH 0770/1529] MdePkg/BaseSynchronizationLib AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- .../Library/BaseSynchronizationLib/AArch64/Synchronization.S | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MdePkg/Library/BaseSynchronizationLib/AArch64/Synchronization.S b/MdePkg/Library/BaseSynchronizationLib/AArch64/Synchronization.S index 1a0eb971a6..dfcfc80d0c 100644 --- a/MdePkg/Library/BaseSynchronizationLib/AArch64/Synchronization.S +++ b/MdePkg/Library/BaseSynchronizationLib/AArch64/Synchronization.S @@ -41,6 +41,7 @@ GCC_ASM_EXPORT(InternalSyncDecrement) // IN UINT16 ExchangeValue // ) ASM_PFX(InternalSyncCompareExchange16): + AARCH64_BTI(c) uxth w1, w1 uxth w2, w2 dmb sy @@ -84,6 +85,7 @@ InternalSyncCompareExchange16Fail: // IN UINT32 ExchangeValue // ) ASM_PFX(InternalSyncCompareExchange32): + AARCH64_BTI(c) dmb sy InternalSyncCompareExchange32Again: @@ -124,6 +126,7 @@ InternalSyncCompareExchange32Fail: // IN UINT64 ExchangeValue // ) ASM_PFX(InternalSyncCompareExchange64): + AARCH64_BTI(c) dmb sy InternalSyncCompareExchange64Again: @@ -159,6 +162,7 @@ InternalSyncCompareExchange64Fail: // IN volatile UINT32 *Value // ) ASM_PFX(InternalSyncIncrement): + AARCH64_BTI(c) dmb sy TryInternalSyncIncrement: ldxr w1, [x0] @@ -188,6 +192,7 @@ TryInternalSyncIncrement: // IN volatile UINT32 *Value // ) ASM_PFX(InternalSyncDecrement): + AARCH64_BTI(c) dmb sy TryInternalSyncDecrement: ldxr w1, [x0] From 284976a57e4b504c059ee4fd8ff7f947fb54d128 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 18:12:55 +0100 Subject: [PATCH 0771/1529] MdePkg/BaseRngLib AARCH64: Make asm files BTI compatible Add the BTI instructions and the associated note to make the AArch64 asm objects compatible with BTI enforcement. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseRngLib/AArch64/ArmReadIdIsar0.S | 3 +-- MdePkg/Library/BaseRngLib/AArch64/ArmRng.S | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Library/BaseRngLib/AArch64/ArmReadIdIsar0.S b/MdePkg/Library/BaseRngLib/AArch64/ArmReadIdIsar0.S index 82a00d3622..d30b63fe5c 100644 --- a/MdePkg/Library/BaseRngLib/AArch64/ArmReadIdIsar0.S +++ b/MdePkg/Library/BaseRngLib/AArch64/ArmReadIdIsar0.S @@ -25,7 +25,6 @@ GCC_ASM_EXPORT(ArmReadIdIsar0) # ); # ASM_PFX(ArmReadIdIsar0): + AARCH64_BTI(c) mrs x0, id_aa64isar0_el1 // Read ID_AA64ISAR0 Register ret - - diff --git a/MdePkg/Library/BaseRngLib/AArch64/ArmRng.S b/MdePkg/Library/BaseRngLib/AArch64/ArmRng.S index 5159f467e3..27a847b996 100644 --- a/MdePkg/Library/BaseRngLib/AArch64/ArmRng.S +++ b/MdePkg/Library/BaseRngLib/AArch64/ArmRng.S @@ -31,6 +31,7 @@ GCC_ASM_EXPORT(ArmRndr) # ); # ASM_PFX(ArmRndr): + AARCH64_BTI(c) mrs x1, RNDR str x1, [x0] cset x0, ne // RNDR sets NZCV to 0b0100 on failure From b90f3d01271c1b55c37db83e440d145c99e51086 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 27 Mar 2023 12:10:06 +0200 Subject: [PATCH 0772/1529] ArmPkg: Emit BTI opcodes when BTI codegen is enabled When building with -mbranch-protection=bti, which affects the compiler codegen only, ensure that the assembler based codegen is aligned with this, by emitting the BTI C opcode at the start of each exported function. While most exported functions are not in fact ever called indirectly, whether or not this is the case is a property of the caller so annotating every exported function is a reasonable default. While at it, fix two occurrences in ArmPkg of exported functions that did not use the ASM_FUNC() macro. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- ArmPkg/Include/AsmMacroIoLibV8.h | 3 ++- ArmPkg/Library/ArmExceptionLib/AArch64/ExceptionSupport.S | 3 +-- ArmPkg/Library/ArmSvcLib/AArch64/ArmSvc.S | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ArmPkg/Include/AsmMacroIoLibV8.h b/ArmPkg/Include/AsmMacroIoLibV8.h index 2c2b1cabd0..135aaeca5d 100644 --- a/ArmPkg/Include/AsmMacroIoLibV8.h +++ b/ArmPkg/Include/AsmMacroIoLibV8.h @@ -38,7 +38,8 @@ .global Name ; \ .section #Section, "ax" ; \ .type Name, %function ; \ - Name: + Name: ; \ + AARCH64_BTI(c) #define ASM_FUNC(Name) _ASM_FUNC(ASM_PFX(Name), .text. ## Name) diff --git a/ArmPkg/Library/ArmExceptionLib/AArch64/ExceptionSupport.S b/ArmPkg/Library/ArmExceptionLib/AArch64/ExceptionSupport.S index 9202952ee9..cd9437b6aa 100644 --- a/ArmPkg/Library/ArmExceptionLib/AArch64/ExceptionSupport.S +++ b/ArmPkg/Library/ArmExceptionLib/AArch64/ExceptionSupport.S @@ -94,7 +94,6 @@ GCC_ASM_EXPORT(ExceptionHandlersEnd) GCC_ASM_EXPORT(CommonCExceptionHandler) -GCC_ASM_EXPORT(RegisterEl0Stack) .text @@ -387,6 +386,6 @@ ASM_PFX(CommonExceptionEntry): eret -ASM_PFX(RegisterEl0Stack): +ASM_FUNC(RegisterEl0Stack) msr sp_el0, x0 ret diff --git a/ArmPkg/Library/ArmSvcLib/AArch64/ArmSvc.S b/ArmPkg/Library/ArmSvcLib/AArch64/ArmSvc.S index 1a7c10cb79..bdba9d7fe9 100644 --- a/ArmPkg/Library/ArmSvcLib/AArch64/ArmSvc.S +++ b/ArmPkg/Library/ArmSvcLib/AArch64/ArmSvc.S @@ -5,12 +5,12 @@ // // +#include + .text .align 3 -GCC_ASM_EXPORT(ArmCallSvc) - -ASM_PFX(ArmCallSvc): +ASM_FUNC(ArmCallSvc) // Push frame pointer and return address on the stack stp x29, x30, [sp, #-32]! mov x29, sp From 3b88eb62d973e0766fa003b171063127db438d93 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 18:05:41 +0100 Subject: [PATCH 0773/1529] ArmPkg/GccLto AARCH64: Add BTI note to LTO helper library The GccLto helper library does not contain any code, as its only purpose is to pull in other libraries that implement intrinsics to which the linker's codegen pass may emit calls. So mark it as BTI compatible, so that the linker does not complain about unannotated objects. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- ArmPkg/Library/GccLto/liblto-aarch64.a | Bin 1016 -> 1128 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/ArmPkg/Library/GccLto/liblto-aarch64.a b/ArmPkg/Library/GccLto/liblto-aarch64.a index 2ab00238f0dad882abf08a1fb9623c9cdea9f17b..6ca3932f1cf30e389ab4c9bdbb77c7db729f1f14 100644 GIT binary patch delta 168 zcmeyt{(@tIhNA`(0~|PjSq==G3>tqY22*!rV6PcEC8Uj_b12NO&gG}O#3KJKKPR?Ui hVl0?Ek=dTnWAa62^~n~@5}Xehfog!j1+0LH3joADAhrMi delta 90 zcmaFC@q>MWhWHOg1~_m4vm6*W7+5D8GU;yYX=R*j#AG(vfk|+322%uM!sLTY%O`8F gNN^s2>N1>oP;~M Date: Sun, 26 Mar 2023 10:58:35 +0200 Subject: [PATCH 0774/1529] ArmPkg, BaseTools AARCH64: Add BTI ELF note to .hii objects The ELF based toolchains use objcopy to create HII object files, which contain only a single .hii section. This means no GNU note is inserted that describes the object as compatible with BTI, even though the lack of executable code in such an object makes the distinction irrelevant. However, the linker will not add the note globally to the resulting ELF executable, and this breaks BTI compatibility. So let's insert a GNU BTI-compatible ELF note by hand when generating such object files. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- ArmPkg/Library/GnuNoteBti.bin | Bin 0 -> 32 bytes BaseTools/Conf/tools_def.template | 5 +++-- 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 ArmPkg/Library/GnuNoteBti.bin diff --git a/ArmPkg/Library/GnuNoteBti.bin b/ArmPkg/Library/GnuNoteBti.bin new file mode 100644 index 0000000000000000000000000000000000000000..339567b4e89943c610b44767ddad5f631229ed3b GIT binary patch literal 32 dcmZQ!U| Date: Mon, 27 Mar 2023 12:38:54 +0200 Subject: [PATCH 0775/1529] ArmPlatformPkg/PrePeiCore: Make vector table object BTI compatible The object file containing the vector table does not contain any callable functions, so it will not be implicitly annotated as BTI compatible on BTI builds. So add the annotation by hand, and use the 'empty' type so we get the GNU ELF note but not the actual BTI opcode. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- ArmPlatformPkg/PrePeiCore/AArch64/Exception.S | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ArmPlatformPkg/PrePeiCore/AArch64/Exception.S b/ArmPlatformPkg/PrePeiCore/AArch64/Exception.S index 43e40f97c3..ffb643a56d 100644 --- a/ArmPlatformPkg/PrePeiCore/AArch64/Exception.S +++ b/ArmPlatformPkg/PrePeiCore/AArch64/Exception.S @@ -112,3 +112,5 @@ _DefaultSError_LowerA32: TO_HANDLER VECTOR_END(PeiVectorTable) + +AARCH64_BTI_NOTE() From 9d5a46fd9dac759d6b8cba14933dfabfe8c5323c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 30 Mar 2023 09:16:19 +0200 Subject: [PATCH 0776/1529] ArmVirtPkg/ArmPlatformLibQemu: Make IdMap.S BTI compatible The IdMap.S asm source file has not executable content, but its lack of a BTI annotation prevents the linker from marking any executables it emits as BTI compatible if this object is part of the build. So add the BTI note by hand. Signed-off-by: Ard Biesheuvel --- ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S index 584ffcb3eb..ba65809e7f 100644 --- a/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S +++ b/ArmVirtPkg/Library/ArmPlatformLibQemu/IdMap.S @@ -57,3 +57,5 @@ idmap: /* level 0 */ .quad PAGE_XIP | (idx << 12) // 2044 KiB of R-X flash mappings .set idx, idx + 1 .endr + +AARCH64_BTI_NOTE() From 953d51c92194489b40212202417dcc683b8de5cb Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 2 Feb 2023 19:03:33 +0100 Subject: [PATCH 0777/1529] MdePkg: Update MemoryAttributesTable to v2.10 UEFI v2.10 introduces a new flag to the memory attributes table to inform the OS whether or not runtime services code regions were emitted by the compiler with guard instructions for forward edge control flow integrity enforcement. So update our definition accordingly. Link: https://uefi.org/specs/UEFI/2.10/04_EFI_System_Table.html#efi-memory-attributes-table Signed-off-by: Ard Biesheuvel Reviewed-by: Michael D Kinney Acked-by: Michael Kubacki Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny --- MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 2 +- MdePkg/Include/Guid/MemoryAttributesTable.h | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c index e079213711..82fa026bce 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c @@ -182,7 +182,7 @@ InstallMemoryAttributesTable ( MemoryAttributesTable->Version = EFI_MEMORY_ATTRIBUTES_TABLE_VERSION; MemoryAttributesTable->NumberOfEntries = RuntimeEntryCount; MemoryAttributesTable->DescriptorSize = (UINT32)DescriptorSize; - MemoryAttributesTable->Reserved = 0; + MemoryAttributesTable->Flags = 0; DEBUG ((DEBUG_VERBOSE, "MemoryAttributesTable:\n")); DEBUG ((DEBUG_VERBOSE, " Version - 0x%08x\n", MemoryAttributesTable->Version)); DEBUG ((DEBUG_VERBOSE, " NumberOfEntries - 0x%08x\n", MemoryAttributesTable->NumberOfEntries)); diff --git a/MdePkg/Include/Guid/MemoryAttributesTable.h b/MdePkg/Include/Guid/MemoryAttributesTable.h index 82f83a67b9..238c14ff92 100644 --- a/MdePkg/Include/Guid/MemoryAttributesTable.h +++ b/MdePkg/Include/Guid/MemoryAttributesTable.h @@ -17,11 +17,15 @@ typedef struct { UINT32 Version; UINT32 NumberOfEntries; UINT32 DescriptorSize; - UINT32 Reserved; + UINT32 Flags; // EFI_MEMORY_DESCRIPTOR Entry[1]; } EFI_MEMORY_ATTRIBUTES_TABLE; -#define EFI_MEMORY_ATTRIBUTES_TABLE_VERSION 0x00000001 +#define EFI_MEMORY_ATTRIBUTES_TABLE_VERSION 0x00000002 + +#define EFI_MEMORY_ATTRIBUTES_FLAGS_RT_FORWARD_CONTROL_FLOW_GUARD 0x1 +// BIT0 implies that Runtime code includes the forward control flow guard +// instruction, such as X86 CET-IBT or ARM BTI. extern EFI_GUID gEfiMemoryAttributesTableGuid; From b3e12b0c27ad7e4c867bad53acd3f796a758bd14 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Wed, 8 Mar 2023 10:53:56 +0800 Subject: [PATCH 0778/1529] RedfishPkg/RedfishPlatformCredentialIpmiLib: IPMI implementation This library follows Redfish Host Interface specification and use IPMI command to get bootstrap account credential(NetFn 2Ch, Command 02h) from BMC. RedfishHostInterfaceDxe will use this credential for the following communication between BIOS and BMC. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Igor Kulchytskyy --- .../RedfishPlatformCredentialIpmiLib.c | 458 ++++++++++++++++++ .../RedfishPlatformCredentialIpmiLib.h | 89 ++++ .../RedfishPlatformCredentialIpmiLib.inf | 42 ++ RedfishPkg/RedfishLibs.dsc.inc | 1 + RedfishPkg/RedfishPkg.dec | 7 + RedfishPkg/RedfishPkg.dsc | 2 + 6 files changed, 599 insertions(+) create mode 100644 RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c create mode 100644 RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.h create mode 100644 RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf diff --git a/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c new file mode 100644 index 0000000000..dacb09bb23 --- /dev/null +++ b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c @@ -0,0 +1,458 @@ +/** @file + Implementation of getting bootstrap credential via IPMI. + + Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Specification Reference: + - Redfish Host Interface Specification + (https://www.dmtf.org/sites/default/files/standards/documents/DSP0270_1.3.0.pdf) +**/ + +#include "RedfishPlatformCredentialIpmiLib.h" + +// +// Global flag of controlling credential service +// +BOOLEAN mRedfishServiceStopped = FALSE; + +/** + Notify the Redfish service provide to stop provide configuration service to this platform. + + This function should be called when the platform is about to leave the safe environment. + It will notify the Redfish service provider to abort all login session, and prohibit + further login with original auth info. GetAuthInfo() will return EFI_UNSUPPORTED once this + function is returned. + + @param[in] This Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL instance. + @param[in] ServiceStopType Reason of stopping Redfish service. + + @retval EFI_SUCCESS Service has been stoped successfully. + @retval EFI_INVALID_PARAMETER This is NULL. + @retval Others Some error happened. + +**/ +EFI_STATUS +EFIAPI +LibStopRedfishService ( + IN EDKII_REDFISH_CREDENTIAL_PROTOCOL *This, + IN EDKII_REDFISH_CREDENTIAL_STOP_SERVICE_TYPE ServiceStopType + ) +{ + EFI_STATUS Status; + + if ((ServiceStopType <= ServiceStopTypeNone) || (ServiceStopType >= ServiceStopTypeMax)) { + return EFI_INVALID_PARAMETER; + } + + // + // Only stop credential service after leaving BIOS + // + if (ServiceStopType != ServiceStopTypeExitBootService) { + return EFI_UNSUPPORTED; + } + + // + // Raise flag first + // + mRedfishServiceStopped = TRUE; + + // + // Delete cached variable + // + Status = SetBootstrapAccountCredentialsToVariable (NULL, NULL, TRUE); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: fail to remove bootstrap credential: %r\n", __FUNCTION__, Status)); + } + + DEBUG ((DEBUG_INFO, "%a: bootstrap credential service stopped\n", __FUNCTION__)); + + return EFI_SUCCESS; +} + +/** + Notification of Exit Boot Service. + + @param[in] This Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL. +**/ +VOID +EFIAPI +LibCredentialExitBootServicesNotify ( + IN EDKII_REDFISH_CREDENTIAL_PROTOCOL *This + ) +{ + // + // Stop the credential support when system is about to enter OS. + // + LibStopRedfishService (This, ServiceStopTypeExitBootService); +} + +/** + Notification of End of DXe. + + @param[in] This Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL. +**/ +VOID +EFIAPI +LibCredentialEndOfDxeNotify ( + IN EDKII_REDFISH_CREDENTIAL_PROTOCOL *This + ) +{ + // + // Do nothing now. + // We can stop credential support when system reach end-of-dxe for security reason. + // +} + +/** + Function to retrieve temporary user credentials for the UEFI redfish client. This function can + also disable bootstrap credential service in BMC. + + @param[in] DisableBootstrapControl TRUE - Tell the BMC to disable the bootstrap credential + service to ensure no one else gains credentials + FALSE Allow the bootstrap credential service to continue + @param[in,out] BootstrapUsername A pointer to a Ascii encoded string for the credential username + When DisableBootstrapControl is TRUE, this pointer can be NULL + @param[in] BootstrapUsernameSize The size of BootstrapUsername including NULL terminator in bytes. + Per specification, the size is USERNAME_MAX_SIZE. + @param[in,out] BootstrapPassword A pointer to a Ascii encoded string for the credential password + When DisableBootstrapControl is TRUE, this pointer can be NULL + @param[in] BootstrapPasswordSize The size of BootstrapPassword including NULL terminator in bytes. + Per specification, the size is PASSWORD_MAX_SIZE. + + @retval EFI_SUCCESS Credentials were successfully fetched and returned. When DisableBootstrapControl + is set to TRUE, the bootstrap credential service is disabled successfully. + @retval EFI_INVALID_PARAMETER BootstrapUsername or BootstrapPassword is NULL when DisableBootstrapControl + is set to FALSE. BootstrapUsernameSize or BootstrapPasswordSize is incorrect when + DisableBootstrapControl is set to FALSE. + @retval EFI_DEVICE_ERROR An IPMI failure occurred +**/ +EFI_STATUS +GetBootstrapAccountCredentials ( + IN BOOLEAN DisableBootstrapControl, + IN OUT CHAR8 *BootstrapUsername, OPTIONAL + IN UINTN BootstrapUsernameSize, + IN OUT CHAR8 *BootstrapPassword, OPTIONAL + IN UINTN BootstrapPasswordSize + ) +{ + EFI_STATUS Status; + IPMI_BOOTSTRAP_CREDENTIALS_COMMAND_DATA CommandData; + IPMI_BOOTSTRAP_CREDENTIALS_RESULT_RESPONSE ResponseData; + UINT32 ResponseSize; + + // + // NULL buffer check + // + if (!DisableBootstrapControl && ((BootstrapUsername == NULL) || (BootstrapPassword == NULL))) { + return EFI_INVALID_PARAMETER; + } + + if ((BootstrapUsernameSize != USERNAME_MAX_SIZE) || (BootstrapPasswordSize != PASSWORD_MAX_SIZE)) { + return EFI_INVALID_PARAMETER; + } + + DEBUG ((DEBUG_VERBOSE, "%a: Disable bootstrap control: 0x%x\n", __FUNCTION__, DisableBootstrapControl)); + + // + // IPMI callout to NetFn 2C, command 02 + // Request data: + // Byte 1: REDFISH_IPMI_GROUP_EXTENSION + // Byte 2: DisableBootstrapControl + // + CommandData.GroupExtensionId = REDFISH_IPMI_GROUP_EXTENSION; + CommandData.DisableBootstrapControl = (DisableBootstrapControl ? REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_DISABLE : REDFISH_IPMI_BOOTSTRAP_CREDENTIAL_ENABLE); + + ResponseSize = sizeof (ResponseData); + + // + // Response data: + // Byte 1 : Completion code + // Byte 2 : REDFISH_IPMI_GROUP_EXTENSION + // Byte 3-18 : Username + // Byte 19-34: Password + // + Status = IpmiSubmitCommand ( + IPMI_NETFN_GROUP_EXT, + REDFISH_IPMI_GET_BOOTSTRAP_CREDENTIALS_CMD, + (UINT8 *)&CommandData, + sizeof (CommandData), + (UINT8 *)&ResponseData, + &ResponseSize + ); + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: IPMI transaction failure. Returning\n", __FUNCTION__)); + return Status; + } else { + if (ResponseData.CompletionCode != IPMI_COMP_CODE_NORMAL) { + if (ResponseData.CompletionCode == REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED) { + DEBUG ((DEBUG_ERROR, "%a: bootstrap credential support was disabled\n", __FUNCTION__)); + return EFI_ACCESS_DENIED; + } + + DEBUG ((DEBUG_ERROR, "%a: Completion code = 0x%x. Returning\n", __FUNCTION__, ResponseData.CompletionCode)); + return EFI_PROTOCOL_ERROR; + } else if (ResponseData.GroupExtensionId != REDFISH_IPMI_GROUP_EXTENSION) { + DEBUG ((DEBUG_ERROR, "%a: Group Extension Response = 0x%x. Returning\n", __FUNCTION__, ResponseData.GroupExtensionId)); + return EFI_DEVICE_ERROR; + } else { + if (BootstrapUsername != NULL) { + CopyMem (BootstrapUsername, ResponseData.Username, USERNAME_MAX_LENGTH); + // + // Manually append null-terminator in case 16 characters username returned. + // + BootstrapUsername[USERNAME_MAX_LENGTH] = '\0'; + } + + if (BootstrapPassword != NULL) { + CopyMem (BootstrapPassword, ResponseData.Password, PASSWORD_MAX_LENGTH); + // + // Manually append null-terminator in case 16 characters password returned. + // + BootstrapPassword[PASSWORD_MAX_LENGTH] = '\0'; + } + } + } + + DEBUG ((DEBUG_INFO, "%a: get bootstrap credential via IPMI: %r\n", __FUNCTION__, Status)); + + return Status; +} + +/** + Function to retrieve temporary user credentials from cached boot time variable. + + @param[in,out] BootstrapUsername A pointer to a Ascii encoded string for the credential username. + @param[in] BootstrapUsernameSize The size of BootstrapUsername including NULL terminator in bytes. + Per specification, the size is USERNAME_MAX_SIZE. + @param[in,out] BootstrapPassword A pointer to a Ascii encoded string for the credential password. + @param[in] BootstrapPasswordSize The size of BootstrapPassword including NULL terminator in bytes. + Per specification, the size is PASSWORD_MAX_SIZE. + + @retval EFI_SUCCESS Credentials were successfully fetched and returned. + @retval EFI_INVALID_PARAMETER BootstrapUsername or BootstrapPassword is NULL. + BootstrapUsernameSize or BootstrapPasswordSize is incorrect. + @retval EFI_NOT_FOUND No variable found for account and credentials. +**/ +EFI_STATUS +GetBootstrapAccountCredentialsFromVariable ( + IN OUT CHAR8 *BootstrapUsername, + IN UINTN BootstrapUsernameSize, + IN OUT CHAR8 *BootstrapPassword, + IN UINTN BootstrapPasswordSize + ) +{ + EFI_STATUS Status; + BOOTSTRAP_CREDENTIALS_VARIABLE *CredentialVariable; + VOID *Data; + UINTN DataSize; + + if ((BootstrapUsername == NULL) || (BootstrapPassword == NULL)) { + return EFI_INVALID_PARAMETER; + } + + if ((BootstrapUsernameSize != USERNAME_MAX_SIZE) || (BootstrapPasswordSize != PASSWORD_MAX_SIZE)) { + return EFI_INVALID_PARAMETER; + } + + DataSize = 0; + Status = GetVariable2 ( + CREDENTIAL_VARIABLE_NAME, + &gEfiRedfishVariableGuid, + (VOID *)&Data, + &DataSize + ); + if (EFI_ERROR (Status)) { + return EFI_NOT_FOUND; + } + + if (DataSize != sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE)) { + DEBUG ((DEBUG_ERROR, "%a: data corruption. returned size: %d != structure size: %d\n", __FUNCTION__, DataSize, sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE))); + FreePool (Data); + return EFI_NOT_FOUND; + } + + CredentialVariable = (BOOTSTRAP_CREDENTIALS_VARIABLE *)Data; + + AsciiStrCpyS (BootstrapUsername, USERNAME_MAX_SIZE, CredentialVariable->Username); + AsciiStrCpyS (BootstrapPassword, PASSWORD_MAX_SIZE, CredentialVariable->Password); + + ZeroMem (CredentialVariable->Username, USERNAME_MAX_SIZE); + ZeroMem (CredentialVariable->Password, PASSWORD_MAX_SIZE); + + FreePool (Data); + + DEBUG ((DEBUG_INFO, "%a: get bootstrap credential from variable\n", __FUNCTION__)); + + return EFI_SUCCESS; +} + +/** + Function to save temporary user credentials into boot time variable. When DeleteVariable is True, + this function delete boot time variable. + + @param[in] BootstrapUsername A pointer to a Ascii encoded string for the credential username. + @param[in] BootstrapPassword A pointer to a Ascii encoded string for the credential password. + @param[in] DeleteVariable True to remove boot time variable. False otherwise. + + @retval EFI_SUCCESS Credentials were successfully saved. + @retval EFI_INVALID_PARAMETER BootstrapUsername or BootstrapPassword is NULL + @retval Others Error occurs +**/ +EFI_STATUS +SetBootstrapAccountCredentialsToVariable ( + IN CHAR8 *BootstrapUsername, OPTIONAL + IN CHAR8 *BootstrapPassword, OPTIONAL + IN BOOLEAN DeleteVariable + ) +{ + EFI_STATUS Status; + BOOTSTRAP_CREDENTIALS_VARIABLE CredentialVariable; + VOID *Data; + + if (!DeleteVariable && ((BootstrapUsername == NULL) || (BootstrapUsername[0] == '\0'))) { + return EFI_INVALID_PARAMETER; + } + + if (!DeleteVariable && ((BootstrapPassword == NULL) || (BootstrapPassword[0] == '\0'))) { + return EFI_INVALID_PARAMETER; + } + + // + // Delete variable + // + Status = GetVariable2 ( + CREDENTIAL_VARIABLE_NAME, + &gEfiRedfishVariableGuid, + (VOID *)&Data, + NULL + ); + if (!EFI_ERROR (Status)) { + FreePool (Data); + gRT->SetVariable ( + CREDENTIAL_VARIABLE_NAME, + &gEfiRedfishVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS, + 0, + NULL + ); + } + + // + // This is request to delete credentials. We are done. + // + if (DeleteVariable) { + return EFI_SUCCESS; + } + + ZeroMem (CredentialVariable.Username, USERNAME_MAX_SIZE); + ZeroMem (CredentialVariable.Password, PASSWORD_MAX_SIZE); + + AsciiStrCpyS (CredentialVariable.Username, USERNAME_MAX_SIZE, BootstrapUsername); + AsciiStrCpyS (CredentialVariable.Password, PASSWORD_MAX_SIZE, BootstrapPassword); + + Status = gRT->SetVariable ( + CREDENTIAL_VARIABLE_NAME, + &gEfiRedfishVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS, + sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE), + (VOID *)&CredentialVariable + ); + + ZeroMem (CredentialVariable.Username, USERNAME_MAX_SIZE); + ZeroMem (CredentialVariable.Password, PASSWORD_MAX_SIZE); + + return Status; +} + +/** + Retrieve platform's Redfish authentication information. + + This functions returns the Redfish authentication method together with the user Id and + password. + - For AuthMethodNone, the UserId and Password could be used for HTTP header authentication + as defined by RFC7235. + - For AuthMethodRedfishSession, the UserId and Password could be used for Redfish + session login as defined by Redfish API specification (DSP0266). + + Callers are responsible for and freeing the returned string storage. + + @param[in] This Pointer to EDKII_REDFISH_CREDENTIAL_PROTOCOL instance. + @param[out] AuthMethod Type of Redfish authentication method. + @param[out] UserId The pointer to store the returned UserId string. + @param[out] Password The pointer to store the returned Password string. + + @retval EFI_SUCCESS Get the authentication information successfully. + @retval EFI_ACCESS_DENIED SecureBoot is disabled after EndOfDxe. + @retval EFI_INVALID_PARAMETER This or AuthMethod or UserId or Password is NULL. + @retval EFI_OUT_OF_RESOURCES There are not enough memory resources. + @retval EFI_UNSUPPORTED Unsupported authentication method is found. + +**/ +EFI_STATUS +EFIAPI +LibCredentialGetAuthInfo ( + IN EDKII_REDFISH_CREDENTIAL_PROTOCOL *This, + OUT EDKII_REDFISH_AUTH_METHOD *AuthMethod, + OUT CHAR8 **UserId, + OUT CHAR8 **Password + ) +{ + EFI_STATUS Status; + BOOLEAN DisableCredentialService; + + if ((AuthMethod == NULL) || (UserId == NULL) || (Password == NULL)) { + return EFI_INVALID_PARAMETER; + } + + *UserId = NULL; + *Password = NULL; + DisableCredentialService = PcdGetBool (PcdRedfishDisableBootstrapCredentialService); + + if (mRedfishServiceStopped) { + DEBUG ((DEBUG_ERROR, "%a: credential service is stopped due to security reason\n", __FUNCTION__)); + return EFI_ACCESS_DENIED; + } + + *AuthMethod = AuthMethodHttpBasic; + + *UserId = AllocateZeroPool (sizeof (CHAR8) * USERNAME_MAX_SIZE); + if (*UserId == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + *Password = AllocateZeroPool (sizeof (CHAR8) * PASSWORD_MAX_SIZE); + if (*Password == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Get bootstrap credential from variable first + // + Status = GetBootstrapAccountCredentialsFromVariable (*UserId, USERNAME_MAX_SIZE, *Password, PASSWORD_MAX_SIZE); + if (!EFI_ERROR (Status)) { + return EFI_SUCCESS; + } + + // + // Make a IPMI query + // + Status = GetBootstrapAccountCredentials (DisableCredentialService, *UserId, USERNAME_MAX_SIZE, *Password, PASSWORD_MAX_SIZE); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: fail to get bootstrap credential: %r\n", __FUNCTION__, Status)); + return Status; + } + + if (DisableCredentialService) { + DEBUG ((DEBUG_INFO, "%a: credential bootstrapping control disabled\n", __FUNCTION__)); + } + + Status = SetBootstrapAccountCredentialsToVariable (*UserId, *Password, FALSE); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: fail to cache bootstrap credential: %r\n", __FUNCTION__, Status)); + } + + return EFI_SUCCESS; +} diff --git a/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.h b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.h new file mode 100644 index 0000000000..898ee88844 --- /dev/null +++ b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.h @@ -0,0 +1,89 @@ +/** @file + Header file for RedfishPlatformCredentialIpmiLib. + + Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef REDFISH_PLATFORM_CREDENTIAL_IPMI_LIB_H_ +#define REDFISH_PLATFORM_CREDENTIAL_IPMI_LIB_H_ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define CREDENTIAL_VARIABLE_NAME L"Partstooblaitnederc" + +/// +/// The bootstrap credential keeping in UEFI variable +/// +typedef struct { + CHAR8 Username[USERNAME_MAX_SIZE]; + CHAR8 Password[PASSWORD_MAX_SIZE]; +} BOOTSTRAP_CREDENTIALS_VARIABLE; + +/** + Function to retrieve temporary user credentials for the UEFI redfish client. This function can + also disable bootstrap credential service in BMC. + + @param[in] DisableBootstrapControl TRUE - Tell the BMC to disable the bootstrap credential + service to ensure no one else gains credentials + FALSE Allow the bootstrap credential service to continue + @param[in,out] BootstrapUsername A pointer to a Ascii encoded string for the credential username + When DisableBootstrapControl is TRUE, this pointer can be NULL + @param[in] BootstrapUsernameSize The size of BootstrapUsername including NULL terminator in bytes. + Per specification, the size is USERNAME_MAX_SIZE. + @param[in,out] BootstrapPassword A pointer to a Ascii encoded string for the credential password + When DisableBootstrapControl is TRUE, this pointer can be NULL + @param[in] BootstrapPasswordSize The size of BootstrapPassword including NULL terminator in bytes. + Per specification, the size is PASSWORD_MAX_SIZE. + + @retval EFI_SUCCESS Credentials were successfully fetched and returned. When DisableBootstrapControl + is set to TRUE, the bootstrap credential service is disabled successfully. + @retval EFI_INVALID_PARAMETER BootstrapUsername or BootstrapPassword is NULL when DisableBootstrapControl + is set to FALSE. BootstrapUsernameSize or BootstrapPasswordSize is incorrect when + DisableBootstrapControl is set to FALSE. + @retval EFI_DEVICE_ERROR An IPMI failure occurred +**/ +EFI_STATUS +GetBootstrapAccountCredentials ( + IN BOOLEAN DisableBootstrapControl, + IN OUT CHAR8 *BootstrapUsername, OPTIONAL + IN UINTN BootstrapUsernameSize, + IN OUT CHAR8 *BootstrapPassword, OPTIONAL + IN UINTN BootstrapPasswordSize + ); + +/** + Function to save temporary user credentials into boot time variable. When DeleteVariable is True, + this function delete boot time variable. + + @param[in] BootstrapUsername A pointer to a Ascii encoded string for the credential username. + @param[in] BootstrapPassword A pointer to a Ascii encoded string for the credential password. + @param[in] DeleteVariable True to remove boot time variable. False otherwise. + + @retval EFI_SUCCESS Credentials were successfully saved. + @retval EFI_INVALID_PARAMETER BootstrapUsername or BootstrapPassword is NULL + @retval Others Error occurs +**/ +EFI_STATUS +SetBootstrapAccountCredentialsToVariable ( + IN CHAR8 *BootstrapUsername, OPTIONAL + IN CHAR8 *BootstrapPassword, OPTIONAL + IN BOOLEAN DeleteVariable + ); + +#endif diff --git a/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf new file mode 100644 index 0000000000..5c20ea22f8 --- /dev/null +++ b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf @@ -0,0 +1,42 @@ +## @file +# INF file for RedfishPlatformCredentialIpmiLib. +# +# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001000b + BASE_NAME = RedfishPlatformCredentialIpmiLib + FILE_GUID = 9C45D622-4C66-417F-814C-F76246D97233 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = RedfishPlatformCredentialIpmiLib + +[Sources] + RedfishPlatformCredentialIpmiLib.c + RedfishPlatformCredentialIpmiLib.h + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + RedfishPkg/RedfishPkg.dec + +[LibraryClasses] + UefiLib + DebugLib + IpmiLib + MemoryAllocationLib + BaseMemoryLib + UefiRuntimeServicesTableLib + +[Pcd] + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishDisableBootstrapCredentialService + +[Guids] + gEfiRedfishVariableGuid + +[Depex] + TRUE diff --git a/RedfishPkg/RedfishLibs.dsc.inc b/RedfishPkg/RedfishLibs.dsc.inc index 84f52d4b27..110526738c 100644 --- a/RedfishPkg/RedfishLibs.dsc.inc +++ b/RedfishPkg/RedfishLibs.dsc.inc @@ -19,5 +19,6 @@ JsonLib|RedfishPkg/Library/JsonLib/JsonLib.inf RedfishLib|RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf RedfishDebugLib|RedfishPkg/Library/RedfishDebugLib/RedfishDebugLib.inf + RedfishPlatformCredentialLib|RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf !endif diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index 42d28d6dac..f171053aec 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -81,6 +81,9 @@ [Guids] gEfiRedfishPkgTokenSpaceGuid = { 0x4fdbccb7, 0xe829, 0x4b4c, { 0x88, 0x87, 0xb2, 0x3f, 0xd7, 0x25, 0x4b, 0x85 }} + # Redfish variable guid + gEfiRedfishVariableGuid = { 0x85ef8dd3, 0xe606, 0x4b89, { 0x8b, 0xbd, 0x93, 0xbf, 0x5c, 0xbe, 0x1c, 0x18 } } + [PcdsFixedAtBuild, PcdsPatchableInModule] # # This PCD is the UEFI device path which is used as the Redfish host interface. @@ -123,3 +126,7 @@ # specification for that. # gEfiRedfishPkgTokenSpaceGuid.PcdRedfishServiceUuid|L"00000000-0000-0000-0000-000000000000"|VOID*|0x00001006 + # + # This PCD indicates that if BMC bootstrap credential service will be disabled by BIOS or not. + # + gEfiRedfishPkgTokenSpaceGuid.PcdRedfishDisableBootstrapCredentialService|FALSE|BOOLEAN|0x00001007 diff --git a/RedfishPkg/RedfishPkg.dsc b/RedfishPkg/RedfishPkg.dsc index 223ab72c1d..5503e65de4 100644 --- a/RedfishPkg/RedfishPkg.dsc +++ b/RedfishPkg/RedfishPkg.dsc @@ -4,6 +4,7 @@ # Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.
# (C) Copyright 2021 Hewlett-Packard Enterprise Development LP. # Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -59,6 +60,7 @@ RedfishPkg/Library/PlatformHostInterfaceLibNull/PlatformHostInterfaceLibNull.inf RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.inf RedfishPkg/Library/PlatformCredentialLibNull/PlatformCredentialLibNull.inf + RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.inf RedfishPkg/Library/RedfishContentCodingLibNull/RedfishContentCodingLibNull.inf RedfishPkg/Library/DxeRestExLib/DxeRestExLib.inf RedfishPkg/Library/BaseUcs2Utf8Lib/BaseUcs2Utf8Lib.inf From c447745815e2c0fd00ffe46cc28948c8f54ab998 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Wed, 29 Mar 2023 14:22:38 -0700 Subject: [PATCH 0779/1529] PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe: PcdRtcDefaultYear bounds Add bounds checks of PcdRtcDefaultYear to guarantee that the year is always between PcdMinimalValidYear and PcdMaximalValidYear. This is required to make the following commit a backwards compatible change and guarantee and invalid year is never set. https://github.com/tianocore/edk2/commit/d55d73152ebf5c793b645d6ec5bc517d219881cd This is required because use of an expression in the DEC file PCD default value is only used to determine the DEC default values. If an INF/DSC overrides PcdRtcDefaultYear, then the DEC expression for PcdMinimalValidYear is not applied again. Cc: Ray Ni Signed-off-by: Michael D Kinney Reviewed-by: Ray Ni --- PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c index b059e92f02..15759463f2 100644 --- a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c +++ b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c @@ -317,7 +317,8 @@ PcRtcInit ( Time.Hour = RTC_INIT_HOUR; Time.Day = RTC_INIT_DAY; Time.Month = RTC_INIT_MONTH; - Time.Year = PcdGet16 (PcdRtcDefaultYear); + Time.Year = MAX (PcdGet16 (PcdRtcDefaultYear), PcdGet16 (PcdMinimalValidYear)); + Time.Year = MIN (Time.Year, PcdGet16 (PcdMaximalValidYear)); Time.Nanosecond = 0; Time.TimeZone = EFI_UNSPECIFIED_TIMEZONE; Time.Daylight = 0; @@ -357,7 +358,8 @@ PcRtcInit ( Time.Hour = RTC_INIT_HOUR; Time.Day = RTC_INIT_DAY; Time.Month = RTC_INIT_MONTH; - Time.Year = PcdGet16 (PcdRtcDefaultYear); + Time.Year = MAX (PcdGet16 (PcdRtcDefaultYear), PcdGet16 (PcdMinimalValidYear)); + Time.Year = MIN (Time.Year, PcdGet16 (PcdMaximalValidYear)); Time.Nanosecond = 0; Time.TimeZone = Global->SavedTimeZone; Time.Daylight = Global->Daylight; From 737702b8f1df72b4d02e016ced55e19bc9ef048e Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 30 Mar 2023 08:13:26 -0700 Subject: [PATCH 0780/1529] .azurepipelines/templates: Increase run to shell timeout Increase the CI agent timeout to boot to UEFI Shell from 1 minute to 2 minutes. There have been a few cases where the boot to shell in QEMU has not quite completed in 1 minute and it is failing the CI check and preventing a PR from being merged. Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki Acked-by: Ard Biesheuvel --- .azurepipelines/templates/platform-build-run-steps.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/platform-build-run-steps.yml b/.azurepipelines/templates/platform-build-run-steps.yml index 087f460d7f..8be46cda0e 100644 --- a/.azurepipelines/templates/platform-build-run-steps.yml +++ b/.azurepipelines/templates/platform-build-run-steps.yml @@ -116,7 +116,7 @@ steps: filename: stuart_build arguments: -c ${{ parameters.build_file }} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} TARGET=${{ parameters.build_target}} -a ${{ parameters.build_arch}} ${{ parameters.build_flags}} ${{ parameters.run_flags }} --FlashOnly condition: and(and(gt(variables.pkg_count, 0), succeeded()), eq(variables['Run'], true)) - timeoutInMinutes: 1 + timeoutInMinutes: 2 # Copy the build logs to the artifact staging directory - task: CopyFiles@2 From c31741de836ac93f3c7cc7699b405fc409ee6528 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 31 Mar 2023 12:10:43 -0400 Subject: [PATCH 0781/1529] OvmfPkg/CI: Revert SMP mode This is causing excessive boot times in the VS2019 IA32/X64 Full run to shell tasks (> 2 minutes) and blocking all edk2 CI. This patch removes the change so it can be root caused separately without blocking other patches unrelated to OVMF. Reverts f92a9dce10281c103b04d6b38283e0ff1d677b91 Cc: Ard Biesheuvel Cc: Jiewen Yao Cc: Jordan Justen Cc: Gerd Hoffmann Cc: Michael D Kinney Signed-off-by: Michael Kubacki --- OvmfPkg/PlatformCI/PlatformBuildLib.py | 1 - 1 file changed, 1 deletion(-) diff --git a/OvmfPkg/PlatformCI/PlatformBuildLib.py b/OvmfPkg/PlatformCI/PlatformBuildLib.py index 1ff85fdc24..64fca48a7d 100644 --- a/OvmfPkg/PlatformCI/PlatformBuildLib.py +++ b/OvmfPkg/PlatformCI/PlatformBuildLib.py @@ -196,7 +196,6 @@ def FlashRomImage(self): args = "-debugcon stdio" # write messages to stdio args += " -global isa-debugcon.iobase=0x402" # debug messages out thru virtual io port args += " -net none" # turn off network - args += " -smp 4" args += f" -drive file=fat:rw:{VirtualDrive},format=raw,media=disk" # Mount disk with startup.nsh if (self.env.GetValue("QEMU_HEADLESS").upper() == "TRUE"): From 7cd147fc43b9c71e6ab20e397cfde9afb5438293 Mon Sep 17 00:00:00 2001 From: "Albecki, Mateusz" Date: Tue, 28 Mar 2023 05:37:35 +0800 Subject: [PATCH 0782/1529] MdeModulePkg/Ahci: Skip retry for non-transient errors bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4011 Currently AHCI driver will try to retry all failed packets regardless of the failure cause. This is a problem in password unlock flow where number of password retries is tracked by the device. If user passes a wrong password Ahci driver will try to send the wrong password multiple times which will exhaust number of password retries and force the user to restart the machine. This commit introduces a logic to check for the cause of packet failure and only retry packets which failed due to transient conditions on the link. With this patch only packets for which CRC error is flagged are retried. Cc: Hao A Wu Cc: Ray Ni Cc: Hunter Chang Cc: Baraneedharan Anbazhagan Signed-off-by: Mateusz Albecki Reviewed-by: Hao A Wu Reviewed-by: Baraneedharan Anbazhagan --- .../Bus/Ata/AtaAtapiPassThru/AhciMode.c | 71 +++++++++++++++++-- .../Bus/Ata/AtaAtapiPassThru/AhciMode.h | 3 +- 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c index 06c4a3e052..c0c8ffbd9e 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c @@ -737,12 +737,68 @@ AhciRecoverPortError ( Status = AhciResetPort (PciIo, Port); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to reset the port %d\n", Port)); + return EFI_DEVICE_ERROR; } } return EFI_SUCCESS; } +/** + This function will check if the failed command should be retired. Only error + conditions which are a result of transient conditions on a link(either to system or to device). + + @param[in] PciIo Pointer to AHCI controller PciIo. + @param[in] Port SATA port index on which to check. + + @retval TRUE Command failure was caused by transient condition and should be retried + @retval FALSE Command should not be retried +**/ +BOOLEAN +AhciShouldCmdBeRetried ( + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port + ) +{ + UINT32 Offset; + UINT32 PortInterrupt; + UINT32 Serr; + UINT32 Tfd; + + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_IS; + PortInterrupt = AhciReadReg (PciIo, Offset); + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_SERR; + Serr = AhciReadReg (PciIo, Offset); + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; + Tfd = AhciReadReg (PciIo, Offset); + + // + // This can occur if there was a CRC error on a path from system memory to + // host controller. + // + if (PortInterrupt & EFI_AHCI_PORT_IS_HBDS) { + return TRUE; + // + // This can occur if there was a CRC error detected by host during communication + // with the device + // + } else if ((PortInterrupt & (EFI_AHCI_PORT_IS_IFS | EFI_AHCI_PORT_IS_INFS)) && + (Serr & EFI_AHCI_PORT_SERR_CRCE)) + { + return TRUE; + // + // This can occur if there was a CRC error detected by device during communication + // with the host. Device returns error status to host with D2H FIS. + // + } else if ((PortInterrupt & EFI_AHCI_PORT_IS_TFES) && + (Tfd & EFI_AHCI_PORT_TFD_ERR_INT_CRC)) + { + return TRUE; + } + + return FALSE; +} + /** Checks if specified FIS has been received. @@ -950,6 +1006,7 @@ AhciPioTransfer ( UINT32 PrdCount; UINT32 Retry; EFI_STATUS RecoveryStatus; + BOOLEAN DoRetry; if (Read) { Flag = EfiPciIoOperationBusMasterWrite; @@ -1027,8 +1084,9 @@ AhciPioTransfer ( if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "PIO command failed at retry %d\n", Retry)); + DoRetry = AhciShouldCmdBeRetried (PciIo, Port); // needs to be called before error recovery RecoveryStatus = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (RecoveryStatus)) { + if (!DoRetry || EFI_ERROR (RecoveryStatus)) { break; } } else { @@ -1124,6 +1182,7 @@ AhciDmaTransfer ( EFI_TPL OldTpl; UINT32 Retry; EFI_STATUS RecoveryStatus; + BOOLEAN DoRetry; Map = NULL; PciIo = Instance->PciIo; @@ -1222,8 +1281,9 @@ AhciDmaTransfer ( Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "DMA command failed at retry: %d\n", Retry)); + DoRetry = AhciShouldCmdBeRetried (PciIo, Port); // needs to be called before error recovery RecoveryStatus = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (RecoveryStatus)) { + if (!DoRetry || EFI_ERROR (RecoveryStatus)) { break; } } else { @@ -1263,6 +1323,7 @@ AhciDmaTransfer ( Status = AhciCheckFisReceived (PciIo, Port, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "DMA command failed at retry: %d\n", Task->RetryTimes)); + DoRetry = AhciShouldCmdBeRetried (PciIo, Port); // call this before error recovery RecoveryStatus = AhciRecoverPortError (PciIo, Port); // // If recovery passed mark the Task as not started and change the status @@ -1270,7 +1331,7 @@ AhciDmaTransfer ( // and on next call the command will be re-issued due to IsStart being FALSE. // This also makes the next condition decrement the RetryTimes. // - if (RecoveryStatus == EFI_SUCCESS) { + if (DoRetry && (RecoveryStatus == EFI_SUCCESS)) { Task->IsStart = FALSE; Status = EFI_NOT_READY; } @@ -1378,6 +1439,7 @@ AhciNonDataTransfer ( EFI_AHCI_COMMAND_LIST CmdList; UINT32 Retry; EFI_STATUS RecoveryStatus; + BOOLEAN DoRetry; // // Package read needed @@ -1418,8 +1480,9 @@ AhciNonDataTransfer ( Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "Non data transfer failed at retry %d\n", Retry)); + DoRetry = AhciShouldCmdBeRetried (PciIo, Port); // call this before error recovery RecoveryStatus = AhciRecoverPortError (PciIo, Port); - if (EFI_ERROR (RecoveryStatus)) { + if (!DoRetry || EFI_ERROR (RecoveryStatus)) { break; } } else { diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h index d7434b408c..5bb31057ec 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h @@ -146,7 +146,8 @@ typedef union { #define EFI_AHCI_PORT_TFD_BSY BIT7 #define EFI_AHCI_PORT_TFD_DRQ BIT3 #define EFI_AHCI_PORT_TFD_ERR BIT0 -#define EFI_AHCI_PORT_TFD_ERR_MASK 0x00FF00 +#define EFI_AHCI_PORT_TFD_ERR_MASK 0x00FF00 // ERROR field is specified by ATA/ATAPI Command Set specification +#define EFI_AHCI_PORT_TFD_ERR_INT_CRC BIT15 #define EFI_AHCI_PORT_SIG 0x0024 #define EFI_AHCI_PORT_SSTS 0x0028 #define EFI_AHCI_PORT_SSTS_DET_MASK 0x000F From ef5d79715e72e9c9b331b12628323d2a087088a0 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Wed, 29 Mar 2023 11:30:31 -0600 Subject: [PATCH 0783/1529] Maintainers.txt: BaseTools Bob Feng -> reviewer, Rebecca Cran -> maintainer Update Maintainers.txt for BaseTools: move Bob Feng from being a maintainer to reviewer, and add myself (Rebecca Cran) as a new maintainer. Signed-off-by: Rebecca Cran Cc: Liming Gao Cc: Bob Feng Reviewed-by: Michael D Kinney Reviewed-by: Bob Feng Reviewed-by: Leif Lindholm Reviewed-by: Liming Gao Acked-by: Ard Biesheuvel --- Maintainers.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index d22224607a..2f8671147a 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -177,8 +177,9 @@ R: Julien Grall [jgrall] BaseTools F: BaseTools/ W: https://github.com/tianocore/tianocore.github.io/wiki/BaseTools -M: Bob Feng [BobCF] +M: Rebecca Cran [bcran] M: Liming Gao [lgao4] +R: Bob Feng [BobCF] R: Yuwei Chen [YuweiChen1110] CryptoPkg From c7f702af1274f10098a7e78abd226113035f3125 Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Sat, 1 Apr 2023 02:19:20 +0800 Subject: [PATCH 0784/1529] UefiCpuPkg/Test: Disable random test cases The random test cases just run for too long that may cause timeout in CI test. Disable them for now. Co-authored-by: Michael Kubacki Signed-off-by: Ray Ni Reviewed-by: Michael Kubacki Reviewed-by: Sean Brogan --- .../UnitTest/CpuPageTableLibUnitTestHost.c | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c index 547f6c2e50..a610011179 100644 --- a/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c +++ b/UefiCpuPkg/Library/CpuPageTableLib/UnitTest/CpuPageTableLibUnitTestHost.c @@ -9,11 +9,11 @@ #include "CpuPageTableLibUnitTest.h" // ----------------------------------------------------------------------- PageMode--TestCount-TestRangeCount---RandomOptions -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 30, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 30, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 30, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 30, 20, USE_RANDOM_ARRAY }; -static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPagingPae = { PagingPae, 30, 20, USE_RANDOM_ARRAY }; +// static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level = { Paging4Level, 30, 20, USE_RANDOM_ARRAY }; +// static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging4Level1GB = { Paging4Level1GB, 30, 20, USE_RANDOM_ARRAY }; +// static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level = { Paging5Level, 30, 20, USE_RANDOM_ARRAY }; +// static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPaging5Level1GB = { Paging5Level1GB, 30, 20, USE_RANDOM_ARRAY }; +// static CPU_PAGE_TABLE_LIB_RANDOM_TEST_CONTEXT mTestContextPagingPae = { PagingPae, 30, 20, USE_RANDOM_ARRAY }; /** Check if the input parameters are not supported. @@ -881,11 +881,11 @@ UefiTestMain ( goto EXIT; } - AddTestCase (RandomTestCase, "Random Test for Paging4Level", "Random Test Case1", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging4Level); - AddTestCase (RandomTestCase, "Random Test for Paging4Level1G", "Random Test Case2", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging4Level1GB); - AddTestCase (RandomTestCase, "Random Test for Paging5Level", "Random Test Case3", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level); - AddTestCase (RandomTestCase, "Random Test for Paging5Level1G", "Random Test Case4", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level1GB); - AddTestCase (RandomTestCase, "Random Test for PagingPae", "Random Test Case5", TestCaseforRandomTest, NULL, NULL, &mTestContextPagingPae); + // AddTestCase (RandomTestCase, "Random Test for Paging4Level", "Random Test Case1", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging4Level); + // AddTestCase (RandomTestCase, "Random Test for Paging4Level1G", "Random Test Case2", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging4Level1GB); + // AddTestCase (RandomTestCase, "Random Test for Paging5Level", "Random Test Case3", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level); + // AddTestCase (RandomTestCase, "Random Test for Paging5Level1G", "Random Test Case4", TestCaseforRandomTest, NULL, NULL, &mTestContextPaging5Level1GB); + // AddTestCase (RandomTestCase, "Random Test for PagingPae", "Random Test Case5", TestCaseforRandomTest, NULL, NULL, &mTestContextPagingPae); // // Execute the tests. From 7132adcebf277b5911fbb5a8c395effe5b417e8e Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 27 Feb 2023 13:26:27 +0800 Subject: [PATCH 0785/1529] MdePkg: Add TME-MK related CPUID and MSR definitions TME (Total Memory Encryption) is the capability to encrypt the entirety of physical memory of a system. TME-MK (Total Memory Encryption-Multi-Key) builds on TME and adds support for multiple encryption keys. The patch adds some necessary CPUID/MSR definitions for TME-MK. Signed-off-by: Ray Ni Cc: Liming Gao Cc: Zhiguang Liu Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- .../Include/Register/Intel/ArchitecturalMsr.h | 106 +++++++++++++++++- MdePkg/Include/Register/Intel/Cpuid.h | 9 +- 2 files changed, 112 insertions(+), 3 deletions(-) diff --git a/MdePkg/Include/Register/Intel/ArchitecturalMsr.h b/MdePkg/Include/Register/Intel/ArchitecturalMsr.h index 071a8c689c..756e7c86ec 100644 --- a/MdePkg/Include/Register/Intel/ArchitecturalMsr.h +++ b/MdePkg/Include/Register/Intel/ArchitecturalMsr.h @@ -6,7 +6,7 @@ returned is a single 32-bit or 64-bit value, then a data structure is not provided for that MSR. - Copyright (c) 2016 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Specification Reference: @@ -5679,6 +5679,110 @@ typedef union { **/ #define MSR_IA32_X2APIC_SELF_IPI 0x0000083F +/** + Memory Encryption Activation MSR. If CPUID.07H:ECX.[13] = 1. + + @param ECX MSR_IA32_TME_ACTIVATE (0x00000982) + @param EAX Lower 32-bits of MSR value. + Described by the type MSR_IA32_TME_ACTIVATE_REGISTER. + @param EDX Upper 32-bits of MSR value. + Described by the type MSR_IA32_TME_ACTIVATE_REGISTER. + + Example usage + @code + MSR_IA32_TME_ACTIVATE_REGISTER Msr; + + Msr.Uint64 = AsmReadMsr64 (MSR_IA32_TME_ACTIVATE); + AsmWriteMsr64 (MSR_IA32_TME_ACTIVATE, Msr.Uint64); + @endcode + @note MSR_IA32_TME_ACTIVATE is defined as IA32_TME_ACTIVATE in SDM. +**/ +#define MSR_IA32_TME_ACTIVATE 0x00000982 + +/** + MSR information returned for MSR index #MSR_IA32_TME_ACTIVATE +**/ +typedef union { + /// + /// Individual bit fields + /// + struct { + /// + /// [Bit 0] Lock R/O: Will be set upon successful WRMSR (or first SMI); + /// written value ignored.. + /// + UINT32 Lock : 1; + /// + /// [Bit 1] Hardware Encryption Enable: This bit also enables MKTME; MKTME + /// cannot be enabled without enabling encryption hardware. + /// + UINT32 TmeEnable : 1; + /// + /// [Bit 2] Key Select: + /// 0: Create a new TME key (expected cold/warm boot). + /// 1: Restore the TME key from storage (Expected when resume from standby). + /// + UINT32 KeySelect : 1; + /// + /// [Bit 3] Save TME Key for Standby: Save key into storage to be used when + /// resume from standby. + /// Note: This may not be supported in all processors. + /// + UINT32 SaveKeyForStandby : 1; + /// + /// [Bit 7:4] TME Policy/Encryption Algorithm: Only algorithms enumerated in + /// IA32_TME_CAPABILITY are allowed. + /// For example: + /// 0000 – AES-XTS-128. + /// 0001 – AES-XTS-128 with integrity. + /// 0010 – AES-XTS-256. + /// Other values are invalid. + /// + UINT32 TmePolicy : 4; + UINT32 Reserved : 23; + /// + /// [Bit 31] TME Encryption Bypass Enable: When encryption hardware is enabled: + /// * Total Memory Encryption is enabled using a CPU generated ephemeral key + /// based on a hardware random number generator when this bit is set to 0. + /// * Total Memory Encryption is bypassed (no encryption/decryption for KeyID0) + /// when this bit is set to 1. + /// Software must inspect Hardware Encryption Enable (bit 1) and TME encryption + /// bypass Enable (bit 31) to determine if TME encryption is enabled. + /// + UINT32 TmeBypassMode : 1; + /// + /// [Bit 35:32] MK_TME_KEYID_BITS: Reserved if MKTME is not enumerated, otherwise: + /// The number of key identifier bits to allocate to MKTME usage. + /// Similar to enumeration, this is an encoded value. + /// Writing a value greater than MK_TME_MAX_KEYID_BITS will result in #GP. + /// Writing a non-zero value to this field will #GP if bit 1 of EAX (Hardware + /// Encryption Enable) is not also set to ‘1, as encryption hardware must be + /// enabled to use MKTME. + /// Example: To support 255 keys, this field would be set to a value of 8. + /// + UINT32 MkTmeKeyidBits : 4; + UINT32 Reserved2 : 12; + /// + /// [Bit 63:48] MK_TME_CRYPTO_ALGS: Reserved if MKTME is not enumerated, otherwise: + /// Bit 48: AES-XTS 128. + /// Bit 49: AES-XTS 128 with integrity. + /// Bit 50: AES-XTS 256. + /// Bit 63:51: Reserved (#GP) + /// Bitmask for BIOS to set which encryption algorithms are allowed for MKTME, would + /// be later enforced by the key loading ISA ('1= allowed) + /// + UINT32 MkTmeCryptoAlgs : 16; + } Bits; + /// + /// All bit fields as a 32-bit value + /// + UINT32 Uint32[2]; + /// + /// All bit fields as a 64-bit value + /// + UINT64 Uint64; +} MSR_IA32_TME_ACTIVATE_REGISTER; + /** Silicon Debug Feature Control (R/W). If CPUID.01H:ECX.[11] = 1. diff --git a/MdePkg/Include/Register/Intel/Cpuid.h b/MdePkg/Include/Register/Intel/Cpuid.h index 350bf60252..1fb880c85c 100644 --- a/MdePkg/Include/Register/Intel/Cpuid.h +++ b/MdePkg/Include/Register/Intel/Cpuid.h @@ -6,7 +6,7 @@ If a register returned is a single 32-bit value, then a data structure is not provided for that register. - Copyright (c) 2015 - 2021, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @par Specification Reference: @@ -1490,7 +1490,12 @@ typedef union { /// RDPKRU/WRPKRU instructions). /// UINT32 OSPKE : 1; - UINT32 Reserved5 : 9; + UINT32 Reserved8 : 8; + /// + /// [Bit 13] If 1, the following MSRs are supported: IA32_TME_CAPABILITY, IA32_TME_ACTIVATE, + /// IA32_TME_EXCLUDE_MASK, and IA32_TME_EXCLUDE_BASE. + /// + UINT32 TME_EN : 1; /// /// [Bits 14] AVX512_VPOPCNTDQ. (Intel Xeon Phi only.). /// From f8a27e5dd91ea5c55972d18689e497949b1dbb3e Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Tue, 28 Feb 2023 16:18:08 +0800 Subject: [PATCH 0786/1529] UefiCpuPkg/MtrrTest: Only claim CPUID max leaf as 1 MtrrLib code queries the CPUID leaf 7h result if support. Update Test code temporary to claim the CPUID only supports max leaf as 1 so MtrrLib skips to query CPUID leaf 7h. Signed-off-by: Ray Ni Cc: Eric Dong Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Michael D Kinney Cc: Ahmad Anadani Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c index 748c403281..260966e7b6 100644 --- a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c @@ -1,7 +1,7 @@ /** @file Unit tests of the MtrrLib instance of the MtrrLib class - Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2018 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -122,6 +122,13 @@ UnitTestMtrrLibAsmCpuid ( ) { switch (Index) { + case CPUID_SIGNATURE: + if (Eax != NULL) { + *Eax = CPUID_VERSION_INFO; + } + + return Index; + break; case CPUID_VERSION_INFO: if (Edx != NULL) { *Edx = mCpuidVersionInfoEdx.Uint32; From 001306c05729c6d3703ae1e29286c2adee12073f Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 27 Feb 2023 13:35:19 +0800 Subject: [PATCH 0787/1529] UefiCpuPkg/MtrrLib: Substract TME-MK KEY_ID_BITS from CPU max PA CPUID enumeration of MAX_PA is unaffected by TME-MK activation and will continue to report the maximum physical address bits available for software to use, irrespective of the number of KeyID bits. So, we need to check if TME is enabled and adjust the PA size accordingly. Signed-off-by: Ray Ni Cc: Eric Dong Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Michael D Kinney Cc: Ahmad Anadani Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- UefiCpuPkg/Library/MtrrLib/MtrrLib.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/Library/MtrrLib/MtrrLib.c b/UefiCpuPkg/Library/MtrrLib/MtrrLib.c index e5c862c83d..a66357e305 100644 --- a/UefiCpuPkg/Library/MtrrLib/MtrrLib.c +++ b/UefiCpuPkg/Library/MtrrLib/MtrrLib.c @@ -756,8 +756,11 @@ MtrrLibInitializeMtrrMask ( OUT UINT64 *MtrrValidAddressMask ) { - UINT32 MaxExtendedFunction; - CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + UINT32 MaxExtendedFunction; + CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + UINT32 MaxFunction; + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX ExtendedFeatureFlagsEcx; + MSR_IA32_TME_ACTIVATE_REGISTER TmeActivate; AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunction, NULL, NULL, NULL); @@ -767,6 +770,23 @@ MtrrLibInitializeMtrrMask ( VirPhyAddressSize.Bits.PhysicalAddressBits = 36; } + // + // CPUID enumeration of MAX_PA is unaffected by TME-MK activation and will continue + // to report the maximum physical address bits available for software to use, + // irrespective of the number of KeyID bits. + // So, we need to check if TME is enabled and adjust the PA size accordingly. + // + AsmCpuid (CPUID_SIGNATURE, &MaxFunction, NULL, NULL, NULL); + if (MaxFunction >= CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS) { + AsmCpuidEx (CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, 0, NULL, NULL, &ExtendedFeatureFlagsEcx.Uint32, NULL); + if (ExtendedFeatureFlagsEcx.Bits.TME_EN == 1) { + TmeActivate.Uint64 = AsmReadMsr64 (MSR_IA32_TME_ACTIVATE); + if (TmeActivate.Bits.TmeEnable == 1) { + VirPhyAddressSize.Bits.PhysicalAddressBits -= TmeActivate.Bits.MkTmeKeyidBits; + } + } + } + *MtrrValidBitsMask = LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits) - 1; *MtrrValidAddressMask = *MtrrValidBitsMask & 0xfffffffffffff000ULL; } From 32517d8e260a2571d13cea4b75e51894b3d3cccd Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 27 Feb 2023 13:43:19 +0800 Subject: [PATCH 0788/1529] UefiCpuPkg/CpuDxe: Refactor to use CPUID definitions The patch does not change any code behavior but only refactors by: * replaces the hardcode 0x80000000 with CPUID_EXTENDED_FUNCTION * replaces the hardcode 0x80000008 with CPUID_VIR_PHY_ADDRESS_SIZE * replace "UINT32 Eax" with "CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize" Signed-off-by: Ray Ni Cc: Eric Dong Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Michael D Kinney Cc: Ahmad Anadani Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- UefiCpuPkg/CpuDxe/CpuDxe.c | 18 ++++++++---------- UefiCpuPkg/CpuDxe/CpuDxe.h | 3 ++- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.c b/UefiCpuPkg/CpuDxe/CpuDxe.c index a6a91507f6..920976c576 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.c +++ b/UefiCpuPkg/CpuDxe/CpuDxe.c @@ -1,7 +1,7 @@ /** @file CPU DXE Module to produce CPU ARCH Protocol. - Copyright (c) 2008 - 2022, Intel Corporation. All rights reserved.
+ Copyright (c) 2008 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -505,20 +505,18 @@ InitializeMtrrMask ( VOID ) { - UINT32 RegEax; - UINT8 PhysicalAddressBits; + UINT32 MaxExtendedFunction; + CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; - AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); + AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunction, NULL, NULL, NULL); - if (RegEax >= 0x80000008) { - AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL); - - PhysicalAddressBits = (UINT8)RegEax; + if (MaxExtendedFunction >= CPUID_VIR_PHY_ADDRESS_SIZE) { + AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE, &VirPhyAddressSize.Uint32, NULL, NULL, NULL); } else { - PhysicalAddressBits = 36; + VirPhyAddressSize.Bits.PhysicalAddressBits = 36; } - mValidMtrrBitsMask = LShiftU64 (1, PhysicalAddressBits) - 1; + mValidMtrrBitsMask = LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits) - 1; mValidMtrrAddressMask = mValidMtrrBitsMask & 0xfffffffffffff000ULL; } diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.h b/UefiCpuPkg/CpuDxe/CpuDxe.h index 49a390b4c4..0e7d88dd35 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.h +++ b/UefiCpuPkg/CpuDxe/CpuDxe.h @@ -1,7 +1,7 @@ /** @file CPU DXE Module to produce CPU ARCH Protocol and CPU MP Protocol. - Copyright (c) 2008 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2008 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -13,6 +13,7 @@ #include #include +#include #include #include From 4ead2a44de89b9200a5b00223f2df0a1217cd26c Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 27 Feb 2023 13:44:29 +0800 Subject: [PATCH 0789/1529] UefiCpuPkg/CpuDxe: Substract TME-MK KEY_ID_BITS from CPU max PA CPUID enumeration of MAX_PA is unaffected by TME-MK activation and will continue to report the maximum physical address bits available for software to use, irrespective of the number of KeyID bits. So, we need to check if TME is enabled and adjust the PA size accordingly. Signed-off-by: Ray Ni Cc: Eric Dong Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Michael D Kinney Cc: Ahmad Anadani Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- UefiCpuPkg/CpuDxe/CpuDxe.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.c b/UefiCpuPkg/CpuDxe/CpuDxe.c index 920976c576..3febd59d99 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.c +++ b/UefiCpuPkg/CpuDxe/CpuDxe.c @@ -505,8 +505,11 @@ InitializeMtrrMask ( VOID ) { - UINT32 MaxExtendedFunction; - CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + UINT32 MaxExtendedFunction; + CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize; + UINT32 MaxFunction; + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX ExtendedFeatureFlagsEcx; + MSR_IA32_TME_ACTIVATE_REGISTER TmeActivate; AsmCpuid (CPUID_EXTENDED_FUNCTION, &MaxExtendedFunction, NULL, NULL, NULL); @@ -516,6 +519,23 @@ InitializeMtrrMask ( VirPhyAddressSize.Bits.PhysicalAddressBits = 36; } + // + // CPUID enumeration of MAX_PA is unaffected by TME-MK activation and will continue + // to report the maximum physical address bits available for software to use, + // irrespective of the number of KeyID bits. + // So, we need to check if TME is enabled and adjust the PA size accordingly. + // + AsmCpuid (CPUID_SIGNATURE, &MaxFunction, NULL, NULL, NULL); + if (MaxFunction >= CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS) { + AsmCpuidEx (CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, 0, NULL, NULL, &ExtendedFeatureFlagsEcx.Uint32, NULL); + if (ExtendedFeatureFlagsEcx.Bits.TME_EN == 1) { + TmeActivate.Uint64 = AsmReadMsr64 (MSR_IA32_TME_ACTIVATE); + if (TmeActivate.Bits.TmeEnable == 1) { + VirPhyAddressSize.Bits.PhysicalAddressBits -= TmeActivate.Bits.MkTmeKeyidBits; + } + } + } + mValidMtrrBitsMask = LShiftU64 (1, VirPhyAddressSize.Bits.PhysicalAddressBits) - 1; mValidMtrrAddressMask = mValidMtrrBitsMask & 0xfffffffffffff000ULL; } From 0bea8887026a4bd813a95775d1b612060f51a2ef Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Tue, 28 Feb 2023 16:57:29 +0800 Subject: [PATCH 0790/1529] UefiCpuPkg/MtrrTest: Add test cases for TME-MK enable case When TME-MK is enabled, the MtrrLib should substract the TME-MK reserved bits from the max PA returned from CPUID instruction. The new test case guarantees such behavior in MtrrLib. Signed-off-by: Ray Ni Cc: Eric Dong Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Michael D Kinney Cc: Ahmad Anadani Acked-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- .../MtrrLib/UnitTest/MtrrLibUnitTest.c | 18 +-- .../MtrrLib/UnitTest/MtrrLibUnitTest.h | 3 +- UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c | 119 ++++++++++++++---- 3 files changed, 107 insertions(+), 33 deletions(-) diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c index b9a97dee09..1409ae27bb 100644 --- a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c @@ -1,7 +1,7 @@ /** @file Unit tests of the MtrrLib instance of the MtrrLib class - Copyright (c) 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2020 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -30,6 +30,8 @@ STATIC MTRR_LIB_SYSTEM_PARAMETER mSystemParameters[] = { { 48, TRUE, TRUE, CacheWriteThrough, 12 }, { 48, TRUE, TRUE, CacheWriteProtected, 12 }, { 48, TRUE, TRUE, CacheWriteCombining, 12 }, + + { 48, TRUE, TRUE, CacheWriteBack, 12, 7}, // 7 bits for MKTME }; UINT32 mFixedMtrrsIndex[] = { @@ -219,7 +221,7 @@ UnitTestMtrrSetMemoryAttributesInMtrrSettings ( &WcCount ); GenerateValidAndConfigurableMtrrPairs ( - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, RawMtrrRange, UcCount, WtCount, @@ -232,7 +234,7 @@ UnitTestMtrrSetMemoryAttributesInMtrrSettings ( ExpectedMemoryRangesCount = ARRAY_SIZE (ExpectedMemoryRanges); GetEffectiveMemoryRanges ( SystemParameter->DefaultCacheType, - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, RawMtrrRange, ExpectedVariableMtrrUsage, ExpectedMemoryRanges, @@ -278,7 +280,7 @@ UnitTestMtrrSetMemoryAttributesInMtrrSettings ( ActualMemoryRangesCount = ARRAY_SIZE (ActualMemoryRanges); CollectTestResult ( SystemParameter->DefaultCacheType, - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, SystemParameter->VariableMtrrCount, &LocalMtrrs, ActualMemoryRanges, @@ -325,7 +327,7 @@ UnitTestInvalidMemoryLayouts ( SystemParameter = (MTRR_LIB_SYSTEM_PARAMETER *)Context; RangeCount = Random32 (1, ARRAY_SIZE (Ranges)); - MaxAddress = 1ull << SystemParameter->PhysicalAddressBits; + MaxAddress = 1ull << (SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits); for (Index = 0; Index < RangeCount; Index++) { do { @@ -967,7 +969,7 @@ UnitTestMtrrSetMemoryAttributeInMtrrSettings ( &WcCount ); GenerateValidAndConfigurableMtrrPairs ( - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, RawMtrrRange, UcCount, WtCount, @@ -980,7 +982,7 @@ UnitTestMtrrSetMemoryAttributeInMtrrSettings ( ExpectedMemoryRangesCount = ARRAY_SIZE (ExpectedMemoryRanges); GetEffectiveMemoryRanges ( SystemParameter->DefaultCacheType, - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, RawMtrrRange, ExpectedVariableMtrrUsage, ExpectedMemoryRanges, @@ -1019,7 +1021,7 @@ UnitTestMtrrSetMemoryAttributeInMtrrSettings ( ActualMemoryRangesCount = ARRAY_SIZE (ActualMemoryRanges); CollectTestResult ( SystemParameter->DefaultCacheType, - SystemParameter->PhysicalAddressBits, + SystemParameter->PhysicalAddressBits - SystemParameter->MkTmeKeyidBits, SystemParameter->VariableMtrrCount, &LocalMtrrs, ActualMemoryRanges, diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h index 57e656c555..4471c1dcf7 100644 --- a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h @@ -1,6 +1,6 @@ /** @file - Copyright (c) 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2020 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -40,6 +40,7 @@ typedef struct { BOOLEAN FixedMtrrSupported; MTRR_MEMORY_CACHE_TYPE DefaultCacheType; UINT32 VariableMtrrCount; + UINT8 MkTmeKeyidBits; } MTRR_LIB_SYSTEM_PARAMETER; extern UINT32 mFixedMtrrsIndex[]; diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c index 260966e7b6..ba1de10034 100644 --- a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c @@ -12,13 +12,15 @@ MTRR_MEMORY_CACHE_TYPE mMemoryCacheTypes[] = { CacheUncacheable, CacheWriteCombining, CacheWriteThrough, CacheWriteProtected, CacheWriteBack }; -UINT64 mFixedMtrrsValue[MTRR_NUMBER_OF_FIXED_MTRR]; -MSR_IA32_MTRR_PHYSBASE_REGISTER mVariableMtrrsPhysBase[MTRR_NUMBER_OF_VARIABLE_MTRR]; -MSR_IA32_MTRR_PHYSMASK_REGISTER mVariableMtrrsPhysMask[MTRR_NUMBER_OF_VARIABLE_MTRR]; -MSR_IA32_MTRR_DEF_TYPE_REGISTER mDefTypeMsr; -MSR_IA32_MTRRCAP_REGISTER mMtrrCapMsr; -CPUID_VERSION_INFO_EDX mCpuidVersionInfoEdx; -CPUID_VIR_PHY_ADDRESS_SIZE_EAX mCpuidVirPhyAddressSizeEax; +UINT64 mFixedMtrrsValue[MTRR_NUMBER_OF_FIXED_MTRR]; +MSR_IA32_MTRR_PHYSBASE_REGISTER mVariableMtrrsPhysBase[MTRR_NUMBER_OF_VARIABLE_MTRR]; +MSR_IA32_MTRR_PHYSMASK_REGISTER mVariableMtrrsPhysMask[MTRR_NUMBER_OF_VARIABLE_MTRR]; +MSR_IA32_MTRR_DEF_TYPE_REGISTER mDefTypeMsr; +MSR_IA32_MTRRCAP_REGISTER mMtrrCapMsr; +MSR_IA32_TME_ACTIVATE_REGISTER mTmeActivateMsr; +CPUID_VERSION_INFO_EDX mCpuidVersionInfoEdx; +CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX mCpuidExtendedFeatureFlagsEcx; +CPUID_VIR_PHY_ADDRESS_SIZE_EAX mCpuidVirPhyAddressSizeEax; BOOLEAN mRandomInput; UINTN mNumberIndex = 0; @@ -87,34 +89,42 @@ GenerateRandomNumbers ( } /** - Retrieves CPUID information. + Retrieves CPUID information using an extended leaf identifier. + + Executes the CPUID instruction with EAX set to the value specified by Index + and ECX set to the value specified by SubIndex. This function always returns + Index. This function is only available on IA-32 and x64. - Executes the CPUID instruction with EAX set to the value specified by Index. - This function always returns Index. If Eax is not NULL, then the value of EAX after CPUID is returned in Eax. If Ebx is not NULL, then the value of EBX after CPUID is returned in Ebx. If Ecx is not NULL, then the value of ECX after CPUID is returned in Ecx. If Edx is not NULL, then the value of EDX after CPUID is returned in Edx. - This function is only available on IA-32 and x64. - @param Index The 32-bit value to load into EAX prior to invoking the CPUID - instruction. - @param Eax The pointer to the 32-bit EAX value returned by the CPUID - instruction. This is an optional parameter that may be NULL. - @param Ebx The pointer to the 32-bit EBX value returned by the CPUID - instruction. This is an optional parameter that may be NULL. - @param Ecx The pointer to the 32-bit ECX value returned by the CPUID - instruction. This is an optional parameter that may be NULL. - @param Edx The pointer to the 32-bit EDX value returned by the CPUID - instruction. This is an optional parameter that may be NULL. + @param Index The 32-bit value to load into EAX prior to invoking the + CPUID instruction. + @param SubIndex The 32-bit value to load into ECX prior to invoking the + CPUID instruction. + @param Eax The pointer to the 32-bit EAX value returned by the CPUID + instruction. This is an optional parameter that may be + NULL. + @param Ebx The pointer to the 32-bit EBX value returned by the CPUID + instruction. This is an optional parameter that may be + NULL. + @param Ecx The pointer to the 32-bit ECX value returned by the CPUID + instruction. This is an optional parameter that may be + NULL. + @param Edx The pointer to the 32-bit EDX value returned by the CPUID + instruction. This is an optional parameter that may be + NULL. @return Index. **/ UINT32 EFIAPI -UnitTestMtrrLibAsmCpuid ( +UnitTestMtrrLibAsmCpuidEx ( IN UINT32 Index, + IN UINT32 SubIndex, OUT UINT32 *Eax OPTIONAL, OUT UINT32 *Ebx OPTIONAL, OUT UINT32 *Ecx OPTIONAL, @@ -124,7 +134,7 @@ UnitTestMtrrLibAsmCpuid ( switch (Index) { case CPUID_SIGNATURE: if (Eax != NULL) { - *Eax = CPUID_VERSION_INFO; + *Eax = CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS; } return Index; @@ -134,6 +144,13 @@ UnitTestMtrrLibAsmCpuid ( *Edx = mCpuidVersionInfoEdx.Uint32; } + return Index; + break; + case CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS: + if (Ecx != NULL) { + *Ecx = mCpuidExtendedFeatureFlagsEcx.Uint32; + } + return Index; break; case CPUID_EXTENDED_FUNCTION: @@ -159,6 +176,44 @@ UnitTestMtrrLibAsmCpuid ( return Index; } +/** + Retrieves CPUID information. + + Executes the CPUID instruction with EAX set to the value specified by Index. + This function always returns Index. + If Eax is not NULL, then the value of EAX after CPUID is returned in Eax. + If Ebx is not NULL, then the value of EBX after CPUID is returned in Ebx. + If Ecx is not NULL, then the value of ECX after CPUID is returned in Ecx. + If Edx is not NULL, then the value of EDX after CPUID is returned in Edx. + This function is only available on IA-32 and x64. + + @param Index The 32-bit value to load into EAX prior to invoking the CPUID + instruction. + @param Eax The pointer to the 32-bit EAX value returned by the CPUID + instruction. This is an optional parameter that may be NULL. + @param Ebx The pointer to the 32-bit EBX value returned by the CPUID + instruction. This is an optional parameter that may be NULL. + @param Ecx The pointer to the 32-bit ECX value returned by the CPUID + instruction. This is an optional parameter that may be NULL. + @param Edx The pointer to the 32-bit EDX value returned by the CPUID + instruction. This is an optional parameter that may be NULL. + + @return Index. + +**/ +UINT32 +EFIAPI +UnitTestMtrrLibAsmCpuid ( + IN UINT32 Index, + OUT UINT32 *Eax OPTIONAL, + OUT UINT32 *Ebx OPTIONAL, + OUT UINT32 *Ecx OPTIONAL, + OUT UINT32 *Edx OPTIONAL + ) +{ + return UnitTestMtrrLibAsmCpuidEx (Index, 0, Eax, Ebx, Ecx, Edx); +} + /** Returns a 64-bit Machine Specific Register(MSR). @@ -207,6 +262,10 @@ UnitTestMtrrLibAsmReadMsr64 ( return mMtrrCapMsr.Uint64; } + if (MsrIndex == MSR_IA32_TME_ACTIVATE) { + return mTmeActivateMsr.Uint64; + } + // // Should never fall through to here // @@ -324,10 +383,22 @@ InitializeMtrrRegs ( // // Hook BaseLib functions used by MtrrLib that require some emulation. // - gUnitTestHostBaseLib.X86->AsmCpuid = UnitTestMtrrLibAsmCpuid; + gUnitTestHostBaseLib.X86->AsmCpuid = UnitTestMtrrLibAsmCpuid; + gUnitTestHostBaseLib.X86->AsmCpuidEx = UnitTestMtrrLibAsmCpuidEx; + gUnitTestHostBaseLib.X86->AsmReadMsr64 = UnitTestMtrrLibAsmReadMsr64; gUnitTestHostBaseLib.X86->AsmWriteMsr64 = UnitTestMtrrLibAsmWriteMsr64; + if (SystemParameter->MkTmeKeyidBits != 0) { + mCpuidExtendedFeatureFlagsEcx.Bits.TME_EN = 1; + mTmeActivateMsr.Bits.TmeEnable = 1; + mTmeActivateMsr.Bits.MkTmeKeyidBits = SystemParameter->MkTmeKeyidBits; + } else { + mCpuidExtendedFeatureFlagsEcx.Bits.TME_EN = 0; + mTmeActivateMsr.Bits.TmeEnable = 0; + mTmeActivateMsr.Bits.MkTmeKeyidBits = 0; + } + return UNIT_TEST_PASSED; } From 76b6617d5091047dae7899d872048a607e7e0991 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Mon, 27 Mar 2023 16:02:07 +0800 Subject: [PATCH 0791/1529] UefiCpuPkg/PiSmmCpuDxeSmm: fix format string BufferPages is UINTN, so we need "%Lu" when printing it to avoid it being truncated. Also cast to UINT64 to make sure it works for 32bit builds too. Fixes: 4f441d024bee ("UefiCpuPkg/PiSmmCpuDxeSmm: fix error handling") Reported-by: Laszlo Ersek Signed-off-by: Gerd Hoffmann Reviewed-by: Laszlo Ersek Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c index cf69161caa..c0e368ea94 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c @@ -880,7 +880,7 @@ PiCpuSmmEntry ( BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)); Buffer = AllocateAlignedCodePages (BufferPages, SIZE_4KB); if (Buffer == NULL) { - DEBUG ((DEBUG_ERROR, "Failed to allocate %d pages.\n", BufferPages)); + DEBUG ((DEBUG_ERROR, "Failed to allocate %Lu pages.\n", (UINT64)BufferPages)); CpuDeadLoop (); return EFI_OUT_OF_RESOURCES; } From 7a3376063eae40acfb5dc7ceb7e0f5bd7d4f4c5f Mon Sep 17 00:00:00 2001 From: "Lendacky, Thomas via groups.io" Date: Wed, 29 Mar 2023 02:09:23 +0800 Subject: [PATCH 0792/1529] UefiCpuPkg/MpInitLib: Reuse VMSA allocation to avoid unreserved allocation https://bugzilla.tianocore.org/show_bug.cgi?id=4353 When parking the APs on exiting from UEFI, a new page allocation is made. This allocation, however, does not end up being marked reserved in the memory map supplied to the OS. To avoid this, re-use the VMSA by clearing the VMSA RMP flag, updating the page contents and re-setting the VMSA RMP flag. Fixes: 06544455d0d4 ("UefiCpuPkg/MpInitLib: Use SEV-SNP AP Creation ...") Signed-off-by: Tom Lendacky Acked-by: Gerd Hoffmann Acked-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c | 198 +++++++++++++--------- 1 file changed, 121 insertions(+), 77 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c index bfda1e1903..509be9b417 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c @@ -13,6 +13,100 @@ #include #include +/** + Perform the requested AP Creation action. + + @param[in] SaveArea Pointer to VM save area (VMSA) + @param[in] ApicId APIC ID of the vCPU + @param[in] Action AP action to perform + + @retval TRUE Action completed successfully + @retval FALSE Action did not complete successfully +**/ +STATIC +BOOLEAN +SevSnpPerformApAction ( + IN SEV_ES_SAVE_AREA *SaveArea, + IN UINT32 ApicId, + IN UINTN Action + ) +{ + MSR_SEV_ES_GHCB_REGISTER Msr; + GHCB *Ghcb; + BOOLEAN InterruptState; + UINT64 ExitInfo1; + UINT64 ExitInfo2; + UINT32 RmpAdjustStatus; + UINT64 VmgExitStatus; + + if (Action == SVM_VMGEXIT_SNP_AP_CREATE) { + // + // To turn the page into a recognized VMSA page, issue RMPADJUST: + // Target VMPL but numerically higher than current VMPL + // Target PermissionMask is not used + // + RmpAdjustStatus = SevSnpRmpAdjust ( + (EFI_PHYSICAL_ADDRESS)(UINTN)SaveArea, + TRUE + ); + if (RmpAdjustStatus != 0) { + DEBUG ((DEBUG_INFO, "SEV-SNP: RMPADJUST failed for VMSA creation\n")); + ASSERT (FALSE); + + return FALSE; + } + } + + ExitInfo1 = (UINT64)ApicId << 32; + ExitInfo1 |= Action; + ExitInfo2 = (UINT64)(UINTN)SaveArea; + + Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB); + Ghcb = Msr.Ghcb; + + CcExitVmgInit (Ghcb, &InterruptState); + + if (Action == SVM_VMGEXIT_SNP_AP_CREATE) { + Ghcb->SaveArea.Rax = SaveArea->SevFeatures; + CcExitVmgSetOffsetValid (Ghcb, GhcbRax); + } + + VmgExitStatus = CcExitVmgExit ( + Ghcb, + SVM_EXIT_SNP_AP_CREATION, + ExitInfo1, + ExitInfo2 + ); + + CcExitVmgDone (Ghcb, InterruptState); + + if (VmgExitStatus != 0) { + DEBUG ((DEBUG_INFO, "SEV-SNP: AP Destroy failed\n")); + ASSERT (FALSE); + + return FALSE; + } + + if (Action == SVM_VMGEXIT_SNP_AP_DESTROY) { + // + // Make the current VMSA not runnable and accessible to be + // reprogrammed. + // + RmpAdjustStatus = SevSnpRmpAdjust ( + (EFI_PHYSICAL_ADDRESS)(UINTN)SaveArea, + FALSE + ); + if (RmpAdjustStatus != 0) { + DEBUG ((DEBUG_INFO, "SEV-SNP: RMPADJUST failed for VMSA reset\n")); + ASSERT (FALSE); + + return FALSE; + } + } + + return TRUE; +} + /** Create an SEV-SNP AP save area (VMSA) for use in running the vCPU. @@ -27,27 +121,33 @@ SevSnpCreateSaveArea ( UINT32 ApicId ) { - SEV_ES_SAVE_AREA *SaveArea; - IA32_CR0 ApCr0; - IA32_CR0 ResetCr0; - IA32_CR4 ApCr4; - IA32_CR4 ResetCr4; - UINTN StartIp; - UINT8 SipiVector; - UINT32 RmpAdjustStatus; - UINT64 VmgExitStatus; - MSR_SEV_ES_GHCB_REGISTER Msr; - GHCB *Ghcb; - BOOLEAN InterruptState; - UINT64 ExitInfo1; - UINT64 ExitInfo2; + SEV_ES_SAVE_AREA *SaveArea; + IA32_CR0 ApCr0; + IA32_CR0 ResetCr0; + IA32_CR4 ApCr4; + IA32_CR4 ResetCr4; + UINTN StartIp; + UINT8 SipiVector; + + if (CpuData->SevEsSaveArea == NULL) { + // + // Allocate a single page for the SEV-ES Save Area and initialize it. + // + SaveArea = AllocateReservedPages (1); + if (!SaveArea) { + return; + } - // - // Allocate a single page for the SEV-ES Save Area and initialize it. - // - SaveArea = AllocateReservedPages (1); - if (!SaveArea) { - return; + CpuData->SevEsSaveArea = SaveArea; + } else { + SaveArea = CpuData->SevEsSaveArea; + + // + // Tell the hypervisor to not use the current VMSA + // + if (!SevSnpPerformApAction (SaveArea, ApicId, SVM_VMGEXIT_SNP_AP_DESTROY)) { + return; + } } ZeroMem (SaveArea, EFI_PAGE_SIZE); @@ -132,63 +232,7 @@ SevSnpCreateSaveArea ( SaveArea->Vmpl = 0; SaveArea->SevFeatures = AsmReadMsr64 (MSR_SEV_STATUS) >> 2; - // - // To turn the page into a recognized VMSA page, issue RMPADJUST: - // Target VMPL but numerically higher than current VMPL - // Target PermissionMask is not used - // - RmpAdjustStatus = SevSnpRmpAdjust ( - (EFI_PHYSICAL_ADDRESS)(UINTN)SaveArea, - TRUE - ); - ASSERT (RmpAdjustStatus == 0); - - ExitInfo1 = (UINT64)ApicId << 32; - ExitInfo1 |= SVM_VMGEXIT_SNP_AP_CREATE; - ExitInfo2 = (UINT64)(UINTN)SaveArea; - - Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB); - Ghcb = Msr.Ghcb; - - CcExitVmgInit (Ghcb, &InterruptState); - Ghcb->SaveArea.Rax = SaveArea->SevFeatures; - CcExitVmgSetOffsetValid (Ghcb, GhcbRax); - VmgExitStatus = CcExitVmgExit ( - Ghcb, - SVM_EXIT_SNP_AP_CREATION, - ExitInfo1, - ExitInfo2 - ); - CcExitVmgDone (Ghcb, InterruptState); - - ASSERT (VmgExitStatus == 0); - if (VmgExitStatus != 0) { - RmpAdjustStatus = SevSnpRmpAdjust ( - (EFI_PHYSICAL_ADDRESS)(UINTN)SaveArea, - FALSE - ); - if (RmpAdjustStatus == 0) { - FreePages (SaveArea, 1); - } else { - DEBUG ((DEBUG_INFO, "SEV-SNP: RMPADJUST failed, leaking VMSA page\n")); - } - - SaveArea = NULL; - } - - if (CpuData->SevEsSaveArea) { - RmpAdjustStatus = SevSnpRmpAdjust ( - (EFI_PHYSICAL_ADDRESS)(UINTN)CpuData->SevEsSaveArea, - FALSE - ); - if (RmpAdjustStatus == 0) { - FreePages (CpuData->SevEsSaveArea, 1); - } else { - DEBUG ((DEBUG_INFO, "SEV-SNP: RMPADJUST failed, leaking VMSA page\n")); - } - } - - CpuData->SevEsSaveArea = SaveArea; + SevSnpPerformApAction (SaveArea, ApicId, SVM_VMGEXIT_SNP_AP_CREATE); } /** From 335c3c54d9cb5e903b8ea0fe9cea0598bd1c1755 Mon Sep 17 00:00:00 2001 From: "Lendacky, Thomas via groups.io" Date: Wed, 29 Mar 2023 02:09:24 +0800 Subject: [PATCH 0793/1529] UefiCpuPkg/MpInitLib: Ensure SEV-SNP VMSA allocations are not 2MB aligned BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4353 Due to AMD erratum #1467, an SEV-SNP VMSA should not be 2MB aligned. To work around this issue, allocate two pages instead of one. Because of the way that page allocation is implemented, always try to use the second page. If the second page is not 2MB aligned, free the first page and use the second page. If the second page is 2MB aligned, free the second page and use the first page. Freeing in this way reduces holes in the memory map. Fixes: 06544455d0d4 ("UefiCpuPkg/MpInitLib: Use SEV-SNP AP Creation ...") Signed-off-by: Tom Lendacky Acked-by: Gerd Hoffmann Acked-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c | 26 ++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c index 509be9b417..c9f0984f41 100644 --- a/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c +++ b/UefiCpuPkg/Library/MpInitLib/X64/AmdSev.c @@ -13,6 +13,8 @@ #include #include +#define _IS_ALIGNED(x, y) (ALIGN_POINTER((x), (y)) == (x)) + /** Perform the requested AP Creation action. @@ -121,6 +123,7 @@ SevSnpCreateSaveArea ( UINT32 ApicId ) { + UINT8 *Pages; SEV_ES_SAVE_AREA *SaveArea; IA32_CR0 ApCr0; IA32_CR0 ResetCr0; @@ -131,13 +134,30 @@ SevSnpCreateSaveArea ( if (CpuData->SevEsSaveArea == NULL) { // - // Allocate a single page for the SEV-ES Save Area and initialize it. + // Allocate a page for the SEV-ES Save Area and initialize it. Due to AMD + // erratum #1467 (VMSA cannot be on a 2MB boundary), allocate an extra page + // to choose from to work around the issue. // - SaveArea = AllocateReservedPages (1); - if (!SaveArea) { + Pages = AllocateReservedPages (2); + if (!Pages) { return; } + // + // Since page allocation works by allocating downward in the address space, + // try to always free the first (lower address) page to limit possible holes + // in the memory map. So, if the address of the second page is 2MB aligned, + // then use the first page and free the second page. Otherwise, free the + // first page and use the second page. + // + if (_IS_ALIGNED (Pages + EFI_PAGE_SIZE, SIZE_2MB)) { + SaveArea = (SEV_ES_SAVE_AREA *)Pages; + FreePages (Pages + EFI_PAGE_SIZE, 1); + } else { + SaveArea = (SEV_ES_SAVE_AREA *)(Pages + EFI_PAGE_SIZE); + FreePages (Pages, 1); + } + CpuData->SevEsSaveArea = SaveArea; } else { SaveArea = CpuData->SevEsSaveArea; From 4eecd7b6c835dd69e46fc9e93ab9ac4f928b8f08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20H=C3=A4user?= Date: Wed, 22 Mar 2023 00:02:38 -0700 Subject: [PATCH 0794/1529] MdeModulePkg: Rename IS_ALIGNED macros to avoid name collisions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This patch is a preparation for the patches that follow. The subsequent patches will introduce and integrate new alignment-related macros, which collide with existing definitions in MdeModulePkg. Temporarily rename them to avoid build failure, till they can be substituted with the new, shared definitions. Cc: Jian J Wang Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Marvin Häuser Signed-off-by: Gerd Hoffmann Reviewed-by: Hao A Wu Reviewed-by: Michael D Kinney --- MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c | 2 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h | 4 +-- .../Bus/Ata/AhciPei/AhciPeiPassThru.c | 6 ++-- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.c | 12 +++---- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.h | 2 +- MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h | 2 +- .../Bus/Ata/AtaBusDxe/AtaPassThruExecute.c | 2 +- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 4 +-- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h | 2 +- .../Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h | 2 +- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.c | 6 ++-- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.h | 2 +- MdeModulePkg/Universal/EbcDxe/EbcExecute.c | 36 +++++++++---------- MdeModulePkg/Universal/EbcDxe/EbcExecute.h | 4 +-- 14 files changed, 43 insertions(+), 43 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c index 7b97887c5d..d93fa78c81 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c @@ -2126,7 +2126,7 @@ TrustTransferAtaDevice ( // ATA PassThru PPI. // if ((AtaPassThru->Mode->IoAlign > 1) && - !IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) + !ADDRESS_IS_ALIGNED_ (Buffer, AtaPassThru->Mode->IoAlign)) { NewBuffer = AllocateAlignedPages ( EFI_SIZE_TO_PAGES (TransferLength), diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h index 4aed1cb7ad..71d34c962a 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h @@ -146,8 +146,8 @@ typedef union { #define AHCI_PORT_SERR 0x0030 #define AHCI_PORT_CI 0x0038 -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) -#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) #pragma pack(1) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c index d5ed93dc4f..0c49059a00 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c @@ -194,15 +194,15 @@ AhciAtaPassThruPassThru ( } IoAlign = This->Mode->IoAlign; - if ((IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((IoAlign > 1) && !IS_ALIGNED (Packet->Asb, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->Asb, IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c index 1070516b35..324abadd02 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c @@ -1299,15 +1299,15 @@ AtaPassThruPassThru ( Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->Asb, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->Asb, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } @@ -2039,15 +2039,15 @@ ExtScsiPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h index 62ba6d6680..7937886614 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h @@ -148,7 +148,7 @@ struct _ATA_NONBLOCK_TASK { #define ATA_ATAPI_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) #define ATA_SPINUP_TIMEOUT EFI_TIMER_PERIOD_SECONDS(10) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h index 4428c484fd..47346e911d 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h @@ -76,7 +76,7 @@ #define ATA_TASK_SIGNATURE SIGNATURE_32 ('A', 'T', 'S', 'K') #define ATA_DEVICE_SIGNATURE SIGNATURE_32 ('A', 'B', 'I', 'D') #define ATA_SUB_TASK_SIGNATURE SIGNATURE_32 ('A', 'S', 'T', 'S') -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) // // ATA bus data structure for ATA controller diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c index 4334169d25..18aa4f9bb6 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c @@ -1040,7 +1040,7 @@ TrustTransferAtaDevice ( // Check the alignment of the incoming buffer prior to invoking underlying ATA PassThru // AtaPassThru = AtaDevice->AtaBusDriverData->AtaPassThru; - if ((AtaPassThru->Mode->IoAlign > 1) && !IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) { + if ((AtaPassThru->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Buffer, AtaPassThru->Mode->IoAlign)) { NewBuffer = AllocateAlignedBuffer (AtaDevice, TransferLength); if (NewBuffer == NULL) { return EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index fbc236cb46..faf4ae332e 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -2029,7 +2029,7 @@ ScsiDiskReceiveData ( goto Done; } - if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !IS_ALIGNED (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { + if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { AlignedBuffer = AllocateAlignedBuffer (ScsiDiskDevice, PayloadBufferSize); if (AlignedBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; @@ -2249,7 +2249,7 @@ ScsiDiskSendData ( goto Done; } - if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !IS_ALIGNED (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { + if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { AlignedBuffer = AllocateAlignedBuffer (ScsiDiskDevice, PayloadBufferSize); if (AlignedBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h index 5b4047e1db..ed384ad521 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h @@ -38,7 +38,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define IS_DEVICE_FIXED(a) (a)->FixedDevice ? 1 : 0 -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define UFS_WLUN_RPMB 0xC4 diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h index a0b615b7ea..1adb382aa8 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h @@ -133,7 +133,7 @@ typedef struct _UFS_PEIM_HC_PRIVATE_DATA { #define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIoPpi, UFS_PEIM_HC_SIG) #define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, UFS_PEIM_HC_SIG) diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c index ae593ff03a..392a295caf 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c @@ -171,15 +171,15 @@ UfsPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h index 2b4f5d32d9..0ec37e5665 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h @@ -105,7 +105,7 @@ typedef struct { #define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ diff --git a/MdeModulePkg/Universal/EbcDxe/EbcExecute.c b/MdeModulePkg/Universal/EbcDxe/EbcExecute.c index 82a7782fb9..28f108c448 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcExecute.c +++ b/MdeModulePkg/Universal/EbcDxe/EbcExecute.c @@ -2015,7 +2015,7 @@ ExecuteJMP ( // check for alignment, and jump absolute. // Data64 = (UINT64)VmReadImmed64 (VmPtr, 2); - if (!IS_ALIGNED ((UINTN)Data64, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED_ ((UINTN)Data64, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -2074,7 +2074,7 @@ ExecuteJMP ( // Form: JMP32 @Rx {Index32} // Addr = VmReadMemN (VmPtr, (UINTN)Data64 + Index32); - if (!IS_ALIGNED ((UINTN)Addr, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED_ ((UINTN)Addr, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -2097,7 +2097,7 @@ ExecuteJMP ( // Form: JMP32 Rx {Immed32} // Addr = (UINTN)(Data64 + Index32); - if (!IS_ALIGNED ((UINTN)Addr, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED_ ((UINTN)Addr, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -3158,7 +3158,7 @@ ExecuteRET ( // Pull the return address off the VM app's stack and set the IP // to it // - if (!IS_ALIGNED ((UINTN)VmPtr->Gpr[0], sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Gpr[0], sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -4733,7 +4733,7 @@ VmWriteMem16 ( // // Do a simple write if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT16))) { *(UINT16 *)Addr = Data; } else { // @@ -4795,7 +4795,7 @@ VmWriteMem32 ( // // Do a simple write if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT32))) { *(UINT32 *)Addr = Data; } else { // @@ -4857,7 +4857,7 @@ VmWriteMem64 ( // // Do a simple write if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT64))) { *(UINT64 *)Addr = Data; } else { // @@ -4922,7 +4922,7 @@ VmWriteMemN ( // // Do a simple write if aligned // - if (IS_ALIGNED (Addr, sizeof (UINTN))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINTN))) { *(UINTN *)Addr = Data; } else { for (Index = 0; Index < sizeof (UINTN) / sizeof (UINT32); Index++) { @@ -4985,7 +4985,7 @@ VmReadImmed16 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (INT16))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (INT16))) { return *(INT16 *)(VmPtr->Ip + Offset); } else { // @@ -5029,7 +5029,7 @@ VmReadImmed32 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { return *(INT32 *)(VmPtr->Ip + Offset); } @@ -5068,7 +5068,7 @@ VmReadImmed64 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { return *(UINT64 *)(VmPtr->Ip + Offset); } @@ -5105,7 +5105,7 @@ VmReadCode16 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT16))) { return *(UINT16 *)(VmPtr->Ip + Offset); } else { // @@ -5147,7 +5147,7 @@ VmReadCode32 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { return *(UINT32 *)(VmPtr->Ip + Offset); } @@ -5184,7 +5184,7 @@ VmReadCode64 ( // // Read direct if aligned // - if (IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { return *(UINT64 *)(VmPtr->Ip + Offset); } @@ -5247,7 +5247,7 @@ VmReadMem16 ( // // Read direct if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT16))) { return *(UINT16 *)Addr; } @@ -5281,7 +5281,7 @@ VmReadMem32 ( // // Read direct if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT32))) { return *(UINT32 *)Addr; } @@ -5319,7 +5319,7 @@ VmReadMem64 ( // // Read direct if aligned // - if (IS_ALIGNED (Addr, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT64))) { return *(UINT64 *)Addr; } @@ -5388,7 +5388,7 @@ VmReadMemN ( // // Read direct if aligned // - if (IS_ALIGNED (Addr, sizeof (UINTN))) { + if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINTN))) { return *(UINTN *)Addr; } diff --git a/MdeModulePkg/Universal/EbcDxe/EbcExecute.h b/MdeModulePkg/Universal/EbcDxe/EbcExecute.h index 32b8670c5b..6dc6730ab0 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcExecute.h +++ b/MdeModulePkg/Universal/EbcDxe/EbcExecute.h @@ -14,8 +14,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Macros to check and set alignment // -#define ASSERT_ALIGNED(addr, size) ASSERT (!((UINT32) (addr) & (size - 1))) -#define IS_ALIGNED(addr, size) !((UINT32) (addr) & (size - 1)) +#define ASSERT_ALIGNED(addr, size) ASSERT (!((UINT32) (addr) & (size - 1))) +#define ADDRESS_IS_ALIGNED_(addr, size) !((UINT32) (addr) & (size - 1)) // // Debug macro From 0605591dc9f4b5b46b7a65f854275fae622b6265 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 22 Mar 2023 00:02:39 -0700 Subject: [PATCH 0795/1529] OvmfPkg: Rename IS_ALIGNED macros to avoid name collisions This patch is a preparation for the patches that follow. The subsequent patches will introduce and integrate new alignment-related macros, which collide with existing definitions in OvmfPkg. Temporarily rename them to avoid build failure, till they can be substituted with the new, shared definitions. Signed-off-by: Gerd Hoffmann Reviewed-by: Michael D Kinney Reviewed-by: Jiewen Yao Acked-by: Tom Lendacky --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 6 +++--- .../BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index a726498e27..71a1eaaf0a 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -44,7 +44,7 @@ STATIC BOOLEAN mAcceptAllMemoryAtEBS = TRUE; STATIC EFI_EVENT mAcceptAllMemoryEvent = NULL; -#define IS_ALIGNED(x, y) ((((x) & ((y) - 1)) == 0)) +#define IS_ALIGNED_(x, y) ((((x) & ((y) - 1)) == 0)) STATIC EFI_STATUS @@ -60,8 +60,8 @@ AmdSevMemoryAccept ( // multiple of SIZE_4KB. Use an assert instead of returning an erros since // this is an EDK2-internal protocol. // - ASSERT (IS_ALIGNED (StartAddress, SIZE_4KB)); - ASSERT (IS_ALIGNED (Size, SIZE_4KB)); + ASSERT (IS_ALIGNED_ (StartAddress, SIZE_4KB)); + ASSERT (IS_ALIGNED_ (Size, SIZE_4KB)); ASSERT (Size != 0); MemEncryptSevSnpPreValidateSystemRam ( diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c index 4d684964d8..f35bba5deb 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c @@ -20,7 +20,7 @@ #include "SnpPageStateChange.h" -#define IS_ALIGNED(x, y) ((((x) & (y - 1)) == 0)) +#define IS_ALIGNED_(x, y) ((((x) & (y - 1)) == 0)) #define PAGES_PER_LARGE_ENTRY 512 STATIC @@ -150,7 +150,7 @@ BuildPageStateBuffer ( // // Is this a 2MB aligned page? Check if we can use the Large RMP entry. // - if (UseLargeEntry && IS_ALIGNED (BaseAddress, SIZE_2MB) && + if (UseLargeEntry && IS_ALIGNED_ (BaseAddress, SIZE_2MB) && ((EndAddress - BaseAddress) >= SIZE_2MB)) { RmpPageSize = PvalidatePageSize2MB; From e9417e1b9fe17b2ed6da779bfd6ef1a9b5477224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20H=C3=A4user?= Date: Wed, 22 Mar 2023 00:02:40 -0700 Subject: [PATCH 0796/1529] MdePkg/Base.h: Introduce various alignment-related macros MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ALIGNOF: Determining the alignment requirement of data types is crucial to ensure safe memory accesses when parsing untrusted data. IS_POW2: Determining whether a value is a power of two is important to verify whether untrusted values are valid alignment values. IS_ALIGNED: In combination with ALIGNOF data offsets can be verified. A more general version of the IS_ALIGNED macro previously defined by several modules. ADDRESS_IS_ALIGNED: Variant of IS_ALIGNED for pointers and addresses. Replaces module-specific definitions throughout the code base. ALIGN_VALUE_ADDEND: The addend to align up can be used to directly determine the required offset for data alignment. Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Vitaly Cheptsov Signed-off-by: Marvin Häuser Signed-off-by: Gerd Hoffmann Reviewed-by: Michael D Kinney --- MdePkg/Include/Base.h | 98 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 97 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/Base.h b/MdePkg/Include/Base.h index e89c84962a..6597e441a6 100644 --- a/MdePkg/Include/Base.h +++ b/MdePkg/Include/Base.h @@ -758,6 +758,40 @@ typedef UINTN *BASE_LIST; #define OFFSET_OF(TYPE, Field) ((UINTN) &(((TYPE *)0)->Field)) #endif +/** + Returns the alignment requirement of a type. + + @param TYPE The name of the type to retrieve the alignment requirement of. + + @return Alignment requirement, in Bytes, of TYPE. +**/ +#if defined (__cplusplus) +// +// Standard C++ operator. +// +#define ALIGNOF(TYPE) alignof (TYPE) +#elif defined (__GNUC__) || defined (__clang__) || (defined (_MSC_VER) && _MSC_VER >= 1900) +// +// All supported versions of GCC and Clang, as well as MSVC 2015 and later, +// support the standard operator _Alignof. +// +#define ALIGNOF(TYPE) _Alignof (TYPE) +#elif defined (_MSC_EXTENSIONS) +// +// Earlier versions of MSVC, at least MSVC 2008 and later, support the vendor +// extension __alignof. +// +#define ALIGNOF(TYPE) __alignof (TYPE) +#else +// +// For compilers that do not support inbuilt alignof operators, use OFFSET_OF. +// CHAR8 is known to have both a size and an alignment requirement of 1 Byte. +// As such, A must be located exactly at the offset equal to its alignment +// requirement. +// +#define ALIGNOF(TYPE) OFFSET_OF (struct { CHAR8 C; TYPE A; }, A) +#endif + /** Portable definition for compile time assertions. Equivalent to C11 static_assert macro from assert.h. @@ -793,6 +827,21 @@ STATIC_ASSERT (sizeof (CHAR16) == 2, "sizeof (CHAR16) does not meet UEFI Specif STATIC_ASSERT (sizeof (L'A') == 2, "sizeof (L'A') does not meet UEFI Specification Data Type requirements"); STATIC_ASSERT (sizeof (L"A") == 4, "sizeof (L\"A\") does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (BOOLEAN) == sizeof (BOOLEAN), "Alignment of BOOLEAN does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (INT8) == sizeof (INT8), "Alignment of INT8 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (UINT8) == sizeof (UINT8), "Alignment of INT16 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (INT16) == sizeof (INT16), "Alignment of INT16 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (UINT16) == sizeof (UINT16), "Alignment of UINT16 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (INT32) == sizeof (INT32), "Alignment of INT32 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (UINT32) == sizeof (UINT32), "Alignment of UINT32 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (INT64) == sizeof (INT64), "Alignment of INT64 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (UINT64) == sizeof (UINT64), "Alignment of UINT64 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (CHAR8) == sizeof (CHAR8), "Alignment of CHAR8 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (CHAR16) == sizeof (CHAR16), "Alignment of CHAR16 does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (INTN) == sizeof (INTN), "Alignment of INTN does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (UINTN) == sizeof (UINTN), "Alignment of UINTN does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (VOID *) == sizeof (VOID *), "Alignment of VOID * does not meet UEFI Specification Data Type requirements"); + // // The following three enum types are used to verify that the compiler // configuration for enum types is compliant with Section 2.3.1 of the @@ -816,6 +865,10 @@ STATIC_ASSERT (sizeof (__VERIFY_UINT8_ENUM_SIZE) == 4, "Size of enum does not me STATIC_ASSERT (sizeof (__VERIFY_UINT16_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); STATIC_ASSERT (sizeof (__VERIFY_INT32_ENUM_SIZE) == 4, "Size of enum does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (__VERIFY_UINT8_ENUM_SIZE) == sizeof (__VERIFY_UINT8_ENUM_SIZE), "Alignment of enum does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (__VERIFY_UINT16_ENUM_SIZE) == sizeof (__VERIFY_UINT16_ENUM_SIZE), "Alignment of enum does not meet UEFI Specification Data Type requirements"); +STATIC_ASSERT (ALIGNOF (__VERIFY_INT32_ENUM_SIZE) == sizeof (__VERIFY_INT32_ENUM_SIZE), "Alignment of enum does not meet UEFI Specification Data Type requirements"); + /** Macro that returns a pointer to the data structure that contains a specified field of that data structure. This is a lightweight method to hide information by placing a @@ -837,6 +890,49 @@ STATIC_ASSERT (sizeof (__VERIFY_INT32_ENUM_SIZE) == 4, "Size of enum does not me **/ #define BASE_CR(Record, TYPE, Field) ((TYPE *) ((CHAR8 *) (Record) - OFFSET_OF (TYPE, Field))) +/** + Checks whether a value is a power of two. + + @param Value The value to check. + + @retval TRUE Value is a power of two. + @retval FALSE Value is not a power of two. +**/ +#define IS_POW2(Value) ((Value) != 0U && ((Value) & ((Value) - 1U)) == 0U) + +/** + Checks whether a value is aligned by a specified alignment. + + @param Value The value to check. + @param Alignment The alignment boundary used to check against. + + @retval TRUE Value is aligned by Alignment. + @retval FALSE Value is not aligned by Alignment. +**/ +#define IS_ALIGNED(Value, Alignment) (((Value) & ((Alignment) - 1U)) == 0U) + +/** + Checks whether a pointer or address is aligned by a specified alignment. + + @param Address The pointer or address to check. + @param Alignment The alignment boundary used to check against. + + @retval TRUE Address is aligned by Alignment. + @retval FALSE Address is not aligned by Alignment. +**/ +#define ADDRESS_IS_ALIGNED(Address, Alignment) IS_ALIGNED ((UINTN) (Address), Alignment) + +/** + Determines the addend to add to a value to round it up to the next boundary of + a specified alignment. + + @param Value The value to round up. + @param Alignment The alignment boundary used to return the addend. + + @return Addend to round Value up to alignment boundary Alignment. +**/ +#define ALIGN_VALUE_ADDEND(Value, Alignment) (((Alignment) - (Value)) & ((Alignment) - 1U)) + /** Rounds a value up to the next boundary using a specified alignment. @@ -849,7 +945,7 @@ STATIC_ASSERT (sizeof (__VERIFY_INT32_ENUM_SIZE) == 4, "Size of enum does not me @return A value up to the next boundary. **/ -#define ALIGN_VALUE(Value, Alignment) ((Value) + (((Alignment) - (Value)) & ((Alignment) - 1))) +#define ALIGN_VALUE(Value, Alignment) ((Value) + ALIGN_VALUE_ADDEND (Value, Alignment)) /** Adjust a pointer by adding the minimum offset required for it to be aligned on From 7bfb19f162558b7c6336945f3862af3741b6b89d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20H=C3=A4user?= Date: Wed, 22 Mar 2023 00:02:41 -0700 Subject: [PATCH 0797/1529] MdeModulePkg: Consume new alignment-related macros MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This patch substitutes the macros that were renamed in the first patch with the new, shared alignment macros. Cc: Jian J Wang Cc: Hao A Wu Cc: Ray Ni Cc: Vitaly Cheptsov Signed-off-by: Marvin Häuser Signed-off-by: Gerd Hoffmann Reviewed-by: Hao A Wu Reviewed-by: Michael D Kinney --- MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c | 2 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h | 3 +- .../Bus/Ata/AhciPei/AhciPeiPassThru.c | 6 ++-- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.c | 12 +++---- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.h | 2 -- MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h | 1 - .../Bus/Ata/AtaBusDxe/AtaPassThruExecute.c | 2 +- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 4 +-- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h | 2 -- .../Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h | 2 -- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.c | 6 ++-- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.h | 2 -- MdeModulePkg/Universal/EbcDxe/EbcExecute.c | 36 +++++++++---------- MdeModulePkg/Universal/EbcDxe/EbcExecute.h | 3 +- 14 files changed, 36 insertions(+), 47 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c index d93fa78c81..0f0198d308 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c @@ -2126,7 +2126,7 @@ TrustTransferAtaDevice ( // ATA PassThru PPI. // if ((AtaPassThru->Mode->IoAlign > 1) && - !ADDRESS_IS_ALIGNED_ (Buffer, AtaPassThru->Mode->IoAlign)) + !ADDRESS_IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) { NewBuffer = AllocateAlignedPages ( EFI_SIZE_TO_PAGES (TransferLength), diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h index 71d34c962a..e2e4ba43e7 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h @@ -146,8 +146,7 @@ typedef union { #define AHCI_PORT_SERR 0x0030 #define AHCI_PORT_CI 0x0038 -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) -#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) +#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) #pragma pack(1) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c index 0c49059a00..cd55272c96 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c @@ -194,15 +194,15 @@ AhciAtaPassThruPassThru ( } IoAlign = This->Mode->IoAlign; - if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->InDataBuffer, IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->OutDataBuffer, IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->Asb, IoAlign)) { + if ((IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->Asb, IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c index 324abadd02..50406fe027 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c @@ -1299,15 +1299,15 @@ AtaPassThruPassThru ( Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->Asb, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->Asb, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } @@ -2039,15 +2039,15 @@ ExtScsiPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h index 7937886614..016fc6890a 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h @@ -148,8 +148,6 @@ struct _ATA_NONBLOCK_TASK { #define ATA_ATAPI_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) #define ATA_SPINUP_TIMEOUT EFI_TIMER_PERIOD_SECONDS(10) -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) - #define ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ ATA_ATAPI_PASS_THRU_INSTANCE, \ diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h index 47346e911d..6bc345f7e7 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h @@ -76,7 +76,6 @@ #define ATA_TASK_SIGNATURE SIGNATURE_32 ('A', 'T', 'S', 'K') #define ATA_DEVICE_SIGNATURE SIGNATURE_32 ('A', 'B', 'I', 'D') #define ATA_SUB_TASK_SIGNATURE SIGNATURE_32 ('A', 'S', 'T', 'S') -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) // // ATA bus data structure for ATA controller diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c index 18aa4f9bb6..a77852bae0 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c @@ -1040,7 +1040,7 @@ TrustTransferAtaDevice ( // Check the alignment of the incoming buffer prior to invoking underlying ATA PassThru // AtaPassThru = AtaDevice->AtaBusDriverData->AtaPassThru; - if ((AtaPassThru->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Buffer, AtaPassThru->Mode->IoAlign)) { + if ((AtaPassThru->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) { NewBuffer = AllocateAlignedBuffer (AtaDevice, TransferLength); if (NewBuffer == NULL) { return EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index faf4ae332e..873581d817 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -2029,7 +2029,7 @@ ScsiDiskReceiveData ( goto Done; } - if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { + if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { AlignedBuffer = AllocateAlignedBuffer (ScsiDiskDevice, PayloadBufferSize); if (AlignedBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; @@ -2249,7 +2249,7 @@ ScsiDiskSendData ( goto Done; } - if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { + if ((ScsiDiskDevice->ScsiIo->IoAlign > 1) && !ADDRESS_IS_ALIGNED (PayloadBuffer, ScsiDiskDevice->ScsiIo->IoAlign)) { AlignedBuffer = AllocateAlignedBuffer (ScsiDiskDevice, PayloadBufferSize); if (AlignedBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h index ed384ad521..5a25b55c49 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h @@ -38,8 +38,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define IS_DEVICE_FIXED(a) (a)->FixedDevice ? 1 : 0 -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) - #define UFS_WLUN_RPMB 0xC4 typedef struct { diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h index 1adb382aa8..ed4776f548 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h @@ -133,8 +133,6 @@ typedef struct _UFS_PEIM_HC_PRIVATE_DATA { #define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) - #define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIoPpi, UFS_PEIM_HC_SIG) #define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, UFS_PEIM_HC_SIG) #define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, UFS_PEIM_HC_SIG) diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c index 392a295caf..880e7d8511 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c @@ -171,15 +171,15 @@ UfsPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED_ (Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !ADDRESS_IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h index 0ec37e5665..bc1139da6e 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h @@ -105,8 +105,6 @@ typedef struct { #define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define ADDRESS_IS_ALIGNED_(addr, size) (((UINTN) (addr) & (size - 1)) == 0) - #define UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ UFS_PASS_THRU_PRIVATE_DATA, \ diff --git a/MdeModulePkg/Universal/EbcDxe/EbcExecute.c b/MdeModulePkg/Universal/EbcDxe/EbcExecute.c index 28f108c448..3221f95a73 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcExecute.c +++ b/MdeModulePkg/Universal/EbcDxe/EbcExecute.c @@ -2015,7 +2015,7 @@ ExecuteJMP ( // check for alignment, and jump absolute. // Data64 = (UINT64)VmReadImmed64 (VmPtr, 2); - if (!ADDRESS_IS_ALIGNED_ ((UINTN)Data64, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED ((UINTN)Data64, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -2074,7 +2074,7 @@ ExecuteJMP ( // Form: JMP32 @Rx {Index32} // Addr = VmReadMemN (VmPtr, (UINTN)Data64 + Index32); - if (!ADDRESS_IS_ALIGNED_ ((UINTN)Addr, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED ((UINTN)Addr, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -2097,7 +2097,7 @@ ExecuteJMP ( // Form: JMP32 Rx {Immed32} // Addr = (UINTN)(Data64 + Index32); - if (!ADDRESS_IS_ALIGNED_ ((UINTN)Addr, sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED ((UINTN)Addr, sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -3158,7 +3158,7 @@ ExecuteRET ( // Pull the return address off the VM app's stack and set the IP // to it // - if (!ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Gpr[0], sizeof (UINT16))) { + if (!ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Gpr[0], sizeof (UINT16))) { EbcDebugSignalException ( EXCEPT_EBC_ALIGNMENT_CHECK, EXCEPTION_FLAG_FATAL, @@ -4733,7 +4733,7 @@ VmWriteMem16 ( // // Do a simple write if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT16))) { *(UINT16 *)Addr = Data; } else { // @@ -4795,7 +4795,7 @@ VmWriteMem32 ( // // Do a simple write if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT32))) { *(UINT32 *)Addr = Data; } else { // @@ -4857,7 +4857,7 @@ VmWriteMem64 ( // // Do a simple write if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT64))) { *(UINT64 *)Addr = Data; } else { // @@ -4922,7 +4922,7 @@ VmWriteMemN ( // // Do a simple write if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINTN))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINTN))) { *(UINTN *)Addr = Data; } else { for (Index = 0; Index < sizeof (UINTN) / sizeof (UINT32); Index++) { @@ -4985,7 +4985,7 @@ VmReadImmed16 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (INT16))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (INT16))) { return *(INT16 *)(VmPtr->Ip + Offset); } else { // @@ -5029,7 +5029,7 @@ VmReadImmed32 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { return *(INT32 *)(VmPtr->Ip + Offset); } @@ -5068,7 +5068,7 @@ VmReadImmed64 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { return *(UINT64 *)(VmPtr->Ip + Offset); } @@ -5105,7 +5105,7 @@ VmReadCode16 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT16))) { return *(UINT16 *)(VmPtr->Ip + Offset); } else { // @@ -5147,7 +5147,7 @@ VmReadCode32 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT32))) { return *(UINT32 *)(VmPtr->Ip + Offset); } @@ -5184,7 +5184,7 @@ VmReadCode64 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED ((UINTN)VmPtr->Ip + Offset, sizeof (UINT64))) { return *(UINT64 *)(VmPtr->Ip + Offset); } @@ -5247,7 +5247,7 @@ VmReadMem16 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT16))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT16))) { return *(UINT16 *)Addr; } @@ -5281,7 +5281,7 @@ VmReadMem32 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT32))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT32))) { return *(UINT32 *)Addr; } @@ -5319,7 +5319,7 @@ VmReadMem64 ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINT64))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINT64))) { return *(UINT64 *)Addr; } @@ -5388,7 +5388,7 @@ VmReadMemN ( // // Read direct if aligned // - if (ADDRESS_IS_ALIGNED_ (Addr, sizeof (UINTN))) { + if (ADDRESS_IS_ALIGNED (Addr, sizeof (UINTN))) { return *(UINTN *)Addr; } diff --git a/MdeModulePkg/Universal/EbcDxe/EbcExecute.h b/MdeModulePkg/Universal/EbcDxe/EbcExecute.h index 6dc6730ab0..f3768e7952 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcExecute.h +++ b/MdeModulePkg/Universal/EbcDxe/EbcExecute.h @@ -14,8 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Macros to check and set alignment // -#define ASSERT_ALIGNED(addr, size) ASSERT (!((UINT32) (addr) & (size - 1))) -#define ADDRESS_IS_ALIGNED_(addr, size) !((UINT32) (addr) & (size - 1)) +#define ASSERT_ALIGNED(addr, size) ASSERT (ADDRESS_IS_ALIGNED (addr, size)) // // Debug macro From 031af6407f651bf0e53ee9ddb5dd39acf94582f8 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 22 Mar 2023 00:02:42 -0700 Subject: [PATCH 0798/1529] OvmfPkg: Consume new alignment-related macros This patch substitutes the macros that were renamed in the second patch with the new, shared alignment macros. Signed-off-by: Gerd Hoffmann Reviewed-by: Michael D Kinney Reviewed-by: Jiewen Yao Acked-by: Tom Lendacky --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 6 ++---- .../BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 71a1eaaf0a..9b0d0e92b6 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -44,8 +44,6 @@ STATIC BOOLEAN mAcceptAllMemoryAtEBS = TRUE; STATIC EFI_EVENT mAcceptAllMemoryEvent = NULL; -#define IS_ALIGNED_(x, y) ((((x) & ((y) - 1)) == 0)) - STATIC EFI_STATUS EFIAPI @@ -60,8 +58,8 @@ AmdSevMemoryAccept ( // multiple of SIZE_4KB. Use an assert instead of returning an erros since // this is an EDK2-internal protocol. // - ASSERT (IS_ALIGNED_ (StartAddress, SIZE_4KB)); - ASSERT (IS_ALIGNED_ (Size, SIZE_4KB)); + ASSERT (IS_ALIGNED (StartAddress, SIZE_4KB)); + ASSERT (IS_ALIGNED (Size, SIZE_4KB)); ASSERT (Size != 0); MemEncryptSevSnpPreValidateSystemRam ( diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c index f35bba5deb..7a8878b1a9 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c @@ -20,7 +20,6 @@ #include "SnpPageStateChange.h" -#define IS_ALIGNED_(x, y) ((((x) & (y - 1)) == 0)) #define PAGES_PER_LARGE_ENTRY 512 STATIC @@ -150,7 +149,7 @@ BuildPageStateBuffer ( // // Is this a 2MB aligned page? Check if we can use the Large RMP entry. // - if (UseLargeEntry && IS_ALIGNED_ (BaseAddress, SIZE_2MB) && + if (UseLargeEntry && IS_ALIGNED (BaseAddress, SIZE_2MB) && ((EndAddress - BaseAddress) >= SIZE_2MB)) { RmpPageSize = PvalidatePageSize2MB; From 789da722f3304161343816c1b6ca5d15f2cfcff3 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 22 Mar 2023 00:02:43 -0700 Subject: [PATCH 0799/1529] UefiCpuPkg/MtrrLib: use new IS_POW2() macro. Drop MtrrLibIsPowerOfTwo function, use the new IS_POW2() macro instead. The ASSERT() removed (inside MtrrLibIsPowerOfTwo) is superfluous, another ASSERT() a few lines up in MtrrLibCalculateMtrrs() already guarantees that Length can not be zero at this point. Signed-off-by: Gerd Hoffmann Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MtrrLib/MtrrLib.c | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/UefiCpuPkg/Library/MtrrLib/MtrrLib.c b/UefiCpuPkg/Library/MtrrLib/MtrrLib.c index a66357e305..22ec8d2a48 100644 --- a/UefiCpuPkg/Library/MtrrLib/MtrrLib.c +++ b/UefiCpuPkg/Library/MtrrLib/MtrrLib.c @@ -1273,21 +1273,6 @@ MtrrLibLowestType ( return (MTRR_MEMORY_CACHE_TYPE)Type; } -/** - Return TRUE when the Operand is exactly power of 2. - - @retval TRUE Operand is exactly power of 2. - @retval FALSE Operand is not power of 2. -**/ -BOOLEAN -MtrrLibIsPowerOfTwo ( - IN UINT64 Operand - ) -{ - ASSERT (Operand != 0); - return (BOOLEAN)((Operand & (Operand - 1)) == 0); -} - /** Calculate the subtractive path from vertex Start to Stop. @@ -1658,7 +1643,7 @@ MtrrLibCalculateMtrrs ( break; } - if ((Weight[M (Start, Stop)] == MAX_WEIGHT) && MtrrLibIsPowerOfTwo (Length)) { + if ((Weight[M (Start, Stop)] == MAX_WEIGHT) && IS_POW2 (Length)) { if (MtrrLibGetNumberOfTypes ( Ranges, RangeCount, From 0a850f43206e5b5713fcc14904922ee1a78ed5f3 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Thu, 30 Mar 2023 13:44:26 -0700 Subject: [PATCH 0800/1529] .github/workflows/codeql-analysis.yml: Add PIP caching Adds caching of PIP dependencies. This reduces overall execution time and decreases likelihood of a network error reaching out pypi to get the dependencies. Caching happens based on modules specified in pip-requirements.txt. Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney --- .github/workflows/codeql-analysis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 791f79d1f0..33cc0bd6b4 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -66,6 +66,8 @@ jobs: uses: actions/setup-python@v4 with: python-version: '3.10.6' + cache: 'pip' + cache-dependency-path: 'pip-requirements.txt' # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL From a020dc08e1b9a75d4a84a84abf249be5c4be2d0f Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 31 Mar 2023 16:48:47 -0700 Subject: [PATCH 0801/1529] .github/dependabot.yml: Disable automatic rebasing Sets the rebase-strategy to "disabled" to prevent automatic rebasing. Rebasing can be done manually in the dependabot PR either through the GitHub UI or the dependabot command. Cc: Sean Brogan Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Sean Brogan Reviewed-by: Michael D Kinney --- .github/dependabot.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b4e0b93b16..479440fe63 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -20,6 +20,7 @@ updates: - "makubacki" - "mdkinney" - "spbrogan" + rebase-strategy: "disabled" - package-ecosystem: "github-actions" directory: "/" @@ -32,3 +33,4 @@ updates: - "makubacki" - "mdkinney" - "spbrogan" + rebase-strategy: "disabled" From 4776c1436e2207bf604cbfea55a112344abf6e98 Mon Sep 17 00:00:00 2001 From: Erich McMillan Date: Tue, 8 Nov 2022 03:23:56 +0000 Subject: [PATCH 0802/1529] MdeModulePkg/SmbiosDxe: Fix pointer and buffer overflow CodeQL alerts Details for these CodeQL alerts can be found here: - Pointer overflow check (cpp/pointer-overflow-check): - https://cwe.mitre.org/data/definitions/758.html - Potential buffer overflow check (cpp/potential-buffer-overflow): - https://cwe.mitre.org/data/definitions/676.html CodeQL alert: - Line 1612 in MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c - Type: Pointer overflow check - Severity: Low - Problem: Range check relying on pointer overflow Cc: Dandan Bi Cc: Erich McMillan Cc: Jian J Wang Cc: Liming Gao Cc: Michael Kubacki Cc: Star Zeng Cc: Zhichao Gao Cc: Zhiguang Liu Co-authored-by: Michael Kubacki Signed-off-by: Erich McMillan Reviewed-by: Liming Gao Reviewed-by: Oliver Smith-Denny --- MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c b/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c index 1d43adc766..dd077bb0cf 100644 --- a/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c +++ b/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c @@ -1608,9 +1608,7 @@ ParseAndAddExistingSmbiosTable ( // // Make sure not to access memory beyond SmbiosEnd // - if ((Smbios.Raw + sizeof (SMBIOS_STRUCTURE) > SmbiosEnd.Raw) || - (Smbios.Raw + sizeof (SMBIOS_STRUCTURE) < Smbios.Raw)) - { + if ((UINTN)(SmbiosEnd.Raw - Smbios.Raw) < sizeof (SMBIOS_STRUCTURE)) { return EFI_INVALID_PARAMETER; } @@ -1625,9 +1623,7 @@ ParseAndAddExistingSmbiosTable ( // Make sure not to access memory beyond SmbiosEnd // Each structure shall be terminated by a double-null (0000h). // - if ((Smbios.Raw + Smbios.Hdr->Length + 2 * sizeof (UINT8) > SmbiosEnd.Raw) || - (Smbios.Raw + Smbios.Hdr->Length + 2 * sizeof (UINT8) < Smbios.Raw)) - { + if ((UINTN)(SmbiosEnd.Raw - Smbios.Raw) < (Smbios.Hdr->Length + 2U)) { return EFI_INVALID_PARAMETER; } From 8ef61f582d27bdc068d981847f5a8bcfa347080e Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 9 Nov 2022 12:22:17 -0500 Subject: [PATCH 0803/1529] BaseTools/PatchCheck.py: Add PCCTS to tab exemption list Purdue Compiler Construction Tool Set (PCCTS) source code was copied/ pasted into BaseTools/Source/C/VfrCompile/Pccts/. The code contains tab characters instead of spaces. PatchCheck.py gives an error on modifications to files that contain tabs. The goal of my upcoming change there is not to mix tabs and spaces but to fix a bug while preserving its current formatting characters. This change adds that directory to the pre-existing list of directories in which tab checks are ignored in PatchCheck.py and also updates the check for makefiles to check for *.makefile: this allows {header,footer,app,lib}.makefile in BaseTools/Source/C/Makefiles to be detected and avoid having PatchCheck.py complain about tab characters. The check for "Makefile" is updated to be case-insensitive since there are some Makefiles named 'makefile' instead of 'Makefile'. Co-authored-by: Rebecca Cran Cc: Bob Feng Cc: Liming Gao Cc: Michael D Kinney Cc: Sean Brogan Cc: Yuwei Chen Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Michael D Kinney Reviewed-by: Rebecca Cran Reviewed-by: Oliver Smith-Denny --- BaseTools/Scripts/PatchCheck.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index fcdabfc8ac..5d17d99a12 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -383,7 +383,10 @@ def run(self): self.force_crlf = False self.force_notabs = False if os.path.basename(self.filename) == 'GNUmakefile' or \ - os.path.basename(self.filename) == 'Makefile': + os.path.basename(self.filename).lower() == 'makefile' or \ + os.path.splitext(self.filename)[1] == '.makefile' or \ + self.filename.startswith( + 'BaseTools/Source/C/VfrCompile/Pccts/'): self.force_notabs = False elif len(line.rstrip()) != 0: self.format_error("didn't find diff command") From a4ed7d6e9aa967cfac662a87efd0476085176cb0 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 9 Nov 2022 11:40:10 -0500 Subject: [PATCH 0804/1529] BaseTools/VfrCompile: Fix potential buffer overwrites While more portable methods exist to handle these cases, this change does not attempt to do more than fix the immediate problem and follow the conventions already established in this code. `snprintf()` is introduced as the minimum improvement apart from making the buffers larger. Fixes the following CodeQL alerts: 1. Failure on line 2339 in BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c - Type: Potentially overrunning write - Severity: Critical - Problem: This 'call to sprintf' operation requires 17 bytes but the destination is only 16 bytes. 2. Failure on line 2341 in BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c - Type: Potentially overrunning write - Severity: Critical - Problem: This 'call to sprintf' operation requires 17 bytes but the destination is only 16 bytes. 3. Failure on line 1309 in BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c - Type: Potentially overrunning write - Severity: Critical - Problem: This 'call to sprintf' operation requires 25 bytes but the destination is only 20 bytes. Cc: Bob Feng Cc: Liming Gao Cc: Michael D Kinney Cc: Sean Brogan Cc: Yuwei Chen Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny --- BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c | 10 +++++----- BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c b/BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c index 8e41239f47..33d9cac4c7 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/gen.c @@ -2331,14 +2331,14 @@ TokNode *p; set_nameErrSet = bufErrSet; /* MR23 */ } else { /* wild card */ - static char buf[sizeof("zzerr")+10]; - static char bufErrSet[sizeof("zzerr")+10]; + static char buf[sizeof("zzerr")+11]; + static char bufErrSet[sizeof("zzerr")+11]; int n = DefErrSet( &b, 0, NULL ); int nErrSet = DefErrSetWithSuffix(0, &bErrSet, 1, NULL, "_set"); - if ( GenCC ) sprintf(buf, "err%d", n); - else sprintf(buf, "zzerr%d", n); + if ( GenCC ) snprintf(buf, 11, "err%d", n); + else snprintf(buf, 11, "zzerr%d", n); if ( GenCC ) sprintf(bufErrSet, "err%d", nErrSet); - else sprintf(bufErrSet, "zzerr%d", nErrSet); + else snprintf(bufErrSet, 11, "zzerr%d", nErrSet); set_name = buf; set_nameErrSet = bufErrSet; } diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c b/BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c index 051ee4ec5d..488b4b9046 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/main.c @@ -1295,7 +1295,7 @@ int token; #endif { int j; - static char imag_name[20]; + static char imag_name[25]; /* look in all lexclasses for the token */ if ( TokenString(token) != NULL ) return TokenString(token); @@ -1306,7 +1306,7 @@ int token; } if (1) { - sprintf(imag_name,"UnknownToken#%d",token); /* MR13 */ + snprintf(imag_name, 25, "UnknownToken#%d", token); /* MR13 */ return imag_name; /* MR13 */ } From 74690a295a960c65c5b69dd4b8406e71cb5b2533 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:15:31 -0500 Subject: [PATCH 0805/1529] CryptoPkg: Fix conditionally uninitialized variable Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Checks the return value from `ASN1_get_object()` to verify values set by the function are valid. Note that the function returns literal `0x80`: `return (0x80);` That is used to check the return value is as the case in other areas of the code. Cc: Erich McMillan Cc: Guomin Jiang Cc: Jian J Wang Cc: Jiewen Yao Cc: Michael Kubacki Cc: Xiaoyu Lu Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Jiewen Yao Reviewed-by: Oliver Smith-Denny --- CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index 2333157e0d..1182323b63 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -807,6 +807,7 @@ X509GetTBSCert ( UINT32 Asn1Tag; UINT32 ObjClass; UINTN Length; + UINTN Inf; // // Check input parameters. @@ -836,9 +837,9 @@ X509GetTBSCert ( // Temp = Cert; Length = 0; - ASN1_get_object (&Temp, (long *)&Length, (int *)&Asn1Tag, (int *)&ObjClass, (long)CertSize); + Inf = ASN1_get_object (&Temp, (long *)&Length, (int *)&Asn1Tag, (int *)&ObjClass, (long)CertSize); - if (Asn1Tag != V_ASN1_SEQUENCE) { + if (((Inf & 0x80) == 0x00) && (Asn1Tag != V_ASN1_SEQUENCE)) { return FALSE; } @@ -848,7 +849,7 @@ X509GetTBSCert ( // // Verify the parsed TBSCertificate is one correct SEQUENCE data. // - if (Asn1Tag != V_ASN1_SEQUENCE) { + if (((Inf & 0x80) == 0x00) && (Asn1Tag != V_ASN1_SEQUENCE)) { return FALSE; } @@ -1888,18 +1889,20 @@ Asn1GetTag ( IN UINT32 Tag ) { - UINT8 *PtrOld; - INT32 ObjTag; - INT32 ObjCls; - long ObjLength; + UINT8 *PtrOld; + INT32 ObjTag; + INT32 ObjCls; + long ObjLength; + UINT32 Inf; // // Save Ptr position // PtrOld = *Ptr; - ASN1_get_object ((CONST UINT8 **)Ptr, &ObjLength, &ObjTag, &ObjCls, (INT32)(End - (*Ptr))); - if ((ObjTag == (INT32)(Tag & CRYPTO_ASN1_TAG_VALUE_MASK)) && + Inf = ASN1_get_object ((CONST UINT8 **)Ptr, &ObjLength, &ObjTag, &ObjCls, (INT32)(End - (*Ptr))); + if (((Inf & 0x80) == 0x00) && + (ObjTag == (INT32)(Tag & CRYPTO_ASN1_TAG_VALUE_MASK)) && (ObjCls == (INT32)(Tag & CRYPTO_ASN1_TAG_CLASS_MASK))) { *Length = (UINTN)ObjLength; From bb3eae239a46f4526a6c2da37c9bd198d5d19880 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:24:54 -0500 Subject: [PATCH 0806/1529] MdeModulePkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Dandan Bi Cc: Eric Dong Cc: Erich McMillan Cc: Guomin Jiang Cc: Jian J Wang Cc: Liming Gao Cc: Michael Kubacki Cc: Ray Ni Cc: Zhichao Gao Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Oliver Smith-Denny --- MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c | 5 +-- MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c | 24 +++++++++----- MdeModulePkg/Core/Dxe/Mem/Page.c | 17 +++++----- .../BootMaintenanceManagerUiLib/BootOption.c | 25 ++++++++------ .../Library/FileExplorerLib/FileExplorer.c | 5 ++- MdeModulePkg/Universal/BdsDxe/BdsEntry.c | 33 ++++++++++--------- .../DisplayEngineDxe/ProcessOptions.c | 11 ++++--- MdeModulePkg/Universal/HiiDatabaseDxe/Font.c | 14 +++++--- .../Universal/Variable/RuntimeDxe/Variable.c | 2 +- 9 files changed, 80 insertions(+), 56 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c index 843815d0cb..14bed54729 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c @@ -1407,6 +1407,7 @@ SupportPaletteSnoopAttributes ( IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation ) { + EFI_STATUS Status; PCI_IO_DEVICE *Temp; UINT16 VGACommand; @@ -1444,13 +1445,13 @@ SupportPaletteSnoopAttributes ( // Check if they are on the same bus // if (Temp->Parent == PciIoDevice->Parent) { - PCI_READ_COMMAND_REGISTER (Temp, &VGACommand); + Status = PCI_READ_COMMAND_REGISTER (Temp, &VGACommand); // // If they are on the same bus, either one can // be set to snoop, the other set to decode // - if ((VGACommand & EFI_PCI_COMMAND_VGA_PALETTE_SNOOP) != 0) { + if (!EFI_ERROR (Status) && ((VGACommand & EFI_PCI_COMMAND_VGA_PALETTE_SNOOP) != 0)) { // // VGA has set to snoop, so GFX can be only set to disable snoop // diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c index 48741085e5..496ffbd5c4 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c @@ -730,10 +730,12 @@ Uhci2ControlTransfer ( Uhc->PciIo->Flush (Uhc->PciIo); - *TransferResult = QhResult.Result; + if (!EFI_ERROR (Status)) { + *TransferResult = QhResult.Result; - if (DataLength != NULL) { - *DataLength = QhResult.Complete; + if (DataLength != NULL) { + *DataLength = QhResult.Complete; + } } UhciDestoryTds (Uhc, TDs); @@ -884,9 +886,11 @@ Uhci2BulkTransfer ( Uhc->PciIo->Flush (Uhc->PciIo); - *TransferResult = QhResult.Result; - *DataToggle = QhResult.NextToggle; - *DataLength = QhResult.Complete; + if (!EFI_ERROR (Status)) { + *TransferResult = QhResult.Result; + *DataToggle = QhResult.NextToggle; + *DataLength = QhResult.Complete; + } UhciDestoryTds (Uhc, TDs); Uhc->PciIo->Unmap (Uhc->PciIo, DataMap); @@ -1210,9 +1214,11 @@ Uhci2SyncInterruptTransfer ( UhciUnlinkTdFromQh (Uhc->SyncIntQh, TDs); Uhc->PciIo->Flush (Uhc->PciIo); - *TransferResult = QhResult.Result; - *DataToggle = QhResult.NextToggle; - *DataLength = QhResult.Complete; + if (!EFI_ERROR (Status)) { + *TransferResult = QhResult.Result; + *DataToggle = QhResult.NextToggle; + *DataLength = QhResult.Complete; + } UhciDestoryTds (Uhc, TDs); Uhc->PciIo->Unmap (Uhc->PciIo, DataMap); diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c index 5903ce7ab5..41af50b3d5 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Page.c +++ b/MdeModulePkg/Core/Dxe/Mem/Page.c @@ -449,14 +449,15 @@ PromoteMemoryResource ( // Promoted = PromoteGuardedFreePages (&StartAddress, &EndAddress); if (Promoted) { - CoreGetMemorySpaceDescriptor (StartAddress, &Descriptor); - CoreAddRange ( - EfiConventionalMemory, - StartAddress, - EndAddress, - Descriptor.Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | - EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME) - ); + if (!EFI_ERROR (CoreGetMemorySpaceDescriptor (StartAddress, &Descriptor))) { + CoreAddRange ( + EfiConventionalMemory, + StartAddress, + EndAddress, + Descriptor.Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | + EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME) + ); + } } } diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c index cdaa2db153..e22aaf3039 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c @@ -909,23 +909,28 @@ BootFromFile ( IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { + EFI_STATUS Status; EFI_BOOT_MANAGER_LOAD_OPTION BootOption; CHAR16 *FileName; + Status = EFI_NOT_STARTED; FileName = NULL; FileName = ExtractFileNameFromDevicePath (FilePath); if (FileName != NULL) { - EfiBootManagerInitializeLoadOption ( - &BootOption, - 0, - LoadOptionTypeBoot, - LOAD_OPTION_ACTIVE, - FileName, - FilePath, - NULL, - 0 - ); + Status = EfiBootManagerInitializeLoadOption ( + &BootOption, + 0, + LoadOptionTypeBoot, + LOAD_OPTION_ACTIVE, + FileName, + FilePath, + NULL, + 0 + ); + } + + if (!EFI_ERROR (Status)) { // // Since current no boot from removable media directly is allowed */ // diff --git a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c index ef949267fc..804a03d868 100644 --- a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c +++ b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c @@ -1075,7 +1075,10 @@ LibCreateNewFile ( NewHandle = NULL; FullFileName = NULL; - LibGetFileHandleFromDevicePath (gFileExplorerPrivate.RetDevicePath, &FileHandle, &ParentName, &DeviceHandle); + if (EFI_ERROR (LibGetFileHandleFromDevicePath (gFileExplorerPrivate.RetDevicePath, &FileHandle, &ParentName, &DeviceHandle))) { + return EFI_DEVICE_ERROR; + } + FullFileName = LibAppendFileName (ParentName, FileName); if (FullFileName == NULL) { return EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c index 766dde3aae..72de8d3211 100644 --- a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c +++ b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c @@ -691,6 +691,7 @@ BdsEntry ( EFI_DEVICE_PATH_PROTOCOL *FilePath; EFI_STATUS BootManagerMenuStatus; EFI_BOOT_MANAGER_LOAD_OPTION PlatformDefaultBootOption; + BOOLEAN PlatformDefaultBootOptionValid; HotkeyTriggered = NULL; Status = EFI_SUCCESS; @@ -809,24 +810,24 @@ BdsEntry ( CpuDeadLoop (); } - Status = EfiBootManagerInitializeLoadOption ( - &PlatformDefaultBootOption, - LoadOptionNumberUnassigned, - LoadOptionTypePlatformRecovery, - LOAD_OPTION_ACTIVE, - L"Default PlatformRecovery", - FilePath, - NULL, - 0 - ); - ASSERT_EFI_ERROR (Status); + PlatformDefaultBootOptionValid = EfiBootManagerInitializeLoadOption ( + &PlatformDefaultBootOption, + LoadOptionNumberUnassigned, + LoadOptionTypePlatformRecovery, + LOAD_OPTION_ACTIVE, + L"Default PlatformRecovery", + FilePath, + NULL, + 0 + ) == EFI_SUCCESS; + ASSERT (PlatformDefaultBootOptionValid == TRUE); // // System firmware must include a PlatformRecovery#### variable specifying // a short-form File Path Media Device Path containing the platform default // file path for removable media if the platform supports Platform Recovery. // - if (PcdGetBool (PcdPlatformRecoverySupport)) { + if (PlatformDefaultBootOptionValid && PcdGetBool (PcdPlatformRecoverySupport)) { LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery); if (EfiBootManagerFindLoadOption (&PlatformDefaultBootOption, LoadOptions, LoadOptionCount) == -1) { for (Index = 0; Index < LoadOptionCount; Index++) { @@ -1104,15 +1105,17 @@ BdsEntry ( LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery); ProcessLoadOptions (LoadOptions, LoadOptionCount); EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount); - } else { + } else if (PlatformDefaultBootOptionValid) { // // When platform recovery is not enabled, still boot to platform default file path. // - EfiBootManagerProcessLoadOption (&PlatformDefaultBootOption); + PlatformDefaultBootOptionValid = EfiBootManagerProcessLoadOption (&PlatformDefaultBootOption) == EFI_SUCCESS; } } - EfiBootManagerFreeLoadOption (&PlatformDefaultBootOption); + if (PlatformDefaultBootOptionValid) { + EfiBootManagerFreeLoadOption (&PlatformDefaultBootOption); + } DEBUG ((DEBUG_ERROR, "[Bds] Unable to boot!\n")); PlatformBootManagerUnableToBoot (); diff --git a/MdeModulePkg/Universal/DisplayEngineDxe/ProcessOptions.c b/MdeModulePkg/Universal/DisplayEngineDxe/ProcessOptions.c index dca3c1df07..0d4cfa4cf0 100644 --- a/MdeModulePkg/Universal/DisplayEngineDxe/ProcessOptions.c +++ b/MdeModulePkg/Universal/DisplayEngineDxe/ProcessOptions.c @@ -944,13 +944,14 @@ PrintMismatchMenuInfo ( UINTN FormsetBufferSize; Question = MenuOption->ThisTag; - HiiGetFormSetFromHiiHandle (gFormData->HiiHandle, &FormsetBuffer, &FormsetBufferSize); - FormSetTitleStr = GetToken (FormsetBuffer->FormSetTitle, gFormData->HiiHandle); - FormTitleStr = GetToken (gFormData->FormTitle, gFormData->HiiHandle); + if (!EFI_ERROR (HiiGetFormSetFromHiiHandle (gFormData->HiiHandle, &FormsetBuffer, &FormsetBufferSize))) { + FormSetTitleStr = GetToken (FormsetBuffer->FormSetTitle, gFormData->HiiHandle); + FormTitleStr = GetToken (gFormData->FormTitle, gFormData->HiiHandle); - DEBUG ((DEBUG_ERROR, "\n[%a]: Mismatch Formset : Formset Guid = %g, FormSet title = %s\n", gEfiCallerBaseName, &gFormData->FormSetGuid, FormSetTitleStr)); - DEBUG ((DEBUG_ERROR, "[%a]: Mismatch Form : FormId = %d, Form title = %s.\n", gEfiCallerBaseName, gFormData->FormId, FormTitleStr)); + DEBUG ((DEBUG_ERROR, "\n[%a]: Mismatch Formset : Formset Guid = %g, FormSet title = %s\n", gEfiCallerBaseName, &gFormData->FormSetGuid, FormSetTitleStr)); + DEBUG ((DEBUG_ERROR, "[%a]: Mismatch Form : FormId = %d, Form title = %s.\n", gEfiCallerBaseName, gFormData->FormId, FormTitleStr)); + } if (Question->OpCode->OpCode == EFI_IFR_ORDERED_LIST_OP) { QuestionName = GetToken (((EFI_IFR_ORDERED_LIST *)MenuOption->ThisTag->OpCode)->Question.Header.Prompt, gFormData->HiiHandle); diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c b/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c index 399f90feb7..8a0b12f72f 100644 --- a/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c +++ b/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c @@ -1745,6 +1745,7 @@ HiiStringToImage ( Attributes = (UINT8 *)AllocateZeroPool (StrLength * sizeof (UINT8)); ASSERT (Attributes != NULL); + FontInfo = NULL; RowInfo = NULL; Status = EFI_SUCCESS; StringIn2 = NULL; @@ -1787,11 +1788,14 @@ HiiStringToImage ( Background = ((EFI_FONT_DISPLAY_INFO *)StringInfo)->BackgroundColor; } else if (Status == EFI_SUCCESS) { FontInfo = &StringInfoOut->FontInfo; - IsFontInfoExisted (Private, FontInfo, NULL, NULL, &GlobalFont); - Height = GlobalFont->FontPackage->Height; - BaseLine = GlobalFont->FontPackage->BaseLine; - Foreground = StringInfoOut->ForegroundColor; - Background = StringInfoOut->BackgroundColor; + if (IsFontInfoExisted (Private, FontInfo, NULL, NULL, &GlobalFont)) { + Height = GlobalFont->FontPackage->Height; + BaseLine = GlobalFont->FontPackage->BaseLine; + Foreground = StringInfoOut->ForegroundColor; + Background = StringInfoOut->BackgroundColor; + } else { + goto Exit; + } } else { goto Exit; } diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 14c176887a..3eb7d935b4 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -2453,7 +2453,7 @@ VariableServiceGetVariable ( AcquireLockOnlyAtBootTime (&mVariableModuleGlobal->VariableGlobal.VariableServicesLock); Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); - if ((Variable.CurrPtr == NULL) || EFI_ERROR (Status)) { + if (EFI_ERROR (Status) || (Variable.CurrPtr == NULL)) { goto Done; } From 952e03f348cb28d503bda6677ee4e1c23bd96ff1 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:29:05 -0500 Subject: [PATCH 0807/1529] MdePkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Note that this change affects the actual return value from the following functions. The functions documented that if an integer overflow occurred, MAX_UINTN would be returned. They were implemented to actually return an undefined value from the stack. This change makes the function follow its description. However, this is technically different than what callers may have previously expected. MdePkg/Library/BaseLib/String.c: - StrDecimalToUintn() - StrDecimalToUint64() - StrHexToUintn() - StrHexToUint64() - AsciiStrDecimalToUintn() - AsciiStrDecimalToUint64() - AsciiStrHexToUintn() - AsciiStrHexToUint64() Cc: Erich McMillan Cc: Liming Gao Cc: Michael D Kinney Cc: Michael Kubacki Cc: Zhiguang Liu Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseLib/String.c | 40 ++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/MdePkg/Library/BaseLib/String.c b/MdePkg/Library/BaseLib/String.c index 98e6d31463..637c96e7b3 100644 --- a/MdePkg/Library/BaseLib/String.c +++ b/MdePkg/Library/BaseLib/String.c @@ -408,7 +408,10 @@ StrDecimalToUintn ( { UINTN Result; - StrDecimalToUintnS (String, (CHAR16 **)NULL, &Result); + if (RETURN_ERROR (StrDecimalToUintnS (String, (CHAR16 **)NULL, &Result))) { + return MAX_UINTN; + } + return Result; } @@ -454,7 +457,10 @@ StrDecimalToUint64 ( { UINT64 Result; - StrDecimalToUint64S (String, (CHAR16 **)NULL, &Result); + if (RETURN_ERROR (StrDecimalToUint64S (String, (CHAR16 **)NULL, &Result))) { + return MAX_UINT64; + } + return Result; } @@ -501,7 +507,10 @@ StrHexToUintn ( { UINTN Result; - StrHexToUintnS (String, (CHAR16 **)NULL, &Result); + if (RETURN_ERROR (StrHexToUintnS (String, (CHAR16 **)NULL, &Result))) { + return MAX_UINTN; + } + return Result; } @@ -548,7 +557,10 @@ StrHexToUint64 ( { UINT64 Result; - StrHexToUint64S (String, (CHAR16 **)NULL, &Result); + if (RETURN_ERROR (StrHexToUint64S (String, (CHAR16 **)NULL, &Result))) { + return MAX_UINT64; + } + return Result; } @@ -989,7 +1001,10 @@ AsciiStrDecimalToUintn ( { UINTN Result; - AsciiStrDecimalToUintnS (String, (CHAR8 **)NULL, &Result); + if (RETURN_ERROR (AsciiStrDecimalToUintnS (String, (CHAR8 **)NULL, &Result))) { + return MAX_UINTN; + } + return Result; } @@ -1031,7 +1046,10 @@ AsciiStrDecimalToUint64 ( { UINT64 Result; - AsciiStrDecimalToUint64S (String, (CHAR8 **)NULL, &Result); + if (RETURN_ERROR (AsciiStrDecimalToUint64S (String, (CHAR8 **)NULL, &Result))) { + return MAX_UINT64; + } + return Result; } @@ -1077,7 +1095,10 @@ AsciiStrHexToUintn ( { UINTN Result; - AsciiStrHexToUintnS (String, (CHAR8 **)NULL, &Result); + if (RETURN_ERROR (AsciiStrHexToUintnS (String, (CHAR8 **)NULL, &Result))) { + return MAX_UINTN; + } + return Result; } @@ -1123,7 +1144,10 @@ AsciiStrHexToUint64 ( { UINT64 Result; - AsciiStrHexToUint64S (String, (CHAR8 **)NULL, &Result); + if (RETURN_ERROR (AsciiStrHexToUint64S (String, (CHAR8 **)NULL, &Result))) { + return MAX_UINT64; + } + return Result; } From b0e5af076ed29f90f41424f6739b001657a5d867 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:30:35 -0500 Subject: [PATCH 0808/1529] NetworkPkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Erich McMillan Cc: Jiaxin Wu Cc: Maciej Rabeda Cc: Michael D Kinney Cc: Michael Kubacki Cc: Siyuan Fu Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny --- NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c | 2 +- NetworkPkg/TcpDxe/TcpInput.c | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c b/NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c index 6a5d78629b..21813463aa 100644 --- a/NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c +++ b/NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c @@ -753,7 +753,7 @@ HttpUrlGetPort ( Status = AsciiStrDecimalToUintnS (Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset, (CHAR8 **)NULL, &Data); - if (Data > HTTP_URI_PORT_MAX_NUM) { + if (EFI_ERROR (Status) || (Data > HTTP_URI_PORT_MAX_NUM)) { Status = EFI_INVALID_PARAMETER; goto ON_EXIT; } diff --git a/NetworkPkg/TcpDxe/TcpInput.c b/NetworkPkg/TcpDxe/TcpInput.c index fb1aa827f8..7b329be64d 100644 --- a/NetworkPkg/TcpDxe/TcpInput.c +++ b/NetworkPkg/TcpDxe/TcpInput.c @@ -1570,6 +1570,9 @@ TcpIcmpInput ( BOOLEAN IcmpErrIsHard; BOOLEAN IcmpErrNotify; + IcmpErrIsHard = FALSE; + IcmpErrNotify = FALSE; + if (Nbuf->TotalSize < sizeof (TCP_HEAD)) { goto CLEAN_EXIT; } From c9d839c8037e7a9768fcd7e6b4cca8781b53b5a8 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:32:41 -0500 Subject: [PATCH 0809/1529] PcAtChipsetPkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Erich McMillan Cc: Michael D Kinney Cc: Michael Kubacki Cc: Ray Ni Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Ray Ni Reviewed-by: Oliver Smith-Denny --- PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c index 15759463f2..d8b9fa8376 100644 --- a/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c +++ b/PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcRtc.c @@ -345,7 +345,7 @@ PcRtcInit ( // so we can use them to get and set wakeup time. // Status = PcRtcGetWakeupTime (&Enabled, &Pending, &Time, Global); - if ((Enabled) || (!EFI_ERROR (Status))) { + if ((!EFI_ERROR (Status)) || (Enabled)) { return EFI_SUCCESS; } @@ -838,8 +838,11 @@ PcRtcSetWakeupTime ( // // Just support set alarm time within 24 hours // - PcRtcGetTime (&RtcTime, &Capabilities, Global); - Status = RtcTimeFieldsValid (&RtcTime); + Status = PcRtcGetTime (&RtcTime, &Capabilities, Global); + if (!EFI_ERROR (Status)) { + Status = RtcTimeFieldsValid (&RtcTime); + } + if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } From c16124c087e64447c63797bcdbdbd3fedc5536f8 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:35:39 -0500 Subject: [PATCH 0810/1529] ShellPkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Erich McMillan Cc: Michael D Kinney Cc: Michael Kubacki Cc: Ray Ni Cc: Zhichao Gao Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Zhichao Gao Reviewed-by: Oliver Smith-Denny --- ShellPkg/Application/Shell/Shell.c | 1 + ShellPkg/Application/Shell/ShellProtocol.c | 60 ++++++++++--------- .../UefiShellCommandLib/UefiShellCommandLib.c | 56 +++++++++-------- .../Library/UefiShellDebug1CommandsLib/Dblk.c | 18 +++--- .../EfiDecompress.c | 9 ++- .../UefiShellDriver1CommandsLib/Connect.c | 14 +++-- .../UefiShellDriver1CommandsLib/Disconnect.c | 17 ++++-- .../UefiShellDriver1CommandsLib/DrvDiag.c | 21 +++---- 8 files changed, 107 insertions(+), 89 deletions(-) diff --git a/ShellPkg/Application/Shell/Shell.c b/ShellPkg/Application/Shell/Shell.c index 0ae6e14a34..f95c799bb2 100644 --- a/ShellPkg/Application/Shell/Shell.c +++ b/ShellPkg/Application/Shell/Shell.c @@ -1300,6 +1300,7 @@ DoStartupScript ( CHAR16 *FullFileStringPath; UINTN NewSize; + CalleeStatus = EFI_SUCCESS; Key.UnicodeChar = CHAR_NULL; Key.ScanCode = 0; diff --git a/ShellPkg/Application/Shell/ShellProtocol.c b/ShellPkg/Application/Shell/ShellProtocol.c index e6d20ab164..da8c31cb03 100644 --- a/ShellPkg/Application/Shell/ShellProtocol.c +++ b/ShellPkg/Application/Shell/ShellProtocol.c @@ -735,50 +735,52 @@ EfiShellGetDeviceName ( // // Now check the parent controller using this as the child. // - if (DeviceNameToReturn == NULL) { - PARSE_HANDLE_DATABASE_PARENTS (DeviceHandle, &ParentControllerCount, &ParentControllerBuffer); + Status = PARSE_HANDLE_DATABASE_PARENTS (DeviceHandle, &ParentControllerCount, &ParentControllerBuffer); + if ((DeviceNameToReturn == NULL) && !EFI_ERROR (Status)) { for (LoopVar = 0; LoopVar < ParentControllerCount; LoopVar++) { - PARSE_HANDLE_DATABASE_UEFI_DRIVERS (ParentControllerBuffer[LoopVar], &ParentDriverCount, &ParentDriverBuffer); - for (HandleCount = 0; HandleCount < ParentDriverCount; HandleCount++) { - // - // try using that driver's component name with controller and our driver as the child. - // - Status = gBS->OpenProtocol ( - ParentDriverBuffer[HandleCount], - &gEfiComponentName2ProtocolGuid, - (VOID **)&CompName2, - gImageHandle, - NULL, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); - if (EFI_ERROR (Status)) { + Status = PARSE_HANDLE_DATABASE_UEFI_DRIVERS (ParentControllerBuffer[LoopVar], &ParentDriverCount, &ParentDriverBuffer); + if (!EFI_ERROR (Status)) { + for (HandleCount = 0; HandleCount < ParentDriverCount; HandleCount++) { + // + // try using that driver's component name with controller and our driver as the child. + // Status = gBS->OpenProtocol ( ParentDriverBuffer[HandleCount], - &gEfiComponentNameProtocolGuid, + &gEfiComponentName2ProtocolGuid, (VOID **)&CompName2, gImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); - } + if (EFI_ERROR (Status)) { + Status = gBS->OpenProtocol ( + ParentDriverBuffer[HandleCount], + &gEfiComponentNameProtocolGuid, + (VOID **)&CompName2, + gImageHandle, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); + } - if (EFI_ERROR (Status)) { - continue; + if (EFI_ERROR (Status)) { + continue; + } + + Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); + Status = CompName2->GetControllerName (CompName2, ParentControllerBuffer[LoopVar], DeviceHandle, Lang, &DeviceNameToReturn); + FreePool (Lang); + Lang = NULL; + if (!EFI_ERROR (Status) && (DeviceNameToReturn != NULL)) { + break; + } } - Lang = GetBestLanguageForDriver (CompName2->SupportedLanguages, Language, FALSE); - Status = CompName2->GetControllerName (CompName2, ParentControllerBuffer[LoopVar], DeviceHandle, Lang, &DeviceNameToReturn); - FreePool (Lang); - Lang = NULL; + SHELL_FREE_NON_NULL (ParentDriverBuffer); if (!EFI_ERROR (Status) && (DeviceNameToReturn != NULL)) { break; } } - - SHELL_FREE_NON_NULL (ParentDriverBuffer); - if (!EFI_ERROR (Status) && (DeviceNameToReturn != NULL)) { - break; - } } SHELL_FREE_NON_NULL (ParentControllerBuffer); diff --git a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c index 36cf46fb2c..4549cbde9b 100644 --- a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c +++ b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c @@ -1399,10 +1399,11 @@ ShellCommandCreateInitialMappingsAndPaths ( CHAR16 *MapName; SHELL_MAP_LIST *MapListItem; - SplitCurDir = NULL; - MapName = NULL; - MapListItem = NULL; - HandleList = NULL; + ConsistMappingTable = NULL; + SplitCurDir = NULL; + MapName = NULL; + MapListItem = NULL; + HandleList = NULL; // // Reset the static members back to zero @@ -1458,32 +1459,35 @@ ShellCommandCreateInitialMappingsAndPaths ( // PerformQuickSort (DevicePathList, Count, sizeof (EFI_DEVICE_PATH_PROTOCOL *), DevicePathCompare); - ShellCommandConsistMappingInitialize (&ConsistMappingTable); - // - // Assign new Mappings to all... - // - for (Count = 0; HandleList[Count] != NULL; Count++) { - // - // Get default name first - // - NewDefaultName = ShellCommandCreateNewMappingName (MappingTypeFileSystem); - ASSERT (NewDefaultName != NULL); - Status = ShellCommandAddMapItemAndUpdatePath (NewDefaultName, DevicePathList[Count], 0, TRUE); - ASSERT_EFI_ERROR (Status); - FreePool (NewDefaultName); - + if (!EFI_ERROR (ShellCommandConsistMappingInitialize (&ConsistMappingTable))) { // - // Now do consistent name + // Assign new Mappings to all... // - NewConsistName = ShellCommandConsistMappingGenMappingName (DevicePathList[Count], ConsistMappingTable); - if (NewConsistName != NULL) { - Status = ShellCommandAddMapItemAndUpdatePath (NewConsistName, DevicePathList[Count], 0, FALSE); + for (Count = 0; HandleList[Count] != NULL; Count++) { + // + // Get default name first + // + NewDefaultName = ShellCommandCreateNewMappingName (MappingTypeFileSystem); + ASSERT (NewDefaultName != NULL); + Status = ShellCommandAddMapItemAndUpdatePath (NewDefaultName, DevicePathList[Count], 0, TRUE); ASSERT_EFI_ERROR (Status); - FreePool (NewConsistName); + FreePool (NewDefaultName); + + // + // Now do consistent name + // + NewConsistName = ShellCommandConsistMappingGenMappingName (DevicePathList[Count], ConsistMappingTable); + if (NewConsistName != NULL) { + Status = ShellCommandAddMapItemAndUpdatePath (NewConsistName, DevicePathList[Count], 0, FALSE); + ASSERT_EFI_ERROR (Status); + FreePool (NewConsistName); + } } } - ShellCommandConsistMappingUnInitialize (ConsistMappingTable); + if (ConsistMappingTable != NULL) { + ShellCommandConsistMappingUnInitialize (ConsistMappingTable); + } SHELL_FREE_NON_NULL (HandleList); SHELL_FREE_NON_NULL (DevicePathList); @@ -1626,12 +1630,12 @@ ShellCommandUpdateMapping ( // PerformQuickSort (DevicePathList, Count, sizeof (EFI_DEVICE_PATH_PROTOCOL *), DevicePathCompare); - ShellCommandConsistMappingInitialize (&ConsistMappingTable); + Status = ShellCommandConsistMappingInitialize (&ConsistMappingTable); // // Assign new Mappings to remainders // - for (Count = 0; !EFI_ERROR (Status) && HandleList[Count] != NULL && !EFI_ERROR (Status); Count++) { + for (Count = 0; !EFI_ERROR (Status) && HandleList[Count] != NULL; Count++) { // // Skip ones that already have // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c index 97a4b57a93..5329b559ba 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dblk.c @@ -158,7 +158,10 @@ ShellCommandRunDblk ( ShellStatus = SHELL_INVALID_PARAMETER; } - ShellConvertStringToUint64 (LbaString, &Lba, TRUE, FALSE); + if (EFI_ERROR (ShellConvertStringToUint64 (LbaString, &Lba, TRUE, FALSE))) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"dblk", LbaString); + ShellStatus = SHELL_INVALID_PARAMETER; + } } if (BlockCountString == NULL) { @@ -169,12 +172,13 @@ ShellCommandRunDblk ( ShellStatus = SHELL_INVALID_PARAMETER; } - ShellConvertStringToUint64 (BlockCountString, &BlockCount, TRUE, FALSE); - if (BlockCount > 0x10) { - BlockCount = 0x10; - } else if (BlockCount == 0) { - ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"dblk", BlockCountString); - ShellStatus = SHELL_INVALID_PARAMETER; + if (!EFI_ERROR (ShellConvertStringToUint64 (BlockCountString, &BlockCount, TRUE, FALSE))) { + if (BlockCount > 0x10) { + BlockCount = 0x10; + } else if (BlockCount == 0) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_PARAM_INV), gShellDebug1HiiHandle, L"dblk", BlockCountString); + ShellStatus = SHELL_INVALID_PARAMETER; + } } } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c index 8bf23a2076..72f8c087cb 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/EfiDecompress.c @@ -112,10 +112,13 @@ ShellCommandRunEfiDecompress ( if (ShellStatus == SHELL_SUCCESS) { Status = FileHandleGetSize (InFileHandle, &Temp64Bit); - ASSERT (Temp64Bit <= (UINT32)(-1)); - InSize = (UINTN)Temp64Bit; ASSERT_EFI_ERROR (Status); - InBuffer = AllocateZeroPool (InSize); + if (!EFI_ERROR (Status)) { + ASSERT (Temp64Bit <= (UINT32)(-1)); + InSize = (UINTN)Temp64Bit; + InBuffer = AllocateZeroPool (InSize); + } + if (InBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; } else { diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c index d7a133c0c5..870c5b0d1d 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Connect.c @@ -508,9 +508,10 @@ ShellCommandRunConnect ( Count = ShellCommandLineGetCount (Package); if (Param1 != NULL) { - Status = ShellConvertStringToUint64 (Param1, &Intermediate, TRUE, FALSE); - Handle1 = ConvertHandleIndexToHandle ((UINTN)Intermediate); - if (EFI_ERROR (Status)) { + Status = ShellConvertStringToUint64 (Param1, &Intermediate, TRUE, FALSE); + if (!EFI_ERROR (Status)) { + Handle1 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + } else { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"connect", Param1); ShellStatus = SHELL_INVALID_PARAMETER; } @@ -519,9 +520,10 @@ ShellCommandRunConnect ( } if (Param2 != NULL) { - Status = ShellConvertStringToUint64 (Param2, &Intermediate, TRUE, FALSE); - Handle2 = ConvertHandleIndexToHandle ((UINTN)Intermediate); - if (EFI_ERROR (Status)) { + Status = ShellConvertStringToUint64 (Param2, &Intermediate, TRUE, FALSE); + if (!EFI_ERROR (Status)) { + Handle2 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + } else { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"connect", Param2); ShellStatus = SHELL_INVALID_PARAMETER; } diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c index 009ae5282b..fd49d1f7ce 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Disconnect.c @@ -160,12 +160,17 @@ ShellCommandRunDisconnect ( Param1 = ShellCommandLineGetRawValue (Package, 1); Param2 = ShellCommandLineGetRawValue (Package, 2); Param3 = ShellCommandLineGetRawValue (Package, 3); - ShellConvertStringToUint64 (Param1, &Intermediate1, TRUE, FALSE); - Handle1 = Param1 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate1) : NULL; - ShellConvertStringToUint64 (Param2, &Intermediate2, TRUE, FALSE); - Handle2 = Param2 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate2) : NULL; - ShellConvertStringToUint64 (Param3, &Intermediate3, TRUE, FALSE); - Handle3 = Param3 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate3) : NULL; + if (!EFI_ERROR (ShellConvertStringToUint64 (Param1, &Intermediate1, TRUE, FALSE))) { + Handle1 = Param1 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate1) : NULL; + } + + if (!EFI_ERROR (ShellConvertStringToUint64 (Param2, &Intermediate2, TRUE, FALSE))) { + Handle2 = Param2 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate2) : NULL; + } + + if (!EFI_ERROR (ShellConvertStringToUint64 (Param3, &Intermediate3, TRUE, FALSE))) { + Handle3 = Param3 != NULL ? ConvertHandleIndexToHandle ((UINTN)Intermediate3) : NULL; + } if ((Param1 != NULL) && (Handle1 == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_GEN_INV_HANDLE), gShellDriver1HiiHandle, L"disconnect", Param1); diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c index c645c9fd68..b845d694b2 100644 --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/DrvDiag.c @@ -438,25 +438,22 @@ ShellCommandRunDrvDiag ( ControllerHandleStr = ShellCommandLineGetRawValue (Package, 2); ChildHandleStr = ShellCommandLineGetRawValue (Package, 3); - if (DriverHandleStr == NULL) { - Handle1 = NULL; - } else { - ShellConvertStringToUint64 (DriverHandleStr, &Intermediate, TRUE, FALSE); + if ((DriverHandleStr != NULL) && !EFI_ERROR (ShellConvertStringToUint64 (DriverHandleStr, &Intermediate, TRUE, FALSE))) { Handle1 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + } else { + Handle1 = NULL; } - if (ControllerHandleStr == NULL) { - Handle2 = NULL; - } else { - ShellConvertStringToUint64 (ControllerHandleStr, &Intermediate, TRUE, FALSE); + if ((ControllerHandleStr != NULL) && !EFI_ERROR (ShellConvertStringToUint64 (ControllerHandleStr, &Intermediate, TRUE, FALSE))) { Handle2 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + } else { + Handle2 = NULL; } - if (ChildHandleStr == NULL) { - Handle3 = NULL; - } else { - ShellConvertStringToUint64 (ChildHandleStr, &Intermediate, TRUE, FALSE); + if ((ChildHandleStr != NULL) && !EFI_ERROR (ShellConvertStringToUint64 (ChildHandleStr, &Intermediate, TRUE, FALSE))) { Handle3 = ConvertHandleIndexToHandle ((UINTN)Intermediate); + } else { + Handle3 = NULL; } Status = DoDiagnostics ( From 2d69a00e799f7194111990f5276ee4c74a294923 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:37:38 -0500 Subject: [PATCH 0811/1529] UefiCpuPkg: Fix conditionally uninitialized variables Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Eric Dong Cc: Erich McMillan Cc: Michael D Kinney Cc: Michael Kubacki Cc: Rahul Kumar Cc: Ray Ni Co-authored-by: Erich McMillan Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny --- UefiCpuPkg/CpuMpPei/CpuBist.c | 8 +++++++- UefiCpuPkg/CpuMpPei/CpuMpPei.c | 8 +++++++- UefiCpuPkg/CpuMpPei/CpuPaging.c | 9 ++++++++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/UefiCpuPkg/CpuMpPei/CpuBist.c b/UefiCpuPkg/CpuMpPei/CpuBist.c index 7dc93cd784..78e0087039 100644 --- a/UefiCpuPkg/CpuMpPei/CpuBist.c +++ b/UefiCpuPkg/CpuMpPei/CpuBist.c @@ -175,7 +175,13 @@ CollectBistDataFromPpi ( EFI_SEC_PLATFORM_INFORMATION_RECORD2 *PlatformInformationRecord2; EFI_SEC_PLATFORM_INFORMATION_CPU *CpuInstanceInHob; - MpInitLibGetNumberOfProcessors (&NumberOfProcessors, &NumberOfEnabledProcessors); + Status = MpInitLibGetNumberOfProcessors (&NumberOfProcessors, &NumberOfEnabledProcessors); + ASSERT_EFI_ERROR (Status); + + if (EFI_ERROR (Status)) { + NumberOfProcessors = 1; + NumberOfEnabledProcessors = 1; + } BistInformationSize = sizeof (EFI_SEC_PLATFORM_INFORMATION_RECORD2) + sizeof (EFI_SEC_PLATFORM_INFORMATION_CPU) * NumberOfProcessors; diff --git a/UefiCpuPkg/CpuMpPei/CpuMpPei.c b/UefiCpuPkg/CpuMpPei/CpuMpPei.c index e7f1fe9f42..b504bea3cf 100644 --- a/UefiCpuPkg/CpuMpPei/CpuMpPei.c +++ b/UefiCpuPkg/CpuMpPei/CpuMpPei.c @@ -473,7 +473,13 @@ InitializeMpExceptionStackSwitchHandlers ( return; } - MpInitLibGetNumberOfProcessors (&NumberOfProcessors, NULL); + Status = MpInitLibGetNumberOfProcessors (&NumberOfProcessors, NULL); + ASSERT_EFI_ERROR (Status); + + if (EFI_ERROR (Status)) { + NumberOfProcessors = 1; + } + SwitchStackData = AllocatePages (EFI_SIZE_TO_PAGES (NumberOfProcessors * sizeof (EXCEPTION_STACK_SWITCH_CONTEXT))); ASSERT (SwitchStackData != NULL); ZeroMem (SwitchStackData, NumberOfProcessors * sizeof (EXCEPTION_STACK_SWITCH_CONTEXT)); diff --git a/UefiCpuPkg/CpuMpPei/CpuPaging.c b/UefiCpuPkg/CpuMpPei/CpuPaging.c index 1354222253..a471f089c8 100644 --- a/UefiCpuPkg/CpuMpPei/CpuPaging.c +++ b/UefiCpuPkg/CpuMpPei/CpuPaging.c @@ -538,6 +538,7 @@ SetupStackGuardPage ( UINTN NumberOfProcessors; UINTN Bsp; UINTN Index; + EFI_STATUS Status; // // One extra page at the bottom of the stack is needed for Guard page. @@ -547,7 +548,13 @@ SetupStackGuardPage ( ASSERT (FALSE); } - MpInitLibGetNumberOfProcessors (&NumberOfProcessors, NULL); + Status = MpInitLibGetNumberOfProcessors (&NumberOfProcessors, NULL); + ASSERT_EFI_ERROR (Status); + + if (EFI_ERROR (Status)) { + NumberOfProcessors = 1; + } + MpInitLibWhoAmI (&Bsp); for (Index = 0; Index < NumberOfProcessors; ++Index) { StackBase = 0; From f76221f4361411dd9d3e29978058833137f20ce5 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 8 Nov 2022 15:46:57 -0500 Subject: [PATCH 0812/1529] .github/codeql/edk2.qls: Enable CWE 457, 676, and 758 queries The previous commits fixed issues with these queries across various packages. Now that those are resolved, enable the queries in the edk2 query set so regressions can be found in the future. Enables: 1. cpp/conditionallyuninitializedvariable - CWE: https://cwe.mitre.org/data/definitions/457.html - @name Conditionally uninitialized variable - @description An initialization function is used to initialize a local variable, but the returned status code is not checked. The variable may be left in an uninitialized state, and reading the variable may result in undefined behavior. - @kind problem - @problem.severity warning - @security-severity 7.8 - @id cpp/conditionally-uninitialized-variable - @tags security - external/cwe/cwe-457 2. cpp/pointer-overflow-check - CWE: https://cwe.mitre.org/data/definitions/758.html - @name Pointer overflow check - @description Adding a value to a pointer to check if it overflows relies on undefined behavior and may lead to memory corruption. - @kind problem - @problem.severity error - @security-severity 2.1 - @precision high - @id cpp/pointer-overflow-check - @tags reliability - security - external/cwe/cwe-758 3. cpp/potential-buffer-overflow - CWE: https://cwe.mitre.org/data/definitions/676.html - @name Potential buffer overflow - @description Using a library function that does not check buffer bounds requires the surrounding program to be very carefully written to avoid buffer overflows. - @kind problem - @id cpp/potential-buffer-overflow - @problem.severity warning - @security-severity 10.0 - @tags reliability - security - external/cwe/cwe-676 - @deprecated This query is deprecated, use Potentially overrunning write (`cpp/overrunning-write`) and Potentially overrunning write with float to string conversion (`cpp/overrunning-write-with-float`) instead. Note that cpp/potential-buffer-overflow is deprecated. This query will be updated to the succeeding queries in the next commit. The query is used in this commit to show that we considered and tested the query in history. Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny --- .github/codeql/edk2.qls | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/codeql/edk2.qls b/.github/codeql/edk2.qls index ef9aae790f..dc2d87764e 100644 --- a/.github/codeql/edk2.qls +++ b/.github/codeql/edk2.qls @@ -8,7 +8,14 @@ # Enable individual queries below. +- include: + id: cpp/conditionallyuninitializedvariable - include: id: cpp/infinite-loop-with-unsatisfiable-exit-condition - include: id: cpp/overflow-buffer +- include: + id: cpp/pointer-overflow-check +- include: + id: cpp/potential-buffer-overflow + From 9ad3fc2c4b919debdad297a630b4d85a364e67eb Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 9 Nov 2022 10:34:07 -0500 Subject: [PATCH 0813/1529] .github/codeql/edk2.qls: Enable CWE 120, 787, and 805 queries As recommended by CodeQL this change replaces cpp/potential-buffer-overflow with cpp/overrunning-write-with-float and cpp/overrunning-write. Enables: 1. cpp/overrunning-write - @name Likely overrunning write - @description Buffer write operations that do not control the length data written may overflow - @kind problem - @problem.severity error - @security-severity 9.3 - @precision high - @id cpp/very-likely-overrunning-write - @tags reliability - security - external/cwe/cwe-120 - external/cwe/cwe-787 - external/cwe/cwe-805 2. cpp/overrunning-write-with-float - @name Potentially overrunning write with float to string conversion - @description Buffer write operations that do not control the length of data written may overflow when floating point inputs take extreme values. - @kind problem - @problem.severity error - @security-severity 9.3 - @precision medium - @id cpp/overrunning-write-with-float - @tags reliability - security - external/cwe/cwe-120 - external/cwe/cwe-787 - external/cwe/cwe-805 3. cpp/very-likely-overrunning-write - @name Likely overrunning write - @description Buffer write operations that do not control the length of data written may overflow - @kind problem - @problem.severity error - @security-severity 9.3 - @precision high - @id cpp/very-likely-overrunning-write - @tags reliability - security - external/cwe/cwe-120 - external/cwe/cwe-787 - external/cwe/cwe-805 - CWEs: - https://cwe.mitre.org/data/definitions/120.html - https://cwe.mitre.org/data/definitions/787.html - https://cwe.mitre.org/data/definitions/805.html Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny --- .github/codeql/edk2.qls | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/codeql/edk2.qls b/.github/codeql/edk2.qls index dc2d87764e..9bea9ba01f 100644 --- a/.github/codeql/edk2.qls +++ b/.github/codeql/edk2.qls @@ -14,8 +14,11 @@ id: cpp/infinite-loop-with-unsatisfiable-exit-condition - include: id: cpp/overflow-buffer +- include: + id: cpp/overrunning-write +- include: + id: cpp/overrunning-write-with-float - include: id: cpp/pointer-overflow-check - include: - id: cpp/potential-buffer-overflow - + id: cpp/very-likely-overrunning-write From b2adef96ea2be6c90e7ddf0f597f3496edfa8ddd Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 3 Apr 2023 09:59:30 -0700 Subject: [PATCH 0814/1529] .github.workflows: Split MdeModulePkg and CryptoPkg analysis MdeModulePkg and CryptoPkg have double the CodeQL analysis time of all other packages. Split these packages up to perform separate analysis of IA32 and X64. Cc: Sean Brogan Cc: Michael Kubacki Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki --- .github/workflows/codeql-analysis.yml | 64 ++++++++++++++++++--------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 33cc0bd6b4..cc7f06f7b5 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -39,25 +39,45 @@ jobs: strategy: fail-fast: false matrix: - package: [ - "ArmPkg", - "CryptoPkg", - "DynamicTablesPkg", - "FatPkg", - "FmpDevicePkg", - "IntelFsp2Pkg", - "IntelFsp2WrapperPkg", - "MdeModulePkg", - "MdePkg", - "PcAtChipsetPkg", - "PrmPkg", - "SecurityPkg", - "ShellPkg", - "SourceLevelDebugPkg", - "StandaloneMmPkg", - "UefiCpuPkg", - "UnitTestFrameworkPkg"] - + include: + - Package: "ArmPkg" + ArchList: "IA32,X64" + - Package: "CryptoPkg" + ArchList: "IA32" + - Package: "CryptoPkg" + ArchList: "X64" + - Package: "DynamicTablesPkg" + ArchList: "IA32,X64" + - Package: "FatPkg" + ArchList: "IA32,X64" + - Package: "FmpDevicePkg" + ArchList: "IA32,X64" + - Package: "IntelFsp2Pkg" + ArchList: "IA32,X64" + - Package: "IntelFsp2WrapperPkg" + ArchList: "IA32,X64" + - Package: "MdeModulePkg" + ArchList: "IA32" + - Package: "MdeModulePkg" + ArchList: "X64" + - Package: "MdePkg" + ArchList: "IA32,X64" + - Package: "PcAtChipsetPkg" + ArchList: "IA32,X64" + - Package: "PrmPkg" + ArchList: "IA32,X64" + - Package: "SecurityPkg" + ArchList: "IA32,X64" + - Package: "ShellPkg" + ArchList: "IA32,X64" + - Package: "SourceLevelDebugPkg" + ArchList: "IA32,X64" + - Package: "StandaloneMmPkg" + ArchList: "IA32,X64" + - Package: "UefiCpuPkg" + ArchList: "IA32,X64" + - Package: "UnitTestFrameworkPkg" + ArchList: "IA32,X64" steps: - name: Checkout repository uses: actions/checkout@v3 @@ -83,16 +103,16 @@ jobs: run: pip install -r pip-requirements.txt --upgrade - name: Setup - run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + run: stuart_setup -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019 - name: Update - run: stuart_update -c .pytool/CISettings.py -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + run: stuart_update -c .pytool/CISettings.py -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019 - name: Build Tools From Source run: python BaseTools/Edk2ToolsBuild.py -t VS2019 - name: CI Build - run: stuart_ci_build -c .pytool/CISettings.py -p ${{ matrix.package }} -t DEBUG -a IA32,X64 TOOL_CHAIN_TAG=VS2019 + run: stuart_ci_build -c .pytool/CISettings.py -p ${{ matrix.Package }} -t DEBUG -a ${{ matrix.ArchList }} TOOL_CHAIN_TAG=VS2019 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 From f613810e01fbfe35cad014035c4d15d2a1e7c2b1 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 3 Apr 2023 10:01:25 -0700 Subject: [PATCH 0815/1529] .azurepilelines/templates: Split CryptoPkg builds CryptoPkg has double the build time of all other packages. Split CryptoPkg up matching the style applied to MdeModulePkg. Cc: Sean Brogan Cc: Michael Kubacki Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Michael Kubacki --- .azurepipelines/templates/pr-gate-build-job.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 3999bb1668..689e2f0987 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -49,9 +49,12 @@ jobs: TARGET_FMP_FAT_TEST: Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestFrameworkPkg,DynamicTablesPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' - TARGET_CRYPTO: + TARGET_CRYPTO_DEBUG: Build.Pkgs: 'CryptoPkg' - Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' + Build.Targets: 'DEBUG,NOOPT' + TARGET_CRYPTO_RELEASE: + Build.Pkgs: 'CryptoPkg' + Build.Targets: 'RELEASE,NO-TARGET' TARGET_FSP: Build.Pkgs: 'IntelFsp2Pkg,IntelFsp2WrapperPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' From 94c11eed88115698a7c347ad11fc4f1fa4a82d93 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Fri, 31 Mar 2023 00:09:27 -0700 Subject: [PATCH 0816/1529] IntelFsp2Pkg: TempRamInit API should preserve EBX/RBX register. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4395 FSP specification defines the TempRamInit API preserved register list which including EBX/RBX, however current implementation unexpectedly overriding EBX/RBX register that should be fixed. Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- .../FspSecCore/Ia32/SaveRestoreSseNasm.inc | 7 +++++++ .../Include/SaveRestoreSseAvxNasm.inc | 21 ++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc b/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc index a222f2e376..016f943b43 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc +++ b/IntelFsp2Pkg/FspSecCore/Ia32/SaveRestoreSseNasm.inc @@ -157,6 +157,9 @@ NextAddress: ; Use CpuId instruction (CPUID.01H:EDX.SSE[bit 25] = 1) to test ; whether the processor supports SSE instruction. ; + ; Save EBX to MM2 + ; + movd mm2, ebx mov eax, 1 cpuid bt edx, 25 @@ -169,6 +172,10 @@ NextAddress: bt ecx, 19 jnc SseError %endif + ; + ; Restore EBX from MM2 + ; + movd ebx, mm2 ; ; Set OSFXSR bit (bit #9) & OSXMMEXCPT bit (bit #10) diff --git a/IntelFsp2Pkg/Include/SaveRestoreSseAvxNasm.inc b/IntelFsp2Pkg/Include/SaveRestoreSseAvxNasm.inc index 38c807a311..002a5a1412 100644 --- a/IntelFsp2Pkg/Include/SaveRestoreSseAvxNasm.inc +++ b/IntelFsp2Pkg/Include/SaveRestoreSseAvxNasm.inc @@ -255,6 +255,10 @@ NextAddress: ; Use CpuId instruction (CPUID.01H:EDX.SSE[bit 25] = 1) to test ; whether the processor supports SSE instruction. ; + ; Save RBX to R11 + ; Save RCX to R10 + ; + mov r11, rbx mov r10, rcx mov rax, 1 cpuid @@ -266,7 +270,12 @@ NextAddress: ; bt ecx, 19 jnc SseError - mov rcx, r10 + ; + ; Restore RBX from R11 + ; Restore RCX from R10 + ; + mov rbx, r11 + mov rcx, r10 ; ; Set OSFXSR bit (bit #9) & OSXMMEXCPT bit (bit #10) @@ -284,6 +293,11 @@ NextAddress: %endmacro %macro ENABLE_AVX 0 + ; + ; Save RBX to R11 + ; Save RCX to R10 + ; + mov r11, rbx mov r10, rcx mov eax, 1 cpuid @@ -307,6 +321,11 @@ EnableAvx: xgetbv ; result in edx:eax or eax, 00000006h ; Set XCR0 bit #1 and bit #2 to enable SSE state and AVX state xsetbv + ; + ; Restore RBX from R11 + ; Restore RCX from R10 + ; + mov rbx, r11 mov rcx, r10 %endmacro From 108acb46483ff25ea477288f8691ddc3f61e3229 Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Thu, 23 Mar 2023 15:39:17 -0700 Subject: [PATCH 0817/1529] IntelFsp2Pkg: LoadMicrocodeDefault() causing unnecessary delay. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4391 FSP should support the scenario that CPU microcode already loaded before calling LoadMicrocodeDefault(), in this case it should return directly without spending more time. Also the LoadMicrocodeDefault() should only attempt to load one version of the microcode for current CPU and return directly without parsing rest of the microcode in FV. This patch also removed unnecessary LoadCheck code after supporting CPU microcode already loaded scenario. Cc: Nate DeSimone Cc: Star Zeng Cc: Ray Ni Signed-off-by: Chasel Chiu Reviewed-by: Ted Kuo Reviewed-by: Nate DeSimone Reviewed-by: Ray Ni --- .../FspSecCore/Ia32/FspApiEntryT.nasm | 46 ++++++++++--------- IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm | 45 +++++++++--------- 2 files changed, 48 insertions(+), 43 deletions(-) diff --git a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm index 2cff8b3643..900126b93b 100644 --- a/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/Ia32/FspApiEntryT.nasm @@ -245,6 +245,22 @@ ASM_PFX(LoadMicrocodeDefault): cmp esp, 0 jz ParamError + ; + ; If microcode already loaded before this function, exit this function with SUCCESS. + ; + mov ecx, MSR_IA32_BIOS_SIGN_ID + xor eax, eax ; Clear EAX + xor edx, edx ; Clear EDX + wrmsr ; Load 0 to MSR at 8Bh + + mov eax, 1 + cpuid + mov ecx, MSR_IA32_BIOS_SIGN_ID + rdmsr ; Get current microcode signature + xor eax, eax + test edx, edx + jnz Exit2 + ; skip loading Microcode if the MicrocodeCodeSize is zero ; and report error if size is less than 2k ; first check UPD header revision @@ -330,7 +346,7 @@ CheckMainHeader: cmp ebx, dword [esi + MicrocodeHdr.MicrocodeHdrProcessor] jne LoadMicrocodeDefault1 test edx, dword [esi + MicrocodeHdr.MicrocodeHdrFlags ] - jnz LoadCheck ; Jif signature and platform ID match + jnz LoadMicrocode ; Jif signature and platform ID match LoadMicrocodeDefault1: ; Check if extended header exists @@ -363,7 +379,7 @@ CheckExtSig: cmp dword [edi + ExtSig.ExtSigProcessor], ebx jne LoadMicrocodeDefault2 test dword [edi + ExtSig.ExtSigFlags], edx - jnz LoadCheck ; Jif signature and platform ID match + jnz LoadMicrocode ; Jif signature and platform ID match LoadMicrocodeDefault2: ; Check if any more extended signatures exist add edi, ExtSig.size @@ -435,23 +451,7 @@ LoadMicrocodeDefault4: ; Is valid Microcode start point ? cmp dword [esi + MicrocodeHdr.MicrocodeHdrVersion], 0ffffffffh jz Done - -LoadCheck: - ; Get the revision of the current microcode update loaded - mov ecx, MSR_IA32_BIOS_SIGN_ID - xor eax, eax ; Clear EAX - xor edx, edx ; Clear EDX - wrmsr ; Load 0 to MSR at 8Bh - - mov eax, 1 - cpuid - mov ecx, MSR_IA32_BIOS_SIGN_ID - rdmsr ; Get current microcode signature - - ; Verify this microcode update is not already loaded - cmp dword [esi + MicrocodeHdr.MicrocodeHdrRevision], edx - je Continue - + jmp CheckMainHeader LoadMicrocode: ; EAX contains the linear address of the start of the Update Data ; EDX contains zero @@ -465,10 +465,12 @@ LoadMicrocode: mov eax, 1 cpuid -Continue: - jmp NextMicrocode - Done: + mov ecx, MSR_IA32_BIOS_SIGN_ID + xor eax, eax ; Clear EAX + xor edx, edx ; Clear EDX + wrmsr ; Load 0 to MSR at 8Bh + mov eax, 1 cpuid mov ecx, MSR_IA32_BIOS_SIGN_ID diff --git a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm index b32fa32a89..698bb063a7 100644 --- a/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm +++ b/IntelFsp2Pkg/FspSecCore/X64/FspApiEntryT.nasm @@ -141,6 +141,22 @@ ASM_PFX(LoadMicrocodeDefault): jz ParamError mov rsp, rcx + ; + ; If microcode already loaded before this function, exit this function with SUCCESS. + ; + mov ecx, MSR_IA32_BIOS_SIGN_ID + xor eax, eax ; Clear EAX + xor edx, edx ; Clear EDX + wrmsr ; Load 0 to MSR at 8Bh + + mov eax, 1 + cpuid + mov ecx, MSR_IA32_BIOS_SIGN_ID + rdmsr ; Get current microcode signature + xor rax, rax + test edx, edx + jnz Exit2 + ; skip loading Microcode if the MicrocodeCodeSize is zero ; and report error if size is less than 2k ; first check UPD header revision @@ -198,7 +214,7 @@ CheckMainHeader: cmp ebx, dword [esi + MicrocodeHdr.MicrocodeHdrProcessor] jne LoadMicrocodeDefault1 test edx, dword [esi + MicrocodeHdr.MicrocodeHdrFlags ] - jnz LoadCheck ; Jif signature and platform ID match + jnz LoadMicrocode ; Jif signature and platform ID match LoadMicrocodeDefault1: ; Check if extended header exists @@ -231,7 +247,7 @@ CheckExtSig: cmp dword [edi + ExtSig.ExtSigProcessor], ebx jne LoadMicrocodeDefault2 test dword [edi + ExtSig.ExtSigFlags], edx - jnz LoadCheck ; Jif signature and platform ID match + jnz LoadMicrocode ; Jif signature and platform ID match LoadMicrocodeDefault2: ; Check if any more extended signatures exist add edi, ExtSig.size @@ -276,22 +292,7 @@ LoadMicrocodeDefault4: ; Is valid Microcode start point ? cmp dword [esi + MicrocodeHdr.MicrocodeHdrVersion], 0ffffffffh jz Done - -LoadCheck: - ; Get the revision of the current microcode update loaded - mov ecx, MSR_IA32_BIOS_SIGN_ID - xor eax, eax ; Clear EAX - xor edx, edx ; Clear EDX - wrmsr ; Load 0 to MSR at 8Bh - - mov eax, 1 - cpuid - mov ecx, MSR_IA32_BIOS_SIGN_ID - rdmsr ; Get current microcode signature - - ; Verify this microcode update is not already loaded - cmp dword [esi + MicrocodeHdr.MicrocodeHdrRevision], edx - je Continue + jmp CheckMainHeader LoadMicrocode: ; EAX contains the linear address of the start of the Update Data @@ -306,10 +307,12 @@ LoadMicrocode: mov eax, 1 cpuid -Continue: - jmp NextMicrocode - Done: + mov ecx, MSR_IA32_BIOS_SIGN_ID + xor eax, eax ; Clear EAX + xor edx, edx ; Clear EDX + wrmsr ; Load 0 to MSR at 8Bh + mov eax, 1 cpuid mov ecx, MSR_IA32_BIOS_SIGN_ID From 1534d4ab9c9883f7d2a027330a0742fb367e8f58 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Mon, 3 Apr 2023 17:41:03 -0600 Subject: [PATCH 0818/1529] pip-requirements.txt: bump edk2-basetools to 0.1.43 Bump the version of edk2-basetools in pip-requirements.txt to 0.1.43. This version contains the update to generate makefiles with both CFLAGS and BUILD_CFLAGS. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 3c3bf921dd..b71e5c4015 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -14,7 +14,7 @@ edk2-pytool-library==0.14.0 edk2-pytool-extensions~=0.21.8 -edk2-basetools==0.1.39 +edk2-basetools==0.1.43 antlr4-python3-runtime==4.7.1 lcov-cobertura==2.0.2 From b9b94861eabaafdfd6595eabd1f5959adaee9904 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 16 Feb 2023 08:40:46 -0700 Subject: [PATCH 0819/1529] BaseTools: Allow users to specify compiler to use with make CC= CXX= In https://bugzilla.tianocore.org/show_bug.cgi?id=2842 clang support was added by having users specify "make CXX=llvm" when building BaseTools. The Makefile then sees that and sets CC=$(CLANG_BIN)clang and CXX=$(CLANG_BIN)clang++. That requires that the executables 'clang' and 'clang++' exist and for example aren't named 'clang-17' and 'clang++-17'. Also, it's an unusual way of specifying the compiler, since many users will expect to be able to override CC and CXX on the make command line. Rework the BaseTools Makefiles removing the 'BUILD_' prefix (BUILD_CC and BUILD_CXX) and using the standard name 'LDFLAGS' instead of 'LFLAGS'. This allows clang to be used by running 'make -C BaseTools CC=clang CXX=clang++'. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/DevicePath/GNUmakefile | 4 +- BaseTools/Source/C/LzmaCompress/GNUmakefile | 2 +- BaseTools/Source/C/Makefiles/app.makefile | 2 +- BaseTools/Source/C/Makefiles/footer.makefile | 6 +-- BaseTools/Source/C/Makefiles/header.makefile | 50 +++++++++---------- BaseTools/Source/C/VfrCompile/GNUmakefile | 14 +++--- .../Source/C/VfrCompile/Pccts/antlr/makefile | 16 +++--- .../Source/C/VfrCompile/Pccts/dlg/makefile | 22 ++++---- .../Source/Python/Workspace/DscBuildData.py | 2 +- 9 files changed, 59 insertions(+), 59 deletions(-) diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile index 13b54ead65..3afc7fc050 100644 --- a/BaseTools/Source/C/DevicePath/GNUmakefile +++ b/BaseTools/Source/C/DevicePath/GNUmakefile @@ -13,12 +13,12 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o DevicePathUtili include $(MAKEROOT)/Makefiles/app.makefile -GCCVERSION = $(shell $(BUILD_CC) -dumpversion | awk -F'.' '{print $$1}') +GCCVERSION = $(shell $(CC) -dumpversion | awk -F'.' '{print $$1}') ifneq ("$(GCCVERSION)", "5") ifneq ($(CXX), llvm) ifneq ($(DARWIN),Darwin) # gcc 12 trips over device path handling -BUILD_CFLAGS += -Wno-error=stringop-overflow +CFLAGS += -Wno-error=stringop-overflow endif endif endif diff --git a/BaseTools/Source/C/LzmaCompress/GNUmakefile b/BaseTools/Source/C/LzmaCompress/GNUmakefile index c837e77823..a00ef4bc80 100644 --- a/BaseTools/Source/C/LzmaCompress/GNUmakefile +++ b/BaseTools/Source/C/LzmaCompress/GNUmakefile @@ -24,4 +24,4 @@ OBJECTS = \ include $(MAKEROOT)/Makefiles/app.makefile -BUILD_CFLAGS += -D_7ZIP_ST +CFLAGS += -D_7ZIP_ST diff --git a/BaseTools/Source/C/Makefiles/app.makefile b/BaseTools/Source/C/Makefiles/app.makefile index 6a2a8f5e8a..506343a6e0 100644 --- a/BaseTools/Source/C/Makefiles/app.makefile +++ b/BaseTools/Source/C/Makefiles/app.makefile @@ -15,7 +15,7 @@ APPLICATION = $(MAKEROOT)/bin/$(APPNAME) all: $(MAKEROOT)/bin $(APPLICATION) $(APPLICATION): $(OBJECTS) - $(LINKER) -o $(APPLICATION) $(BUILD_LFLAGS) $(OBJECTS) -L$(MAKEROOT)/libs $(LIBS) + $(LINKER) -o $(APPLICATION) $(LDFLAGS) $(OBJECTS) -L$(MAKEROOT)/libs $(LIBS) $(OBJECTS): $(MAKEROOT)/Include/Common/BuildVersion.h diff --git a/BaseTools/Source/C/Makefiles/footer.makefile b/BaseTools/Source/C/Makefiles/footer.makefile index 85c3374224..7546da8cf5 100644 --- a/BaseTools/Source/C/Makefiles/footer.makefile +++ b/BaseTools/Source/C/Makefiles/footer.makefile @@ -15,13 +15,13 @@ install: $(MAKEROOT)/libs-$(HOST_ARCH) $(LIBRARY) cp $(LIBRARY) $(MAKEROOT)/libs-$(HOST_ARCH) $(LIBRARY): $(OBJECTS) - $(BUILD_AR) crs $@ $^ + $(AR) crs $@ $^ %.o : %.c - $(BUILD_CC) -c $(BUILD_CPPFLAGS) $(BUILD_CFLAGS) $< -o $@ + $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ %.o : %.cpp - $(BUILD_CXX) -c $(BUILD_CPPFLAGS) $(BUILD_CXXFLAGS) $< -o $@ + $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ .PHONY: clean clean: diff --git a/BaseTools/Source/C/Makefiles/header.makefile b/BaseTools/Source/C/Makefiles/header.makefile index 4e88a4fbd8..0fb315a25a 100644 --- a/BaseTools/Source/C/Makefiles/header.makefile +++ b/BaseTools/Source/C/Makefiles/header.makefile @@ -45,19 +45,19 @@ CYGWIN:=$(findstring CYGWIN, $(shell uname -s)) LINUX:=$(findstring Linux, $(shell uname -s)) DARWIN:=$(findstring Darwin, $(shell uname -s)) ifeq ($(CXX), llvm) -BUILD_CC ?= $(CLANG_BIN)clang -BUILD_CXX ?= $(CLANG_BIN)clang++ -BUILD_AS ?= $(CLANG_BIN)clang -BUILD_AR ?= $(CLANG_BIN)llvm-ar -BUILD_LD ?= $(CLANG_BIN)llvm-ld +CC ?= $(CLANG_BIN)clang +CXX ?= $(CLANG_BIN)clang++ +AS ?= $(CLANG_BIN)clang +AR ?= $(CLANG_BIN)llvm-ar +LD ?= $(CLANG_BIN)llvm-ld else -BUILD_CC ?= gcc -BUILD_CXX ?= g++ -BUILD_AS ?= gcc -BUILD_AR ?= ar -BUILD_LD ?= ld +CC ?= gcc +CXX ?= g++ +AS ?= gcc +AR ?= ar +LD ?= ld endif -LINKER ?= $(BUILD_CC) +LINKER ?= $(CC) ifeq ($(HOST_ARCH), IA32) ARCH_INCLUDE = -I $(MAKEROOT)/Include/Ia32/ @@ -81,34 +81,34 @@ $(error Bad HOST_ARCH) endif INCLUDE = $(TOOL_INCLUDE) -I $(MAKEROOT) -I $(MAKEROOT)/Include/Common -I $(MAKEROOT)/Include/ -I $(MAKEROOT)/Include/IndustryStandard -I $(MAKEROOT)/Common/ -I .. -I . $(ARCH_INCLUDE) -BUILD_CPPFLAGS = $(INCLUDE) +CPPFLAGS = $(INCLUDE) # keep EXTRA_OPTFLAGS last BUILD_OPTFLAGS = -O2 $(EXTRA_OPTFLAGS) ifeq ($(DARWIN),Darwin) # assume clang or clang compatible flags on OS X -BUILD_CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -Wall -Werror \ +CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -Wall -Werror \ -Wno-deprecated-declarations -Wno-self-assign -Wno-unused-result -nostdlib -g else ifeq ($(CXX), llvm) -BUILD_CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ +CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ -fno-delete-null-pointer-checks -Wall -Werror \ -Wno-deprecated-declarations -Wno-self-assign \ -Wno-unused-result -nostdlib -g else -BUILD_CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ +CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ -fno-delete-null-pointer-checks -Wall -Werror \ -Wno-deprecated-declarations -Wno-stringop-truncation -Wno-restrict \ -Wno-unused-result -nostdlib -g endif endif ifeq ($(CXX), llvm) -BUILD_LFLAGS = -BUILD_CXXFLAGS = -Wno-deprecated-register -Wno-unused-result +LDFLAGS = +CXXFLAGS = -Wno-deprecated-register -Wno-unused-result else -BUILD_LFLAGS = -BUILD_CXXFLAGS = -Wno-unused-result +LDFLAGS = +CXXFLAGS = -Wno-unused-result endif ifeq ($(HOST_ARCH), IA32) # @@ -117,18 +117,18 @@ ifeq ($(HOST_ARCH), IA32) # so only do this is uname -m returns i386. # ifeq ($(DARWIN),Darwin) - BUILD_CFLAGS += -arch i386 - BUILD_CPPFLAGS += -arch i386 - BUILD_LFLAGS += -arch i386 + CFLAGS += -arch i386 + CPPFLAGS += -arch i386 + LDFLAGS += -arch i386 endif endif # keep BUILD_OPTFLAGS last -BUILD_CFLAGS += $(BUILD_OPTFLAGS) -BUILD_CXXFLAGS += $(BUILD_OPTFLAGS) +CFLAGS += $(BUILD_OPTFLAGS) +CXXFLAGS += $(BUILD_OPTFLAGS) # keep EXTRA_LDFLAGS last -BUILD_LFLAGS += $(EXTRA_LDFLAGS) +LDFLAGS += $(EXTRA_LDFLAGS) .PHONY: all .PHONY: install diff --git a/BaseTools/Source/C/VfrCompile/GNUmakefile b/BaseTools/Source/C/VfrCompile/GNUmakefile index fc329944b9..e227b10791 100644 --- a/BaseTools/Source/C/VfrCompile/GNUmakefile +++ b/BaseTools/Source/C/VfrCompile/GNUmakefile @@ -17,9 +17,9 @@ TOOL_INCLUDE = -I Pccts/h OBJECTS = AParser.o DLexerBase.o ATokenBuffer.o EfiVfrParser.o VfrLexer.o VfrSyntax.o \ VfrFormPkg.o VfrError.o VfrUtilityLib.o VfrCompiler.o ifeq ($(CXX), llvm) -VFR_CPPFLAGS = -Wno-deprecated-register -DPCCTS_USE_NAMESPACE_STD $(BUILD_CPPFLAGS) +VFR_CPPFLAGS = -Wno-deprecated-register -std=c++14 -DPCCTS_USE_NAMESPACE_STD $(CPPFLAGS) else -VFR_CPPFLAGS = -DPCCTS_USE_NAMESPACE_STD $(BUILD_CPPFLAGS) +VFR_CPPFLAGS = -DPCCTS_USE_NAMESPACE_STD $(CPPFLAGS) endif # keep BUILD_OPTFLAGS last VFR_CXXFLAGS = $(BUILD_OPTFLAGS) @@ -27,7 +27,7 @@ VFR_CXXFLAGS = $(BUILD_OPTFLAGS) # keep EXTRA_LDFLAGS last VFR_LFLAGS = $(EXTRA_LDFLAGS) -LINKER = $(BUILD_CXX) +LINKER = $(CXX) EXTRA_CLEAN_OBJECTS = EfiVfrParser.cpp EfiVfrParser.h VfrParser.dlg VfrTokens.h VfrLexer.cpp VfrLexer.h VfrSyntax.cpp tokens.h @@ -60,16 +60,16 @@ Pccts/dlg/dlg: BIN_DIR='.' $(MAKE) -C Pccts/dlg ATokenBuffer.o: Pccts/h/ATokenBuffer.cpp - $(BUILD_CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ + $(CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ DLexerBase.o: Pccts/h/DLexerBase.cpp - $(BUILD_CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ + $(CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ AParser.o: Pccts/h/AParser.cpp - $(BUILD_CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ + $(CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ VfrSyntax.o: VfrSyntax.cpp - $(BUILD_CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ + $(CXX) -c $(VFR_CPPFLAGS) $(INC) $(VFR_CXXFLAGS) $? -o $@ clean: localClean diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile index 559b1c99f1..3bd9b6b1df 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile @@ -157,7 +157,7 @@ PCCTS_H=../h # $(DLG) -C2 parser.dlg scan.c # #set.$(OBJ_EXT): $(SET)/set.c -# $(BUILD_CC) $(BUILD_CFLAGS) -c $(OUT_OBJ)set.$(OBJ_EXT) $(SET)/set.c +# $(CC) $(CFLAGS) -c $(OUT_OBJ)set.$(OBJ_EXT) $(SET)/set.c @@ -165,17 +165,17 @@ PCCTS_H=../h # UNIX (default) # ifeq ($(CXX), llvm) -BUILD_CC?=$(CLANG_BIN)clang +CC?=$(CLANG_BIN)clang else -BUILD_CC?=gcc +CC?=gcc endif COPT=-O ANTLR=${BIN_DIR}/antlr DLG=${BIN_DIR}/dlg OBJ_EXT=o OUT_OBJ = -o -BUILD_CFLAGS= $(COPT) -I. -I$(SET) -I$(PCCTS_H) -DUSER_ZZSYN $(COTHER) -DZZLEXBUFSIZE=65536 -BUILD_CPPFLAGS= +CFLAGS= $(COPT) -I. -I$(SET) -I$(PCCTS_H) -DUSER_ZZSYN $(COTHER) -DZZLEXBUFSIZE=65536 +CPPFLAGS= # # SGI Users, use this CFLAGS # @@ -184,7 +184,7 @@ OBJ=antlr.o scan.o err.o bits.o build.o fset2.o fset.o gen.o \ globals.o hash.o lex.o main.o misc.o set.o pred.o egman.o mrhoist.o fcache.o $(BIN_DIR)/antlr : $(OBJ) $(SRC) - $(BUILD_CC) $(BUILD_CFLAGS) -o $(BIN_DIR)/antlr $(OBJ) + $(CC) $(CFLAGS) -o $(BIN_DIR)/antlr $(OBJ) # what files does PCCTS generate (both ANTLR and DLG) PCCTS_GEN=antlr.c scan.c err.c tokens.h mode.h parser.dlg stdpccts.h remap.h @@ -207,10 +207,10 @@ scan.o : scan.c mode.h tokens.h # $(DLG) -C2 parser.dlg scan.c set.o : $(SET)/set.c - $(BUILD_CC) $(BUILD_CFLAGS) -c -o set.o $(SET)/set.c + $(CC) $(CFLAGS) -c -o set.o $(SET)/set.c %.o : %.c - $(BUILD_CC) -c $(BUILD_CFLAGS) $(BUILD_CPPFLAGS) $< -o $@ + $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ # # ****** These next targets are common to UNIX and PC world ******** diff --git a/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile b/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile index 5a3561edec..61366185c1 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile +++ b/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile @@ -35,7 +35,7 @@ PCCTS_H=../h # #$(LIBS: = +^ #) -#$(DEF_FILE) $(LFLAGS) ; +#$(DEF_FILE) $(LDFLAGS) ; #<< # bind $@ c:\os2\doscalls.lib # copy *.exe ..\bin @@ -59,7 +59,7 @@ PCCTS_H=../h #$@ /Tde /c # #$(LIBS) -#$(DEF_FILE) $(LFLAGS) ; +#$(DEF_FILE) $(LDFLAGS) ; #| # copy *.exe ..\bin # @@ -83,7 +83,7 @@ PCCTS_H=../h # #$(LIBS: = +^ #) -#$(DEF_FILE) $(LFLAGS) ; +#$(DEF_FILE) $(LDFLAGS) ; #<< # copy *.exe ..\bin # @@ -122,15 +122,15 @@ endif COPT=-O ANTLR=${BIN_DIR}/antlr DLG=${BIN_DIR}/dlg -BUILD_CFLAGS= $(COPT) -I. -I$(SET) -I$(PCCTS_H) -DUSER_ZZSYN -DZZLEXBUFSIZE=65536 -BUILD_CPPFLAGS= +CFLAGS= $(COPT) -I. -I$(SET) -I$(PCCTS_H) -DUSER_ZZSYN -DZZLEXBUFSIZE=65536 +CPPFLAGS= OBJ_EXT=o OUT_OBJ = -o OBJ = dlg_p.o dlg_a.o main.o err.o set.o support.o output.o \ relabel.o automata.o $(BIN_DIR)/dlg : $(OBJ) $(SRC) - $(BUILD_CC) $(BUILD_CFLAGS) -o $(BIN_DIR)/dlg $(OBJ) + $(CC) $(CFLAGS) -o $(BIN_DIR)/dlg $(OBJ) SRC = dlg_p.c dlg_a.c main.c err.c $(SET)/set.c support.c output.c \ relabel.c automata.c @@ -142,19 +142,19 @@ SRC = dlg_p.c dlg_a.c main.c err.c $(SET)/set.c support.c output.c \ # $(DLG) -C2 parser.dlg dlg_a.c dlg_p.$(OBJ_EXT) : dlg_p.c dlg.h tokens.h mode.h - $(BUILD_CC) $(BUILD_CFLAGS) -c dlg_p.c + $(CC) $(CFLAGS) -c dlg_p.c dlg_a.$(OBJ_EXT) : dlg_a.c dlg.h tokens.h mode.h - $(BUILD_CC) $(BUILD_CFLAGS) -c dlg_a.c + $(CC) $(CFLAGS) -c dlg_a.c main.$(OBJ_EXT) : main.c dlg.h - $(BUILD_CC) $(BUILD_CFLAGS) -c main.c + $(CC) $(CFLAGS) -c main.c set.$(OBJ_EXT) : $(SET)/set.c - $(BUILD_CC) -c $(BUILD_CFLAGS) $(SET)/set.c + $(CC) -c $(CFLAGS) $(SET)/set.c %.o : %.c - $(BUILD_CC) -c $(BUILD_CFLAGS) $(BUILD_CPPFLAGS) $< -o $@ + $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ lint: lint *.c diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/Source/Python/Workspace/DscBuildData.py index 73c6ee4006..8fd949dc50 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -89,7 +89,7 @@ def _IsFieldValueAnArray (Value): ''' WindowsCFLAGS = 'CFLAGS = $(CFLAGS) /wd4200 /wd4034 /wd4101 ' -LinuxCFLAGS = 'BUILD_CFLAGS += -Wno-pointer-to-int-cast -Wno-unused-variable ' +LinuxCFLAGS = 'CFLAGS += -Wno-pointer-to-int-cast -Wno-unused-variable ' PcdMakefileEnd = ''' !INCLUDE $(BASE_TOOLS_PATH)\Source\C\Makefiles\ms.common !INCLUDE $(BASE_TOOLS_PATH)\Source\C\Makefiles\ms.app From 9339318ad3128dd00f6f3a5ec873dabdf3e5c18b Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 16 Feb 2023 09:34:32 -0700 Subject: [PATCH 0820/1529] BaseTools: Allow users to build with clang using CC=clang CXX=clang++ In https://bugzilla.tianocore.org/show_bug.cgi?id=2842 clang support was added by having users specify "make CXX=llvm" when building BaseTools. The Makefile then sees that and sets CC=$(CLANG_BIN)clang and CXX=$(CLANG_BIN)clang++. That requires that the executables 'clang' and 'clang++' exist and for example aren't named 'clang-17' and 'clang++-17'. Also, it's an unusual way of specifying the compiler, since many users will expect to be able to override CC and CXX on the make command line. Rework the BaseTools Makefiles removing the 'BUILD_' prefix (BUILD_CC and BUILD_CXX) and using the standard name 'LDFLAGS' instead of 'LFLAGS'. This allows clang to be used by running 'make -C BaseTools CC=clang CXX=clang++'. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/DevicePath/GNUmakefile | 3 ++- BaseTools/Source/C/Makefiles/header.makefile | 19 ++++++++++--------- BaseTools/Source/C/VfrCompile/GNUmakefile | 3 ++- .../Source/C/VfrCompile/Pccts/antlr/makefile | 6 +++--- .../Source/C/VfrCompile/Pccts/dlg/makefile | 9 +++++---- 5 files changed, 22 insertions(+), 18 deletions(-) diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile index 3afc7fc050..f61b1b2f17 100644 --- a/BaseTools/Source/C/DevicePath/GNUmakefile +++ b/BaseTools/Source/C/DevicePath/GNUmakefile @@ -14,8 +14,9 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o DevicePathUtili include $(MAKEROOT)/Makefiles/app.makefile GCCVERSION = $(shell $(CC) -dumpversion | awk -F'.' '{print $$1}') +CLANG := $(shell $(CC) --version | grep clang) ifneq ("$(GCCVERSION)", "5") -ifneq ($(CXX), llvm) +ifeq ($(CLANG),) ifneq ($(DARWIN),Darwin) # gcc 12 trips over device path handling CFLAGS += -Wno-error=stringop-overflow diff --git a/BaseTools/Source/C/Makefiles/header.makefile b/BaseTools/Source/C/Makefiles/header.makefile index 0fb315a25a..bcc2791998 100644 --- a/BaseTools/Source/C/Makefiles/header.makefile +++ b/BaseTools/Source/C/Makefiles/header.makefile @@ -44,18 +44,19 @@ endif CYGWIN:=$(findstring CYGWIN, $(shell uname -s)) LINUX:=$(findstring Linux, $(shell uname -s)) DARWIN:=$(findstring Darwin, $(shell uname -s)) -ifeq ($(CXX), llvm) +CLANG:=$(shell $(CC) --version | grep clang) +ifneq ($(CLANG),) CC ?= $(CLANG_BIN)clang CXX ?= $(CLANG_BIN)clang++ AS ?= $(CLANG_BIN)clang AR ?= $(CLANG_BIN)llvm-ar LD ?= $(CLANG_BIN)llvm-ld -else -CC ?= gcc -CXX ?= g++ -AS ?= gcc -AR ?= ar -LD ?= ld +else ifeq ($(origin CC),default) +CC = gcc +CXX = g++ +AS = gcc +AR = ar +LD = ld endif LINKER ?= $(CC) ifeq ($(HOST_ARCH), IA32) @@ -91,7 +92,7 @@ ifeq ($(DARWIN),Darwin) CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -Wall -Werror \ -Wno-deprecated-declarations -Wno-self-assign -Wno-unused-result -nostdlib -g else -ifeq ($(CXX), llvm) +ifneq ($(CLANG),) CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ -fno-delete-null-pointer-checks -Wall -Werror \ -Wno-deprecated-declarations -Wno-self-assign \ @@ -103,7 +104,7 @@ CFLAGS = -MD -fshort-wchar -fno-strict-aliasing -fwrapv \ -Wno-unused-result -nostdlib -g endif endif -ifeq ($(CXX), llvm) +ifneq ($(CLANG),) LDFLAGS = CXXFLAGS = -Wno-deprecated-register -Wno-unused-result else diff --git a/BaseTools/Source/C/VfrCompile/GNUmakefile b/BaseTools/Source/C/VfrCompile/GNUmakefile index e227b10791..7d5976649d 100644 --- a/BaseTools/Source/C/VfrCompile/GNUmakefile +++ b/BaseTools/Source/C/VfrCompile/GNUmakefile @@ -16,7 +16,8 @@ TOOL_INCLUDE = -I Pccts/h #OBJECTS = VfrSyntax.o VfrServices.o DLGLexer.o EfiVfrParser.o ATokenBuffer.o DLexerBase.o AParser.o OBJECTS = AParser.o DLexerBase.o ATokenBuffer.o EfiVfrParser.o VfrLexer.o VfrSyntax.o \ VfrFormPkg.o VfrError.o VfrUtilityLib.o VfrCompiler.o -ifeq ($(CXX), llvm) +CLANG:=$(shell $(CC) --version | grep clang) +ifneq ($(CLANG),) VFR_CPPFLAGS = -Wno-deprecated-register -std=c++14 -DPCCTS_USE_NAMESPACE_STD $(CPPFLAGS) else VFR_CPPFLAGS = -DPCCTS_USE_NAMESPACE_STD $(CPPFLAGS) diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile index 3bd9b6b1df..42b603571f 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile @@ -164,10 +164,10 @@ PCCTS_H=../h # # UNIX (default) # -ifeq ($(CXX), llvm) +ifneq ($(CLANG),) CC?=$(CLANG_BIN)clang -else -CC?=gcc +else ifeq ($(origin CC),default) +CC=gcc endif COPT=-O ANTLR=${BIN_DIR}/antlr diff --git a/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile b/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile index 61366185c1..e45ac98e04 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile +++ b/BaseTools/Source/C/VfrCompile/Pccts/dlg/makefile @@ -114,10 +114,11 @@ PCCTS_H=../h # # UNIX # -ifeq ($(CXX), llvm) -BUILD_CC?=$(CLANG_BIN)clang -else -BUILD_CC?=cc +CLANG:=$(shell $(CC) --version | grep clang) +ifneq ($(CLANG),) +CC?=$(CLANG_BIN)clang +else ifeq ($(origin CC),default) +CC=gcc endif COPT=-O ANTLR=${BIN_DIR}/antlr From 4f2108db61880c6a4f458ac50ab9c21bae48d145 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 16 Feb 2023 09:38:29 -0700 Subject: [PATCH 0821/1529] BaseTools: Build against C++14 when building with clang clang 17 defaults to C++17, where the 'register' keyword is deprecated and the warning changed to an error. To avoid build errors, compile against C++14 by specifying '-std=c++14' in CXXFLAGS. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/Makefiles/header.makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/C/Makefiles/header.makefile b/BaseTools/Source/C/Makefiles/header.makefile index bcc2791998..1bf003523b 100644 --- a/BaseTools/Source/C/Makefiles/header.makefile +++ b/BaseTools/Source/C/Makefiles/header.makefile @@ -106,7 +106,7 @@ endif endif ifneq ($(CLANG),) LDFLAGS = -CXXFLAGS = -Wno-deprecated-register -Wno-unused-result +CXXFLAGS = -Wno-deprecated-register -Wno-unused-result -std=c++14 else LDFLAGS = CXXFLAGS = -Wno-unused-result From c27d99fbc85b2cee114ae125fa83ae5d3216a703 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Wed, 5 Apr 2023 12:09:09 -0600 Subject: [PATCH 0822/1529] BaseTools/Conf/tools_def: Fix linking using CLANGDWARF_IA32 The clang toolchain might default to fPIE/fPIC, which prevents lld from linking the objects into a binary. Specify -fno-pie -fno-pic as done on GCC to fix linking. Test: Building the Universal Payload using the command 'python UefiPayloadPkg/UniversalPayloadBuild.py -a IA32' actually works. Signed-off-by: Patrick Rudolph Reviewed-by: Rebecca Cran Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=4356 --- BaseTools/Conf/tools_def.template | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index ae43101853..39c49b8001 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2889,7 +2889,7 @@ DEFINE CLANGDWARF_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x22 *_CLANGDWARF_IA32_RC_PATH = DEF(CLANGDWARF_IA32_PREFIX)llvm-rc *_CLANGDWARF_IA32_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -m32 -fno-lto DEF(CLANG38_IA32_TARGET) -*_CLANGDWARF_IA32_ASLDLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_ASLDLINK_FLAGS) -Wl,-m,elf_i386 -fuse-ld=lld +*_CLANGDWARF_IA32_ASLDLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_ASLDLINK_FLAGS) -Wl,-m,elf_i386 -fuse-ld=lld -no-pie *_CLANGDWARF_IA32_ASM_FLAGS = DEF(GCC5_ASM_FLAGS) -m32 -march=i386 DEF(CLANG38_IA32_TARGET) *_CLANGDWARF_IA32_RC_FLAGS = DEF(GCC_IA32_RC_FLAGS) *_CLANGDWARF_IA32_OBJCOPY_FLAGS = @@ -2898,17 +2898,17 @@ DEFINE CLANGDWARF_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x22 *_CLANGDWARF_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG38_IA32_TARGET) *_CLANGDWARF_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG38_IA32_TARGET) -DEBUG_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double +DEBUG_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -fno-pic -fno-pie -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double DEBUG_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -flto -Wl,-O3 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 -DEBUG_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld +DEBUG_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld -no-pie -RELEASE_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -malign-double +RELEASE_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -fno-pic -fno-pie -m32 -Oz -flto -march=i586 DEF(CLANG38_IA32_TARGET) -malign-double RELEASE_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -flto -Wl,-O3 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 -RELEASE_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld +RELEASE_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O3 -fuse-ld=lld -no-pie -NOOPT_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double +NOOPT_CLANGDWARF_IA32_CC_FLAGS = DEF(CLANG38_ALL_CC_FLAGS) -fno-pic -fno-pie -m32 -O0 -march=i586 DEF(CLANG38_IA32_TARGET) -g -malign-double NOOPT_CLANGDWARF_IA32_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_FLAGS) -Wl,-O0 -Wl,-melf_i386 -Wl,--oformat,elf32-i386 -NOOPT_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O0 -fuse-ld=lld +NOOPT_CLANGDWARF_IA32_DLINK2_FLAGS = DEF(CLANGDWARF_IA32_DLINK2_FLAGS) -O0 -fuse-ld=lld -no-pie ########################## # CLANGDWARF X64 definitions From 8c3193a8fa017e2e420c4fd9f66caadecfd19dde Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Wed, 5 Apr 2023 10:01:26 -0700 Subject: [PATCH 0823/1529] BaseTools: Update antlr makefile to use cc by default Update the antlr makefile to remove the explicit setting of CC to either clang or gcc. This causes it to use /usr/bin/cc or whatever the user has set $(CC) to. This removes the last dependency on gcc for BaseTools. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao --- BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile | 5 ----- 1 file changed, 5 deletions(-) diff --git a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile index 42b603571f..746d58b5e2 100644 --- a/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile +++ b/BaseTools/Source/C/VfrCompile/Pccts/antlr/makefile @@ -164,11 +164,6 @@ PCCTS_H=../h # # UNIX (default) # -ifneq ($(CLANG),) -CC?=$(CLANG_BIN)clang -else ifeq ($(origin CC),default) -CC=gcc -endif COPT=-O ANTLR=${BIN_DIR}/antlr DLG=${BIN_DIR}/dlg From c1c9a2a4e40ca849190caee6b10a812c31551476 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:15 +0800 Subject: [PATCH 0824/1529] BaseTools/tools_def CLANGDWARF: Permit text relocations We rely on PIE executables to get the codegen that is suitable for PE/COFF conversion where the resulting executables can be loaded anywhere in the address space. However, ELF linkers may default to disallowing text relocations in PIE executables, as this would require text segments to be updated at runtime, which is bad for security and increases the copy-on-write footprint of ELF executables and shared libraries. However, none of those concerns apply to PE/COFF executables in the context of EFI, which are copied into memory rather than mmap()'ed, and fixed up by the loader before launch. So pass -z notext to the LLD linker to permit runtime relocations in read-only sections. Signed-off-by: Ard Biesheuvel Reviewed-by: Rebecca Cran --- BaseTools/Conf/tools_def.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 39c49b8001..9a5c11f6a3 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -2870,7 +2870,7 @@ DEFINE CLANGDWARF_X64_PREFIX = ENV(CLANG_BIN) DEFINE CLANGDWARF_IA32_X64_DLINK_COMMON = -nostdlib -Wl,-q,--gc-sections -z max-page-size=0x40 DEFINE CLANGDWARF_DLINK2_FLAGS_COMMON = -Wl,--script=$(EDK_TOOLS_PATH)/Scripts/ClangBase.lds DEFINE CLANGDWARF_IA32_X64_ASLDLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_COMMON) -Wl,--defsym=PECOFF_HEADER_SIZE=0 DEF(CLANGDWARF_DLINK2_FLAGS_COMMON) -Wl,--entry,ReferenceAcpiTable -u ReferenceAcpiTable -DEFINE CLANGDWARF_IA32_X64_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_COMMON) -Wl,--entry,$(IMAGE_ENTRY_POINT) -u $(IMAGE_ENTRY_POINT) -Wl,-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map,--whole-archive +DEFINE CLANGDWARF_IA32_X64_DLINK_FLAGS = DEF(CLANGDWARF_IA32_X64_DLINK_COMMON) -Wl,--entry,$(IMAGE_ENTRY_POINT) -u $(IMAGE_ENTRY_POINT) -Wl,-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map,--whole-archive -Wl,-z,notext DEFINE CLANGDWARF_IA32_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x220 DEF(CLANGDWARF_DLINK2_FLAGS_COMMON) DEFINE CLANGDWARF_X64_DLINK2_FLAGS = -Wl,--defsym=PECOFF_HEADER_SIZE=0x228 DEF(CLANGDWARF_DLINK2_FLAGS_COMMON) From 923e3863b587b71405f3389ab78a309fbb059d9b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:16 +0800 Subject: [PATCH 0825/1529] UefiCpuPkg/CpuExceptionHandlerLib: Use single SEC/PEI version Currently, we use the non-Xcode5 version of ExceptionHandlerAsm.nasm only for the SEC and PEI phases, and this version was not compatible with the XCODE or LLD linkers, which do not permit absolute relocations in read-only sections. Given that SEC and PEI code typically executes in place from flash and does not use page alignment for sections, we can simply emit the code carrying the absolute symbol references into the .data segment instead. This works around the linker's objections, and the resulting image will be mapped executable in its entirety anyway. Since this is only needed for XCODE, let's make this change conditionally using a preprocessor macro. Let's rename the .nasm file to reflect the fact that is used for the SecPei flavor of this library only, and while at it, remove some unnecessary absolute references. Also update the Xcode specific version of this library, and use this source file instead. This is necesessary, as the Xcode specific version modifies its own code at runtime, which is not permitted in SEC or PEI. Note that this also removes CET support from the Xcode5 specific build of the SEC/PEI version of this library, but this is not needed this early in any case, and this aligns it with other toolchains, which use this version of the library, which does not have CET support either. 1. Change for non-XCODE SecPeiCpuExceptionHandlerLib: . Use SecPeiExceptionHandlerAsm.nasm (renamed from ExceptionHandlerAsm.nasm) . Removed some unnecessary absolute references (32 IDT stubs are still in .text.) 2. Change for XCODE SecPeiCpuExceptionHandlerLib: . Use SecPeiExceptionHandlerAsm.nasm instead of Xcode5ExceptionHandlerAsm.nasm . CET logic is not in SecPeiExceptionHandlerAsm.nasm (but aligns to non-XCODE lib instance) . Fixed a bug that does runtime fixup in TEXT section in SPI flash. . Emitted the code carrying the absolute symbol references into the .data which XCODE or LLD linkers allow. . Then fixup can be done by other build tools such as GenFv if the code runs in SPI flash, or by PE coff loader if the code is loaded to memory. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../SecPeiCpuExceptionHandlerLib.inf | 4 +++- ...andlerAsm.nasm => SecPeiExceptionHandlerAsm.nasm} | 12 ++++++++---- .../Xcode5SecPeiCpuExceptionHandlerLib.inf | 4 +++- 3 files changed, 14 insertions(+), 6 deletions(-) rename UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/{ExceptionHandlerAsm.nasm => SecPeiExceptionHandlerAsm.nasm} (94%) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf index df44371fe0..e7b1144f69 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf @@ -28,7 +28,7 @@ Ia32/ArchInterruptDefs.h [Sources.X64] - X64/ExceptionHandlerAsm.nasm + X64/SecPeiExceptionHandlerAsm.nasm X64/ArchExceptionHandler.c X64/ArchInterruptDefs.h @@ -58,3 +58,5 @@ [FeaturePcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard ## CONSUMES +[BuildOptions] + XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/SecPeiExceptionHandlerAsm.nasm similarity index 94% rename from UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm rename to UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/SecPeiExceptionHandlerAsm.nasm index aaf8d622e6..5c7a59c99d 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/SecPeiExceptionHandlerAsm.nasm @@ -27,7 +27,9 @@ extern ASM_PFX(CommonExceptionHandler) SECTION .data DEFAULT REL +%ifndef NO_ABSOLUTE_RELOCS_IN_TEXT SECTION .text +%endif ALIGN 8 @@ -51,6 +53,9 @@ HookAfterStubHeaderBegin: push rax mov rax, HookAfterStubHeaderEnd jmp rax + +SECTION .text + HookAfterStubHeaderEnd: mov rax, rsp and sp, 0xfff0 ; make sure 16-byte aligned for exception context @@ -276,8 +281,7 @@ DrFinish: ; and make sure RSP is 16-byte aligned ; sub rsp, 4 * 8 + 8 - mov rax, ASM_PFX(CommonExceptionHandler) - call rax + call ASM_PFX(CommonExceptionHandler) add rsp, 4 * 8 + 8 cli @@ -384,10 +388,10 @@ DoIret: ; comments here for definition of address map global ASM_PFX(AsmGetTemplateAddressMap) ASM_PFX(AsmGetTemplateAddressMap): - mov rax, AsmIdtVectorBegin + lea rax, [AsmIdtVectorBegin] mov qword [rcx], rax mov qword [rcx + 0x8], (AsmIdtVectorEnd - AsmIdtVectorBegin) / 32 - mov rax, HookAfterStubHeaderBegin + lea rax, [HookAfterStubHeaderBegin] mov qword [rcx + 0x10], rax ret diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf index 619b39d7f1..accc081a95 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf @@ -33,7 +33,7 @@ Ia32/ArchInterruptDefs.h [Sources.X64] - X64/Xcode5ExceptionHandlerAsm.nasm + X64/SecPeiExceptionHandlerAsm.nasm X64/ArchExceptionHandler.c X64/ArchInterruptDefs.h @@ -63,3 +63,5 @@ [FeaturePcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard ## CONSUMES +[BuildOptions] + XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT From cf43a061ef432af98bb0bc4ddbab12691a32b06b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:17 +0800 Subject: [PATCH 0826/1529] UefiCpuPkg/PeiCpuExceptionHandlerLib: Use SEC/PEI specific asm component The PEI flavor of CpuExceptionHandlerLib never populates more than 32 IDT vectors, and there is no CET shadow stack support in the PEI phase. So there is no need to use the generic ExceptionHandler NASM source, which carries a 256-entry template and CET support, and writes to its own .text section when built using XCODE, which is not permitted in the PEI phase. So let's switch to the reduced SEC/PEI version of this component, which is sufficient for PEI and doesn't suffer from the same issue. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf index 5339f8e604..3bcaff5c5f 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf @@ -28,7 +28,7 @@ Ia32/ArchInterruptDefs.h [Sources.X64] - X64/Xcode5ExceptionHandlerAsm.nasm + X64/SecPeiExceptionHandlerAsm.nasm X64/ArchExceptionHandler.c X64/ArchInterruptDefs.h @@ -62,3 +62,5 @@ [FeaturePcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard ## CONSUMES +[BuildOptions] + XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT From af0fb0e4bb8315ca88ffded270718ca31ede71ec Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:18 +0800 Subject: [PATCH 0827/1529] UefiCpuPkg/CpuExceptionHandlerLib: Make runtime fixups XCODE-only The CPU exception handler library code was rewritten at some point to populate the vector code templates with absolute references at runtime, given that the XCODE linker does not permit absolute references in executable code when creating PIE executables. This is rather unfortunate, as this prevents us from using strict permissions on the memory mappings, given that the .text section needs to be writable at runtime for this arrangement to work. So let's make this hack XCODE-only, by setting a preprocessor #define from the command line when using the XCODE toolchain, and only including the runtime fixup code when the macro is defined. While at it, rename the Xcode5ExceptionHandlerAsm.nasm source file and drop the Xcode5 prefix: this code is used by other toolchains too. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../DxeCpuExceptionHandlerLib.inf | 5 ++++- .../SmmCpuExceptionHandlerLib.inf | 4 +++- ...ceptionHandlerAsm.nasm => ExceptionHandlerAsm.nasm} | 10 ++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) rename UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/{Xcode5ExceptionHandlerAsm.nasm => ExceptionHandlerAsm.nasm} (95%) diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf index d0f82095cf..fdbebadab9 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf @@ -28,7 +28,7 @@ Ia32/ArchInterruptDefs.h [Sources.X64] - X64/Xcode5ExceptionHandlerAsm.nasm + X64/ExceptionHandlerAsm.nasm X64/ArchExceptionHandler.c X64/ArchInterruptDefs.h @@ -61,3 +61,6 @@ MemoryAllocationLib DebugLib CcExitLib + +[BuildOptions] + XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf index 8f8a5dab79..27f0b96fa9 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf @@ -28,7 +28,7 @@ Ia32/ArchInterruptDefs.h [Sources.X64] - X64/Xcode5ExceptionHandlerAsm.nasm + X64/ExceptionHandlerAsm.nasm X64/ArchExceptionHandler.c X64/ArchInterruptDefs.h @@ -61,3 +61,5 @@ [FeaturePcd] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard ## CONSUMES +[BuildOptions] + XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/Xcode5ExceptionHandlerAsm.nasm b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm similarity index 95% rename from UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/Xcode5ExceptionHandlerAsm.nasm rename to UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm index 9574785742..3d64ac9080 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/Xcode5ExceptionHandlerAsm.nasm +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ExceptionHandlerAsm.nasm @@ -59,7 +59,11 @@ AsmIdtVectorBegin: %rep 256 push strict dword %[Vector] ; This instruction pushes sign-extended 8-byte value on stack push rax +%ifdef NO_ABSOLUTE_RELOCS_IN_TEXT mov rax, strict qword 0 ; mov rax, ASM_PFX(CommonInterruptEntry) +%else + mov rax, ASM_PFX(CommonInterruptEntry) +%endif jmp rax %assign Vector Vector+1 %endrep @@ -69,8 +73,12 @@ HookAfterStubHeaderBegin: push strict dword 0 ; 0 will be fixed VectorNum: push rax +%ifdef NO_ABSOLUTE_RELOCS_IN_TEXT mov rax, strict qword 0 ; mov rax, HookAfterStubHeaderEnd JmpAbsoluteAddress: +%else + mov rax, HookAfterStubHeaderEnd +%endif jmp rax HookAfterStubHeaderEnd: mov rax, rsp @@ -457,6 +465,7 @@ ASM_PFX(AsmGetTemplateAddressMap): lea rax, [HookAfterStubHeaderBegin] mov qword [rcx + 0x10], rax +%ifdef NO_ABSOLUTE_RELOCS_IN_TEXT ; Fix up CommonInterruptEntry address lea rax, [ASM_PFX(CommonInterruptEntry)] lea rcx, [AsmIdtVectorBegin] @@ -468,6 +477,7 @@ ASM_PFX(AsmGetTemplateAddressMap): lea rax, [HookAfterStubHeaderEnd] lea rcx, [JmpAbsoluteAddress] mov qword [rcx - 8], rax +%endif ret From 0b09822aed6bd36a805e0370c4df3d22826aff59 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:19 +0800 Subject: [PATCH 0828/1529] OvmfPkg: Drop special Xcode5 version of exception handler library The generic and XCODE5 versions of this library are now identical, so drop the special case. The library will be removed entirely in a subsequent patch. Signed-off-by: Ard Biesheuvel Acked-by: Jiewen Yao --- OvmfPkg/AmdSev/AmdSevX64.dsc | 4 ---- OvmfPkg/CloudHv/CloudHvX64.dsc | 4 ---- OvmfPkg/IntelTdx/IntelTdxX64.dsc | 4 ---- OvmfPkg/Microvm/MicrovmX64.dsc | 4 ---- OvmfPkg/OvmfPkgIa32.dsc | 4 ---- OvmfPkg/OvmfPkgIa32X64.dsc | 4 ---- OvmfPkg/OvmfPkgX64.dsc | 4 ---- OvmfPkg/OvmfXen.dsc | 4 ---- 8 files changed, 32 deletions(-) diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc index c005e474dd..943c4eed98 100644 --- a/OvmfPkg/AmdSev/AmdSevX64.dsc +++ b/OvmfPkg/AmdSev/AmdSevX64.dsc @@ -224,11 +224,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc index b9820cc14b..cc2dd925bc 100644 --- a/OvmfPkg/CloudHv/CloudHvX64.dsc +++ b/OvmfPkg/CloudHv/CloudHvX64.dsc @@ -270,11 +270,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc index 5c56858d06..f734409055 100644 --- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc +++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc @@ -238,11 +238,7 @@ ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf PrePiHobListPointerLib|OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc index 384b0b7afc..e9aab51559 100644 --- a/OvmfPkg/Microvm/MicrovmX64.dsc +++ b/OvmfPkg/Microvm/MicrovmX64.dsc @@ -272,11 +272,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index a6db902f54..86177bb948 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -275,11 +275,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 076fc0353d..065b544506 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -280,11 +280,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index b2f3d14cd9..3d405cd4ad 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -297,11 +297,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" || $(TOOL_CHAIN_TAG) == "CLANGDWARF" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif CcExitLib|OvmfPkg/Library/CcExitLib/SecCcExitLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf CcProbeLib|OvmfPkg/Library/CcProbeLib/SecPeiCcProbeLib.inf diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc index 990225d2dd..8bfc16c2d3 100644 --- a/OvmfPkg/OvmfXen.dsc +++ b/OvmfPkg/OvmfXen.dsc @@ -247,11 +247,7 @@ PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf [LibraryClasses.common.PEI_CORE] From ad8be56e172aa166d482780ccc3fa2be8881b389 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 3 Apr 2023 22:29:20 +0800 Subject: [PATCH 0829/1529] UefiCpuPkg/CpuExceptionHandlerLib: Drop special XCODE5 version This library is no longer used or needed, so let's remove it. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../Xcode5SecPeiCpuExceptionHandlerLib.inf | 67 ------------------- .../Xcode5SecPeiCpuExceptionHandlerLib.uni | 18 ----- UefiCpuPkg/UefiCpuPkg.dsc | 7 -- 3 files changed, 92 deletions(-) delete mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf delete mode 100644 UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.uni diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf deleted file mode 100644 index accc081a95..0000000000 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf +++ /dev/null @@ -1,67 +0,0 @@ -## @file -# CPU Exception Handler library instance for SEC/PEI modules. -# -# Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
-# Copyright (c) 2012 - 2022, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -# This is the XCODE5 variant of the SEC/PEI CpuExceptionHandlerLib. This -# variant performs binary patching to fix up addresses that allow the -# XCODE5 toolchain to be used. -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = Xcode5SecPeiCpuExceptionHandlerLib - MODULE_UNI_FILE = Xcode5SecPeiCpuExceptionHandlerLib.uni - FILE_GUID = 49C481AF-1621-42F3-8FA1-27C64143E304 - MODULE_TYPE = PEIM - VERSION_STRING = 1.1 - LIBRARY_CLASS = CpuExceptionHandlerLib|SEC PEI_CORE PEIM - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources.Ia32] - Ia32/ExceptionHandlerAsm.nasm - Ia32/ExceptionTssEntryAsm.nasm - Ia32/ArchExceptionHandler.c - Ia32/ArchInterruptDefs.h - -[Sources.X64] - X64/SecPeiExceptionHandlerAsm.nasm - X64/ArchExceptionHandler.c - X64/ArchInterruptDefs.h - -[Sources.common] - CpuExceptionCommon.h - CpuExceptionCommon.c - SecPeiCpuException.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UefiCpuPkg/UefiCpuPkg.dec - -[LibraryClasses] - BaseLib - SerialPortLib - PrintLib - LocalApicLib - PeCoffGetEntryPointLib - CcExitLib - -[Pcd] - gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard - gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList - gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize - -[FeaturePcd] - gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard ## CONSUMES - -[BuildOptions] - XCODE:*_*_X64_NASM_FLAGS = -D NO_ABSOLUTE_RELOCS_IN_TEXT diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.uni b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.uni deleted file mode 100644 index a63b25f39d..0000000000 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.uni +++ /dev/null @@ -1,18 +0,0 @@ -// /** @file -// XCODE5 CPU Exception Handler library instance for SEC/PEI modules. -// -// CPU Exception Handler library instance for SEC/PEI modules when built -// using the XCODE5 toolchain. -// -// Copyright (C) 2020, Advanced Micro Devices, Inc. All rights reserved.
-// Copyright (c) 2012 - 2014, Intel Corporation. All rights reserved.
-// -// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "CPU Exception Handler library instance for SEC/PEI modules with the XCODE5 toolchain." - -#string STR_MODULE_DESCRIPTION #language en-US "CPU Exception Handler library instance for SEC/PEI modules with the XCODE5 toolchain." - diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index a7318d3fe9..d85d56916f 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -69,11 +69,7 @@ [LibraryClasses.common.SEC] PlatformSecLib|UefiCpuPkg/Library/PlatformSecLibNull/PlatformSecLibNull.inf -!if $(TOOL_CHAIN_TAG) == "XCODE5" - CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf -!else CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf @@ -145,12 +141,9 @@ UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf -!if $(TOOL_CHAIN_TAG) != "XCODE5" UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf -!endif UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf - UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf UefiCpuPkg/Library/MpInitLibUp/MpInitLibUp.inf From 41ae8074c7c34fd7d8967d5245776b6c87d85823 Mon Sep 17 00:00:00 2001 From: KasimX Liu Date: Thu, 16 Mar 2023 14:25:52 +0800 Subject: [PATCH 0830/1529] UefiPayloadPkg:Add new build commands for UniversalPayload REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4375 add '-pb' command of build bios with exist PreUniversalPayload file. '-e' command of olny build the UniversalPayloadentry file. Cc: Guo Dong Cc: Ray Ni Reviewed-by: James Lu Reviewed-by: Gua Guo Signed-off-by: KasimX Liu --- UefiPayloadPkg/UniversalPayloadBuild.py | 78 +++++++++++++------------ 1 file changed, 42 insertions(+), 36 deletions(-) diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 7cd04fdceb..db7ce0500b 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -102,6 +102,8 @@ def BuildUniversalPayload(Args, MacroList): ObjCopyFlag = "elf32-i386" EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("IA32/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll")) + if Args.PreBuildUplBinary is not None: + EntryOutputDir = os.path.abspath(Args.PreBuildUplBinary) EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc") DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) @@ -132,18 +134,19 @@ def BuildUniversalPayload(Args, MacroList): # # Building DXE core and DXE drivers as DXEFV. # - BuildPayload = "build -p {} -b {} -a X64 -t {} -y {} {}".format (DscPath, BuildTarget, ToolChain, PayloadReportPath, Quiet) - BuildPayload += Pcds - BuildPayload += Defines - RunCommand(BuildPayload) + if Args.BuildEntryOnly == False: + BuildPayload = "build -p {} -b {} -a X64 -t {} -y {} {}".format (DscPath, BuildTarget, ToolChain, PayloadReportPath, Quiet) + BuildPayload += Pcds + BuildPayload += Defines + RunCommand(BuildPayload) # # Building Universal Payload entry. # - BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, ElfToolChain, ModuleReportPath, Quiet) - BuildModule += Pcds - BuildModule += Defines - RunCommand(BuildModule) - + if Args.PreBuildUplBinary is None: + BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, ElfToolChain, ModuleReportPath, Quiet) + BuildModule += Pcds + BuildModule += Defines + RunCommand(BuildModule) # # Buid Universal Payload Information Section ".upld_info" # @@ -157,33 +160,34 @@ def BuildUniversalPayload(Args, MacroList): fp.write(bytearray(upld_info_hdr)) fp.close() - # - # Copy the DXEFV as a section in elf format Universal Payload entry. - # - remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv --remove-section .upld.bds_fv {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} --add-section .upld.bds_fv={} {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - UpldInfoFile, - DxeFvOutputDir, - BdsFvOutputDir, - EntryOutputDir - ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - RunCommand(remove_section) - RunCommand(add_section) - RunCommand(set_section) + if Args.BuildEntryOnly == False: + # + # Copy the DXEFV as a section in elf format Universal Payload entry. + # + remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv --remove-section .upld.bds_fv {}'.format ( + LlvmObjcopyPath, + ObjCopyFlag, + ObjCopyFlag, + EntryOutputDir + ) + add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} --add-section .upld.bds_fv={} {}'.format ( + LlvmObjcopyPath, + ObjCopyFlag, + ObjCopyFlag, + UpldInfoFile, + DxeFvOutputDir, + BdsFvOutputDir, + EntryOutputDir + ) + set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( + LlvmObjcopyPath, + ObjCopyFlag, + ObjCopyFlag, + EntryOutputDir + ) + RunCommand(remove_section) + RunCommand(add_section) + RunCommand(set_section) shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf')) @@ -199,6 +203,8 @@ def main(): parser.add_argument("-s", "--SpecRevision", type=GenSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build') parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).') + parser.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file') + parser.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file') MacroList = {} args = parser.parse_args() if args.Macro is not None: From 9c037ca964cdcf073b8eb2aac563b9c2feca213f Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sun, 26 Mar 2023 10:38:01 +0200 Subject: [PATCH 0831/1529] BaseTools/GenFw: Parse IBT/BTI support status from ELF note REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4405 When performing ELF to PE/COFF conversion, parse any notes sections to decide whether the image supports forward CFI landing pads. This will be used to set the associated DllCharacteristicsEx flag in a subsequent patch. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny Acked-by: Michael Kubacki Reviewed-by: Liming Gao --- BaseTools/Source/C/GenFw/Elf64Convert.c | 50 +++++++++++++++++++++++++ BaseTools/Source/C/GenFw/elf_common.h | 9 +++++ 2 files changed, 59 insertions(+) diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index 8b50774beb..2a810e835d 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -770,6 +770,49 @@ WriteSectionRiscV64 ( } } +STATIC UINT16 mDllCharacteristicsEx; + +STATIC +VOID +ParseNoteSection ( + CONST Elf_Shdr *Shdr + ) +{ + CONST Elf_Note *Note; + CONST UINT32 *Prop; + UINT32 Prop0; + UINT32 Prop2; + + Note = (Elf_Note *)((UINT8 *)mEhdr + Shdr->sh_offset); + + if ((Note->n_type == NT_GNU_PROPERTY_TYPE_0) && + (Note->n_namesz == sizeof ("GNU")) && + (strcmp ((CHAR8 *)(Note + 1), "GNU") == 0) && + (Note->n_descsz > sizeof (UINT32[2]))) { + Prop = (UINT32 *)((UINT8 *)(Note + 1) + sizeof("GNU")); + + switch (mEhdr->e_machine) { + case EM_AARCH64: + Prop0 = GNU_PROPERTY_AARCH64_FEATURE_1_AND; + Prop2 = GNU_PROPERTY_AARCH64_FEATURE_1_BTI; + break; + + case EM_X86_64: + Prop0 = GNU_PROPERTY_X86_FEATURE_1_AND; + Prop2 = GNU_PROPERTY_X86_FEATURE_1_IBT; + break; + + default: + return; + } + if ((Prop[0] == Prop0) && + (Prop[1] >= sizeof (UINT32)) && + ((Prop[2] & Prop2) != 0)) { + mDllCharacteristicsEx |= EFI_IMAGE_DLLCHARACTERISTICS_EX_FORWARD_CFI_COMPAT; + } + } +} + // // Elf functions interface implementation // @@ -826,6 +869,13 @@ ScanSections64 ( } } + for (i = 0; i < mEhdr->e_shnum; i++) { + Elf_Shdr *shdr = GetShdrByIndex(i); + if (shdr->sh_type == SHT_NOTE) { + ParseNoteSection (shdr); + } + } + // // Check if mCoffAlignment is larger than MAX_COFF_ALIGNMENT // diff --git a/BaseTools/Source/C/GenFw/elf_common.h b/BaseTools/Source/C/GenFw/elf_common.h index 7b7fdeb329..ccd32804b0 100644 --- a/BaseTools/Source/C/GenFw/elf_common.h +++ b/BaseTools/Source/C/GenFw/elf_common.h @@ -59,6 +59,15 @@ typedef struct { UINT32 n_type; /* Type of this note. */ } Elf_Note; +#define NT_GNU_PROPERTY_TYPE_0 5 + +#define GNU_PROPERTY_X86_FEATURE_1_AND 0xc0000002 +#define GNU_PROPERTY_X86_FEATURE_1_IBT 0x1 + +#define GNU_PROPERTY_AARCH64_FEATURE_1_AND 0xc0000000 +#define GNU_PROPERTY_AARCH64_FEATURE_1_BTI 0x1 +#define GNU_PROPERTY_AARCH64_FEATURE_1_PAC 0x2 + /* Indexes into the e_ident array. Keep synced with http://www.sco.com/developers/gabi/latest/ch4.eheader.html */ #define EI_MAG0 0 /* Magic number, byte 0. */ From a0d95b723ce9e246329e3fa251af9af2c6299d32 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Sat, 25 Mar 2023 15:50:54 +0100 Subject: [PATCH 0832/1529] BaseTools/GenFw: Add DllCharacteristicsEx field to debug data REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4405 The PE/COFF spec describes an additional DllCharacteristics field implemented as a debug directory entry, which carries flags related to which control flow integrity (CFI) features are supported by the binary. So let's add this entry when doing ELF to PE/COFF conversion - we will add support for setting the flags in a subsequent patch. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael Kubacki Reviewed-by: Liming Gao --- BaseTools/Source/C/GenFw/Elf64Convert.c | 54 ++++++++++++++----- BaseTools/Source/C/GenFw/GenFw.c | 3 +- .../C/Include/IndustryStandard/PeImage.h | 13 ++++- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index 2a810e835d..9c17c90b16 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -992,6 +992,16 @@ ScanSections64 ( sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + strlen(mInImageName) + 1; + // + // Add more space in the .debug data region for the DllCharacteristicsEx + // field. + // + if (mDllCharacteristicsEx != 0) { + mCoffOffset = DebugRvaAlign(mCoffOffset) + + sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) + + sizeof (EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY); + } + mCoffOffset = CoffAlign(mCoffOffset); if (SectionCount == 0) { mDataOffset = mCoffOffset; @@ -2244,29 +2254,47 @@ WriteDebug64 ( VOID ) { - UINT32 Len; - EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; - EFI_IMAGE_DATA_DIRECTORY *DataDir; - EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir; - EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10; + UINT32 Len; + EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; + EFI_IMAGE_DATA_DIRECTORY *DataDir; + EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir; + EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10; + EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY *DllEntry; Len = strlen(mInImageName) + 1; + NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset); + DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]; + DataDir->VirtualAddress = mDebugOffset; + DataDir->Size = sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); + Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset); + + if (mDllCharacteristicsEx != 0) { + DataDir->Size += sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); + + Dir->Type = EFI_IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS; + Dir->SizeOfData = sizeof (EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY); + Dir->FileOffset = mDebugOffset + DataDir->Size + + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + + DebugRvaAlign(Len); + Dir->RVA = Dir->FileOffset; + + DllEntry = (VOID *)(mCoffFile + Dir->FileOffset); + + DllEntry->DllCharacteristicsEx = mDllCharacteristicsEx; + + Dir++; + } + Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW; Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len; - Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); - Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); + Dir->RVA = mDebugOffset + DataDir->Size; + Dir->FileOffset = mDebugOffset + DataDir->Size; Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1); Nb10->Signature = CODEVIEW_SIGNATURE_NB10; strcpy ((char *)(Nb10 + 1), mInImageName); - - - NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset); - DataDir = &NtHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]; - DataDir->VirtualAddress = mDebugOffset; - DataDir->Size = sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); } STATIC diff --git a/BaseTools/Source/C/GenFw/GenFw.c b/BaseTools/Source/C/GenFw/GenFw.c index 6f61f16788..d0e52ccc26 100644 --- a/BaseTools/Source/C/GenFw/GenFw.c +++ b/BaseTools/Source/C/GenFw/GenFw.c @@ -2932,7 +2932,8 @@ Routine Description: if (mIsConvertXip) { DebugEntry->FileOffset = DebugEntry->RVA; } - if (ZeroDebugFlag || DebugEntry->Type != EFI_IMAGE_DEBUG_TYPE_CODEVIEW) { + if ((ZeroDebugFlag || DebugEntry->Type != EFI_IMAGE_DEBUG_TYPE_CODEVIEW) && + (DebugEntry->Type != EFI_IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS)) { memset (FileBuffer + DebugEntry->FileOffset, 0, DebugEntry->SizeOfData); memset (DebugEntry, 0, sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY)); } diff --git a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h index 77ded3f611..22161edf44 100644 --- a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h +++ b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h @@ -615,7 +615,8 @@ typedef struct { /// /// Debug Format /// -#define EFI_IMAGE_DEBUG_TYPE_CODEVIEW 2 +#define EFI_IMAGE_DEBUG_TYPE_CODEVIEW 2 +#define EFI_IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS 20 typedef struct { UINT32 Characteristics; @@ -664,6 +665,16 @@ typedef struct { // } EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY; +/// +/// Extended DLL Characteristics +/// +#define EFI_IMAGE_DLLCHARACTERISTICS_EX_CET_COMPAT 0x0001 +#define EFI_IMAGE_DLLCHARACTERISTICS_EX_FORWARD_CFI_COMPAT 0x0040 + +typedef struct { + UINT32 DllCharacteristicsEx; +} EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY; + // // .pdata entries for X64 // From a7c651b08a531876820a6b56febdc050452b5c8c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 13 Mar 2023 18:17:05 +0100 Subject: [PATCH 0833/1529] MdePkg/PeCoffLib: Capture DLL characteristics fields in image context REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4405 When loading a PE/COFF image, capture the DLL characteristics fields of the header into our image context structure so we can refer to them when mapping the image. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael Kubacki Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/PeImage.h | 13 ++++++- MdePkg/Include/Library/PeCoffLib.h | 6 +++ MdePkg/Library/BasePeCoffLib/BasePeCoff.c | 46 +++++++++++++++++------ 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/PeImage.h b/MdePkg/Include/IndustryStandard/PeImage.h index dd4cc25483..8646ff22b5 100644 --- a/MdePkg/Include/IndustryStandard/PeImage.h +++ b/MdePkg/Include/IndustryStandard/PeImage.h @@ -625,7 +625,8 @@ typedef struct { UINT32 FileOffset; ///< The file pointer to the debug data. } EFI_IMAGE_DEBUG_DIRECTORY_ENTRY; -#define EFI_IMAGE_DEBUG_TYPE_CODEVIEW 2 ///< The Visual C++ debug information. +#define EFI_IMAGE_DEBUG_TYPE_CODEVIEW 2 ///< The Visual C++ debug information. +#define EFI_IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS 20 /// /// Debug Data Structure defined in Microsoft C++. @@ -669,6 +670,16 @@ typedef struct { // } EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY; +/// +/// Extended DLL Characteristics +/// +#define EFI_IMAGE_DLLCHARACTERISTICS_EX_CET_COMPAT 0x0001 +#define EFI_IMAGE_DLLCHARACTERISTICS_EX_FORWARD_CFI_COMPAT 0x0040 + +typedef struct { + UINT32 DllCharacteristicsEx; +} EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY; + /// /// Resource format. /// diff --git a/MdePkg/Include/Library/PeCoffLib.h b/MdePkg/Include/Library/PeCoffLib.h index b458794537..74cceb37bf 100644 --- a/MdePkg/Include/Library/PeCoffLib.h +++ b/MdePkg/Include/Library/PeCoffLib.h @@ -171,6 +171,12 @@ typedef struct { /// UINT16 ImageType; /// + /// Set by PeCoffLoaderGetImageInfo() to the DLL flags stored in the PE/COFF header and + /// in the DllCharacteristicsEx debug table. + /// + UINT16 DllCharacteristics; + UINT32 DllCharacteristicsEx; + /// /// Set by PeCoffLoaderGetImageInfo() to TRUE if the PE/COFF image does not contain /// relocation information. /// diff --git a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c index 97a8aaf8c7..4b71176a0c 100644 --- a/MdePkg/Library/BasePeCoffLib/BasePeCoff.c +++ b/MdePkg/Library/BasePeCoffLib/BasePeCoff.c @@ -308,10 +308,11 @@ PeCoffLoaderGetPeHeader ( // // Use PE32 offset // - ImageContext->ImageType = Hdr.Pe32->OptionalHeader.Subsystem; - ImageContext->ImageSize = (UINT64)Hdr.Pe32->OptionalHeader.SizeOfImage; - ImageContext->SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; - ImageContext->SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders; + ImageContext->ImageType = Hdr.Pe32->OptionalHeader.Subsystem; + ImageContext->ImageSize = (UINT64)Hdr.Pe32->OptionalHeader.SizeOfImage; + ImageContext->SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; + ImageContext->SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders; + ImageContext->DllCharacteristics = Hdr.Pe32->OptionalHeader.DllCharacteristics; } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) { // // 1. Check FileHeader.NumberOfRvaAndSizes filed. @@ -429,10 +430,11 @@ PeCoffLoaderGetPeHeader ( // // Use PE32+ offset // - ImageContext->ImageType = Hdr.Pe32Plus->OptionalHeader.Subsystem; - ImageContext->ImageSize = (UINT64)Hdr.Pe32Plus->OptionalHeader.SizeOfImage; - ImageContext->SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; - ImageContext->SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders; + ImageContext->ImageType = Hdr.Pe32Plus->OptionalHeader.Subsystem; + ImageContext->ImageSize = (UINT64)Hdr.Pe32Plus->OptionalHeader.SizeOfImage; + ImageContext->SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; + ImageContext->SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders; + ImageContext->DllCharacteristics = Hdr.Pe32Plus->OptionalHeader.DllCharacteristics; } else { ImageContext->ImageError = IMAGE_ERROR_INVALID_MACHINE_TYPE; return RETURN_UNSUPPORTED; @@ -545,8 +547,9 @@ PeCoffLoaderGetPeHeader ( Retrieves information about a PE/COFF image. Computes the PeCoffHeaderOffset, IsTeImage, ImageType, ImageAddress, ImageSize, - DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, and - DebugDirectoryEntryRva fields of the ImageContext structure. + DestinationAddress, RelocationsStripped, SectionAlignment, SizeOfHeaders, + DllCharacteristics, DllCharacteristicsEx and DebugDirectoryEntryRva fields of + the ImageContext structure. If ImageContext is NULL, then return RETURN_INVALID_PARAMETER. If the PE/COFF image accessed through the ImageRead service in the ImageContext structure is not a supported PE/COFF image type, then return RETURN_UNSUPPORTED. @@ -752,7 +755,28 @@ PeCoffLoaderGetImageInfo ( ImageContext->ImageSize += DebugEntry.SizeOfData; } - return RETURN_SUCCESS; + continue; + } + + if (DebugEntry.Type == EFI_IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) { + Size = sizeof (EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY); + ReadSize = sizeof (EFI_IMAGE_DEBUG_EX_DLLCHARACTERISTICS_ENTRY); + Status = ImageContext->ImageRead ( + ImageContext->Handle, + DebugEntry.FileOffset, + &Size, + &ImageContext->DllCharacteristicsEx + ); + if (RETURN_ERROR (Status) || (Size != ReadSize)) { + ImageContext->ImageError = IMAGE_ERROR_IMAGE_READ; + if (Size != ReadSize) { + Status = RETURN_UNSUPPORTED; + } + + return Status; + } + + continue; } } } From 3c0571060af32eb484cb6110354d88d4eca7c54f Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 2 Feb 2023 19:03:34 +0100 Subject: [PATCH 0834/1529] MdeModulePkg: Enable forward edge CFI in mem attributes table REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4405 The memory attributes table has been extended with a flag that indicates whether or not the OS is permitted to map the EFI runtime code regions with strict enforcement for IBT/BTI landing pad instructions. Given that the PE/COFF spec now defines a DllCharacteristicsEx flag that indicates whether or not a loaded image is compatible with this, we can wire this up to the flag in the memory attributes table, and set it if all loaded runtime image are compatible with it. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael Kubacki Reviewed-by: Liming Gao --- MdeModulePkg/Core/Dxe/DxeMain.h | 2 ++ MdeModulePkg/Core/Dxe/Image/Image.c | 10 ++++++++++ MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 8 +++++++- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Core/Dxe/DxeMain.h b/MdeModulePkg/Core/Dxe/DxeMain.h index 815a6b4bd8..43daa037be 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain.h +++ b/MdeModulePkg/Core/Dxe/DxeMain.h @@ -280,6 +280,8 @@ extern EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] extern BOOLEAN gDispatcherRunning; extern EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate; +extern BOOLEAN gMemoryAttributesTableForwardCfi; + extern EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable; extern BOOLEAN gLoadFixedAddressCodeMemoryReady; // diff --git a/MdeModulePkg/Core/Dxe/Image/Image.c b/MdeModulePkg/Core/Dxe/Image/Image.c index 8704ebea9a..9dbfb2a1fa 100644 --- a/MdeModulePkg/Core/Dxe/Image/Image.c +++ b/MdeModulePkg/Core/Dxe/Image/Image.c @@ -1399,6 +1399,16 @@ CoreLoadImageCommon ( CoreNewDebugImageInfoEntry (EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, &Image->Info, Image->Handle); } + // + // Check whether we are loading a runtime image that lacks support for + // IBT/BTI landing pads. + // + if ((Image->ImageContext.ImageCodeMemoryType == EfiRuntimeServicesCode) && + ((Image->ImageContext.DllCharacteristicsEx & EFI_IMAGE_DLLCHARACTERISTICS_EX_FORWARD_CFI_COMPAT) == 0)) + { + gMemoryAttributesTableForwardCfi = FALSE; + } + // // Reinstall loaded image protocol to fire any notifications // diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c index 82fa026bce..fd127ee167 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c @@ -89,6 +89,7 @@ BOOLEAN mMemoryAttributesTableEnable = TRUE; BOOLEAN mMemoryAttributesTableEndOfDxe = FALSE; EFI_MEMORY_ATTRIBUTES_TABLE *mMemoryAttributesTable = NULL; BOOLEAN mMemoryAttributesTableReadyToBoot = FALSE; +BOOLEAN gMemoryAttributesTableForwardCfi = TRUE; /** Install MemoryAttributesTable. @@ -182,7 +183,12 @@ InstallMemoryAttributesTable ( MemoryAttributesTable->Version = EFI_MEMORY_ATTRIBUTES_TABLE_VERSION; MemoryAttributesTable->NumberOfEntries = RuntimeEntryCount; MemoryAttributesTable->DescriptorSize = (UINT32)DescriptorSize; - MemoryAttributesTable->Flags = 0; + if (gMemoryAttributesTableForwardCfi) { + MemoryAttributesTable->Flags = EFI_MEMORY_ATTRIBUTES_FLAGS_RT_FORWARD_CONTROL_FLOW_GUARD; + } else { + MemoryAttributesTable->Flags = 0; + } + DEBUG ((DEBUG_VERBOSE, "MemoryAttributesTable:\n")); DEBUG ((DEBUG_VERBOSE, " Version - 0x%08x\n", MemoryAttributesTable->Version)); DEBUG ((DEBUG_VERBOSE, " NumberOfEntries - 0x%08x\n", MemoryAttributesTable->NumberOfEntries)); From 69227584d986801c4084387e349b4ca7d32b31f4 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Wed, 21 Dec 2022 11:56:07 -0800 Subject: [PATCH 0835/1529] UnitTestFrameworkPkg: Add subhook submodule required for gmock REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Add subhook submodule that is required to hook internal functions when using gmock. https://github.com/Zeex/subhook Add SubhookLib library class and SubhookLib library instance. Include the SUBHOOK_STATIC define in the SubhookLib INF file so it builds as a static library. Also include the SUBHOOK_STATIC define in SubhookLib.h so all modules using SubhookLib properly link SubhookLib as a static library. Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Cc: Michael Kubacki Cc: Sean Brogan Signed-off-by: Chris Johnson Reviewed-by: Leif Lindholm Reviewed-by: Michael Kubacki Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- .gitmodules | 3 ++ ReadMe.rst | 1 + .../Include/Library/SubhookLib.h | 15 +++++++++ .../Library/SubhookLib/SubhookLib.inf | 31 +++++++++++++++++++ .../Library/SubhookLib/SubhookLib.uni | 11 +++++++ .../Library/SubhookLib/subhook | 1 + .../Test/UnitTestFrameworkPkgHostTest.dsc | 1 + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 2 ++ .../UnitTestFrameworkPkgHost.dsc.inc | 1 + 9 files changed, 66 insertions(+) create mode 100644 UnitTestFrameworkPkg/Include/Library/SubhookLib.h create mode 100644 UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf create mode 100644 UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.uni create mode 160000 UnitTestFrameworkPkg/Library/SubhookLib/subhook diff --git a/.gitmodules b/.gitmodules index 8011a88d9d..fe8a43be93 100644 --- a/.gitmodules +++ b/.gitmodules @@ -23,3 +23,6 @@ [submodule "UnitTestFrameworkPkg/Library/GoogleTestLib/googletest"] path = UnitTestFrameworkPkg/Library/GoogleTestLib/googletest url = https://github.com/google/googletest.git +[submodule "UnitTestFrameworkPkg/Library/SubhookLib/subhook"] + path = UnitTestFrameworkPkg/Library/SubhookLib/subhook + url = https://github.com/Zeex/subhook.git diff --git a/ReadMe.rst b/ReadMe.rst index 497d963559..91b9cf3c5e 100644 --- a/ReadMe.rst +++ b/ReadMe.rst @@ -94,6 +94,7 @@ that are covered by additional licenses. - `MdeModulePkg/Universal/RegularExpressionDxe/oniguruma `__ - `UnitTestFrameworkPkg/Library/CmockaLib/cmocka `__ - `UnitTestFrameworkPkg/Library/GoogleTestLib/googletest `__ +- `UnitTestFrameworkPkg/Library/SubhookLib/subhook `__ - `RedfishPkg/Library/JsonLib/jansson `__ The EDK II Project is composed of packages. The maintainers for each package diff --git a/UnitTestFrameworkPkg/Include/Library/SubhookLib.h b/UnitTestFrameworkPkg/Include/Library/SubhookLib.h new file mode 100644 index 0000000000..46783adfcc --- /dev/null +++ b/UnitTestFrameworkPkg/Include/Library/SubhookLib.h @@ -0,0 +1,15 @@ +/** @file + SubhookLib class with APIs from the subhook project + + Copyright (c) 2022, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef SUBHOOK_LIB_H_ +#define SUBHOOK_LIB_H_ + +#define SUBHOOK_STATIC +#include + +#endif diff --git a/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf b/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf new file mode 100644 index 0000000000..a67be890d8 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf @@ -0,0 +1,31 @@ +## @file +# This module provides Subhook Library implementation. +# +# Copyright (c) 2022, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010018 + BASE_NAME = SubhookLib + MODULE_UNI_FILE = SubhookLib.uni + FILE_GUID = 70E03378-E140-46A8-8E65-7719DA14A240 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 0.1 + LIBRARY_CLASS = SubhookLib + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + subhook/subhook.c + +[Packages] + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS == /c /EHsc /Zi /DSUBHOOK_STATIC /Od + GCC:*_*_IA32_CC_FLAGS == -g -c -O0 -m32 + GCC:*_*_X64_CC_FLAGS == -g -c -O0 -m64 diff --git a/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.uni b/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.uni new file mode 100644 index 0000000000..eb61f03404 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.uni @@ -0,0 +1,11 @@ +// /** @file +// This module provides Subhook Library implementation. +// +// Copyright (c) 2022, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Subhook Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides Subhook Library implementation." diff --git a/UnitTestFrameworkPkg/Library/SubhookLib/subhook b/UnitTestFrameworkPkg/Library/SubhookLib/subhook new file mode 160000 index 0000000000..83d4e1ebef --- /dev/null +++ b/UnitTestFrameworkPkg/Library/SubhookLib/subhook @@ -0,0 +1 @@ +Subproject commit 83d4e1ebef3588fae48b69a7352cc21801cb70bc diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 708ef7f9ab..722509c8f2 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -33,6 +33,7 @@ # UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf + UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 14e387d63a..30b489915d 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -20,6 +20,7 @@ Library/CmockaLib/cmocka/include Library/GoogleTestLib/googletest/googletest/include Library/GoogleTestLib/googletest/googlemock/include + Library/SubhookLib/subhook [Includes.Common.Private] PrivateInclude @@ -34,6 +35,7 @@ ## @libraryclass GoogleTest infrastructure # GoogleTestLib|Include/Library/GoogleTestLib.h + SubhookLib|Include/Library/SubhookLib.h [LibraryClasses.Common.Private] ## @libraryclass Provides a unit test result report diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 7f5dfa30ed..e77897bd32 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -15,6 +15,7 @@ CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLibNull/BaseCacheMaintenanceLibNull.inf CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf GoogleTestLib|UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf + SubhookLib|UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf From 8eedc6187fc349b92eb4ef813c8faa6c2221c410 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Thu, 23 Mar 2023 17:06:33 -0700 Subject: [PATCH 0836/1529] .pytool/CISettings.py: Add subhook submodule REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Add submodule for https://github.com/Zeex/subhook This submodule is required to hook internal functions when using gmock. Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Chris Johnson Reviewed-by: Leif Lindholm Reviewed-by: Michael Kubacki Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- .pytool/CISettings.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index d87c8e838e..e3f44add58 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -193,6 +193,8 @@ def GetRequiredSubmodules(self): "BaseTools/Source/C/BrotliCompress/brotli", False)) rs.append(RequiredSubmodule( "RedfishPkg/Library/JsonLib/jansson", False)) + rs.append(RequiredSubmodule( + "UnitTestFrameworkPkg/Library/SubhookLib/subhook", False)) return rs def GetName(self): From 8660ed91644b60bcb8a08523c89c0c48728120e6 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Fri, 24 Mar 2023 16:43:10 -0700 Subject: [PATCH 0837/1529] UnitTestFrameworkPkg: Add gmock support to GoogleTestLib REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 * Add gmock support to GoogleTestLib * Add FunctionMockLib library class and library instance * Add GoogleTest extension to GoogleTestLib.h for CHAR16 type * Add GoogleTest extension to GoogleTestLib.h for buffer types * HOST_APPLICATION only supports IA32/X64 Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Signed-off-by: Chris Johnson Reviewed-by: Michael Kubacki Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- .../Include/Library/FunctionMockLib.h | 131 ++++++++++++++++++ .../Include/Library/GoogleTestLib.h | 96 +++++++++++++ .../Library/CmockaLib/CmockaLib.inf | 2 +- .../Library/FunctionMockLib/FunctionMockLib.c | 7 + .../FunctionMockLib/FunctionMockLib.inf | 31 +++++ .../FunctionMockLib/FunctionMockLib.uni | 11 ++ .../Library/GoogleTestLib/GoogleTestLib.inf | 21 ++- .../Library/GoogleTestLib/GoogleTestLib.uni | 3 - .../Test/UnitTestFrameworkPkgHostTest.dsc | 3 +- .../UnitTestFrameworkPkg.ci.yaml | 7 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 2 + .../UnitTestFrameworkPkgHost.dsc.inc | 1 + 12 files changed, 297 insertions(+), 18 deletions(-) create mode 100644 UnitTestFrameworkPkg/Include/Library/FunctionMockLib.h create mode 100644 UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.c create mode 100644 UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf create mode 100644 UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.uni diff --git a/UnitTestFrameworkPkg/Include/Library/FunctionMockLib.h b/UnitTestFrameworkPkg/Include/Library/FunctionMockLib.h new file mode 100644 index 0000000000..bf7a706656 --- /dev/null +++ b/UnitTestFrameworkPkg/Include/Library/FunctionMockLib.h @@ -0,0 +1,131 @@ +/** @file + This header allows the mocking of free (C style) functions using gmock. + + Copyright (c) 2023, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef FUNCTION_MOCK_LIB_H_ +#define FUNCTION_MOCK_LIB_H_ + +#include +#include +#include + +////////////////////////////////////////////////////////////////////////////// +// The below macros are the public function mock interface that are intended +// to be used outside this file. + +#define MOCK_INTERFACE_DECLARATION(MOCK) \ + static MOCK * Instance; \ + MOCK (); \ + ~MOCK (); + +#define MOCK_INTERFACE_DEFINITION(MOCK) \ + MOCK_STATIC_INSTANCE_DEFINITION (MOCK) \ + MOCK_INTERFACE_CONSTRUCTOR (MOCK) \ + MOCK_INTERFACE_DECONSTRUCTOR (MOCK) + +// Mock function declaration for external functions (i.e. functions to +// mock that do not exist in the compilation unit). +#define MOCK_FUNCTION_DECLARATION(RET_TYPE, FUNC, ARGS) \ + MOCK_FUNCTION_TYPE_DEFINITIONS(RET_TYPE, FUNC, ARGS) \ + MOCK_METHOD (RET_TYPE, FUNC, ARGS); + +// Mock function definition for external functions (i.e. functions to +// mock that do not exist in the compilation unit). +#define MOCK_FUNCTION_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE) \ + FUNCTION_DEFINITION_TO_CALL_MOCK(MOCK, FUNC, FUNC, NUM_ARGS, CALL_TYPE) + +// Mock function declaration for internal functions (i.e. functions to +// mock that already exist in the compilation unit). +#define MOCK_FUNCTION_INTERNAL_DECLARATION(RET_TYPE, FUNC, ARGS) \ + MOCK_FUNCTION_DECLARATION(RET_TYPE, FUNC, ARGS) \ + MOCK_FUNCTION_HOOK_DECLARATIONS(FUNC) + +// Mock function definition for internal functions (i.e. functions to +// mock that already exist in the compilation unit). This definition also +// implements MOCK_FUNC() which is later hooked as FUNC(). +#define MOCK_FUNCTION_INTERNAL_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE) \ + FUNCTION_DEFINITION_TO_CALL_MOCK(MOCK, FUNC, MOCK##_##FUNC, NUM_ARGS, CALL_TYPE) \ + MOCK_FUNCTION_HOOK_DEFINITIONS(MOCK, FUNC) + +////////////////////////////////////////////////////////////////////////////// +// The below macros are private and should not be used outside this file. + +#define MOCK_FUNCTION_HOOK_DECLARATIONS(FUNC) \ + static subhook::Hook Hook##FUNC; \ + struct MockContainer_##FUNC { \ + MockContainer_##FUNC (); \ + ~MockContainer_##FUNC (); \ + }; \ + MockContainer_##FUNC MockContainerInst_##FUNC; + +// This definition implements a constructor and destructor inside a nested +// class to enable automatic installation of the hooks to the associated +// MOCK_FUNC() when the mock object is instantiated in scope and automatic +// removal when the instantiated mock object goes out of scope. +#define MOCK_FUNCTION_HOOK_DEFINITIONS(MOCK, FUNC) \ + subhook :: Hook MOCK :: Hook##FUNC; \ + MOCK :: MockContainer_##FUNC :: MockContainer_##FUNC () { \ + if (MOCK :: Instance == NULL) \ + MOCK :: Hook##FUNC .Install( \ + (FUNC##_ret_type *) ::FUNC, \ + (FUNC##_ret_type *) MOCK##_##FUNC); \ + } \ + MOCK :: MockContainer_##FUNC :: ~MockContainer_##FUNC () { \ + MOCK :: Hook##FUNC .Remove(); \ + } \ + static_assert( \ + std::is_same::value, \ + "Function signature from 'MOCK_FUNCTION_INTERNAL_DEFINITION' macro " \ + "invocation for '" #FUNC "' does not match the function signature " \ + "of '" #FUNC "' function it is mocking. Mismatch could be due to " \ + "different return type, arguments, or calling convention. See " \ + "associated 'MOCK_FUNCTION_INTERNAL_DECLARATION' macro invocation " \ + "for more details."); + +#define MOCK_FUNCTION_TYPE_DEFINITIONS(RET_TYPE, FUNC, ARGS) \ + using FUNC##_ret_type = RET_TYPE; \ + using FUNC##_type = FUNC##_ret_type ARGS; + +// This function definition simply calls MOCK::Instance->FUNC() which is the +// mocked counterpart of the original function. This allows using gmock with +// C free functions (since by default gmock only works with object methods). +#define FUNCTION_DEFINITION_TO_CALL_MOCK(MOCK, FUNC, FUNC_DEF_NAME, NUM_ARGS, CALL_TYPE) \ + extern "C" { \ + typename MOCK :: FUNC##_ret_type CALL_TYPE FUNC_DEF_NAME( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, \ + (MOCK :: FUNC##_type), \ + NUM_ARGS)) \ + { \ + EXPECT_TRUE(MOCK :: Instance != NULL) \ + << "Called '" #FUNC "' in '" #MOCK "' function mock object before " \ + << "an instance of '" #MOCK "' was created in test '" \ + << ::testing::UnitTest::GetInstance()->current_test_info()->name() \ + << "'."; \ + return MOCK :: Instance->FUNC( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, \ + (MOCK :: FUNC##_type), \ + NUM_ARGS)); \ + } \ + } + +#define MOCK_STATIC_INSTANCE_DEFINITION(MOCK) MOCK * MOCK :: Instance = NULL; + +#define MOCK_INTERFACE_CONSTRUCTOR(MOCK) \ + MOCK :: MOCK () { \ + EXPECT_TRUE(MOCK :: Instance == NULL) \ + << "Multiple instances of '" #MOCK "' function mock object were " \ + << "created and only one instance is allowed in test '" \ + << ::testing::UnitTest::GetInstance()->current_test_info()->name() \ + << "'."; \ + MOCK :: Instance = this; \ + } + +#define MOCK_INTERFACE_DECONSTRUCTOR(MOCK) \ + MOCK :: ~ MOCK () { \ + MOCK :: Instance = NULL; \ + } + +#endif // FUNCTION_MOCK_LIB_H_ diff --git a/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h b/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h index ebec766d4c..c0a3d8e660 100644 --- a/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h +++ b/UnitTestFrameworkPkg/Include/Library/GoogleTestLib.h @@ -10,5 +10,101 @@ #define GOOGLE_TEST_LIB_H_ #include +#include +#include + +extern "C" { +#include +} + +////////////////////////////////////////////////////////////////////////////// +// Below are the action extensions to GoogleTest and gmock for EDK2 types. +// These actions are intended to be used in EXPECT_CALL (and related gmock +// macros) to support assignments to output arguments in the expected call. +// + +// Action to support pointer types to a buffer (such as UINT8* or VOID*) +ACTION_TEMPLATE ( + SetArgBuffer, + HAS_1_TEMPLATE_PARAMS (size_t, ArgNum), + AND_2_VALUE_PARAMS (Buffer, ByteSize) + ) { + auto ArgBuffer = std::get(args); + + std::memcpy (ArgBuffer, Buffer, ByteSize); +} + +////////////////////////////////////////////////////////////////////////////// +// Below are the matcher extensions to GoogleTest and gmock for EDK2 types. +// These matchers are intended to be used in EXPECT_CALL (and related gmock +// macros) to support comparisons to input arguments in the expected call. +// +// Note that these matchers can also be used in the EXPECT_THAT or ASSERT_THAT +// macros to compare whether two values are equal. +// + +// Matcher to support pointer types to a buffer (such as UINT8* or VOID* or +// any structure pointer) +MATCHER_P2 ( + BufferEq, + Buffer, + ByteSize, + std::string ("buffer data to ") + (negation ? "not " : "") + "be the same" + ) { + UINT8 *Actual = (UINT8 *)arg; + UINT8 *Expected = (UINT8 *)Buffer; + + for (size_t i = 0; i < ByteSize; i++) { + if (Actual[i] != Expected[i]) { + *result_listener << "byte at offset " << i + << " does not match expected. [" << std::hex + << "Actual: 0x" << std::setw (2) << std::setfill ('0') + << (unsigned int)Actual[i] << ", " + << "Expected: 0x" << std::setw (2) << std::setfill ('0') + << (unsigned int)Expected[i] << "]"; + return false; + } + } + + *result_listener << "all bytes match"; + return true; +} + +// Matcher to support CHAR16* type +MATCHER_P ( + Char16StrEq, + String, + std::string ("strings to ") + (negation ? "not " : "") + "be the same" + ) { + CHAR16 *Actual = (CHAR16 *)arg; + CHAR16 *Expected = (CHAR16 *)String; + + for (size_t i = 0; Actual[i] != 0; i++) { + if (Actual[i] != Expected[i]) { + *result_listener << "character at offset " << i + << " does not match expected. [" << std::hex + << "Actual: 0x" << std::setw (4) << std::setfill ('0') + << Actual[i]; + + if (std::isprint (Actual[i])) { + *result_listener << " ('" << (char)Actual[i] << "')"; + } + + *result_listener << ", Expected: 0x" << std::setw (4) << std::setfill ('0') + << Expected[i]; + + if (std::isprint (Expected[i])) { + *result_listener << " ('" << (char)Expected[i] << "')"; + } + + *result_listener << "]"; + + return false; + } + } + + *result_listener << "strings match"; + return true; +} #endif diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf index 052c7f5572..eeee6bc2b3 100644 --- a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf @@ -16,7 +16,7 @@ LIBRARY_CLASS = CmockaLib|HOST_APPLICATION # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.c b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.c new file mode 100644 index 0000000000..b7bb23f186 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.c @@ -0,0 +1,7 @@ +/** @file + Macro-only FunctionMockLib library instance with no services. + + Copyright (c) 2023, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ diff --git a/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf new file mode 100644 index 0000000000..44c5946be5 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf @@ -0,0 +1,31 @@ +## @file +# This module provides FunctionMockLib Library implementation. +# +# Copyright (c) 2023, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010018 + BASE_NAME = FunctionMockLib + MODULE_UNI_FILE = FunctionMockLib.uni + FILE_GUID = DF1CAF2F-D584-4EC1-9ABF-07E8B10AD560 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 0.1 + LIBRARY_CLASS = FunctionMockLib + +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + FunctionMockLib.c + +[LibraryClasses] + GoogleTestLib + SubhookLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec diff --git a/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.uni b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.uni new file mode 100644 index 0000000000..13e5308ce0 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.uni @@ -0,0 +1,11 @@ +// /** @file +// This module provides FunctionMockLib Library implementation. +// +// Copyright (c) 2023, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "FunctionMockLib Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides FunctionMockLib Library implementation." diff --git a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf index 68db75d702..0104384953 100644 --- a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf +++ b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf @@ -7,30 +7,27 @@ ## [Defines] - INF_VERSION = 0x00010005 + INF_VERSION = 0x00010018 BASE_NAME = GoogleTestLib MODULE_UNI_FILE = GoogleTestLib.uni FILE_GUID = A90E4751-AD30-43CC-980B-01E356B49ADF - MODULE_TYPE = BASE + MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 0.1 - LIBRARY_CLASS = GoogleTestLib|HOST_APPLICATION + LIBRARY_CLASS = GoogleTestLib # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] googletest/googletest/src/gtest-all.cc + googletest/googlemock/src/gmock-all.cc [Packages] + MdePkg/MdePkg.dec UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [BuildOptions] - MSFT:*_*_*_CC_FLAGS == /c /EHsc /Zi - MSFT:NOOPT_*_*_CC_FLAGS = /Od - - GCC:*_*_*_CC_FLAGS == -g -c - - GCC:NOOPT_*_*_CC_FLAGS = -O0 - GCC:*_*_IA32_CC_FLAGS = -m32 - GCC:*_*_X64_CC_FLAGS = -m64 + MSFT:*_*_*_CC_FLAGS == /c /EHsc /Zi /Od + GCC:*_*_IA32_CC_FLAGS == -g -c -fshort-wchar -O0 -m32 + GCC:*_*_X64_CC_FLAGS == -g -c -fshort-wchar -O0 -m64 diff --git a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni index 14c862a237..695588ce3f 100644 --- a/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni +++ b/UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.uni @@ -1,10 +1,7 @@ // /** @file // This module provides GoogleTest Library implementation. // -// This module provides GoogleTest Library implementation. -// // Copyright (c) 2022, Intel Corporation. All rights reserved.
-// // SPDX-License-Identifier: BSD-2-Clause-Patent // // **/ diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 722509c8f2..dbb429faae 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -32,8 +32,9 @@ # Build HOST_APPLICATION Libraries # UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf - UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf + UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index d8f8e024c4..be839d1af0 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -79,9 +79,14 @@ "AuditOnly": False, # Fails test but run in AuditOnly mode to collect log "IgnoreFiles": [ # use gitignore syntax to ignore errors in matching files "Library/CmockaLib/cmocka/**/*.*", # not going to spell check a submodule - "Library/GoogleTestLib/googletest/**/*.*" # not going to spell check a submodule + "Library/GoogleTestLib/googletest/**/*.*", # not going to spell check a submodule + "Library/SubhookLib/subhook/**/*.*" # not going to spell check a submodule ], "ExtendWords": [ # words to extend to the dictionary for this package + "Pointee", + "gmock", + "GMOCK", + "DSUBHOOK", "testcase", "testsuites", "cmocka", diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 30b489915d..ef0a148d48 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -26,6 +26,7 @@ PrivateInclude Library/CmockaLib/cmocka/include/cmockery Library/GoogleTestLib/googletest/googletest + Library/GoogleTestLib/googletest/googlemock [LibraryClasses] ## @libraryclass Allows save and restore unit test internal state @@ -36,6 +37,7 @@ # GoogleTestLib|Include/Library/GoogleTestLib.h SubhookLib|Include/Library/SubhookLib.h + FunctionMockLib|Include/Library/FunctionMockLib.h [LibraryClasses.Common.Private] ## @libraryclass Provides a unit test result report diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index e77897bd32..7866c36e66 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -16,6 +16,7 @@ CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf GoogleTestLib|UnitTestFrameworkPkg/Library/GoogleTestLib/GoogleTestLib.inf SubhookLib|UnitTestFrameworkPkg/Library/SubhookLib/SubhookLib.inf + FunctionMockLib|UnitTestFrameworkPkg/Library/FunctionMockLib/FunctionMockLib.inf UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf From 547ea76ed9daf392013b78547b8a650c6a7a8854 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Fri, 24 Mar 2023 16:08:38 -0700 Subject: [PATCH 0838/1529] UnitTestFrameworkPkg/ReadMe.md: Add gmock documentation REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Cc: Sean Brogan Cc: Michael Kubacki Cc: Michael D Kinney Signed-off-by: Chris Johnson Reviewed-by: Michael Kubacki Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- UnitTestFrameworkPkg/ReadMe.md | 1013 ++++++++++++++++++++++++++++++-- 1 file changed, 970 insertions(+), 43 deletions(-) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 3fa4e1910f..7da6a320a7 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -20,12 +20,15 @@ that require mocked interfaces can use the mocking infrastructure provided by ### GoogleTest The second unit test framework supported by the UnitTestFrameworkPkg is -[GoogleTest](http://google.github.io/googletest/) that can be used to implement host-based unit tests. -Use of GoogleTest for target-based unit tests of EDK II components is not supported. If a -host-based unit test requires mocked interfaces, then the Framework with cmocka support should be -used instead. Enabling support for mocked interfaces with GoogleTest is being actively investigated. +[GoogleTest](http://google.github.io/googletest/) and can be used to implement host-based unit tests. [GoogleTest on GitHub](https://github.com/google/googletest) is included in the UnitTestFrameworkPkg -as a submodule. +as a submodule. Use of GoogleTest for target-based unit tests of EDK II components is not supported. +Host-based unit tests that require mocked interfaces can use the mocking infrastructure included with +GoogleTest called [gMock](https://github.com/google/googletest/tree/main/googlemock). Note that the +gMock framework does not directly support mocking of free (C style) functions, so the FunctionMockLib +(containing a set of macros that wrap gMock's MOCK_METHOD macro) was created within the +UnitTestFrameworkPkg to enable this support. The details and usage of these macros in the +FunctionMockLib are described later. GoogleTest requires less overhead to register test suites and test cases compared to the Framework. There are also a number of tools that layer on top of GoogleTest that improve developer productivity. @@ -33,13 +36,19 @@ One example is the VS Code extension [C++ TestMate](https://marketplace.visualstudio.com/items?itemName=matepek.vscode-catch2-test-adapter) that may be used to implement, run, and debug unit tests implemented using GoogleTest. -If a component can be tested with host-based unit tests without support for mocked interfaces, -then GoogleTest is recommended. The MdePkg contains a port of the BaseSafeIntLib unit tests in -the GoogleTest style so the differences between GoogleTest and Framework unit tests can be reviewed. -The paths to the BaseSafeIntLib unit tests are: +If a component can be tested with host-based unit tests, then GoogleTest is recommended. The MdePkg +contains a port of the BaseSafeIntLib unit tests in the GoogleTest style so the differences between +GoogleTest and Framework unit tests can be reviewed. The paths to the BaseSafeIntLib unit tests are: -* MdePkg\Test\UnitTest\Library\BaseSafeIntLib -* MdePkg\Test\GoogleTest\Library\BaseSafeIntLib +* `MdePkg/Test/UnitTest/Library/BaseSafeIntLib` +* `MdePkg/Test/GoogleTest/Library/BaseSafeIntLib` + +Furthermore, the SecurityPkg contains unit tests for the SecureBootVariableLib using mocks in both +the Framework/cmocka and GoogleTest/gMock style so the differences between cmocka and gMock can be +reviewed. The paths to the SecureBootVariableLib unit tests are: + +* `SecurityPkg/Library/SecureBootVariableLib/UnitTest` +* `SecurityPkg/Library/SecureBootVariableLib/GoogleTest` ## Framework and GoogleTest Feature Comparison @@ -56,7 +65,7 @@ The paths to the BaseSafeIntLib unit tests are: | Typed Tests | NO | YES | | Type-Parameterized Tests | NO | YES | | Timeout Support | NO | YES | -| Mocking Support | Cmocka | NO | +| Mocking Support | Cmocka | gMock | | JUNIT XML Reports | YES | YES | | Execute subset of tests | NO | YES | | VS Code Extensions | NO | YES | @@ -104,7 +113,7 @@ This section is built a lot like a "Getting Started". We'll go through some of t when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe how to check for expected conditions in test cases and a bit of the logging characteristics. -Most of these examples will refer to the SampleUnitTestUefiShell app found in this package. +Most of these examples will refer to the `SampleUnitTestUefiShell` app found in this package. ### Framework Requirements - INF @@ -113,7 +122,7 @@ header for the `UnitTestLib` is located in `MdePkg`, so you shouldn't need to de packages. As long as your DSC file knows where to find the lib implementation that you want to use, you should be good to go. -See this example in 'SampleUnitTestUefiShell.inf'... +See this example in `SampleUnitTestUefiShell.inf`... ``` [Packages] @@ -127,7 +136,7 @@ See this example in 'SampleUnitTestUefiShell.inf'... PrintLib ``` -Also, if you want you test to automatically be picked up by the Test Runner plugin, you will need +Also, if you want your test to automatically be picked up by the Test Runner plugin, you will need to make sure that the module `BASE_NAME` contains the word `Test`... ``` @@ -135,6 +144,43 @@ to make sure that the module `BASE_NAME` contains the word `Test`... BASE_NAME = SampleUnitTestUefiShell ``` +### Framework Requirements - DSC + +In our DSC file, we'll need to bring in the INF file that was just created into the `[Components]` +section so that the unit tests will be built. + +See this example in `UnitTestFrameworkPkg.dsc`... + +``` +[Components] + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf +``` + +Also, based on the type of tests that are being created, the associated DSC include file from the +UnitTestFrameworkPkg for Host or Target based tests should also be included at the top of the DSC +file. + +``` +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc +``` + +Lastly, in the case that the test build has specific dependent libraries associated with it, +they should be added in the \ sub-section for the INF file in the +`[Components]` section of the DSC file. + +See this example in `SecurityPkgHostTest.dsc`... + +``` +[Components] + SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.inf { + + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + UefiRuntimeServicesTableLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf + PlatformPKProtectionLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf + UefiLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf + } +``` + ### Framework Requirements - Code Not to state the obvious, but let's make sure we have the following include before getting too far along... @@ -143,7 +189,7 @@ Not to state the obvious, but let's make sure we have the following include befo #include ``` -Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). +Now that we've got that squared away, let's look at our 'Main()' routine (or DriverEntryPoint() or whatever). ### Framework Configuration @@ -157,7 +203,7 @@ The long name and version strings are just for user presentation and relatively will be used to name any cache files and/or test results, so should be a name that makes sense in that context. These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. -In the 'SampleUnitTestUefiShell' app, the module name is used as the short name, so the initialization looks like this. +In the `SampleUnitTestUefiShell` app, the module name is used as the short name, so the initialization looks like this. ```c DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); @@ -184,7 +230,7 @@ called once at the start of the suite (before _any_ tests have run) and once at tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are `UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`. -Looking at 'SampleUnitTestUefiShell' app, you can see that the first test suite is created as below... +Looking at `SampleUnitTestUefiShell` app, you can see that the first test suite is created as below... ```c // @@ -218,7 +264,7 @@ of the context pointer is to allow test case reuse with different input data. (A around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`. -In 'SampleUnitTestUefiShell' app, the first test case is added using the code below... +In `SampleUnitTestUefiShell` app, the first test case is added using the code below... ```c AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); @@ -282,6 +328,617 @@ leverage the `cmocka.h` interface and write tests with all the features of the C Documentation for Cmocka can be found here: https://api.cmocka.org/ +## GoogleTest Libraries + +### GoogleTestLib + +GoogleTestLib is the core library used for GoogleTest in EDK II. This library is mainly a wrapper +around the GoogleTest and gMock header and source files. So all the standard +[GoogleTest](http://google.github.io/googletest/) and +[gMock](https://github.com/google/googletest/tree/main/googlemock) documentation for writing tests +and using mocks applies. + +Additionally, to support the use of some primitive types that are not directly supported by +GoogleTest and gMock (but are needed to allow gMock to be used in EDK II), some custom gMock +actions and matchers were added to GoogleTestLib. These customizations are briefly described in +the following tables. + +#### Custom Actions + +| Action Name | Similar gMock Generic Action | Usage | +|:--- |:--- |:--- | +| `SetArgBuffer()` | `SetArgPointee()` | Used to set a buffer output argument (such as UINT8*, VOID*, a structure pointer, etc.) with data in an expect call. Can be used in an `EXPECT_CALL()` | + +#### Custom Matchers + +| Matcher Name | Similar gMock Generic Matcher | Usage | +|:--- |:--- |:--- | +| `BufferEq()` | `Pointee(Eq())` | Used to compare two buffer pointer types (such as UINT8*, VOID*, a structure pointer, etc.). Can be used in an `EXPECT_CALL()`, `EXPECT_THAT()`, or anywhere else a matcher to compare two buffers is needed. | +| `Char16StrEq()` | `Pointee(Eq())` | Used to compare two CHAR16* strings. Can be used in an `EXPECT_CALL()`, `EXPECT_THAT()`, or anywhere else a matcher to compare two CHAR16* strings is needed. | + +### FunctionMockLib + +FunctionMockLib is the library that allows gMock to be used with free (C style) functions. This +library contains a set of macros that wrap gMock's MOCK_METHOD macro to enable the standard gMock +capabilities to be used with free functions. The details of how this is implemented is outside the +scope of this document, but a brief description of each of the public macros in FunctionMockLib is +described below. A full example of how to use these macros to create a mock is described in a +later section. + +In total there are six public macros in FunctionMockLib. Four of the macros are related to creating +the mock functions, and the other two macros are related to creating an interface that is necessary +to contain the mock functions and connect them into the gMock framework. + +The macros used to create the interface are... +1. `MOCK_INTERFACE_DECLARATION(MOCK)` +2. `MOCK_INTERFACE_DEFINITION(MOCK)` + +These macros both take one argument which is the name of the interface for the mock. The +`MOCK_INTERFACE_DECLARATION` macro is used to declare the interface in the `.h` file and the +`MOCK_INTERFACE_DEFINITION` macro is used to define the interface in the `.cpp` file. For +example, to create a mock for the `UefiLib`, a `MockUefiLib.h` file would be created and the +below code would be added to it. + +```cpp +struct MockUefiLib { + MOCK_INTERFACE_DECLARATION(MockUefiLib); +}; +``` + +Additionally, the below code would be written into a `MockUefiLib.cpp` file. + +```cpp +MOCK_INTERFACE_DEFINITION(MockUefiLib); +``` + +The macros used to create the mock functions are... +1. `MOCK_FUNCTION_DECLARATION(RET_TYPE, FUNC, ARGS)` +2. `MOCK_FUNCTION_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE)` +3. `MOCK_FUNCTION_INTERNAL_DECLARATION(RET_TYPE, FUNC, ARGS)` +4. `MOCK_FUNCTION_INTERNAL_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE)` + +You will notice that there are two sets of macros: one to mock external functions and +another to mock internal functions. Each set of macros has the exact same arguments, but +they are used for slightly different use cases. The details of these different use cases +is described in detail in a later section. For now, we will focus on the usage of the macro +arguments since that is common between them. + +The `MOCK_FUNCTION_DECLARATION` macro is used to declare the mock function in the `.h` file, +and it takes three arguments: return type, function name, and argument list. The +`MOCK_FUNCTION_DEFINITION` macro is used to define the mock function in the `.cpp` file, +and it takes four arguments: name of the interface for the mock, function name, number of +arguments the function takes, and calling convention type of the function. For example, to +continue with the `UefiLib` mock example above, the `GetVariable2` and `GetEfiGlobalVariable2` +functions are declared in `UefiLib.h` as shown below. + +```cpp +EFI_STATUS +EFIAPI +GetVariable2 ( + IN CONST CHAR16 *Name, + IN CONST EFI_GUID *Guid, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL + ); + +EFI_STATUS +EFIAPI +GetEfiGlobalVariable2 ( + IN CONST CHAR16 *Name, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL + ); +``` + +To declare mocks for these functions within the previously created `MockUefiLib` interface, +the below code would be added to the `MockUefiLib.h` file. Note that the previously added +interface declaration is also included in the code below for context. + +```cpp +struct MockUefiLib { + MOCK_INTERFACE_DECLARATION (MockUefiLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetVariable2, + (IN CONST CHAR16 *Name, + IN CONST EFI_GUID *Guid, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetEfiGlobalVariable2, + (IN CONST CHAR16 *Name, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); +}; +``` + +Additionally, the below code would be added into the `MockUefiLib.cpp` file to provide +the definitions for these mock functions. Again, the previously added interface +definition is also included in the code below for context. + +```cpp +MOCK_INTERFACE_DEFINITION(MockUefiLib); + +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI); +``` + +That concludes the basic overview on how to use the macros, but a more detailed +description on how to name the mocks, where to put the files, how to build the +mocks, and how to use the mocks is described in detail later. + +### SubhookLib + +SubhookLib is the library used by FunctionMockLib to implement the macros to +mock internal functions: `MOCK_FUNCTION_INTERNAL_DECLARATION` and +`MOCK_FUNCTION_INTERNAL_DEFINITION`. These macros require the additional +functionality provided by SubhookLib because they create mock functions +for functions that are already defined and compiled within the module being +tested. More detail on this is provided in a later section, but for now it is +sufficient to know that the SubhookLib allows a second definition of the +function to be compiled into the test application and then hooked to during a +test. + +This library is mainly a wrapper around the +[subhook](https://github.com/Zeex/subhook) header and source files. It is +important to note that the use of the mock function macros and the creation +of mock functions requires no knowledge about the SubhookLib. The SubhookLib +library is entirely hidden and encapsulated within FunctionMockLib, and it +is only mentioned here to provide a complete explanation on all the libraries +used in the implementation. + +## FunctionMockLib Mocks + +This section describes the details on how to use the mock function macros in +FunctionMockLib to create mock functions, name them, organize their files, +and build them so that they can be used within GoogleTest tests. The usage +of the mock functions is detailed in a later section while this section +simply details how to create them, build them, and where to put them. + +### FunctionMockLib Mocks - External vs. Internal + +The first question to ask when creating a mock function is if the function being +mocked is external or internal to the module being tested. This is very important +because the macros in FunctionMockLib used to create the mock function are named +differently for these two use cases. Fortunately, the arguments to these macros +and the usage of the mock functions within the tests are exactly the same. +However, because of the different underlying implementations, two different sets +of macros are used. + +A more detailed description of when to use the external vs. internal mock function +macros is in the following sections, but the quick summary is as follows. + +* External mock function macros are used to mock functions that are outside the +module being tested and use link-time replacement. +* Internal mock function macros are used to mock functions that are inside the +module being tested and use run-time replacement. + +The below table shows which macros to use in these two use cases. However, note that +for the creation of the interface, the same macros are used in both cases. + +| Mock Function Use Case | Mock Interface Macros | Mock Function Macros | +|:--- |:--- |:--- | +| External mock functions | `MOCK_INTERFACE_DECLARATION`
`MOCK_INTERFACE_DEFINITION` | `MOCK_FUNCTION_DECLARATION`
`MOCK_FUNCTION_DEFINITION` | +| Internal mock functions | `MOCK_INTERFACE_DECLARATION`
`MOCK_INTERFACE_DEFINITION` | `MOCK_FUNCTION_INTERNAL_DECLARATION`
`MOCK_FUNCTION_INTERNAL_DEFINITION` | + +#### FunctionMockLib Mocks - External mock function + +The external mock function macros are used to create mock function definitions +for a library, global service, or protocol that is defined outside of the module +being tested. These mock function definitions are linked into the test application +instead of linking in the design function definitions. In other words, the +external mock function macros use link-time replacement of the design functions. + +The `.h/.cpp` files for these mock functions are created within the package +directory where the library, global table, or protocol that is being mocked is +declared. These files are compiled into their own separate library (using +an INF file) that can be shared and linked into many test applications, but more +on that later. + +#### FunctionMockLib Mocks - Internal mock function + +The internal mock function macros are used to create mock function definitions +for functions that are defined within the module being tested. These mock +function definitions are compiled into the test application along with the design +function definitions. This is possible because the mock functions are given a +slightly different name during compilation. Then during test execution, the +design function is hooked and replaced with the mock function. In other words, +the internal mock function macros use run-time replacement of the design +functions. + +The `.h/.cpp` files for these mock functions are created within the GoogleTest +directory containing the specific tests that are using them. These files are +compiled directly in the GoogleTest INF file that builds the test application, +and they are not shared outside of that GoogleTest directory, but more on that +later. + +### FunctionMockLib Mocks - Declaration + +The declaration of mock functions using the FunctionMockLib macros are done +in header files. The name of the header file is determined by the interface +(such as a library or a protocol) that is being created for the mock functions. +The rules for naming the file are shown in the table below. + +| Interface Type | Header File Name | +| :--- | :--- | +| Library | Mock\Lib.h | +| Global Table (e.g. gRT, gBS, etc.) | Mock\Lib.h | +| Protocol | Mock\Protocol.h | + +The below table shows examples for file names with each of the above cases. + +| Interface Type | Interface Name | Header File Name | +| :--- | :--- | :--- | +| Library | UefiLib | MockUefiLib.h | +| Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MockUefiRuntimeServicesTableLib.h | +| Protocol | EFI_USB_IO_PROTOCOL | MockEfiUsbIoProtocol.h | + +Once the header file name is known, the file needs to be created in the proper +location. For internal mock functions, the location is simply the same +GoogleTest directory that contains the INF file that builds the test application. +For external mock functions, the location is within the `Test` directory under the +package where the library, global table, or protocol that is being mocked is +declared. The exact location depends on the interface type and is shown in the +below table. + +| Interface Type | Header File Location | +| :--- | :--- | +| Library | \/Test/Mock/Include/GoogleTest/Library | +| Global Table (e.g. gRT, gBS, etc.) | \/Test/Mock/Include/GoogleTest/Library | +| Protocol | \/Test/Mock/Include/GoogleTest/Protocol | + +The below table shows examples for file locations with each of the above cases. + +| Interface Type | Interface Name | Header File Location | +| :--- | :--- | :--- | +| Library | UefiLib | MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h | +| Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h | +| Protocol | EFI_USB_IO_PROTOCOL | MdePkg/Test/Mock/Include/GoogleTest/Protocol/MockEfiUsbIoProtocol.h | + +Now that the file location is known, the contents can be added to it. After the +standard `#ifndef` for a header file is added at the top of the file, the +`GoogleTestLib.h` and `FunctionMockLib.h` files are always added. Following these +includes other EDK II related include files are added and must be wrapped in +`extern "C" {}` because they are C include files. Failure to do this will cause +link errors to occur. Note that a `#include` of the interface being mocked must +also be added. This causes the declarations of the functions being mocked to be +included in the compilation and allows the compilation to verify that the function +signatures of the mock and design functions are identical. + +After all the needed includes have been added in the file , a `struct` is declared +using the same name as the header file (which was determined using the rules +above). Within this structure declaration a `MOCK_INTERFACE_DECLARATION` is +added along with a `MOCK_FUNCTION_DECLARATION` (or a +`MOCK_FUNCTION_INTERNAL_DECLARATION` if this interface is for internal mock +functions) for each function in the interface. To build on the examples above, +the complete `MockUefiLib.h` file would be as shown below. Note that for brevity +only the `GetVariable2` and `GetEfiGlobalVariable2` declarations are included in +the example. + +```cpp +#ifndef MOCK_UEFI_LIB_H_ +#define MOCK_UEFI_LIB_H_ + +#include +#include +extern "C" { + #include + #include +} + +struct MockUefiLib { + MOCK_INTERFACE_DECLARATION (MockUefiLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetVariable2, + (IN CONST CHAR16 *Name, + IN CONST EFI_GUID *Guid, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetEfiGlobalVariable2, + (IN CONST CHAR16 *Name, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); +}; + +#endif +``` + +In the case of libraries, the function names in the mock declarations +align exactly with the function names in the design. However, in the +case of global tables and protocols, to eliminate possible function +name collisions, the names are adjusted slightly in the mock +declarations as shown in the below table. + +| Mock Function Use Case | Design Function Name | Mock Function Name | +| :--- | :--- | :--- | +| Library | GetVariable2 | GetVariable2 | +| Global Table (e.g. gRT, gBS, etc.) | gRT->GetVariable | gRT_GetVariable | +| Protocol | UsbIoProtocol->UsbPortReset | UsbIoProtocol_UsbPortReset | + +Lastly, when creating mock functions, there are two limitations to be +aware of in gMock that extend into FunctionMockLib. + +1. gMock does not support mocking functions that have more than 15 arguments. +2. gMock does not support mocking variadic functions. + +With those limitations in mind, that completes the mock function +declarations, and now the mock function definitions for those declarations +can be created. + +### FunctionMockLib Mocks - Definition + +The definition of mock functions using the FunctionMockLib macros are done +in source files. The name of the source file is determined by the interface +(such as a library or a protocol) that is being created for the mock functions. +The rules for naming the file align with the naming of the file for declarations +and are shown in the table below. + +| Interface Type | Source File Name | +| :--- | :--- | +| Library | Mock\Lib.cpp | +| Global Table (e.g. gRT, gBS, etc.) | Mock\Lib.cpp | +| Protocol | Mock\Protocol.cpp | + +The below table shows examples for file names with each of the above cases. + +| Interface Type | Interface Name | Source File Name | +| :--- | :--- | :--- | +| Library | UefiLib | MockUefiLib.cpp | +| Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MockUefiRuntimeServicesTableLib.cpp | +| Protocol | EFI_USB_IO_PROTOCOL | MockEfiUsbIoProtocol.cpp | + +Once the source file name is known, the file needs to be created in the proper +location. The location of the source file is aligned with the location for the +header file. For internal mock functions, the location is simply the same +GoogleTest directory that contains the INF file that builds the test application. +For external mock functions, the location is within the `Test` directory under the +package where the library, global table, or protocol that is being mocked is +declared. The exact location depends on the interface type and is shown in the +below table. + +| Interface Type | Source File Location | +| :--- | :--- | +| Library | \/Test/Mock/Library/GoogleTest/Mock\Lib | +| Global Table (e.g. gRT, gBS, etc.) | \/Test/Mock/Library/GoogleTest/Mock\Lib | +| Protocol | \/Test/Mock/Library/GoogleTest/Mock\Protocol | + +The below table shows examples for file locations with each of the above cases. + +| Interface Type | Interface Name | Source File Location | +| :--- | :--- | :--- | +| Library | UefiLib | MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp | +| Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp | +| Protocol | EFI_USB_IO_PROTOCOL | MdePkg/Test/Mock/Library/GoogleTest/MockEfiUsbIoProtocol/MockEfiUsbIoProtocol.cpp | + +Now that the file location is known, the contents can be added to it. At the top +of the file, the header file containing the mock function declarations is always +added. After this `#include`, the interface definition is created using +`MOCK_INTERFACE_DEFINITION` with the interface name that was used in the mock +function declaration header file. A `MOCK_FUNCTION_DEFINITION` is then added (or +a `MOCK_FUNCTION_INTERNAL_DEFINITION` if this interface is for internal mock +functions) for each function that was declared in the interface. To build on the +prior declaration examples, the complete `MockUefiLib.cpp` file would be as shown +below. Note that for brevity only the `GetVariable2` and `GetEfiGlobalVariable2` +definitions are included in the example. + +```cpp +#include + +MOCK_INTERFACE_DEFINITION(MockUefiLib); + +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI); +``` + +When creating the defintions, there are a few things to keep in mind. + +First, when using `MOCK_FUNCTION_DEFINITION`, some functions being mocked do +not specify a calling convention. In this case, it is fine to leave the last +argument of `MOCK_FUNCTION_DEFINITION` empty. For example, if `GetVariable2` +did not specify the `EFIAPI` calling convention in its declaration, then the +below code would be used for the mock function definition. + +```cpp +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, ); +``` + +Second, the function name used in `MOCK_FUNCTION_DEFINITION` must align with +the function name used in the associated `MOCK_FUNCTION_DECLARATION` in the +header file. + +Last, if the interface is mocking a global table or protocol, then the structure +of function pointers for that interface must also be defined within the source +file as a `static` structure with the mock function definitions being assigned +to the associated entries in the structure. The address of this `static` +structure is then assigned to the global table or protocol pointer. Note that +this pointer must be wrapped in `extern "C" {}` because it needs C style +linkage. Failure to do this will cause link errors to occur. For example, when +creating the definition of the mock for the global runtime services table, the +complete `MockUefiRuntimeServicesTableLib.cpp` file would be as shown below. +Note that for brevity only the `GetVariable` and `SetVariable` definitions are +included in the example. + +```cpp +#include + +MOCK_INTERFACE_DEFINITION(MockUefiRuntimeServicesTableLib); + +MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_GetVariable, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_SetVariable, 5, EFIAPI); + +static EFI_RUNTIME_SERVICES localRt = { + {0}, // EFI_TABLE_HEADER + + NULL, // EFI_GET_TIME + NULL, // EFI_SET_TIME + NULL, // EFI_GET_WAKEUP_TIME + NULL, // EFI_SET_WAKEUP_TIME + + NULL, // EFI_SET_VIRTUAL_ADDRESS_MAP + NULL, // EFI_CONVERT_POINTER + + gRT_GetVariable, // EFI_GET_VARIABLE + NULL, // EFI_GET_NEXT_VARIABLE_NAME + gRT_SetVariable, // EFI_SET_VARIABLE + + NULL, // EFI_GET_NEXT_HIGH_MONO_COUNT + NULL, // EFI_RESET_SYSTEM + + NULL, // EFI_UPDATE_CAPSULE + NULL, // EFI_QUERY_CAPSULE_CAPABILITIES + + NULL, // EFI_QUERY_VARIABLE_INFO +}; + +extern "C" { + EFI_RUNTIME_SERVICES* gRT = &localRt; +} +``` + +That completes the mock function definitions. So now these mock function +definitions can be compiled. + +### FunctionMockLib Mocks - Build + +The building of mock functions using FunctionMockLib is done slightly +differently for external and internal function mocks. External mock +functions are built using their own separate INF file and internal mock +functions are built as source files directly referenced in the GoogleTest +INF file that builds the test application. + +#### FunctionMockLib Mocks - Build External Mock Functions + +The building of external mock functions is done using their own separate INF +file which is placed in the same location as the associated source file +containing the mock function definitions. The name of the INF file is exactly +the same as the mock function definitions file, but uses the `.inf` extension +rather than `.cpp`. + +Within the `.inf` file the `BASE_NAME` should be set to the same name as the +file (minus the extension), the `MODULE_TYPE` should be set to +`HOST_APPLICATION`, and the `LIBRARY_CLASS` should be the same as the +`BASE_NAME` but without the `Mock` prefix. + +The `[Sources]` section will contain the single mock function definition +source file, the `[Packages]` section will contain all the necessary DEC +files to compile the mock functions (which at a minimum will include the +`UnitTestFrameworkPkg.dec` file), the `[LibraryClasses]` section will contain +the `GoogleTestLib`, and the `[BuildOptions]` will need to append the `/EHsc` +compilation flag to all MSFT builds to enable proper use of the C++ exception +handler. Below is the complete `MockUefiLib.inf` as an example. + +``` +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockUefiLib + FILE_GUID = 47211F7A-6D90-4DFB-BDF9-610B69197C2E + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockUefiLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc +``` + +To ensure that this specific set of mock functions are always buildable even +if no test uses it yet, this created INF file needs to be added into the +`[Components]` section of the associated `Test` DSC file for the package in +which this INF file resides. For example, the above `MockUefiLib.inf` would +need to be added to the `MdePkg/Test/MdePkgHostTest.dsc` file as shown below. + +``` +[Components] + MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf +``` + +This created INF file will also be referenced within the necessary `Test` DSC +files in order to include the mock function definitions in the test +applications which use this set of mock functions, but more on that later. + +One small additional requirement is that if this INF file is added into a +package that does not yet have any other external mock functions in it, then +that package's DEC file will need to have the mock include directory (more +specifically the `Test/Mock/Include` directory) added to its `[Includes]` +section so that test files who want to use the mock functions will be able to +locate the mock function header file. For example, if `MockUefiLib.inf` were +the first mock added to the `MdePkg`, then the below snippet would need to be +added to the `MdePkg.dec` file. + +``` +[Includes] + Test/Mock/Include +``` + +#### FunctionMockLib Mocks - Build Internal Mock Functions + +The building of internal mock functions is done using the GoogleTest INF file +that already needs to exist to build the test application. This is easy to +manage since the source and header files for the internal mock functions are +also located in the same GoogleTest directory as the GoogleTest INF file that +will reference them. + +The only additions that are required to the GoogleTest INF file are that the +mock function definitions file be added to the `[Sources]` section, the +`UnitTestFrameworkPkg.dec` file be added to the `[Packages]` section, and the +`GoogleTestLib` and `SubhookLib` be added to the `[LibraryClasses]` section. +Below is a minimal contrived example for a `MyModuleGoogleTest.inf` that uses a +`MockMyModuleInternalFunctions.cpp` source file for its internal mock functions. + +``` +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = MyModuleGoogleTest + FILE_GUID = 814B09B9-2D51-4786-8A77-2E10CD1C55F3 + VERSION_STRING = 1.0 + MODULE_TYPE = HOST_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MyModuleGoogleTest.cpp + MockMyModuleInternalFunctions.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + SubhookLib +``` + ## GoogleTest Samples There is a sample unit test provided as both an example of how to write a unit test and leverage @@ -291,22 +948,31 @@ directory. The sample is provided for the HOST_APPLICATION build type, which can be run on a host system without needing a target. +There is also a sample unit test provided as both an example of how to write a unit test with +mock functions and leverage some of the gMock features. This sample can be found in the +`SecurityPkg/Library/SecureBootVariableLib/GoogleTest` directory. + +It too is provided for the HOST_APPLICATION build type, which can be run on a host system without +needing a target. + ## GoogleTest Usage This section is built a lot like a "Getting Started". We'll go through some of the components that are needed when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe how to check for expected conditions in test cases and a bit of the logging characteristics. -Most of these examples will refer to the SampleGoogleTestHost app found in this package. +Most of these examples will refer to the `SampleGoogleTestHost` app found in this package, but +the examples related to mock functions will refer to the `SecureBootVariableLibGoogleTest` app +found in the `SecurityPkg`. ### GoogleTest Requirements - INF -In our INF file, we'll need to bring in the `GoogleTest` library. Conveniently, the interface -header for the `GoogleTest` is in `UnitTestFrameworkPkg`, so you shouldn't need to depend on any other +In our INF file, we'll need to bring in the `GoogleTestLib` library. Conveniently, the interface +header for the `GoogleTestLib` is in `UnitTestFrameworkPkg`, so you shouldn't need to depend on any other packages. As long as your DSC file knows where to find the lib implementation that you want to use, you should be good to go. -See this example in 'SampleGoogleTestHost.inf'... +See this example in `SampleGoogleTestHost.inf`... ``` [Packages] @@ -319,7 +985,7 @@ See this example in 'SampleGoogleTestHost.inf'... DebugLib ``` -Also, if you want you test to automatically be picked up by the Test Runner plugin, you will need +Also, if you want your test to automatically be picked up by the Test Runner plugin, you will need to make sure that the module `BASE_NAME` contains the word `Test`... ``` @@ -327,12 +993,54 @@ to make sure that the module `BASE_NAME` contains the word `Test`... BASE_NAME = SampleGoogleTestHost ``` -### GoogleTest Requirements - Code +### GoogleTest Requirements - DSC -Not to state the obvious, but let's make sure we have the following include before getting too far along... +In our DSC file, we'll need to bring in the INF file that was just created into the `[Components]` +section so that the unit tests will be built. + +See this example in `UnitTestFrameworkPkgHostTest.dsc`... ``` -#include +[Components] + UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf +``` + +Also, based on the type of tests that are being created, the associated DSC include file from the +UnitTestFrameworkPkg for Host or Target based tests should also be included at the top of the DSC +file. + +``` +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +``` + +Lastly, in the case that the test build has specific dependent libraries associated with it, +they should be added in the \ sub-section for the INF file in the +`[Components]` section of the DSC file. Note that it is within this sub-section where you can +control whether the design or mock version of a component is linked into the test exectuable. + +See this example in `SecurityPkgHostTest.dsc` where the `SecureBootVariableLib` design is +being tested using mock versions of `UefiRuntimeServicesTableLib`, `PlatformPKProtectionLib`, +and `UefiLib`... + +``` +[Components] + SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf { + + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf + PlatformPKProtectionLib|SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf + UefiLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf + } +``` + +### GoogleTest Requirements - Code + +GoogleTest applications are implemented in C++, so make sure that your test file has +a `.cpp` extension. With that behind us, not to state the obvious, but let's make sure +we have the following includes before getting too far along in the file... + +```cpp +#include extern "C" { #include #include @@ -340,33 +1048,75 @@ extern "C" { } ``` -GoogleTest applications are implemented in C++. The first include brings in the -GoogleTest definitions. Other EDK II related include files must be wrapped in -`extern "C" {}` because they are C include files. Link failures will occur if -this is not done. +The first include brings in the GoogleTest definitions. Other EDK II related include +files must be wrapped in `extern "C" {}` because they are C include files. Link +failures will occur if this is not done. + +Also, when using GoogleTest it is helpful to add a `using` declaration for its +`testing` namespace. This `using` statement greatly reduces the amount of code you +need to write in the tests when referencing the utilities within the `testing` +namespace. For example, instead of writing `::testing::Return` or `::testing::Test`, +you can just write `Return` or `Test` respectively, and these types of references +occur numerous times within the tests. + +Lastly, in the case that tests within a GoogleTest application require the usage of +mock functions, it is also necessary to include the header files for those interfaces +as well. As an example, the `SecureBootVariableLibGoogleTest` uses the mock versions +of `UefiLib` and `UefiRuntimeServicesTableLib`. So its test file contains the below +includes. Note that the `using` declaration mentioned above is also shown in the code +below for completeness of the example. + +```cpp +#include +#include +#include -Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). +extern "C" { + #include + ... +} + +using namespace testing; +``` + +Now that we've got that squared away, let's look at our 'Main()' routine (or DriverEntryPoint() or whatever). ### GoogleTest Configuration Unlike the Framework, GoogleTest does not require test suites or test cases to be registered. Instead, the test cases declare the test suite name and test case name as part of their implementation. The only requirement for GoogleTest -is to have a `main()` function that initialize the GoogleTest infrastructure and -call the service `RUN_ALL_TESTS()` to run all the unit tests. +is to have a `main()` function that initializes the GoogleTest infrastructure +and calls the service `RUN_ALL_TESTS()` to run all the unit tests. -```c +```cpp int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ``` +However, while GoogleTest does not require test suites or test cases to be +registered, there is still one rule within EDK II that currently needs to be +followed. This rule is that all tests for a given GoogleTest application must +be contained within the same source file that contains the `main()` function +shown above. These tests can be written directly in the file or a `#include` +can be used to add them into the file indirectly. + +The reason for this is due to EDK II taking the host application INF file and +first compiling all of its source files into a static library. This static +library is then linked into the final host application. The problem with this +method is that only the tests in the object file containing the `main()` +function are linked into the final host application. This is because the other +tests are contained in their own object files within the static library and +they have no symbols in them that the final host application depends on, so +those object files are not linked into the final host application. + ### GoogleTest - A Simple Test Case -We'll look at the below test case from 'SampleGoogleTestHost'... +Below is a sample test case from `SampleGoogleTestHost`. -```c +```cpp TEST(SimpleMathTests, OnePlusOneShouldEqualTwo) { UINTN A; UINTN B; @@ -393,9 +1143,175 @@ detailed logs. When in doubt, there are always `ASSERT_TRUE` and `ASSERT_FALSE`. test criterium will immediately return from the test case with a failed status and log an error string. _Note_ that this early return can have implications for memory leakage. -There is no return status from a GooglTest unit test. If no assertions are +For most `ASSERT` macros in GoogleTest there is also an equivalent `EXPECT` macro. Both macro versions +will ultimately cause the `TEST` to fail if the check fails. However, the difference between the two +macro versions is that when the check fails, the `ASSERT` version immediately returns from the `TEST` +while the `EXPECT` version continues running the `TEST`. + +There is no return status from a GooglTest unit test. If no assertions (or expectations) are triggered then the unit test has a passing status. +### GoogleTest - A gMock Test Case + +Below is a sample test case from `SecureBootVariableLibGoogleTest`. Although +actually, the test case is not written exactly like this in the test file, but +more on that in a bit. + +```cpp +TEST(SetSecureBootModeTest, SetVarError) { + MockUefiRuntimeServicesTableLib RtServicesMock; + UINT8 SecureBootMode; + EFI_STATUS Status; + + // Any random magic number can be used for these tests + SecureBootMode = 0xAB; + + EXPECT_CALL(RtServicesMock, gRT_SetVariable) + .WillOnce(Return(EFI_INVALID_PARAMETER)); + + Status = SetSecureBootMode(SecureBootMode); + EXPECT_EQ(Status, EFI_INVALID_PARAMETER); +} +``` + +Keep in mind that this test is written to verify that `SetSecureBootMode()` will +return `EFI_INVALID_PARAMETER` when the call to `gRT->SetVariable()` within the +implementation of `SetSecureBootMode()` returns `EFI_INVALID_PARAMETER`. With that +in mind, let's discuss how a mock function is used to accomplish this in the test. + +In this test case, the `MockUefiRuntimeServicesTableLib` interface is instantiated as +`RtServicesMock` which enables its associated mock functions. These interface +instantiations that contain the mock functions are very important for mock function +based unit tests because without these instantiations, the mock functions within that +interface will not exist and can not be used. + +The next line of interest is the `EXPECT_CALL`, which is a standard part of the gMock +framework. This macro is telling the test that a call is expected to occur to a +specific function on a specific interface. The first argument is the name of the +interface object that was instantiated in this test, and the second argument is the +name of the mock function within that interface that is expected to be called. The +`WillOnce(Return(EFI_INVALID_PARAMETER))` associated with this `EXPECT_CALL` states +that the `gRT_SetVariable()` function (remember from earlier in this documentation +that this refers to the `gRT->SetVariable()` function) will be called once during +this test, and when it does get called, we want it to return `EFI_INVALID_PARAMETER`. + +Once this `EXPECT_CALL` has been setup, the call to `SetSecureBootMode()` occurs in +the test, and its return value is saved in `Status` so that it can be tested. Based +on the `EXPECT_CALL` that was setup earlier, when `SetSecureBootMode()` internally +calls `gRT->SetVariable()`, it returns `EFI_INVALID_PARAMETER`. This value should +then be returned by `SetSecureBootMode()`, and the +`EXPECT_EQ(Status, EFI_INVALID_PARAMETER)` verifies this is the case. + +There is much more that can be done with `EXPECT_CALL` and mock functions, but we +will leave those details to be explained in the gMock documentation. + +Now it was mentioned earlier that this test case is not written exactly like this +in the test file, and the next section describes how this test is slightly +refactored to reduce the total amount of code in the entire test suite. + +### GoogleTest - A gMock Test Case (refactored) + +The sample test case from `SecureBootVariableLibGoogleTest` in the prior section is +actually written as shown below. + +```cpp +class SetSecureBootModeTest : public Test { + protected: + MockUefiRuntimeServicesTableLib RtServicesMock; + UINT8 SecureBootMode; + EFI_STATUS Status; + + void SetUp() override { + // Any random magic number can be used for these tests + SecureBootMode = 0xAB; + } +}; + +TEST_F(SetSecureBootModeTest, SetVarError) { + EXPECT_CALL(RtServicesMock, gRT_SetVariable) + .WillOnce(Return(EFI_INVALID_PARAMETER)); + + Status = SetSecureBootMode(SecureBootMode); + EXPECT_EQ(Status, EFI_INVALID_PARAMETER); +} +``` + +This code may at first seem more complicated, but you will notice that the code +with in it is still the same. There is still a `MockUefiRuntimeServicesTableLib` +instantiation, there is still a `SecureBootMode` and `Status` variable defined, +there is still an `EXPECT_CALL`, and etc. However, the benefit of constructing +the test this way is that the new `TEST_F()` requires less code than the prior +`TEST()`. + +This is made possible by the usage of what GoogleTest calls a _test fixture_. +This concept of a test fixture allows multiple tests to use (or more specifically +inherit from a base class) a common set of variables and initial conditions. +Notice that using `TEST_F()` requires the first argument to be a name that aligns +with a test fixture (in this case `SetSecureBootModeTest`), and the second +argument is the name of the test (just like in the `TEST()` macro). + +All `TEST_F()` tests that use a specific test fixture can be thought of as having +all of that test fixture's variables automatically defined in the test as well as +having that text fixture's `SetUp()` function called before entering the test. + +This means that another `TEST_F()` can be written without needing to worry about +defining a bunch of variables or instantiating a bunch of interfaces for mock +functions. For example, the below test (also in `SecureBootVariableLibGoogleTest`) +uses the same test fixture and makes use of its `RtServicesMock`, `Status`, and +`SecureBootMode` variables. + +```cpp +TEST_F(SetSecureBootModeTest, PropogateModeToSetVar) { + EXPECT_CALL(RtServicesMock, + gRT_SetVariable( + Char16StrEq(EFI_CUSTOM_MODE_NAME), + BufferEq(&gEfiCustomModeEnableGuid, sizeof(EFI_GUID)), + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, + sizeof(SecureBootMode), + BufferEq(&SecureBootMode, sizeof(SecureBootMode)))) + .WillOnce(Return(EFI_SUCCESS)); + + Status = SetSecureBootMode(SecureBootMode); + EXPECT_EQ(Status, EFI_SUCCESS); +} +``` + +The biggest benefit is that the `TEST_F()` code can now focus on what is being +tested and not worry about any repetitive setup. There is more that can be done +with test fixtures, but we will leave those details to be explained in the +gMock documentation. + +Now, as for what is in the above test, it is slightly more complicated than the +first test. So let's explain this added complexity and what it is actually +testing. In this test, there is still an `EXPECT_CALL` for the +`gRT_SetVariable()` function. However, in this test we are stating that we +expect the input arguments passed to `gRT_SetVariable()` be specific values. +The order they are provided in the `EXPECT_CALL` align with the order of the +arguments in the `gRT_SetVariable()` function. In this case the order of the +`gRT_SetVariable()` arguments is as shown below. + +```cpp +IN CHAR16 *VariableName, +IN EFI_GUID *VendorGuid, +IN UINT32 Attributes, +IN UINTN DataSize, +IN VOID *Data +``` + +So in the `EXPECT_CALL` we are stating that the call to `gRT_SetVariable()` +will be made with the below input argument values. + +1. `VariableName` is equal to the `EFI_CUSTOM_MODE_NAME` string +2. `VendorGuid` is equal to the `gEfiCustomModeEnableGuid` GUID (which has a byte length of `sizeof(EFI_GUID)`) +3. `Attributes` is equal to `EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS` +4. `DataSize` is equal to `sizeof(SecureBootMode)` +5. `Data` is equal to `SecureBootMode` (which has a byte length of `sizeof(SecureBootMode)`) + +If any one of these input arguments does not match in the actual call to +`gRT_SetVariable()` in the design, then the test will fail. There is much more +that can be done with `EXPECT_CALL` and mock functions, but again we will +leave those details to be explained in the gMock documentation. + ### GoogleTest - More Complex Cases To write more advanced tests, take a look at the @@ -587,7 +1503,7 @@ This mode is used by the test running plugin to aggregate the results for CI tes Host based Unit Tests will automatically enable coverage data. -For Windows, This is primarily leverage for pipeline builds, but this can be leveraged locally using the +For Windows, this is primarily leveraged for pipeline builds, but this can be leveraged locally using the OpenCppCoverage windows tool to parse coverage data to cobertura xml format. - Windows Prerequisite @@ -607,7 +1523,7 @@ OpenCppCoverage windows tool to parse coverage data to cobertura xml format. ``` -For Linux, This is primarily leveraged for pipeline builds, but this can be leveraged locally using the +For Linux, this is primarily leveraged for pipeline builds, but this can be leveraged locally using the lcov linux tool, and parsed using the lcov_cobertura python tool to parse it to cobertura xml format. - Linux Prerequisite @@ -654,8 +1570,8 @@ We will continue trying to make these as similar as possible. Code/Test | Location --------- | -------- -Host-Based Unit Tests for a Library/Protocol/PPI/GUID Interface | If what's being tested is an interface (e.g. a library with a public header file, like DebugLib), the test should be scoped to the parent package.
Example: `MdePkg/Test/UnitTest/[Library/Protocol/Ppi/Guid]/`

A real-world example of this is the BaseSafeIntLib test in MdePkg.
`MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf` -Host-Based Unit Tests for a Library/Driver (PEI/DXE/SMM) implementation | If what's being tested is a specific implementation (e.g. BaseDebugLibSerialPort for DebugLib), the test should be scoped to the implementation directory itself, in a UnitTest subdirectory.

Module Example: `MdeModulePkg/Universal/EsrtFmpDxe/UnitTest/`
Library Example: `MdePkg/Library/BaseMemoryLib/UnitTest/` +Host-Based Unit Tests for a Library/Protocol/PPI/GUID Interface | If what's being tested is an interface (e.g. a library with a public header file, like DebugLib) and the test is agnostic to a specific implementation, then the test should be scoped to the parent package.
Example: `MdePkg/Test/UnitTest/[Library/Protocol/Ppi/Guid]/`

A real-world example of this is the BaseSafeIntLib test in MdePkg.
`MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf` +Host-Based Unit Tests for a Library/Driver (PEI/DXE/SMM) implementation | If what's being tested is a specific implementation (e.g. BaseDebugLibSerialPort for DebugLib), then the test should be scoped to the implementation directory itself, in a UnitTest (or GoogleTest) subdirectory.

Module Example: `MdeModulePkg/Universal/EsrtFmpDxe/UnitTest/`
Library Example: `MdePkg/Library/BaseMemoryLib/UnitTest/`
Library Example (GoogleTest): `SecurityPkg/Library/SecureBootVariableLib/GoogleTest/` Host-Based Tests for a Functionality or Feature | If you're writing a functional test that operates at the module level (i.e. if it's more than a single file or library), the test should be located in the package-level Tests directory under the HostFuncTest subdirectory.
For example, if you were writing a test for the entire FMP Device Framework, you might put your test in:
`FmpDevicePkg/Test/HostFuncTest/FmpDeviceFramework`

If the feature spans multiple packages, it's location should be determined by the package owners related to the feature. Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a Functionality or Feature | Similar to Host-Based, if the feature is in one package, should be located in the `*Pkg/Test/[Shell/Dxe/Smm/Pei]Test` directory.

If the feature spans multiple packages, it's location should be determined by the package owners related to the feature.

USAGE EXAMPLES
PEI Example: MP_SERVICE_PPI. Or check MTRR configuration in a notification function.
SMM Example: a test in a protocol callback function. (It is different with the solution that SmmAgent+ShellApp)
DXE Example: a test in a UEFI event call back to check SPI/SMRAM status.
Shell Example: the SMM handler audit test has a shell-based app that interacts with an SMM handler to get information. The SMM paging audit test gathers information about both DXE and SMM. And the SMM paging functional test actually forces errors into SMM via a DXE driver. @@ -713,8 +1629,19 @@ Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a Functionality or Feature | Simi GeneralPurposeLibTest.c GeneralPurposeLibHostUnitTest.inf - Pkg.dsc # Standard Modules and any Target-Based Test Apps (including in Test/) + Mock/ + Include/ + GoogleTest/ + Library/ + MockGeneralPurposeLib.h + Library/ + GoogleTest/ + MockGeneralPurposeLib/ + MockGeneralPurposeLib.cpp + MockGeneralPurposeLib.inf + + Pkg.dsc # Standard Modules and any Target-Based Test Apps (including in Test/) ``` ### Future Locations in Consideration From e59743ff4d5bd0c90760df64040e331c256f5474 Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Fri, 24 Mar 2023 16:10:22 -0700 Subject: [PATCH 0839/1529] MdePkg: Add gmock examples REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Chris Johnson Acked-by: Liming Gao Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- MdePkg/MdePkg.dec | 1 + MdePkg/Test/MdePkgHostTest.dsc | 2 + .../Include/GoogleTest/Library/MockUefiLib.h | 39 +++++++++++++++++ .../Library/MockUefiRuntimeServicesTableLib.h | 42 +++++++++++++++++++ .../GoogleTest/MockUefiLib/MockUefiLib.cpp | 12 ++++++ .../GoogleTest/MockUefiLib/MockUefiLib.inf | 33 +++++++++++++++ .../MockUefiRuntimeServicesTableLib.cpp | 40 ++++++++++++++++++ .../MockUefiRuntimeServicesTableLib.inf | 33 +++++++++++++++ 8 files changed, 202 insertions(+) create mode 100644 MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h create mode 100644 MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h create mode 100644 MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp create mode 100644 MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf create mode 100644 MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp create mode 100644 MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 5cf04bc0cb..a46f28fff4 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -27,6 +27,7 @@ [Includes] Include Test/UnitTest/Include + Test/Mock/Include [Includes.IA32] Include/Ia32 diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc index b8b186dd8b..35e3ef6d97 100644 --- a/MdePkg/Test/MdePkgHostTest.dsc +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -34,3 +34,5 @@ # Build HOST_APPLICATION Libraries # MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf + MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h new file mode 100644 index 0000000000..dec2c93e1b --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h @@ -0,0 +1,39 @@ +/** @file + Google Test mocks for UefiLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_UEFI_LIB_H_ +#define MOCK_UEFI_LIB_H_ + +#include +#include +extern "C" { +#include +#include +} + +struct MockUefiLib { + MOCK_INTERFACE_DECLARATION (MockUefiLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetVariable2, + (IN CONST CHAR16 *Name, + IN CONST EFI_GUID *Guid, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + GetEfiGlobalVariable2, + (IN CONST CHAR16 *Name, + OUT VOID **Value, + OUT UINTN *Size OPTIONAL) + ); +}; + +#endif diff --git a/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h new file mode 100644 index 0000000000..afdfc6b855 --- /dev/null +++ b/MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h @@ -0,0 +1,42 @@ +/** @file + Google Test mocks for UefiRuntimeServicesTableLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_UEFI_RUNTIME_SERVICES_TABLE_LIB_H_ +#define MOCK_UEFI_RUNTIME_SERVICES_TABLE_LIB_H_ + +#include +#include +extern "C" { +#include +#include +} + +struct MockUefiRuntimeServicesTableLib { + MOCK_INTERFACE_DECLARATION (MockUefiRuntimeServicesTableLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gRT_GetVariable, + (IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + OUT UINT32 *Attributes OPTIONAL, + IN OUT UINTN *DataSize, + OUT VOID *Data) + ); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + gRT_SetVariable, + (IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINT32 Attributes, + IN UINTN DataSize, + IN VOID *Data) + ); +}; + +#endif diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp new file mode 100644 index 0000000000..5339d040c9 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp @@ -0,0 +1,12 @@ +/** @file + Google Test mocks for UefiLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +MOCK_INTERFACE_DEFINITION(MockUefiLib); + +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, EFIAPI); +MOCK_FUNCTION_DEFINITION(MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI); diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf new file mode 100644 index 0000000000..1a7461e444 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf @@ -0,0 +1,33 @@ +## @file +# Google Test mocks for UefiLib +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockUefiLib + FILE_GUID = 47211F7A-6D90-4DFB-BDF9-610B69197C2E + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockUefiLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp new file mode 100644 index 0000000000..ecd1ba8236 --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp @@ -0,0 +1,40 @@ +/** @file + Google Test mocks for UefiRuntimeServicesTableLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +MOCK_INTERFACE_DEFINITION(MockUefiRuntimeServicesTableLib); + +MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_GetVariable, 5, EFIAPI); +MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_SetVariable, 5, EFIAPI); + +static EFI_RUNTIME_SERVICES localRt = { + {0}, // EFI_TABLE_HEADER + + NULL, // EFI_GET_TIME + NULL, // EFI_SET_TIME + NULL, // EFI_GET_WAKEUP_TIME + NULL, // EFI_SET_WAKEUP_TIME + + NULL, // EFI_SET_VIRTUAL_ADDRESS_MAP + NULL, // EFI_CONVERT_POINTER + + gRT_GetVariable, // EFI_GET_VARIABLE + NULL, // EFI_GET_NEXT_VARIABLE_NAME + gRT_SetVariable, // EFI_SET_VARIABLE + + NULL, // EFI_GET_NEXT_HIGH_MONO_COUNT + NULL, // EFI_RESET_SYSTEM + + NULL, // EFI_UPDATE_CAPSULE + NULL, // EFI_QUERY_CAPSULE_CAPABILITIES + + NULL, // EFI_QUERY_VARIABLE_INFO +}; + +extern "C" { + EFI_RUNTIME_SERVICES* gRT = &localRt; +} diff --git a/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf new file mode 100644 index 0000000000..7ba74d93bf --- /dev/null +++ b/MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf @@ -0,0 +1,33 @@ +## @file +# Google Test mocks for UefiRuntimeServicesTableLib +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockUefiRuntimeServicesTableLib + FILE_GUID = 0A0E13C2-4176-4293-89C7-C2497AA31B92 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiRuntimeServicesTableLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockUefiRuntimeServicesTableLib.cpp + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc From 7b5052f04d89b066a8a38ef7e470852c4db0c48b Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Fri, 24 Mar 2023 16:16:01 -0700 Subject: [PATCH 0840/1529] MdeModulePkg/Library/UefiSortLib: Add GoogleTestLib example REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Cc: Jian J Wang Cc: Liming Gao Signed-off-by: Chris Johnson Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- .../MockUefiRuntimeServicesTableLib.inf | 4 +- .../GoogleTest/UefiSortLibGoogleTest.cpp | 61 +++++++++++++++++++ .../GoogleTest/UefiSortLibGoogleTest.inf | 31 ++++++++++ MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 6 ++ 4 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.cpp create mode 100644 MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf index e716b855a3..15eb646d7c 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf @@ -10,9 +10,9 @@ INF_VERSION = 0x00010005 BASE_NAME = MockUefiRuntimeServicesTableLib FILE_GUID = 4EA215EE-85C1-4A0A-847F-D2A8DE20805F - MODULE_TYPE = UEFI_DRIVER + MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiRuntimeServicesTableLib|HOST_APPLICATION + LIBRARY_CLASS = UefiRuntimeServicesTableLib # # VALID_ARCHITECTURES = IA32 X64 EBC diff --git a/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.cpp b/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.cpp new file mode 100644 index 0000000000..23f6e9cc06 --- /dev/null +++ b/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.cpp @@ -0,0 +1,61 @@ +/** @file + Unit tests for the implementation of UefiSortLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +extern "C" { + #include + #include +} + +using namespace testing; + +INTN +EFIAPI +CompareUint32 ( + IN CONST VOID *Left, + IN CONST VOID *Right + ) +{ + if (*(UINT32*)Right > *(UINT32*)Left) { + return 1; + } else if (*(UINT32*)Right < *(UINT32*)Left) { + return -1; + } + + return 0; +} + +// Test PerformQuickSort() API from UefiSortLib to verify a UINT32 array +// with 9 elements in ascending order is sorted into descending order. +TEST(PerformQuickSortTest, SortUint32AscendingArray_Size9) { + CONST UINT32 ArraySize = 9; + UINT32 BuffActual[ArraySize]; + UINT32 BuffExpected[ArraySize]; + + for (UINT32 Index = 0; Index < ArraySize; Index++) { + BuffActual[Index] = Index + 1; + BuffExpected[Index] = ArraySize - Index; + } + + PerformQuickSort (BuffActual, (UINTN)ArraySize, sizeof(UINT32), (SORT_COMPARE)CompareUint32); + EXPECT_THAT(BuffActual, ElementsAreArray(BuffExpected, ArraySize)); +} + +// Test StringCompare() API from UefiSortLib to verify the comparison +// succeeds when the same buffer is compared with itself. +TEST(StringCompareTest, CompareSameBuffer) { + INTN RetVal; + CONST CHAR16 *Buffer = (CHAR16*)L"abcdefg"; + + RetVal = StringCompare (&Buffer, &Buffer); + EXPECT_EQ(RetVal, 0); +} + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf b/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf new file mode 100644 index 0000000000..ac5ffb3bc2 --- /dev/null +++ b/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf @@ -0,0 +1,31 @@ +## @file +# Unit test suite for the UefiSortLib using Google Test +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UefiSortLibGoogleTest + FILE_GUID = 78FB0BEE-D0EA-4E1A-BD38-67458C8ECDEF + VERSION_STRING = 1.0 + MODULE_TYPE = HOST_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + UefiSortLibGoogleTest.cpp + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + UefiSortLib diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index c9ec835df6..a2bbbe8adf 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -47,3 +47,9 @@ UefiSortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf } + + MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.inf { + + UefiSortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + } From fc2e401bf950a10cfea5e6ede08e8bb73707ea9c Mon Sep 17 00:00:00 2001 From: Chris Johnson Date: Fri, 24 Mar 2023 16:12:17 -0700 Subject: [PATCH 0841/1529] SecurityPkg: Add gmock example REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4389 Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Chris Johnson Acked-by: Jiewen Yao Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael D Kinney --- .../SecureBootVariableLibGoogleTest.cpp | 174 ++++++++++++++++++ .../SecureBootVariableLibGoogleTest.inf | 32 ++++ .../UnitTest/MockPlatformPKProtectionLib.inf | 4 +- .../UnitTest/MockUefiLib.inf | 4 +- .../MockUefiRuntimeServicesTableLib.inf | 4 +- .../UnitTest/SecureBootVariableLibUnitTest.c | 2 +- SecurityPkg/SecurityPkg.dec | 1 + .../Library/MockPlatformPKProtectionLib.h | 28 +++ .../MockPlatformPKProtectionLib.cpp | 11 ++ .../MockPlatformPKProtectionLib.inf | 34 ++++ SecurityPkg/Test/SecurityPkgHostTest.dsc | 8 + 11 files changed, 295 insertions(+), 7 deletions(-) create mode 100644 SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.cpp create mode 100644 SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf create mode 100644 SecurityPkg/Test/Mock/Include/GoogleTest/Library/MockPlatformPKProtectionLib.h create mode 100644 SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.cpp create mode 100644 SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf diff --git a/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.cpp b/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.cpp new file mode 100644 index 0000000000..c9190c8ffd --- /dev/null +++ b/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.cpp @@ -0,0 +1,174 @@ +/** @file + Unit tests for the implementation of SecureBootVariableLib. + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include +#include +#include + +extern "C" { + #include + #include + #include + #include + #include + #include +} + +using namespace testing; + +////////////////////////////////////////////////////////////////////////////// +class SetSecureBootModeTest : public Test { + protected: + MockUefiRuntimeServicesTableLib RtServicesMock; + UINT8 SecureBootMode; + EFI_STATUS Status; + + void SetUp() override { + // Any random magic number can be used for these tests + SecureBootMode = 0xAB; + } +}; + +// Test SetSecureBootMode() API from SecureBootVariableLib to verify the +// expected error is returned when the call to gRT->SetVariable() fails. +TEST_F(SetSecureBootModeTest, SetVarError) { + EXPECT_CALL(RtServicesMock, gRT_SetVariable) + .WillOnce(Return(EFI_INVALID_PARAMETER)); + + Status = SetSecureBootMode(SecureBootMode); + EXPECT_EQ(Status, EFI_INVALID_PARAMETER); +} + +// Test SetSecureBootMode() API from SecureBootVariableLib to verify the +// expected secure boot mode is written to the correct variable in the call +// to gRT->SetVariable(). +TEST_F(SetSecureBootModeTest, PropogateModeToSetVar) { + EXPECT_CALL(RtServicesMock, + gRT_SetVariable( + Char16StrEq(EFI_CUSTOM_MODE_NAME), + BufferEq(&gEfiCustomModeEnableGuid, sizeof(EFI_GUID)), + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, + sizeof(SecureBootMode), + BufferEq(&SecureBootMode, sizeof(SecureBootMode)))) + .WillOnce(Return(EFI_SUCCESS)); + + Status = SetSecureBootMode(SecureBootMode); + EXPECT_EQ(Status, EFI_SUCCESS); +} + +////////////////////////////////////////////////////////////////////////////// +class GetSetupModeTest : public Test { + protected: + MockUefiRuntimeServicesTableLib RtServicesMock; + UINT8 SetupMode; + EFI_STATUS Status; + UINT8 ExpSetupMode; + + void SetUp() override { + // Any random magic number can be used for these tests + ExpSetupMode = 0xAB; + } +}; + +// Test GetSetupMode() API from SecureBootVariableLib to verify the expected +// error is returned when the call to gRT->GetVariable() fails. +TEST_F(GetSetupModeTest, GetVarError) { + EXPECT_CALL(RtServicesMock, gRT_GetVariable) + .WillOnce(Return(EFI_INVALID_PARAMETER)); + + Status = GetSetupMode (&SetupMode); + EXPECT_EQ(Status, EFI_INVALID_PARAMETER); +} + +// Test GetSetupMode() API from SecureBootVariableLib to verify the expected +// setup mode is returned (and with a success return code) when the mode is +// successfully read from the call to gRT->GetVariable(). +TEST_F(GetSetupModeTest, FetchModeFromGetVar) { + EXPECT_CALL(RtServicesMock, + gRT_GetVariable( + Char16StrEq(EFI_SETUP_MODE_NAME), + BufferEq(&gEfiGlobalVariableGuid, sizeof(EFI_GUID)), + _, + Pointee(Eq(sizeof(SetupMode))), + NotNull())) + .WillOnce(DoAll( + SetArgPointee<3>(sizeof(ExpSetupMode)), + SetArgBuffer<4>(&ExpSetupMode, sizeof(ExpSetupMode)), + Return(EFI_SUCCESS))); + + Status = GetSetupMode (&SetupMode); + ASSERT_EQ(Status, EFI_SUCCESS); + EXPECT_EQ(SetupMode, ExpSetupMode); +} + +////////////////////////////////////////////////////////////////////////////// +class IsSecureBootEnabledTest : public Test { + protected: + MockUefiLib UefiLibMock; + BOOLEAN Enabled; +}; + +// Test IsSecureBootEnabled() API from SecureBootVariableLib to verify FALSE +// is returned when the call to GetEfiGlobalVariable2() fails. +TEST_F(IsSecureBootEnabledTest, GetVarError) { + EXPECT_CALL(UefiLibMock, GetEfiGlobalVariable2) + .WillOnce(Return(EFI_ABORTED)); + + Enabled = IsSecureBootEnabled (); + EXPECT_EQ(Enabled, FALSE); +} + +////////////////////////////////////////////////////////////////////////////// +class IsSecureBootEnabledAllocTest : public IsSecureBootEnabledTest { + protected: + UINT8 *BootEnabledBuffer; + + void SetUp() override { + BootEnabledBuffer = (UINT8*) AllocatePool(1); + ASSERT_NE(BootEnabledBuffer, nullptr); + } +}; + +// Test IsSecureBootEnabled() API from SecureBootVariableLib to verify TRUE +// is returned when the call to GetEfiGlobalVariable2() is successful and +// returns SECURE_BOOT_MODE_ENABLE. +TEST_F(IsSecureBootEnabledAllocTest, IsEnabled) { + *BootEnabledBuffer = SECURE_BOOT_MODE_ENABLE; + EXPECT_CALL(UefiLibMock, + GetEfiGlobalVariable2( + Char16StrEq(EFI_SECURE_BOOT_MODE_NAME), + NotNull(), + _)) + .WillOnce(DoAll( + SetArgBuffer<1>(&BootEnabledBuffer, sizeof(VOID*)), + Return(EFI_SUCCESS))); + + Enabled = IsSecureBootEnabled (); + EXPECT_EQ(Enabled, TRUE); +} + +// Test IsSecureBootEnabled() API from SecureBootVariableLib to verify FALSE +// is returned when the call to GetEfiGlobalVariable2() is successful and +// returns SECURE_BOOT_MODE_DISABLE. +TEST_F(IsSecureBootEnabledAllocTest, IsDisabled) { + *BootEnabledBuffer = SECURE_BOOT_MODE_DISABLE; + EXPECT_CALL(UefiLibMock, + GetEfiGlobalVariable2( + Char16StrEq(EFI_SECURE_BOOT_MODE_NAME), + NotNull(), + _)) + .WillOnce(DoAll( + SetArgBuffer<1>(&BootEnabledBuffer, sizeof(VOID*)), + Return(EFI_SUCCESS))); + + Enabled = IsSecureBootEnabled (); + EXPECT_EQ(Enabled, FALSE); +} + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf b/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf new file mode 100644 index 0000000000..5503dcfa32 --- /dev/null +++ b/SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf @@ -0,0 +1,32 @@ +## @file +# Unit test suite for the SecureBootVariableLib using Google Test +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = SecureBootVariableLibGoogleTest + FILE_GUID = C88372AB-726B-4344-A250-6C7F826C874E + VERSION_STRING = 1.0 + MODULE_TYPE = HOST_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SecureBootVariableLibGoogleTest.cpp + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + SecurityPkg/SecurityPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + SecureBootVariableLib diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf index 1e19033c5a..c927ef7099 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf @@ -10,9 +10,9 @@ INF_VERSION = 0x00010005 BASE_NAME = MockPlatformPKProtectionLib FILE_GUID = 5FCD74D3-3965-4D56-AB83-000B9B4806A0 - MODULE_TYPE = DXE_DRIVER + MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 - LIBRARY_CLASS = PlatformPKProtectionLib|HOST_APPLICATION + LIBRARY_CLASS = PlatformPKProtectionLib # # The following information is for reference only and not required by the build tools. diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf index a84242ac72..fecf468411 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf @@ -18,9 +18,9 @@ INF_VERSION = 0x00010005 BASE_NAME = MockUefiLib FILE_GUID = E3B7AEF9-4E55-49AF-B035-ED776C928EC6 - MODULE_TYPE = UEFI_DRIVER + MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiLib|HOST_APPLICATION + LIBRARY_CLASS = UefiLib # # VALID_ARCHITECTURES = IA32 X64 EBC diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf index f832a93e22..6fe0418960 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf @@ -10,9 +10,9 @@ INF_VERSION = 0x00010005 BASE_NAME = MockUefiRuntimeServicesTableLib FILE_GUID = 84CE0021-ABEE-403C-9A1B-763CCF2D40F1 - MODULE_TYPE = UEFI_DRIVER + MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiRuntimeServicesTableLib|HOST_APPLICATION + LIBRARY_CLASS = UefiRuntimeServicesTableLib # # VALID_ARCHITECTURES = IA32 X64 EBC diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c index a23135dfb0..3a92d5d834 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c @@ -163,7 +163,7 @@ MockGetVariable ( return EFI_BUFFER_TOO_SMALL; } else { assert_non_null (Data); - CopyMem (Data, (VOID *)mock (), TargetSize); + CopyMem (Data, (VOID *)(UINTN)mock (), TargetSize); } return EFI_SUCCESS; diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 0382090f4e..0a8042d63f 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -21,6 +21,7 @@ [Includes] Include + Test/Mock/Include [LibraryClasses] ## @libraryclass Provides hash interfaces from different implementations. diff --git a/SecurityPkg/Test/Mock/Include/GoogleTest/Library/MockPlatformPKProtectionLib.h b/SecurityPkg/Test/Mock/Include/GoogleTest/Library/MockPlatformPKProtectionLib.h new file mode 100644 index 0000000000..8024f4be29 --- /dev/null +++ b/SecurityPkg/Test/Mock/Include/GoogleTest/Library/MockPlatformPKProtectionLib.h @@ -0,0 +1,28 @@ +/** @file + Google Test mocks for PlatformPKProtectionLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#ifndef MOCK_PLATFORM_PK_PROTECTION_LIB_H_ +#define MOCK_PLATFORM_PK_PROTECTION_LIB_H_ + +#include +#include +extern "C" { +#include +#include +} + +struct MockPlatformPKProtectionLib { + MOCK_INTERFACE_DECLARATION (MockPlatformPKProtectionLib); + + MOCK_FUNCTION_DECLARATION ( + EFI_STATUS, + DisablePKProtection, + () + ); +}; + +#endif diff --git a/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.cpp b/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.cpp new file mode 100644 index 0000000000..5ea030f6df --- /dev/null +++ b/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.cpp @@ -0,0 +1,11 @@ +/** @file + Google Test mocks for PlatformPKProtectionLib + + Copyright (c) 2022, Intel Corporation. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ +#include + +MOCK_INTERFACE_DEFINITION(MockPlatformPKProtectionLib); + +MOCK_FUNCTION_DEFINITION(MockPlatformPKProtectionLib, DisablePKProtection, 0, EFIAPI); diff --git a/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf b/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf new file mode 100644 index 0000000000..3ed638eaf7 --- /dev/null +++ b/SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf @@ -0,0 +1,34 @@ +## @file +# Google Test mocks for PlatformPKProtectionLib +# +# Copyright (c) 2022, Intel Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockPlatformPKProtectionLib + FILE_GUID = C1383D85-E0ED-44E0-A0A6-125F1D78B6E9 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = PlatformPKProtectionLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + MockPlatformPKProtectionLib.cpp + +[Packages] + MdePkg/MdePkg.dec + SecurityPkg/SecurityPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + GoogleTestLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /EHsc diff --git a/SecurityPkg/Test/SecurityPkgHostTest.dsc b/SecurityPkg/Test/SecurityPkgHostTest.dsc index c4df01fe1b..ad5b4fc350 100644 --- a/SecurityPkg/Test/SecurityPkgHostTest.dsc +++ b/SecurityPkg/Test/SecurityPkgHostTest.dsc @@ -25,6 +25,7 @@ SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf + SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf # # Build SecurityPkg HOST_APPLICATION Tests @@ -36,3 +37,10 @@ PlatformPKProtectionLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf UefiLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf } + SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf { + + SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf + PlatformPKProtectionLib|SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf + UefiLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf + } From a4fdf7973e141290e30af92491eba11e761e719a Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 23 Mar 2023 19:29:03 -0700 Subject: [PATCH 0842/1529] SecurityPkg/Library/SecureBootVariableLib: Fix VS20xx 4122 errors The unit test code for the SecureBootVariableLib is initializing local variable structures in their declaration from other local variables that are also initialized in their declaration. ANSI C does not allow this and error 4122 is generated on VS20xx compilers. The test cases are updated to initialize the local structure fields in C statements instead of their local variable declaration. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao Reviewed-by: Oliver Smith-Denny --- .../UnitTest/SecureBootVariableLibUnitTest.c | 170 +++++++++--------- 1 file changed, 83 insertions(+), 87 deletions(-) diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c index 3a92d5d834..e4cdc68bbb 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c @@ -351,10 +351,10 @@ SecureBootCreateDataFromInputSimple ( UINTN SigListSize = 0; EFI_STATUS Status; UINT8 TestData[] = { 0 }; - SECURE_BOOT_CERTIFICATE_INFO KeyInfo = { - .Data = TestData, - .DataSize = sizeof (TestData) - }; + SECURE_BOOT_CERTIFICATE_INFO KeyInfo; + + KeyInfo.Data = TestData; + KeyInfo.DataSize = sizeof (TestData); Status = SecureBootCreateDataFromInput (&SigListSize, &SigList, 1, &KeyInfo); @@ -441,16 +441,12 @@ SecureBootCreateDataFromInputMultiple ( UINT8 TestData1[] = { 0 }; UINT8 TestData2[] = { 1, 2 }; EFI_STATUS Status; - SECURE_BOOT_CERTIFICATE_INFO KeyInfo[2] = { - { - .Data = TestData1, - .DataSize = sizeof (TestData1) - }, - { - .Data = TestData2, - .DataSize = sizeof (TestData2) - } - }; + SECURE_BOOT_CERTIFICATE_INFO KeyInfo[2]; + + KeyInfo[0].Data = TestData1; + KeyInfo[0].DataSize = sizeof (TestData1); + KeyInfo[1].Data = TestData2; + KeyInfo[1].DataSize = sizeof (TestData2); Status = SecureBootCreateDataFromInput (&SigListSize, &SigList, 2, KeyInfo); UT_ASSERT_NOT_EFI_ERROR (Status); @@ -1219,19 +1215,19 @@ SetSecureBootVariablesShouldComplete ( UINT8 PkDummy = 0xFE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .DbtPtr = &DbtDummy, - .DbtSize = sizeof (DbtDummy), - .KekPtr = &KekDummy, - .KekSize = sizeof (KekDummy), - .PkPtr = &PkDummy, - .PkSize = sizeof (PkDummy), - .SecureBootKeyName = L"Food" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.DbtPtr = &DbtDummy; + PayloadInfo.DbtSize = sizeof (DbtDummy); + PayloadInfo.KekPtr = &KekDummy; + PayloadInfo.KekSize = sizeof (KekDummy); + PayloadInfo.PkPtr = &PkDummy; + PayloadInfo.PkSize = sizeof (PkDummy); + PayloadInfo.SecureBootKeyName = L"Food"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1385,11 +1381,11 @@ SetSecureBootVariablesShouldStopFailDBX ( UINT8 DbxDummy = 0xBE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbxDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .SecureBootKeyName = L"Fail DBX" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.SecureBootKeyName = L"Fail DBX"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1442,13 +1438,13 @@ SetSecureBootVariablesShouldStopFailDB ( UINT8 DbxDummy = 0xBE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .SecureBootKeyName = L"Fail DB" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.SecureBootKeyName = L"Fail DB"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1516,15 +1512,15 @@ SetSecureBootVariablesShouldStopFailDBT ( UINT8 DbxDummy = 0xBE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .DbtPtr = &DbtDummy, - .DbtSize = sizeof (DbtDummy), - .SecureBootKeyName = L"Fail DBT" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.DbtPtr = &DbtDummy; + PayloadInfo.DbtSize = sizeof (DbtDummy); + PayloadInfo.SecureBootKeyName = L"Fail DBT"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1608,19 +1604,19 @@ SetSecureBootVariablesShouldStopFailKEK ( UINT8 PkDummy = 0xFE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .DbtPtr = &DbtDummy, - .DbtSize = sizeof (DbtDummy), - .KekPtr = &KekDummy, - .KekSize = sizeof (KekDummy), - .PkPtr = &PkDummy, - .PkSize = sizeof (PkDummy), - .SecureBootKeyName = L"Food" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.DbtPtr = &DbtDummy; + PayloadInfo.DbtSize = sizeof (DbtDummy); + PayloadInfo.KekPtr = &KekDummy; + PayloadInfo.KekSize = sizeof (KekDummy); + PayloadInfo.PkPtr = &PkDummy; + PayloadInfo.PkSize = sizeof (PkDummy); + PayloadInfo.SecureBootKeyName = L"Food"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1718,19 +1714,19 @@ SetSecureBootVariablesShouldStopFailPK ( UINT8 PkDummy = 0xFE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .DbtPtr = &DbtDummy, - .DbtSize = sizeof (DbtDummy), - .KekPtr = &KekDummy, - .KekSize = sizeof (KekDummy), - .PkPtr = &PkDummy, - .PkSize = sizeof (PkDummy), - .SecureBootKeyName = L"Food" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.DbtPtr = &DbtDummy; + PayloadInfo.DbtSize = sizeof (DbtDummy); + PayloadInfo.KekPtr = &KekDummy; + PayloadInfo.KekSize = sizeof (KekDummy); + PayloadInfo.PkPtr = &PkDummy; + PayloadInfo.PkSize = sizeof (PkDummy); + PayloadInfo.SecureBootKeyName = L"Food"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); @@ -1841,19 +1837,19 @@ SetSecureBootVariablesDBTOptional ( UINT8 PkDummy = 0xFE; UINT8 *Payload = NULL; UINTN PayloadSize = sizeof (DbDummy); - SECURE_BOOT_PAYLOAD_INFO PayloadInfo = { - .DbPtr = &DbDummy, - .DbSize = sizeof (DbDummy), - .DbxPtr = &DbxDummy, - .DbxSize = sizeof (DbxDummy), - .DbtPtr = NULL, - .DbtSize = 0, - .KekPtr = &KekDummy, - .KekSize = sizeof (KekDummy), - .PkPtr = &PkDummy, - .PkSize = sizeof (PkDummy), - .SecureBootKeyName = L"Food" - }; + SECURE_BOOT_PAYLOAD_INFO PayloadInfo; + + PayloadInfo.DbPtr = &DbDummy; + PayloadInfo.DbSize = sizeof (DbDummy); + PayloadInfo.DbxPtr = &DbxDummy; + PayloadInfo.DbxSize = sizeof (DbxDummy); + PayloadInfo.DbtPtr = NULL; + PayloadInfo.DbtSize = 0; + PayloadInfo.KekPtr = &KekDummy; + PayloadInfo.KekSize = sizeof (KekDummy); + PayloadInfo.PkPtr = &PkDummy; + PayloadInfo.PkSize = sizeof (PkDummy); + PayloadInfo.SecureBootKeyName = L"Food"; expect_memory (MockGetVariable, VariableName, EFI_SECURE_BOOT_MODE_NAME, sizeof (EFI_SECURE_BOOT_MODE_NAME)); expect_value (MockGetVariable, VendorGuid, &gEfiGlobalVariableGuid); From abfbf01722107ebd2a4449291cd6231681926da3 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 24 Mar 2023 15:28:01 -0700 Subject: [PATCH 0843/1529] SecurityPkg/Library/SecureBootVariableLib: HOST_APPLICATION IA32/X64 only Update SecureBootVariableLib host-based unit test INF file to only list VALID_ARCHITECTURES of IA32 and X64 to align with all other host-based unit test INF files. The UnitTestFrameworkPkg only provides build support of host-based unit tests to OS applications for IA32 and X64. Cc: Jiewen Yao Cc: Jian J Wang Signed-off-by: Michael D Kinney Reviewed-by: Jiewen Yao Reviewed-by: Oliver Smith-Denny --- .../UnitTest/MockPlatformPKProtectionLib.inf | 2 +- .../Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf | 2 +- .../UnitTest/MockUefiRuntimeServicesTableLib.inf | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf index c927ef7099..3698e4fad0 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf @@ -17,7 +17,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf index fecf468411..e02d04f376 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf @@ -23,7 +23,7 @@ LIBRARY_CLASS = UefiLib # -# VALID_ARCHITECTURES = IA32 X64 EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf index 6fe0418960..e59a3394d5 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf @@ -15,7 +15,7 @@ LIBRARY_CLASS = UefiRuntimeServicesTableLib # -# VALID_ARCHITECTURES = IA32 X64 EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] From be7e22947342d51ddab8295c56ccb4035b93c6d1 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 24 Mar 2023 15:28:16 -0700 Subject: [PATCH 0844/1529] MdePkg/Library/BaseLib: HOST_APPLICATION IA32/X64 only Update BaseLib host-based unit test INF file to only list VALID_ARCHITECTURES of IA32 and X64 to align with all other host-based unit test INF files. The UnitTestFrameworkPkg only provides build support of host-based unit tests to OS applications for IA32 and X64. Cc: Liming Gao Cc: Zhiguang Liu Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao Reviewed-by: Oliver Smith-Denny --- MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf b/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf index 12a5cdcc0a..1d53f940f5 100644 --- a/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf +++ b/MdePkg/Library/BaseLib/UnitTestHostBaseLib.inf @@ -23,7 +23,7 @@ LIBRARY_CLASS = UnitTestHostBaseLib|HOST_APPLICATION # -# VALID_ARCHITECTURES = IA32 X64 EBC ARM AARCH64 RISCV64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] From 5c27a9f68f0688a324d8cb6a1772ffe2599137e7 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 24 Mar 2023 15:28:30 -0700 Subject: [PATCH 0845/1529] MdeModulePkg: HOST_APPLICATION IA32/X64 only Update MdeModulePkg host-based unit test INF files to only list VALID_ARCHITECTURES of IA32 and X64 to align with all other host-based unit test INF files. The UnitTestFrameworkPkg only provides build support of host-based unit tests to OS applications for IA32 and X64. Cc: Jian J Wang Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny Reviewed-by: Liming Gao --- .../UnitTest/MockUefiRuntimeServicesTableLib.inf | 2 +- .../RuntimeDxeUnitTest/VariableLockRequestToLockUnitTest.inf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf index 15eb646d7c..24dc934f8d 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf @@ -15,7 +15,7 @@ LIBRARY_CLASS = UefiRuntimeServicesTableLib # -# VALID_ARCHITECTURES = IA32 X64 EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableLockRequestToLockUnitTest.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableLockRequestToLockUnitTest.inf index 2a659d7e13..59c743ad1f 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableLockRequestToLockUnitTest.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/RuntimeDxeUnitTest/VariableLockRequestToLockUnitTest.inf @@ -15,7 +15,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] From ed77400c6f376745e41ac9cfb1c085f0ac155a47 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 24 Mar 2023 15:28:41 -0700 Subject: [PATCH 0846/1529] PrmPkg/Library: HOST_APPLICATION IA32/X64 only Update PrmPkg host-based unit test INF files to only list VALID_ARCHITECTURES of IA32 and X64 to align with all other host-based unit test INF files. The UnitTestFrameworkPkg only provides build support of host-based unit tests to OS applications for IA32 and X64. Cc: Michael Kubacki Cc: Nate DeSimone Signed-off-by: Michael D Kinney Reviewed-by: Oliver Smith-Denny Reviewed-by: Michael Kubacki --- .../UnitTest/DxePrmContextBufferLibUnitTestHost.inf | 2 +- .../UnitTest/DxePrmModuleDiscoveryLibUnitTestHost.inf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTestHost.inf b/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTestHost.inf index 7cf6a16867..eefaddb10a 100644 --- a/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTestHost.inf +++ b/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTestHost.inf @@ -17,7 +17,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/PrmPkg/Library/DxePrmModuleDiscoveryLib/UnitTest/DxePrmModuleDiscoveryLibUnitTestHost.inf b/PrmPkg/Library/DxePrmModuleDiscoveryLib/UnitTest/DxePrmModuleDiscoveryLibUnitTestHost.inf index 8aae1f7cd7..fd4b44a9bf 100644 --- a/PrmPkg/Library/DxePrmModuleDiscoveryLib/UnitTest/DxePrmModuleDiscoveryLibUnitTestHost.inf +++ b/PrmPkg/Library/DxePrmModuleDiscoveryLib/UnitTest/DxePrmModuleDiscoveryLibUnitTestHost.inf @@ -17,7 +17,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# VALID_ARCHITECTURES = IA32 X64 # [Sources] From cf71d7a3df2faec0370bcf977c2fc9b072b0f6e8 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:45:15 -0600 Subject: [PATCH 0847/1529] ArmPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout ArmPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- ArmPkg/Drivers/ArmGic/ArmGicCommonDxe.c | 4 +-- ArmPkg/Drivers/CpuDxe/MemoryAttribute.c | 10 +++--- .../Library/ArmMmuLib/AArch64/ArmMmuLibCore.c | 4 +-- .../ArmPsciResetSystemLib.c | 2 +- .../LinuxBootBootManagerLib/LinuxBootBm.c | 2 +- .../PlatformBootManagerLib/PlatformBm.c | 32 +++++++++---------- .../ProcessorSubClassDxe/ProcessorSubClass.c | 2 +- .../Type00/MiscBiosVendorFunction.c | 2 +- .../Type01/MiscSystemManufacturerFunction.c | 2 +- .../MiscBaseBoardManufacturerFunction.c | 2 +- .../Type03/MiscChassisManufacturerFunction.c | 2 +- ...MiscNumberOfInstallableLanguagesFunction.c | 2 +- .../Type32/MiscBootInformationFunction.c | 2 +- 13 files changed, 34 insertions(+), 34 deletions(-) diff --git a/ArmPkg/Drivers/ArmGic/ArmGicCommonDxe.c b/ArmPkg/Drivers/ArmGic/ArmGicCommonDxe.c index cd12fcda27..d560c42fc9 100644 --- a/ArmPkg/Drivers/ArmGic/ArmGicCommonDxe.c +++ b/ArmPkg/Drivers/ArmGic/ArmGicCommonDxe.c @@ -137,7 +137,7 @@ CpuArchEventProtocolNotify ( DEBUG (( DEBUG_ERROR, "%a: Cpu->RegisterInterruptHandler() - %r\n", - __FUNCTION__, + __func__, Status )); return; @@ -153,7 +153,7 @@ CpuArchEventProtocolNotify ( DEBUG (( DEBUG_ERROR, "%a: Cpu->RegisterInterruptHandler() - %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c b/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c index cbc8261a68..61ba8fbbae 100644 --- a/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c +++ b/ArmPkg/Drivers/CpuDxe/MemoryAttribute.c @@ -92,7 +92,7 @@ GetMemoryAttributes ( DEBUG (( DEBUG_VERBOSE, "%a: BaseAddress == 0x%lx, Length == 0x%lx\n", - __FUNCTION__, + __func__, BaseAddress, Length )); @@ -113,7 +113,7 @@ GetMemoryAttributes ( DEBUG (( DEBUG_VERBOSE, "%a: RegionAddress == 0x%lx, RegionLength == 0x%lx, RegionAttributes == 0x%lx\n", - __FUNCTION__, + __func__, (UINT64)RegionAddress, (UINT64)RegionLength, (UINT64)RegionAttributes @@ -130,7 +130,7 @@ GetMemoryAttributes ( DEBUG (( DEBUG_VERBOSE, "%a: Union == %lx, Intersection == %lx\n", - __FUNCTION__, + __func__, (UINT64)Union, (UINT64)Intersection )); @@ -188,7 +188,7 @@ SetMemoryAttributes ( DEBUG (( DEBUG_INFO, "%a: BaseAddress == 0x%lx, Length == 0x%lx, Attributes == 0x%lx\n", - __FUNCTION__, + __func__, (UINTN)BaseAddress, (UINTN)Length, (UINTN)Attributes @@ -272,7 +272,7 @@ ClearMemoryAttributes ( DEBUG (( DEBUG_INFO, "%a: BaseAddress == 0x%lx, Length == 0x%lx, Attributes == 0x%lx\n", - __FUNCTION__, + __func__, (UINTN)BaseAddress, (UINTN)Length, (UINTN)Attributes diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c index 7acfd2e89a..7ed758fbbc 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibCore.c @@ -139,7 +139,7 @@ ReplaceTableEntry ( (((RegionStart ^ (UINTN)Entry) & ~BlockMask) == 0)) { DisableMmu = TRUE; - DEBUG ((DEBUG_WARN, "%a: splitting block entry with MMU disabled\n", __FUNCTION__)); + DEBUG ((DEBUG_WARN, "%a: splitting block entry with MMU disabled\n", __func__)); } mReplaceLiveEntryFunc (Entry, Value, RegionStart, DisableMmu); @@ -233,7 +233,7 @@ UpdateRegionMappingRecursive ( DEBUG (( DEBUG_VERBOSE, "%a(%d): %llx - %llx set %lx clr %lx\n", - __FUNCTION__, + __func__, Level, RegionStart, RegionEnd, diff --git a/ArmPkg/Library/ArmPsciResetSystemLib/ArmPsciResetSystemLib.c b/ArmPkg/Library/ArmPsciResetSystemLib/ArmPsciResetSystemLib.c index 7bcd348495..02b0c27e4d 100644 --- a/ArmPkg/Library/ArmPsciResetSystemLib/ArmPsciResetSystemLib.c +++ b/ArmPkg/Library/ArmPsciResetSystemLib/ArmPsciResetSystemLib.c @@ -65,7 +65,7 @@ LibResetSystem ( ArmCallSmc (&ArmSmcArgs); // We should never be here - DEBUG ((DEBUG_ERROR, "%a: PSCI Reset failed\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: PSCI Reset failed\n", __func__)); CpuDeadLoop (); return EFI_UNSUPPORTED; } diff --git a/ArmPkg/Library/LinuxBootBootManagerLib/LinuxBootBm.c b/ArmPkg/Library/LinuxBootBootManagerLib/LinuxBootBm.c index 5a44af5a75..75998eabb1 100644 --- a/ArmPkg/Library/LinuxBootBootManagerLib/LinuxBootBm.c +++ b/ArmPkg/Library/LinuxBootBootManagerLib/LinuxBootBm.c @@ -151,7 +151,7 @@ PlatformBootManagerAfterConsole ( LOAD_OPTION_ACTIVE ); } else { - DEBUG ((DEBUG_ERROR, "%a: PcdLinuxBootFileGuid was not set!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: PcdLinuxBootFileGuid was not set!\n", __func__)); } } diff --git a/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c b/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c index 2fb1a4aa4f..08998ffe4d 100644 --- a/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c +++ b/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c @@ -195,7 +195,7 @@ FilterAndProcess ( DEBUG (( DEBUG_VERBOSE, "%a: %g: %r\n", - __FUNCTION__, + __func__, ProtocolGuid, Status )); @@ -266,7 +266,7 @@ IsPciDisplay ( &Pci ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __func__, ReportText, Status)); return FALSE; } @@ -330,7 +330,7 @@ Connect ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %s: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -356,7 +356,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: handle %p: device path not found\n", - __FUNCTION__, + __func__, ReportText, Handle )); @@ -368,7 +368,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ConOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -380,7 +380,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ErrOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -390,7 +390,7 @@ AddOutput ( DEBUG (( DEBUG_VERBOSE, "%a: %s: added to ConOut and ErrOut\n", - __FUNCTION__, + __func__, ReportText )); } @@ -547,7 +547,7 @@ GetPlatformOptions ( DEBUG (( DEBUG_ERROR, "%a: failed to register \"%s\": %r\n", - __FUNCTION__, + __func__, BootOptions[Index].Description, Status )); @@ -575,7 +575,7 @@ GetPlatformOptions ( DEBUG (( DEBUG_ERROR, "%a: failed to register hotkey for \"%s\": %r\n", - __FUNCTION__, + __func__, BootOptions[Index].Description, Status )); @@ -757,7 +757,7 @@ HandleCapsules ( BOOLEAN NeedReset; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: processing capsules ...\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: processing capsules ...\n", __func__)); Status = gBS->LocateProtocol ( &gEsrtManagementProtocolGuid, @@ -785,7 +785,7 @@ HandleCapsules ( DEBUG (( DEBUG_ERROR, "%a: failed to process capsule %p - %r\n", - __FUNCTION__, + __func__, CapsuleHeader, Status )); @@ -800,7 +800,7 @@ HandleCapsules ( DEBUG (( DEBUG_WARN, "%a: capsule update successful, resetting ...\n", - __FUNCTION__ + __func__ )); gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); @@ -868,7 +868,7 @@ BootDiscoveryPolicyHandler ( DEBUG (( DEBUG_INFO, "%a - Unexpected DiscoveryPolicy (0x%x). Run Minimal Discovery Policy\n", - __FUNCTION__, + __func__, DiscoveryPolicy )); return EFI_SUCCESS; @@ -884,14 +884,14 @@ BootDiscoveryPolicyHandler ( DEBUG_INFO, "%a - Failed to locate gEfiBootManagerPolicyProtocolGuid." "Driver connect will be skipped.\n", - __FUNCTION__ + __func__ )); return Status; } Status = BMPolicy->ConnectDeviceClass (BMPolicy, Class); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - ConnectDeviceClass returns - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - ConnectDeviceClass returns - %r\n", __func__, Status)); return Status; } @@ -1096,7 +1096,7 @@ PlatformBootManagerUnableToBoot ( DEBUG (( DEBUG_WARN, "%a: rebooting after refreshing all boot options\n", - __FUNCTION__ + __func__ )); gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); } diff --git a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c index 3b12e26abf..9050588500 100644 --- a/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c +++ b/ArmPkg/Universal/Smbios/ProcessorSubClassDxe/ProcessorSubClass.c @@ -741,7 +741,7 @@ AddSmbiosProcessorTypeTable ( DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type04 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c index c9f25b7502..38f3864b16 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type00/MiscBiosVendorFunction.c @@ -287,7 +287,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBiosVendor) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type00 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c index 22fb5eccaa..8867de4815 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type01/MiscSystemManufacturerFunction.c @@ -184,7 +184,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscSystemManufacturer) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type01 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c index 3441e77988..feb42e6f5d 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type02/MiscBaseBoardManufacturerFunction.c @@ -214,7 +214,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBaseBoardManufacturer) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type02 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type03/MiscChassisManufacturerFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type03/MiscChassisManufacturerFunction.c index d161970c02..6b3b63b0e8 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type03/MiscChassisManufacturerFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type03/MiscChassisManufacturerFunction.c @@ -179,7 +179,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscChassisManufacturer) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type03 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type13/MiscNumberOfInstallableLanguagesFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type13/MiscNumberOfInstallableLanguagesFunction.c index 386b8800e2..951ac2a905 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type13/MiscNumberOfInstallableLanguagesFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type13/MiscNumberOfInstallableLanguagesFunction.c @@ -161,7 +161,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscNumberOfInstallableLanguages) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type13 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); diff --git a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type32/MiscBootInformationFunction.c b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type32/MiscBootInformationFunction.c index fdf6262aa7..fa1ea95f2b 100644 --- a/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type32/MiscBootInformationFunction.c +++ b/ArmPkg/Universal/Smbios/SmbiosMiscDxe/Type32/MiscBootInformationFunction.c @@ -69,7 +69,7 @@ SMBIOS_MISC_TABLE_FUNCTION (MiscBootInformation) { DEBUG (( DEBUG_ERROR, "[%a]:[%dL] Smbios Type32 Table Log Failed! %r \n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Status )); From 8efed4b52808900dc8315f9b4302e8cf97ccd6a2 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:47:56 -0600 Subject: [PATCH 0848/1529] ArmVirtPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout ArmVirtPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- .../CloudHvAcpiPlatformDxe/CloudHvAcpi.c | 4 ++-- .../ArmVirtGicArchLib/ArmVirtGicArchLib.c | 2 +- .../ArmVirtPL031FdtClientLib.c | 4 ++-- .../ArmVirtPsciResetSystemLib.c | 6 +++--- .../ArmVirtPsciResetSystemPeiLib.c | 6 +++--- .../CloudHvVirtMemInfoLib.c | 10 +++++----- .../KvmtoolRtcFdtClientLib.c | 4 ++-- .../KvmtoolVirtMemInfoLib.c | 2 +- .../NorFlashKvmtoolLib/NorFlashKvmtool.c | 4 ++-- .../Library/NorFlashQemuLib/NorFlashQemuLib.c | 2 +- .../PlatformBootManagerLib/PlatformBm.c | 20 +++++++++---------- .../PlatformBootManagerLib/QemuKernel.c | 2 +- .../Library/PlatformPeiLib/PlatformPeiLib.c | 6 +++--- .../QemuVirtMemInfoLib/QemuVirtMemInfoLib.c | 4 ++-- .../QemuVirtMemInfoPeiLibConstructor.c | 4 ++-- .../XenAcpiPlatformDxe/XenAcpiPlatformDxe.c | 4 ++-- ArmVirtPkg/XenioFdtDxe/XenioFdtDxe.c | 4 ++-- 17 files changed, 44 insertions(+), 44 deletions(-) diff --git a/ArmVirtPkg/CloudHvAcpiPlatformDxe/CloudHvAcpi.c b/ArmVirtPkg/CloudHvAcpiPlatformDxe/CloudHvAcpi.c index 0595b0e1d3..254aa978c6 100644 --- a/ArmVirtPkg/CloudHvAcpiPlatformDxe/CloudHvAcpi.c +++ b/ArmVirtPkg/CloudHvAcpiPlatformDxe/CloudHvAcpi.c @@ -106,7 +106,7 @@ InstallCloudHvAcpiTables ( } // while if (DsdtPtr == NULL) { - DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __func__)); return EFI_NOT_FOUND; } @@ -151,7 +151,7 @@ CloudHvAcpiPlatformEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: Fail to install Acpi table: %r\n", - __FUNCTION__, + __func__, Status )); CpuDeadLoop (); diff --git a/ArmVirtPkg/Library/ArmVirtGicArchLib/ArmVirtGicArchLib.c b/ArmVirtPkg/Library/ArmVirtGicArchLib/ArmVirtGicArchLib.c index 57bbfd20d0..cf9434e534 100644 --- a/ArmVirtPkg/Library/ArmVirtGicArchLib/ArmVirtGicArchLib.c +++ b/ArmVirtPkg/Library/ArmVirtGicArchLib/ArmVirtGicArchLib.c @@ -150,7 +150,7 @@ ArmVirtGicArchLibConstructor ( break; default: - DEBUG ((DEBUG_ERROR, "%a: No GIC revision specified!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: No GIC revision specified!\n", __func__)); return RETURN_NOT_FOUND; } diff --git a/ArmVirtPkg/Library/ArmVirtPL031FdtClientLib/ArmVirtPL031FdtClientLib.c b/ArmVirtPkg/Library/ArmVirtPL031FdtClientLib/ArmVirtPL031FdtClientLib.c index 45dd9f179c..01bcd58d30 100644 --- a/ArmVirtPkg/Library/ArmVirtPL031FdtClientLib/ArmVirtPL031FdtClientLib.c +++ b/ArmVirtPkg/Library/ArmVirtPL031FdtClientLib/ArmVirtPL031FdtClientLib.c @@ -42,7 +42,7 @@ ArmVirtPL031FdtClientLibConstructor ( DEBUG (( DEBUG_WARN, "%a: No 'arm,pl031' compatible DT node found\n", - __FUNCTION__ + __func__ )); return EFI_SUCCESS; } @@ -58,7 +58,7 @@ ArmVirtPL031FdtClientLibConstructor ( DEBUG (( DEBUG_WARN, "%a: No 'reg' property found in 'arm,pl031' compatible DT node\n", - __FUNCTION__ + __func__ )); return EFI_SUCCESS; } diff --git a/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c b/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c index c7065b7ec5..1f27b7648d 100644 --- a/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c +++ b/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c @@ -65,7 +65,7 @@ ArmPsciResetSystemLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Unknown PSCI method \"%a\"\n", - __FUNCTION__, + __func__, Prop )); return EFI_NOT_FOUND; @@ -105,7 +105,7 @@ ResetCold ( break; default: - DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __func__)); } } @@ -154,7 +154,7 @@ ResetShutdown ( break; default: - DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __func__)); } } diff --git a/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.c b/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.c index 03d14fe432..dffc1fb979 100644 --- a/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.c +++ b/ArmVirtPkg/Library/ArmVirtPsciResetSystemPeiLib/ArmVirtPsciResetSystemPeiLib.c @@ -73,7 +73,7 @@ DiscoverPsciMethod ( DEBUG (( DEBUG_ERROR, "%a: Missing PSCI method property\n", - __FUNCTION__ + __func__ )); return PsciMethodUnknown; } @@ -86,7 +86,7 @@ DiscoverPsciMethod ( DEBUG (( DEBUG_ERROR, "%a: Unknown PSCI method \"%a\"\n", - __FUNCTION__, + __func__, Prop )); return PsciMethodUnknown; @@ -119,7 +119,7 @@ PerformPsciAction ( break; default: - DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no PSCI method defined\n", __func__)); ASSERT (FALSE); } } diff --git a/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoLib.c b/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoLib.c index 28a0c0b078..98cc138705 100644 --- a/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoLib.c +++ b/ArmVirtPkg/Library/CloudHvVirtMemInfoLib/CloudHvVirtMemInfoLib.c @@ -98,7 +98,7 @@ CloudHvVirtMemInfoPeiLibConstructor ( DEBUG (( DEBUG_INFO, "%a: System RAM @ 0x%lx - 0x%lx\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1 )); @@ -124,7 +124,7 @@ CloudHvVirtMemInfoPeiLibConstructor ( DEBUG (( DEBUG_WARN, "%a: memory node larger than %d will not be included into Memory System\n", - __FUNCTION__, + __func__, CLOUDHV_MAX_MEM_NODE_NUM )); break; @@ -133,7 +133,7 @@ CloudHvVirtMemInfoPeiLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Failed to parse FDT memory node\n", - __FUNCTION__ + __func__ )); } } @@ -186,7 +186,7 @@ ArmVirtGetMemoryMap ( ); if (VirtualMemoryTable == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Error: Failed AllocatePool()\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Error: Failed AllocatePool()\n", __func__)); return; } @@ -205,7 +205,7 @@ ArmVirtGetMemoryMap ( "\tPhysicalBase: 0x%lX\n" "\tVirtualBase: 0x%lX\n" "\tLength: 0x%lX\n", - __FUNCTION__, + __func__, MemNodeIndex, VirtualMemoryTable[Index].PhysicalBase, VirtualMemoryTable[Index].VirtualBase, diff --git a/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.c b/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.c index 89eee757d1..e8d3576a71 100644 --- a/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.c +++ b/ArmVirtPkg/Library/KvmtoolRtcFdtClientLib/KvmtoolRtcFdtClientLib.c @@ -147,7 +147,7 @@ KvmtoolRtcFdtClientLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: No 'motorola,mc146818' compatible DT node found\n", - __FUNCTION__ + __func__ )); return Status; } @@ -163,7 +163,7 @@ KvmtoolRtcFdtClientLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: No 'reg' property found in 'motorola,mc146818' compatible DT node\n", - __FUNCTION__ + __func__ )); return Status; } diff --git a/ArmVirtPkg/Library/KvmtoolVirtMemInfoLib/KvmtoolVirtMemInfoLib.c b/ArmVirtPkg/Library/KvmtoolVirtMemInfoLib/KvmtoolVirtMemInfoLib.c index 29122856b6..79412897f2 100644 --- a/ArmVirtPkg/Library/KvmtoolVirtMemInfoLib/KvmtoolVirtMemInfoLib.c +++ b/ArmVirtPkg/Library/KvmtoolVirtMemInfoLib/KvmtoolVirtMemInfoLib.c @@ -54,7 +54,7 @@ ArmVirtGetMemoryMap ( DEBUG (( DEBUG_ERROR, "%a: Error: Failed to Allocate Pages\n", - __FUNCTION__ + __func__ )); return; } diff --git a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c index 129c16b711..43f5858644 100644 --- a/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c +++ b/ArmVirtPkg/Library/NorFlashKvmtoolLib/NorFlashKvmtool.c @@ -265,7 +265,7 @@ NorFlashPlatformLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: GetNodeProperty ('label') failed (Status == %r)\n", - __FUNCTION__, + __func__, Status )); } else if (AsciiStrCmp (Label, LABEL_UEFI_VAR_STORE) == 0) { @@ -284,7 +284,7 @@ NorFlashPlatformLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: GetNodeProperty () failed (Status == %r)\n", - __FUNCTION__, + __func__, Status )); continue; diff --git a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c index 55bce88bc8..d0fa7e5046 100644 --- a/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c +++ b/ArmVirtPkg/Library/NorFlashQemuLib/NorFlashQemuLib.c @@ -75,7 +75,7 @@ VirtNorFlashPlatformGetDevices ( DEBUG (( DEBUG_ERROR, "%a: GetNodeProperty () failed (Status == %r)\n", - __FUNCTION__, + __func__, Status )); continue; diff --git a/ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBm.c b/ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBm.c index 3ad1ecd9d2..10c815378c 100644 --- a/ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBm.c +++ b/ArmVirtPkg/Library/PlatformBootManagerLib/PlatformBm.c @@ -190,7 +190,7 @@ FilterAndProcess ( DEBUG (( DEBUG_VERBOSE, "%a: %g: %r\n", - __FUNCTION__, + __func__, ProtocolGuid, Status )); @@ -261,7 +261,7 @@ IsPciDisplay ( &Pci ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __func__, ReportText, Status)); return FALSE; } @@ -410,7 +410,7 @@ IsVirtioPciRng ( return FALSE; PciError: - DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __func__, ReportText, Status)); return FALSE; } @@ -437,7 +437,7 @@ Connect ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %s: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -463,7 +463,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: handle %p: device path not found\n", - __FUNCTION__, + __func__, ReportText, Handle )); @@ -475,7 +475,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ConOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -487,7 +487,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ErrOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -497,7 +497,7 @@ AddOutput ( DEBUG (( DEBUG_VERBOSE, "%a: %s: added to ConOut and ErrOut\n", - __FUNCTION__, + __func__, ReportText )); } @@ -698,7 +698,7 @@ RemoveStaleFvFileOptions ( DEBUG (( EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_VERBOSE, "%a: removing stale Boot#%04x %s: %r\n", - __FUNCTION__, + __func__, (UINT32)BootOptions[Index].OptionNumber, DevicePathString == NULL ? L"" : DevicePathString, Status @@ -878,7 +878,7 @@ PlatformBootManagerBeforeConsole ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: SetVariable(%s, %u): %r\n", - __FUNCTION__, + __func__, EFI_TIME_OUT_VARIABLE_NAME, FrontPageTimeout, Status diff --git a/ArmVirtPkg/Library/PlatformBootManagerLib/QemuKernel.c b/ArmVirtPkg/Library/PlatformBootManagerLib/QemuKernel.c index c66b7c7b21..7dc59ae14d 100644 --- a/ArmVirtPkg/Library/PlatformBootManagerLib/QemuKernel.c +++ b/ArmVirtPkg/Library/PlatformBootManagerLib/QemuKernel.c @@ -66,7 +66,7 @@ TryRunningQemuKernel ( DEBUG (( DEBUG_ERROR, "%a: QemuStartKernelImage(): %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c b/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c index bb71fee649..8d9dcf504d 100644 --- a/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c +++ b/ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c @@ -111,7 +111,7 @@ PlatformPeim ( UartBase = fdt64_to_cpu (ReadUnaligned64 (RegProp)); - DEBUG ((DEBUG_INFO, "%a: PL011 UART @ 0x%lx\n", __FUNCTION__, UartBase)); + DEBUG ((DEBUG_INFO, "%a: PL011 UART @ 0x%lx\n", __func__, UartBase)); *UartHobData = UartBase; break; @@ -148,7 +148,7 @@ PlatformPeim ( DEBUG (( DEBUG_WARN, "%a: 'ranges' property has unexpected size %d\n", - __FUNCTION__, + __func__, RangesLen )); break; @@ -175,7 +175,7 @@ PlatformPeim ( if (FeaturePcdGet (PcdTpm2SupportEnabled)) { if (TpmBase != 0) { - DEBUG ((DEBUG_INFO, "%a: TPM @ 0x%lx\n", __FUNCTION__, TpmBase)); + DEBUG ((DEBUG_INFO, "%a: TPM @ 0x%lx\n", __func__, TpmBase)); Status = (EFI_STATUS)PcdSet64S (PcdTpmBaseAddress, TpmBase); ASSERT_EFI_ERROR (Status); diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c index 9cf43f06c0..23bd0fe68e 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoLib.c @@ -83,7 +83,7 @@ ArmVirtGetMemoryMap ( ); if (VirtualMemoryTable == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Error: Failed AllocatePool()\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Error: Failed AllocatePool()\n", __func__)); return; } @@ -99,7 +99,7 @@ ArmVirtGetMemoryMap ( "\tPhysicalBase: 0x%lX\n" "\tVirtualBase: 0x%lX\n" "\tLength: 0x%lX\n", - __FUNCTION__, + __func__, VirtualMemoryTable[0].PhysicalBase, VirtualMemoryTable[0].VirtualBase, VirtualMemoryTable[0].Length diff --git a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c index c47ab82966..1bcc2e26aa 100644 --- a/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c +++ b/ArmVirtPkg/Library/QemuVirtMemInfoLib/QemuVirtMemInfoPeiLibConstructor.c @@ -64,7 +64,7 @@ QemuVirtMemInfoPeiLibConstructor ( DEBUG (( DEBUG_INFO, "%a: System RAM @ 0x%lx - 0x%lx\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1 )); @@ -77,7 +77,7 @@ QemuVirtMemInfoPeiLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Failed to parse FDT memory node\n", - __FUNCTION__ + __func__ )); } } diff --git a/ArmVirtPkg/XenAcpiPlatformDxe/XenAcpiPlatformDxe.c b/ArmVirtPkg/XenAcpiPlatformDxe/XenAcpiPlatformDxe.c index 96bc442f69..32c8b1e94e 100644 --- a/ArmVirtPkg/XenAcpiPlatformDxe/XenAcpiPlatformDxe.c +++ b/ArmVirtPkg/XenAcpiPlatformDxe/XenAcpiPlatformDxe.c @@ -68,7 +68,7 @@ GetXenArmAcpiRsdp ( DEBUG (( DEBUG_WARN, "%a: No 'xen,guest-acpi' compatible DT node found\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -140,7 +140,7 @@ InstallXenArmTables ( // Status = GetXenArmAcpiRsdp (&XenAcpiRsdpStructurePtr); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: No RSDP table found\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: No RSDP table found\n", __func__)); return Status; } diff --git a/ArmVirtPkg/XenioFdtDxe/XenioFdtDxe.c b/ArmVirtPkg/XenioFdtDxe/XenioFdtDxe.c index 23d504cc64..f626c455c4 100644 --- a/ArmVirtPkg/XenioFdtDxe/XenioFdtDxe.c +++ b/ArmVirtPkg/XenioFdtDxe/XenioFdtDxe.c @@ -49,7 +49,7 @@ InitializeXenioFdtDxe ( DEBUG (( DEBUG_WARN, "%a: No 'xen,xen' compatible DT node found\n", - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } @@ -70,7 +70,7 @@ InitializeXenioFdtDxe ( DEBUG_ERROR, "%a: XenIoMmioInstall () failed on a new handle " "(Status == %r)\n", - __FUNCTION__, + __func__, Status )); return Status; From 65d61963a55cf751e4a7c5ec5d1f040d853733c9 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:49:10 -0600 Subject: [PATCH 0849/1529] UefiCpuPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout UefiCpuPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Ray Ni Reviewed-by: Sunil V L --- UefiCpuPkg/CpuDxe/CpuDxe.c | 8 ++++---- UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c | 6 +++--- UefiCpuPkg/CpuS3DataDxe/CpuS3Data.c | 2 +- .../CpuExceptionHandlerLib.c | 2 +- .../UnitTest/CpuExceptionHandlerTestCommon.c | 2 +- UefiCpuPkg/Library/MpInitLib/DxeMpLib.c | 2 +- UefiCpuPkg/Library/MpInitLib/Microcode.c | 8 ++++---- UefiCpuPkg/Library/MpInitLib/MpLib.c | 2 +- UefiCpuPkg/Library/MpInitLib/PeiMpLib.c | 2 +- UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c | 2 +- UefiCpuPkg/SecCore/SecMain.c | 10 +++++----- .../EfiMpServicesUnitTestCommom.c | 16 ++++++++-------- .../Universal/Acpi/S3Resume2Pei/S3Resume.c | 2 +- 13 files changed, 32 insertions(+), 32 deletions(-) diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.c b/UefiCpuPkg/CpuDxe/CpuDxe.c index 3febd59d99..804ef5d1fe 100644 --- a/UefiCpuPkg/CpuDxe/CpuDxe.c +++ b/UefiCpuPkg/CpuDxe/CpuDxe.c @@ -1078,7 +1078,7 @@ IntersectMemoryDescriptor ( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, IntersectionBase, IntersectionEnd, Status @@ -1091,7 +1091,7 @@ IntersectMemoryDescriptor ( "%a: %a: desc [%Lx, %Lx) type %u cap %Lx conflicts " "with aperture [%Lx, %Lx) cap %Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length, (UINT32)Descriptor->GcdMemoryType, @@ -1132,7 +1132,7 @@ AddMemoryMappedIoSpace ( DEBUG_ERROR, "%a: %a: GetMemorySpaceMap(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return Status; @@ -1215,7 +1215,7 @@ AddLocalApicMemorySpace ( DEBUG_INFO, "%a: %a: AllocateMemorySpace() Status - %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); } diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c index 7551e06536..25fe3f54c3 100644 --- a/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c +++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxe.c @@ -296,7 +296,7 @@ CpuSetMemoryAttributes ( IN UINT64 Attributes ) { - DEBUG ((DEBUG_INFO, "%a: Set memory attributes not supported yet\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Set memory attributes not supported yet\n", __func__)); return EFI_SUCCESS; } @@ -328,10 +328,10 @@ InitializeCpu ( return EFI_NOT_FOUND; } - DEBUG ((DEBUG_INFO, " %a: Firmware Context is at 0x%x.\n", __FUNCTION__, FirmwareContext)); + DEBUG ((DEBUG_INFO, " %a: Firmware Context is at 0x%x.\n", __func__, FirmwareContext)); mBootHartId = FirmwareContext->BootHartId; - DEBUG ((DEBUG_INFO, " %a: mBootHartId = 0x%x.\n", __FUNCTION__, mBootHartId)); + DEBUG ((DEBUG_INFO, " %a: mBootHartId = 0x%x.\n", __func__, mBootHartId)); InitializeCpuExceptionHandlers (NULL); diff --git a/UefiCpuPkg/CpuS3DataDxe/CpuS3Data.c b/UefiCpuPkg/CpuS3DataDxe/CpuS3Data.c index 59a5d932ee..86ce5303ca 100644 --- a/UefiCpuPkg/CpuS3DataDxe/CpuS3Data.c +++ b/UefiCpuPkg/CpuS3DataDxe/CpuS3Data.c @@ -127,7 +127,7 @@ CpuS3DataOnEndOfDxe ( ); ASSERT_EFI_ERROR (Status); - DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a\n", __func__)); MtrrGetAllMtrrs (&AcpiCpuDataEx->MtrrTable); // diff --git a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c index bce089feb0..73a9dd5765 100644 --- a/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c +++ b/UefiCpuPkg/Library/BaseRiscV64CpuExceptionHandlerLib/CpuExceptionHandlerLib.c @@ -230,7 +230,7 @@ RegisterCpuInterruptHandler ( IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler ) { - DEBUG ((DEBUG_INFO, "%a: Type:%x Handler: %x\n", __FUNCTION__, ExceptionType, InterruptHandler)); + DEBUG ((DEBUG_INFO, "%a: Type:%x Handler: %x\n", __func__, ExceptionType, InterruptHandler)); if (EXCEPT_RISCV_IS_IRQ (ExceptionType)) { if (EXCEPT_RISCV_IRQ_INDEX (ExceptionType) > EXCEPT_RISCV_MAX_IRQS) { return EFI_UNSUPPORTED; diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c index 17afb592d3..9ba70c5b73 100644 --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c @@ -292,7 +292,7 @@ GetBspStackBase ( DEBUG (( DEBUG_INFO, "%a: Bsp StackBase = 0x%016lx StackSize = 0x%016lx\n", - __FUNCTION__, + __func__, MemoryHob->AllocDescriptor.MemoryBaseAddress, MemoryHob->AllocDescriptor.MemoryLength )); diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c index 330676b700..57ddb86600 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c @@ -463,7 +463,7 @@ MpInitChangeApLoopCallback ( ); } - DEBUG ((DEBUG_INFO, "%a() done!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() done!\n", __func__)); } /** diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index f9f070fa8b..11720560af 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -170,7 +170,7 @@ ShadowMicrocodePatchWorker ( DEBUG (( DEBUG_INFO, "%a: Required microcode patches have been loaded at 0x%lx, with size 0x%lx.\n", - __FUNCTION__, + __func__, CpuMpData->MicrocodePatchAddress, CpuMpData->MicrocodePatchRegionSize )); @@ -305,7 +305,7 @@ ShadowMicrocodePatchByPcd ( DEBUG (( DEBUG_INFO, "%a: 0x%x microcode patches will be loaded into memory, with size 0x%x.\n", - __FUNCTION__, + __func__, PatchCount, TotalLoadSize )); @@ -365,7 +365,7 @@ GetMicrocodePatchInfoFromHob ( GuidHob = GetFirstGuidHob (&gEdkiiMicrocodePatchHobGuid); if (GuidHob == NULL) { - DEBUG ((DEBUG_INFO, "%a: Microcode patch cache HOB is not found.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Microcode patch cache HOB is not found.\n", __func__)); return FALSE; } @@ -377,7 +377,7 @@ GetMicrocodePatchInfoFromHob ( DEBUG (( DEBUG_INFO, "%a: MicrocodeBase = 0x%lx, MicrocodeSize = 0x%lx\n", - __FUNCTION__, + __func__, *Address, *RegionSize )); diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index e5dc852ed9..f1f2840714 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -1537,7 +1537,7 @@ TimedWaitForApFinish ( DEBUG (( DEBUG_VERBOSE, "%a: reached FinishedApLimit=%u in %Lu microseconds\n", - __FUNCTION__, + __func__, FinishedApLimit, DivU64x64Remainder ( MultU64x32 (CpuMpData->TotalTime, 1000000), diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c index e732371ddd..013f89b197 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c @@ -758,7 +758,7 @@ PlatformShadowMicrocode ( DEBUG (( DEBUG_INFO, "%a: Required microcode patches have been loaded at 0x%lx, with size 0x%lx.\n", - __FUNCTION__, + __func__, CpuMpData->MicrocodePatchAddress, CpuMpData->MicrocodePatchRegionSize )); diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c index 240eee6a7d..0f7ee0372d 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c @@ -932,7 +932,7 @@ InitSmmS3ResumeState ( DEBUG (( DEBUG_ERROR, "ERROR:%a(): HOB(gEfiAcpiVariableGuid=%g) needed by S3 resume doesn't exist!\n", - __FUNCTION__, + __func__, &gEfiAcpiVariableGuid )); CpuDeadLoop (); diff --git a/UefiCpuPkg/SecCore/SecMain.c b/UefiCpuPkg/SecCore/SecMain.c index fe03d8019a..95375850ec 100644 --- a/UefiCpuPkg/SecCore/SecMain.c +++ b/UefiCpuPkg/SecCore/SecMain.c @@ -170,7 +170,7 @@ SecStartup ( DEBUG (( DEBUG_INFO, "%a() TempRAM Base: 0x%x, TempRAM Size: 0x%x, BootFirmwareVolume 0x%x\n", - __FUNCTION__, + __func__, TempRamBase, SizeOfRam, BootFirmwareVolume @@ -242,7 +242,7 @@ SecStartup ( DEBUG (( DEBUG_INFO, "%a() BFV Base: 0x%x, BFV Size: 0x%x, TempRAM Base: 0x%x, TempRAM Size: 0x%x, PeiTempRamBase: 0x%x, PeiTempRamSize: 0x%x, StackBase: 0x%x, StackSize: 0x%x\n", - __FUNCTION__, + __func__, SecCoreData.BootFirmwareVolumeBase, SecCoreData.BootFirmwareVolumeSize, SecCoreData.TemporaryRamBase, @@ -345,7 +345,7 @@ SecStartupPhase2 ( DEBUG (( DEBUG_INFO, "%a() PeiCoreEntryPoint: 0x%x\n", - __FUNCTION__, + __func__, PeiCoreEntryPoint )); @@ -394,7 +394,7 @@ SecStartupPhase2 ( DEBUG (( DEBUG_INFO, "%a() PeiTemporaryRamBase: 0x%x, PeiTemporaryRamSize: 0x%x\n", - __FUNCTION__, + __func__, SecCoreData->PeiTemporaryRamBase, SecCoreData->PeiTemporaryRamSize )); @@ -408,7 +408,7 @@ SecStartupPhase2 ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%p, Stack Size: 0x%x\n", - __FUNCTION__, + __func__, SecCoreData->StackBase, (UINT32)SecCoreData->StackSize )); diff --git a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c index ff79c5e8d4..7cd3f48d76 100644 --- a/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c +++ b/UefiCpuPkg/Test/UnitTest/EfiMpServicesPpiProtocol/EfiMpServicesUnitTestCommom.c @@ -45,7 +45,7 @@ InitUTContext ( Status = MpServicesUnitTestWhoAmI (LocalContext->MpServices, &BspNumber); UT_ASSERT_NOT_EFI_ERROR (Status); - DEBUG ((DEBUG_INFO, "%a: BspNumber = 0x%x\n", __FUNCTION__, BspNumber)); + DEBUG ((DEBUG_INFO, "%a: BspNumber = 0x%x\n", __func__, BspNumber)); Status = MpServicesUnitTestGetNumberOfProcessors ( LocalContext->MpServices, @@ -56,7 +56,7 @@ InitUTContext ( DEBUG (( DEBUG_INFO, "%a: NumberOfProcessors = 0x%x, NumberOfEnabledProcessors = 0x%x\n", - __FUNCTION__, + __func__, NumberOfProcessors, NumberOfEnabledProcessors )); @@ -89,7 +89,7 @@ InitUTContext ( LocalContext->DisabledApNumber[IndexOfDisabledAPs] = ProcessorNumber; IndexOfDisabledAPs++; - DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled and temporarily enable it.\n", __FUNCTION__, ProcessorNumber)); + DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled and temporarily enable it.\n", __func__, ProcessorNumber)); Status = MpServicesUnitTestEnableDisableAP ( LocalContext->MpServices, ProcessorNumber, @@ -134,7 +134,7 @@ CheckUTContext ( if (BspNumber != LocalContext->BspNumber) { LocalContext->BspNumber = BspNumber; - DEBUG ((DEBUG_INFO, "%a: New BspNumber = 0x%x\n", __FUNCTION__, BspNumber)); + DEBUG ((DEBUG_INFO, "%a: New BspNumber = 0x%x\n", __func__, BspNumber)); } ASSERT (BspNumber == LocalContext->BspNumber); @@ -148,11 +148,11 @@ CheckUTContext ( if (NumberOfProcessors != LocalContext->NumberOfProcessors) { LocalContext->NumberOfProcessors = NumberOfProcessors; - DEBUG ((DEBUG_INFO, "%a: New NumberOfProcessors = 0x%x\n", __FUNCTION__, NumberOfProcessors)); + DEBUG ((DEBUG_INFO, "%a: New NumberOfProcessors = 0x%x\n", __func__, NumberOfProcessors)); } if (NumberOfEnabledProcessors != LocalContext->NumberOfProcessors) { - DEBUG ((DEBUG_INFO, "%a: New NumberOfEnabledProcessors = 0x%x\n", __FUNCTION__, NumberOfEnabledProcessors)); + DEBUG ((DEBUG_INFO, "%a: New NumberOfEnabledProcessors = 0x%x\n", __func__, NumberOfEnabledProcessors)); for (ProcessorNumber = 0; ProcessorNumber < LocalContext->NumberOfProcessors; ProcessorNumber++) { Status = MpServicesUnitTestGetProcessorInfo ( @@ -163,7 +163,7 @@ CheckUTContext ( ASSERT_EFI_ERROR (Status); if (!(ProcessorInfoBuffer.StatusFlag & PROCESSOR_ENABLED_BIT)) { - DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled unexpectedly and reenable it.\n", __FUNCTION__, ProcessorNumber)); + DEBUG ((DEBUG_INFO, "%a: AP(0x%x) is disabled unexpectedly and reenable it.\n", __func__, ProcessorNumber)); Status = MpServicesUnitTestEnableDisableAP ( LocalContext->MpServices, ProcessorNumber, @@ -204,7 +204,7 @@ FreeUTContext ( DEBUG (( DEBUG_INFO, "%a: Disable AP(0x%x) to restore its state.\n", - __FUNCTION__, + __func__, LocalContext->DisabledApNumber[IndexOfDisabledAPs] )); diff --git a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c index e82f179569..9ea5f6f4e5 100644 --- a/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c +++ b/UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume.c @@ -509,7 +509,7 @@ S3ResumeBootOs ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%x, Stack Size: 0x%x\n", - __FUNCTION__, + __func__, TempStackTop, sizeof (TempStack) )); From 2d59a0983ea09e4ccade12a68f757d69786ad943 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:49:41 -0600 Subject: [PATCH 0850/1529] OvmfPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout OvmfPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Sunil V L --- OvmfPkg/AcpiPlatformDxe/BootScript.c | 4 +- OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c | 4 +- OvmfPkg/AcpiPlatformDxe/EntryPoint.c | 8 +-- OvmfPkg/AcpiPlatformDxe/PciDecoding.c | 10 +-- OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 64 +++++++++---------- .../BlobVerifierSevHashes.c | 18 +++--- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 2 +- OvmfPkg/Bhyve/AcpiPlatformDxe/EntryPoint.c | 8 +-- OvmfPkg/Bhyve/AcpiPlatformDxe/PciDecoding.c | 10 +-- OvmfPkg/Bhyve/BhyveRfbDxe/VbeShim.c | 6 +- OvmfPkg/Bhyve/PlatformPei/ClearCache.c | 6 +- OvmfPkg/Bhyve/PlatformPei/MemDetect.c | 12 ++-- OvmfPkg/Bhyve/PlatformPei/Platform.c | 10 +-- OvmfPkg/CpuHotplugSmm/CpuHotplug.c | 40 ++++++------ OvmfPkg/CpuHotplugSmm/QemuCpuhp.c | 32 +++++----- OvmfPkg/CpuHotplugSmm/Smbase.c | 10 +-- OvmfPkg/CpuS3DataDxe/CpuS3Data.c | 2 +- OvmfPkg/Csm/CsmSupportLib/LegacyInterrupt.c | 2 +- OvmfPkg/Csm/CsmSupportLib/LegacyRegion.c | 2 +- OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.c | 2 +- .../FdtPciHostBridgeLib/FdtPciHostBridgeLib.c | 28 ++++---- .../FdtPciPcdProducerLib.c | 4 +- OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c | 10 +-- OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.c | 10 +-- .../IncompatiblePciDeviceSupport.c | 2 +- OvmfPkg/IoMmuDxe/CcIoMmu.c | 18 +++--- OvmfPkg/IoMmuDxe/IoMmuBuffer.c | 8 +-- .../Library/AcpiTimerLib/BaseAcpiTimerLib.c | 2 +- .../AcpiTimerLib/BaseRomAcpiTimerLib.c | 4 +- .../Library/AcpiTimerLib/DxeAcpiTimerLib.c | 2 +- .../X64/PeiDxeVirtualMemory.c | 22 +++---- .../X64/SnpPageStateChangeInternal.c | 4 +- .../BaseMemEncryptTdxLib/MemoryEncryption.c | 26 ++++---- OvmfPkg/Library/BasePciCapLib/BasePciCapLib.c | 4 +- OvmfPkg/Library/CcExitLib/CcExitVeHandler.c | 18 +++--- .../GenericQemuLoadImageLib.c | 6 +- .../Library/HardwareInfoLib/HardwareInfoDxe.c | 2 +- OvmfPkg/Library/LockBoxLib/LockBoxLib.c | 10 +-- .../PciHostBridgeUtilityLib.c | 22 +++---- .../PeilessStartupLib/X64/VirtualMemory.c | 2 +- .../PlatformBmPrintScLib/StatusCodeHandler.c | 12 ++-- .../PlatformBootManagerLib/BdsPlatform.c | 12 ++-- .../PlatformBootManagerLib/QemuKernel.c | 2 +- .../PlatformBootManagerLibBhyve/BdsPlatform.c | 10 +-- .../PlatformBootManagerLibGrub/BdsPlatform.c | 10 +-- .../PlatformBootManagerLibGrub/QemuKernel.c | 2 +- OvmfPkg/Library/PlatformInitLib/MemDetect.c | 28 ++++---- OvmfPkg/Library/PlatformInitLib/Platform.c | 20 +++--- .../QemuBootOrderLib/ExtraRootBusMap.c | 2 +- .../QemuBootOrderLib/QemuBootOrderLib.c | 42 ++++++------ OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c | 18 +++--- .../Library/QemuFwCfgLib/QemuFwCfgLibMmio.c | 2 +- .../Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c | 34 +++++----- .../ResetSystemLib/DxeResetSystemLibMicrovm.c | 8 +-- .../ResetSystemLib/ResetSystemLibMicrovm.c | 8 +-- .../SerializeVariablesLib.c | 4 +- .../SmbiosVersionLib/DetectSmbiosVersionLib.c | 4 +- .../SmmCpuFeaturesLib/SmmCpuFeaturesLib.c | 4 +- .../TlsAuthConfigLib/TlsAuthConfigLib.c | 24 +++---- .../VirtioMmioDeviceLib/VirtioMmioDevice.c | 4 +- .../X86QemuLoadImageLib/X86QemuLoadImageLib.c | 8 +-- OvmfPkg/Library/XenIoMmioLib/XenIoMmioLib.c | 4 +- .../LinuxInitrdDynamicShellCommand.c | 2 +- OvmfPkg/LsiScsiDxe/LsiScsi.c | 4 +- OvmfPkg/MptScsiDxe/MptScsi.c | 10 +-- OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c | 6 +- OvmfPkg/PlatformDxe/Platform.c | 14 ++-- OvmfPkg/PlatformPei/ClearCache.c | 6 +- OvmfPkg/PlatformPei/FeatureControl.c | 6 +- OvmfPkg/PlatformPei/MemDetect.c | 12 ++-- OvmfPkg/PlatformPei/MemTypeInfo.c | 10 +-- OvmfPkg/PlatformPei/Platform.c | 18 +++--- OvmfPkg/PvScsiDxe/PvScsi.c | 4 +- .../QemuKernelLoaderFsDxe.c | 12 ++-- OvmfPkg/QemuRamfbDxe/QemuRamfb.c | 2 +- OvmfPkg/QemuVideoDxe/Gop.c | 2 +- OvmfPkg/QemuVideoDxe/Initialize.c | 14 ++-- OvmfPkg/QemuVideoDxe/VbeShim.c | 12 ++-- .../PlatformBootManagerLib/PlatformBm.c | 20 +++--- .../PlatformBootManagerLib/QemuKernel.c | 2 +- .../PrePiHobListPointer.c | 4 +- OvmfPkg/RiscVVirt/Sec/Memory.c | 10 +-- OvmfPkg/RiscVVirt/Sec/Platform.c | 12 ++-- OvmfPkg/RiscVVirt/Sec/SecMain.c | 2 +- OvmfPkg/Sec/SecMain.c | 2 +- OvmfPkg/SmmAccess/SmmAccessPei.c | 6 +- OvmfPkg/SmmControl2Dxe/SmiFeatures.c | 22 +++---- OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.c | 18 +++--- OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c | 8 +-- .../TpmMmioSevDecryptPeim.c | 6 +- OvmfPkg/TdxDxe/TdxAcpiTable.c | 2 +- OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c | 4 +- OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c | 22 +++---- OvmfPkg/VirtioBlkDxe/VirtioBlk.c | 8 +-- OvmfPkg/VirtioFsDxe/FuseFlush.c | 2 +- OvmfPkg/VirtioFsDxe/FuseFsync.c | 2 +- OvmfPkg/VirtioFsDxe/FuseGetAttr.c | 2 +- OvmfPkg/VirtioFsDxe/FuseInit.c | 2 +- OvmfPkg/VirtioFsDxe/FuseLookup.c | 2 +- OvmfPkg/VirtioFsDxe/FuseMkDir.c | 2 +- OvmfPkg/VirtioFsDxe/FuseOpen.c | 2 +- OvmfPkg/VirtioFsDxe/FuseOpenDir.c | 2 +- OvmfPkg/VirtioFsDxe/FuseOpenOrCreate.c | 2 +- OvmfPkg/VirtioFsDxe/FuseRead.c | 2 +- OvmfPkg/VirtioFsDxe/FuseRelease.c | 2 +- OvmfPkg/VirtioFsDxe/FuseRename.c | 2 +- OvmfPkg/VirtioFsDxe/FuseSetAttr.c | 2 +- OvmfPkg/VirtioFsDxe/FuseStatFs.c | 2 +- OvmfPkg/VirtioFsDxe/FuseUnlink.c | 2 +- OvmfPkg/VirtioFsDxe/FuseWrite.c | 2 +- OvmfPkg/VirtioFsDxe/Helpers.c | 2 +- OvmfPkg/VirtioFsDxe/SimpleFsOpen.c | 4 +- OvmfPkg/VirtioGpuDxe/Commands.c | 6 +- OvmfPkg/VirtioGpuDxe/DriverBinding.c | 8 +-- OvmfPkg/VirtioGpuDxe/Gop.c | 2 +- OvmfPkg/VirtioNetDxe/Events.c | 2 +- OvmfPkg/VirtioRngDxe/VirtioRng.c | 2 +- OvmfPkg/VirtioScsiDxe/VirtioScsi.c | 2 +- OvmfPkg/XenAcpiPlatformDxe/Xen.c | 2 +- OvmfPkg/XenPlatformPei/ClearCache.c | 6 +- OvmfPkg/XenPlatformPei/MemDetect.c | 6 +- OvmfPkg/XenPlatformPei/Platform.c | 2 +- OvmfPkg/XenPvBlkDxe/BlockFront.c | 4 +- 123 files changed, 540 insertions(+), 540 deletions(-) diff --git a/OvmfPkg/AcpiPlatformDxe/BootScript.c b/OvmfPkg/AcpiPlatformDxe/BootScript.c index 08d0f41bda..ff1491de0d 100644 --- a/OvmfPkg/AcpiPlatformDxe/BootScript.c +++ b/OvmfPkg/AcpiPlatformDxe/BootScript.c @@ -175,7 +175,7 @@ SaveCondensedWritePointerToS3Context ( DEBUG (( DEBUG_VERBOSE, "%a: 0x%04x/[0x%08x+%d] := 0x%Lx (%Lu)\n", - __FUNCTION__, + __func__, PointerItem, PointerOffset, PointerSize, @@ -225,7 +225,7 @@ AppendFwCfgBootScript ( } } - DEBUG ((DEBUG_VERBOSE, "%a: boot script fragment saved\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: boot script fragment saved\n", __func__)); ReleaseS3Context (S3Context); return; diff --git a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c index d56eb074a9..d3e73c155e 100644 --- a/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/CloudHvAcpi.c @@ -69,7 +69,7 @@ InstallCloudHvTablesTdx ( // then we're out of sync with the hypervisor, and cannot continue. // if (DsdtTable == NULL) { - DEBUG ((DEBUG_INFO, "%a: no DSDT found\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: no DSDT found\n", __func__)); ASSERT (FALSE); } @@ -201,7 +201,7 @@ InstallCloudHvTables ( // then we're out of sync with the hypervisor, and cannot continue. // if (DsdtTable == NULL) { - DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __func__)); ASSERT (FALSE); CpuDeadLoop (); } diff --git a/OvmfPkg/AcpiPlatformDxe/EntryPoint.c b/OvmfPkg/AcpiPlatformDxe/EntryPoint.c index 143e860fe1..17f1c4017f 100644 --- a/OvmfPkg/AcpiPlatformDxe/EntryPoint.c +++ b/OvmfPkg/AcpiPlatformDxe/EntryPoint.c @@ -46,11 +46,11 @@ OnRootBridgesConnected ( DEBUG (( DEBUG_INFO, "%a: root bridges have been connected, installing ACPI tables\n", - __FUNCTION__ + __func__ )); Status = InstallAcpiTables (FindAcpiTableProtocol ()); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: InstallAcpiTables: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: InstallAcpiTables: %r\n", __func__, Status)); } gBS->CloseEvent (Event); @@ -76,7 +76,7 @@ AcpiPlatformEntryPoint ( DEBUG_INFO, "%a: PCI or its enumeration disabled, installing " "ACPI tables\n", - __FUNCTION__ + __func__ )); return InstallAcpiTables (FindAcpiTableProtocol ()); } @@ -99,7 +99,7 @@ AcpiPlatformEntryPoint ( DEBUG (( DEBUG_INFO, "%a: waiting for root bridges to be connected, registered callback\n", - __FUNCTION__ + __func__ )); } diff --git a/OvmfPkg/AcpiPlatformDxe/PciDecoding.c b/OvmfPkg/AcpiPlatformDxe/PciDecoding.c index c178f857a2..c7dbfb1baa 100644 --- a/OvmfPkg/AcpiPlatformDxe/PciDecoding.c +++ b/OvmfPkg/AcpiPlatformDxe/PciDecoding.c @@ -78,7 +78,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: LocateHandleBuffer(): %r\n", - __FUNCTION__, + __func__, Status )); return; @@ -89,7 +89,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: AllocatePool(): out of resources\n", - __FUNCTION__ + __func__ )); goto FreeHandles; } @@ -122,7 +122,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationGet: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; @@ -141,7 +141,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationSupported: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; @@ -161,7 +161,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationEnable: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; diff --git a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c index 68abc34f22..a073b292b7 100644 --- a/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c +++ b/OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c @@ -238,7 +238,7 @@ CollectAllocationsRestrictedTo32Bit ( } if (AddPointer->PointeeFile[QEMU_LOADER_FNAME_SIZE - 1] != '\0') { - DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __func__)); Status = EFI_PROTOCOL_ERROR; goto RollBack; } @@ -253,7 +253,7 @@ CollectAllocationsRestrictedTo32Bit ( DEBUG (( DEBUG_VERBOSE, "%a: restricting blob \"%a\" from 64-bit allocation\n", - __FUNCTION__, + __func__, AddPointer->PointeeFile )); break; @@ -330,7 +330,7 @@ ProcessCmdAllocate ( BLOB *Blob; if (Allocate->File[QEMU_LOADER_FNAME_SIZE - 1] != '\0') { - DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -338,7 +338,7 @@ ProcessCmdAllocate ( DEBUG (( DEBUG_ERROR, "%a: unsupported alignment 0x%x\n", - __FUNCTION__, + __func__, Allocate->Alignment )); return EFI_UNSUPPORTED; @@ -349,7 +349,7 @@ ProcessCmdAllocate ( DEBUG (( DEBUG_ERROR, "%a: QemuFwCfgFindFile(\"%a\"): %r\n", - __FUNCTION__, + __func__, Allocate->File, Status )); @@ -392,7 +392,7 @@ ProcessCmdAllocate ( DEBUG (( DEBUG_ERROR, "%a: duplicated file \"%a\"\n", - __FUNCTION__, + __func__, Allocate->File )); Status = EFI_PROTOCOL_ERROR; @@ -410,7 +410,7 @@ ProcessCmdAllocate ( DEBUG_VERBOSE, "%a: File=\"%a\" Alignment=0x%x Zone=%d Size=0x%Lx " "Address=0x%Lx\n", - __FUNCTION__, + __func__, Allocate->File, Allocate->Alignment, Allocate->Zone, @@ -477,7 +477,7 @@ ProcessCmdAddPointer ( if ((AddPointer->PointerFile[QEMU_LOADER_FNAME_SIZE - 1] != '\0') || (AddPointer->PointeeFile[QEMU_LOADER_FNAME_SIZE - 1] != '\0')) { - DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -487,7 +487,7 @@ ProcessCmdAddPointer ( DEBUG (( DEBUG_ERROR, "%a: invalid blob reference(s) \"%a\" / \"%a\"\n", - __FUNCTION__, + __func__, AddPointer->PointerFile, AddPointer->PointeeFile )); @@ -504,7 +504,7 @@ ProcessCmdAddPointer ( DEBUG (( DEBUG_ERROR, "%a: invalid pointer location or size in \"%a\"\n", - __FUNCTION__, + __func__, AddPointer->PointerFile )); return EFI_PROTOCOL_ERROR; @@ -517,7 +517,7 @@ ProcessCmdAddPointer ( DEBUG (( DEBUG_ERROR, "%a: invalid pointer value in \"%a\"\n", - __FUNCTION__, + __func__, AddPointer->PointerFile )); return EFI_PROTOCOL_ERROR; @@ -537,7 +537,7 @@ ProcessCmdAddPointer ( DEBUG_ERROR, "%a: relocated pointer value unrepresentable in " "\"%a\"\n", - __FUNCTION__, + __func__, AddPointer->PointerFile )); return EFI_PROTOCOL_ERROR; @@ -549,7 +549,7 @@ ProcessCmdAddPointer ( DEBUG_VERBOSE, "%a: PointerFile=\"%a\" PointeeFile=\"%a\" " "PointerOffset=0x%x PointerSize=%d\n", - __FUNCTION__, + __func__, AddPointer->PointerFile, AddPointer->PointeeFile, AddPointer->PointerOffset, @@ -585,7 +585,7 @@ ProcessCmdAddChecksum ( BLOB *Blob; if (AddChecksum->File[QEMU_LOADER_FNAME_SIZE - 1] != '\0') { - DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -594,7 +594,7 @@ ProcessCmdAddChecksum ( DEBUG (( DEBUG_ERROR, "%a: invalid blob reference \"%a\"\n", - __FUNCTION__, + __func__, AddChecksum->File )); return EFI_PROTOCOL_ERROR; @@ -608,7 +608,7 @@ ProcessCmdAddChecksum ( DEBUG (( DEBUG_ERROR, "%a: invalid checksum range in \"%a\"\n", - __FUNCTION__, + __func__, AddChecksum->File )); return EFI_PROTOCOL_ERROR; @@ -622,7 +622,7 @@ ProcessCmdAddChecksum ( DEBUG_VERBOSE, "%a: File=\"%a\" ResultOffset=0x%x Start=0x%x " "Length=0x%x\n", - __FUNCTION__, + __func__, AddChecksum->File, AddChecksum->ResultOffset, AddChecksum->Start, @@ -680,7 +680,7 @@ ProcessCmdWritePointer ( if ((WritePointer->PointerFile[QEMU_LOADER_FNAME_SIZE - 1] != '\0') || (WritePointer->PointeeFile[QEMU_LOADER_FNAME_SIZE - 1] != '\0')) { - DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: malformed file name\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -694,7 +694,7 @@ ProcessCmdWritePointer ( DEBUG (( DEBUG_ERROR, "%a: invalid fw_cfg file or blob reference \"%a\" / \"%a\"\n", - __FUNCTION__, + __func__, WritePointer->PointerFile, WritePointer->PointeeFile )); @@ -710,7 +710,7 @@ ProcessCmdWritePointer ( DEBUG (( DEBUG_ERROR, "%a: invalid pointer location or size in \"%a\"\n", - __FUNCTION__, + __func__, WritePointer->PointerFile )); return EFI_PROTOCOL_ERROR; @@ -719,7 +719,7 @@ ProcessCmdWritePointer ( PointeeBlob = OrderedCollectionUserStruct (PointeeEntry); PointerValue = WritePointer->PointeeOffset; if (PointerValue >= PointeeBlob->Size) { - DEBUG ((DEBUG_ERROR, "%a: invalid PointeeOffset\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid PointeeOffset\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -736,7 +736,7 @@ ProcessCmdWritePointer ( DEBUG (( DEBUG_ERROR, "%a: pointer value unrepresentable in \"%a\"\n", - __FUNCTION__, + __func__, WritePointer->PointerFile )); return EFI_PROTOCOL_ERROR; @@ -776,7 +776,7 @@ ProcessCmdWritePointer ( DEBUG_VERBOSE, "%a: PointerFile=\"%a\" PointeeFile=\"%a\" " "PointerOffset=0x%x PointeeOffset=0x%x PointerSize=%d\n", - __FUNCTION__, + __func__, WritePointer->PointerFile, WritePointer->PointeeFile, WritePointer->PointerOffset, @@ -822,7 +822,7 @@ UndoCmdWritePointer ( DEBUG (( DEBUG_VERBOSE, "%a: PointerFile=\"%a\" PointerOffset=0x%x PointerSize=%d\n", - __FUNCTION__, + __func__, WritePointer->PointerFile, WritePointer->PointerOffset, WritePointer->PointerSize @@ -953,7 +953,7 @@ Process2ndPassCmdAddPointer ( DEBUG (( DEBUG_VERBOSE, "%a: PointerValue=0x%Lx already processed, skipping.\n", - __FUNCTION__, + __func__, PointerValue )); Status = EFI_SUCCESS; @@ -967,7 +967,7 @@ Process2ndPassCmdAddPointer ( DEBUG_VERBOSE, "%a: checking for ACPI header in \"%a\" at 0x%Lx " "(remaining: 0x%Lx): ", - __FUNCTION__, + __func__, AddPointer->PointeeFile, PointerValue, (UINT64)Blob2Remaining @@ -1042,7 +1042,7 @@ Process2ndPassCmdAddPointer ( DEBUG (( DEBUG_ERROR, "%a: can't install more than %d tables\n", - __FUNCTION__, + __func__, INSTALLED_TABLES_MAX )); Status = EFI_OUT_OF_RESOURCES; @@ -1059,7 +1059,7 @@ Process2ndPassCmdAddPointer ( DEBUG (( DEBUG_ERROR, "%a: InstallAcpiTable(): %r\n", - __FUNCTION__, + __func__, Status )); goto RollbackSeenPointer; @@ -1128,7 +1128,7 @@ InstallQemuFwCfgTables ( DEBUG (( DEBUG_ERROR, "%a: \"etc/table-loader\" has invalid size 0x%Lx\n", - __FUNCTION__, + __func__, (UINT64)FwCfgSize )); return EFI_PROTOCOL_ERROR; @@ -1236,7 +1236,7 @@ InstallQemuFwCfgTables ( DEBUG (( DEBUG_VERBOSE, "%a: unknown loader command: 0x%x\n", - __FUNCTION__, + __func__, LoaderEntry->Type )); break; @@ -1311,7 +1311,7 @@ InstallQemuFwCfgTables ( S3Context = NULL; } - DEBUG ((DEBUG_INFO, "%a: installed %d tables\n", __FUNCTION__, Installed)); + DEBUG ((DEBUG_INFO, "%a: installed %d tables\n", __func__, Installed)); UninstallQemuAcpiTableNotifyProtocol: if (EFI_ERROR (Status)) { @@ -1380,7 +1380,7 @@ InstallQemuFwCfgTables ( DEBUG (( DEBUG_VERBOSE, "%a: freeing \"%a\"\n", - __FUNCTION__, + __func__, Blob->File )); gBS->FreePages ((UINTN)Blob->Base, EFI_SIZE_TO_PAGES (Blob->Size)); diff --git a/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c b/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c index 65f040f947..2e58794c3c 100644 --- a/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c +++ b/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c @@ -101,7 +101,7 @@ VerifyBlob ( DEBUG (( DEBUG_ERROR, "%a: Verifier called but no hashes table discoverd in MEMFD\n", - __FUNCTION__ + __func__ )); return EFI_ACCESS_DENIED; } @@ -111,7 +111,7 @@ VerifyBlob ( DEBUG (( DEBUG_ERROR, "%a: Unknown blob name \"%s\"\n", - __FUNCTION__, + __func__, BlobName )); return EFI_ACCESS_DENIED; @@ -134,14 +134,14 @@ VerifyBlob ( continue; } - DEBUG ((DEBUG_INFO, "%a: Found GUID %g in table\n", __FUNCTION__, Guid)); + DEBUG ((DEBUG_INFO, "%a: Found GUID %g in table\n", __func__, Guid)); EntrySize = Entry->Len - sizeof Entry->Guid - sizeof Entry->Len; if (EntrySize != SHA256_DIGEST_SIZE) { DEBUG (( DEBUG_ERROR, "%a: Hash has the wrong size %d != %d\n", - __FUNCTION__, + __func__, EntrySize, SHA256_DIGEST_SIZE )); @@ -159,7 +159,7 @@ VerifyBlob ( DEBUG (( DEBUG_INFO, "%a: Hash comparison succeeded for \"%s\"\n", - __FUNCTION__, + __func__, BlobName )); } else { @@ -167,7 +167,7 @@ VerifyBlob ( DEBUG (( DEBUG_ERROR, "%a: Hash comparison failed for \"%s\"\n", - __FUNCTION__, + __func__, BlobName )); } @@ -178,7 +178,7 @@ VerifyBlob ( DEBUG (( DEBUG_ERROR, "%a: Hash GUID %g not found in table\n", - __FUNCTION__, + __func__, Guid )); return EFI_ACCESS_DENIED; @@ -218,7 +218,7 @@ BlobVerifierLibSevHashesConstructor ( DEBUG (( DEBUG_INFO, "%a: Found injected hashes table in secure location\n", - __FUNCTION__ + __func__ )); mHashesTable = (HASH_TABLE *)Ptr->Data; @@ -227,7 +227,7 @@ BlobVerifierLibSevHashesConstructor ( DEBUG (( DEBUG_VERBOSE, "%a: mHashesTable=0x%p, Size=%u\n", - __FUNCTION__, + __func__, mHashesTable, mHashesTableSize )); diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 9b0d0e92b6..05b728d32a 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -276,7 +276,7 @@ AmdSevDxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: MemEncryptSevClearPageEncMask(): %r\n", - __FUNCTION__, + __func__, Status )); ASSERT (FALSE); diff --git a/OvmfPkg/Bhyve/AcpiPlatformDxe/EntryPoint.c b/OvmfPkg/Bhyve/AcpiPlatformDxe/EntryPoint.c index b6ef101b2a..23d1856ad5 100644 --- a/OvmfPkg/Bhyve/AcpiPlatformDxe/EntryPoint.c +++ b/OvmfPkg/Bhyve/AcpiPlatformDxe/EntryPoint.c @@ -41,11 +41,11 @@ OnRootBridgesConnected ( DEBUG (( DEBUG_INFO, "%a: root bridges have been connected, installing ACPI tables\n", - __FUNCTION__ + __func__ )); Status = InstallAcpiTables (FindAcpiTableProtocol ()); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: InstallAcpiTables: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: InstallAcpiTables: %r\n", __func__, Status)); } gBS->CloseEvent (Event); @@ -71,7 +71,7 @@ AcpiPlatformEntryPoint ( DEBUG_INFO, "%a: PCI or its enumeration disabled, installing " "ACPI tables\n", - __FUNCTION__ + __func__ )); return InstallAcpiTables (FindAcpiTableProtocol ()); } @@ -94,7 +94,7 @@ AcpiPlatformEntryPoint ( DEBUG (( DEBUG_INFO, "%a: waiting for root bridges to be connected, registered callback\n", - __FUNCTION__ + __func__ )); } diff --git a/OvmfPkg/Bhyve/AcpiPlatformDxe/PciDecoding.c b/OvmfPkg/Bhyve/AcpiPlatformDxe/PciDecoding.c index d31fd65393..0dcf3517f1 100644 --- a/OvmfPkg/Bhyve/AcpiPlatformDxe/PciDecoding.c +++ b/OvmfPkg/Bhyve/AcpiPlatformDxe/PciDecoding.c @@ -76,7 +76,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: LocateHandleBuffer(): %r\n", - __FUNCTION__, + __func__, Status )); return; @@ -87,7 +87,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: AllocatePool(): out of resources\n", - __FUNCTION__ + __func__ )); goto FreeHandles; } @@ -120,7 +120,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationGet: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; @@ -139,7 +139,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationSupported: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; @@ -159,7 +159,7 @@ EnablePciDecoding ( DEBUG (( DEBUG_WARN, "%a: EfiPciIoAttributeOperationEnable: %r\n", - __FUNCTION__, + __func__, Status )); goto RestoreAttributes; diff --git a/OvmfPkg/Bhyve/BhyveRfbDxe/VbeShim.c b/OvmfPkg/Bhyve/BhyveRfbDxe/VbeShim.c index 41f0180001..ea7a364d85 100644 --- a/OvmfPkg/Bhyve/BhyveRfbDxe/VbeShim.c +++ b/OvmfPkg/Bhyve/BhyveRfbDxe/VbeShim.c @@ -147,7 +147,7 @@ InstallVbeShim ( DEBUG (( DEBUG_VERBOSE, "%a: Video BIOS handler found at %04x:%04x\n", - __FUNCTION__, + __func__, Int0x10->Segment, Int0x10->Offset )); @@ -161,7 +161,7 @@ InstallVbeShim ( DEBUG (( DEBUG_VERBOSE, "%a: failed to allocate page at zero: %r\n", - __FUNCTION__, + __func__, Status )); } else { @@ -271,7 +271,7 @@ InstallVbeShim ( DEBUG (( DEBUG_INFO, "%a: VBE shim installed to %x:%x\n", - __FUNCTION__, + __func__, Int0x10->Segment, Int0x10->Offset )); diff --git a/OvmfPkg/Bhyve/PlatformPei/ClearCache.c b/OvmfPkg/Bhyve/PlatformPei/ClearCache.c index 9f23f9a428..9e59f31df7 100644 --- a/OvmfPkg/Bhyve/PlatformPei/ClearCache.c +++ b/OvmfPkg/Bhyve/PlatformPei/ClearCache.c @@ -59,7 +59,7 @@ ClearCacheOnMpServicesAvailable ( EFI_PEI_MP_SERVICES_PPI *MpServices; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __func__)); // // Clear cache on all the APs in parallel. @@ -74,7 +74,7 @@ ClearCacheOnMpServicesAvailable ( NULL // ProcedureArgument ); if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) { - DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __func__, Status)); return Status; } @@ -108,7 +108,7 @@ InstallClearCacheCallback ( DEBUG (( DEBUG_ERROR, "%a: failed to set up MP Services callback: %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/Bhyve/PlatformPei/MemDetect.c b/OvmfPkg/Bhyve/PlatformPei/MemDetect.c index 1949e586a0..29cbb9e3dc 100644 --- a/OvmfPkg/Bhyve/PlatformPei/MemDetect.c +++ b/OvmfPkg/Bhyve/PlatformPei/MemDetect.c @@ -58,7 +58,7 @@ Q35TsegMbytesInitialization ( DEBUG_ERROR, "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; " "only DID=0x%04x (Q35) is supported\n", - __FUNCTION__, + __func__, mHostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); @@ -92,7 +92,7 @@ Q35TsegMbytesInitialization ( DEBUG (( DEBUG_INFO, "%a: QEMU offers an extended TSEG (%d MB)\n", - __FUNCTION__, + __func__, ExtendedTsegMbytes )); PcdStatus = PcdSet16S (PcdQ35TsegMbytes, ExtendedTsegMbytes); @@ -185,7 +185,7 @@ GetFirstNonAddress ( DEBUG (( DEBUG_INFO, "%a: disabling 64-bit PCI host aperture\n", - __FUNCTION__ + __func__ )); PcdStatus = PcdSet64S (PcdPciMmio64Size, 0); ASSERT_RETURN_ERROR (PcdStatus); @@ -228,7 +228,7 @@ GetFirstNonAddress ( DEBUG (( DEBUG_INFO, "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n", - __FUNCTION__, + __func__, Pci64Base, Pci64Size )); @@ -392,7 +392,7 @@ PublishPeiMemory ( DEBUG (( DEBUG_INFO, "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n", - __FUNCTION__, + __func__, mPhysMemAddressWidth, PeiMemoryCap >> 10 )); @@ -441,7 +441,7 @@ QemuInitializeRam ( MTRR_SETTINGS MtrrSettings; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a called\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a called\n", __func__)); // // Determine total memory size available diff --git a/OvmfPkg/Bhyve/PlatformPei/Platform.c b/OvmfPkg/Bhyve/PlatformPei/Platform.c index eba7c60fce..2523e49e36 100644 --- a/OvmfPkg/Bhyve/PlatformPei/Platform.c +++ b/OvmfPkg/Bhyve/PlatformPei/Platform.c @@ -373,7 +373,7 @@ MiscInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, mHostBridgeDevId )); ASSERT (FALSE); @@ -501,17 +501,17 @@ S3Verification ( DEBUG (( DEBUG_ERROR, "%a: S3Resume2Pei doesn't support X64 PEI + SMM yet.\n", - __FUNCTION__ + __func__ )); DEBUG (( DEBUG_ERROR, "%a: Please disable S3 on the QEMU command line (see the README),\n", - __FUNCTION__ + __func__ )); DEBUG (( DEBUG_ERROR, "%a: or build OVMF with \"OvmfPkgIa32X64.dsc\".\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); CpuDeadLoop (); @@ -558,7 +558,7 @@ MaxCpuCountInitialization ( DEBUG (( DEBUG_INFO, "%a: QEMU reports %d processor(s)\n", - __FUNCTION__, + __func__, ProcessorCount )); } diff --git a/OvmfPkg/CpuHotplugSmm/CpuHotplug.c b/OvmfPkg/CpuHotplugSmm/CpuHotplug.c index 97ecd32eb6..d504163026 100644 --- a/OvmfPkg/CpuHotplugSmm/CpuHotplug.c +++ b/OvmfPkg/CpuHotplugSmm/CpuHotplug.c @@ -135,7 +135,7 @@ ProcessHotAddedCpus ( DEBUG_VERBOSE, "%a: APIC ID " FMT_APIC_ID " was hot-plugged " "before; ignoring it\n", - __FUNCTION__, + __func__, NewApicId )); PluggedIdx++; @@ -155,7 +155,7 @@ ProcessHotAddedCpus ( DEBUG (( DEBUG_ERROR, "%a: no room for APIC ID " FMT_APIC_ID "\n", - __FUNCTION__, + __func__, NewApicId )); return EFI_OUT_OF_RESOURCES; @@ -190,7 +190,7 @@ ProcessHotAddedCpus ( DEBUG (( DEBUG_ERROR, "%a: AddProcessor(" FMT_APIC_ID "): %r\n", - __FUNCTION__, + __func__, NewApicId, Status )); @@ -201,7 +201,7 @@ ProcessHotAddedCpus ( DEBUG_INFO, "%a: hot-added APIC ID " FMT_APIC_ID ", SMBASE 0x%Lx, " "EFI_SMM_CPU_SERVICE_PROTOCOL assigned number %Lu\n", - __FUNCTION__, + __func__, NewApicId, (UINT64)mCpuHotPlugData->SmBase[NewSlot], (UINT64)NewProcessorNumberByProtocol @@ -310,7 +310,7 @@ EjectCpu ( DEBUG_INFO, "%a: Unplugged ProcessorNum %u, " "QemuSelector %Lu\n", - __FUNCTION__, + __func__, Idx, QemuSelector )); @@ -454,7 +454,7 @@ UnplugCpus ( DEBUG_VERBOSE, "%a: did not find APIC ID " FMT_APIC_ID " to unplug\n", - __FUNCTION__, + __func__, RemoveApicId )); ToUnplugIdx++; @@ -469,7 +469,7 @@ UnplugCpus ( DEBUG (( DEBUG_ERROR, "%a: RemoveProcessor(" FMT_APIC_ID "): %r\n", - __FUNCTION__, + __func__, RemoveApicId, Status )); @@ -493,7 +493,7 @@ UnplugCpus ( DEBUG_ERROR, "%a: ProcessorNum %Lu maps to QemuSelector %Lu, " "cannot also map to %u\n", - __FUNCTION__, + __func__, (UINT64)ProcessorNum, mCpuHotEjectData->QemuSelectorMap[ProcessorNum], QemuSelector @@ -511,7 +511,7 @@ UnplugCpus ( DEBUG_INFO, "%a: Started hot-unplug on ProcessorNum %Lu, APIC ID " FMT_APIC_ID ", QemuSelector %u\n", - __FUNCTION__, + __func__, (UINT64)ProcessorNum, RemoveApicId, QemuSelector @@ -635,7 +635,7 @@ CpuHotplugMmi ( DEBUG (( DEBUG_ERROR, "%a: failed to read ICH9_APM_CNT: %r\n", - __FUNCTION__, + __func__, Status )); // @@ -736,7 +736,7 @@ CpuHotplugEntry ( (VOID **)&mMmCpuIo ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: locate MmCpuIo: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: locate MmCpuIo: %r\n", __func__, Status)); goto Fatal; } @@ -749,7 +749,7 @@ CpuHotplugEntry ( DEBUG (( DEBUG_ERROR, "%a: locate MmCpuService: %r\n", - __FUNCTION__, + __func__, Status )); goto Fatal; @@ -767,7 +767,7 @@ CpuHotplugEntry ( if (mCpuHotPlugData == NULL) { Status = EFI_NOT_FOUND; - DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_PLUG_DATA: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_PLUG_DATA: %r\n", __func__, Status)); goto Fatal; } @@ -787,7 +787,7 @@ CpuHotplugEntry ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_EJECT_DATA: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: CPU_HOT_EJECT_DATA: %r\n", __func__, Status)); goto Fatal; } @@ -799,7 +799,7 @@ CpuHotplugEntry ( RETURN_ERROR (SafeUintnMult (sizeof (UINT32), Len, &SizeSel))) { Status = EFI_ABORTED; - DEBUG ((DEBUG_ERROR, "%a: invalid CPU_HOT_PLUG_DATA\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid CPU_HOT_PLUG_DATA\n", __func__)); goto Fatal; } @@ -809,7 +809,7 @@ CpuHotplugEntry ( (VOID **)&mPluggedApicIds ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __func__, Status)); goto Fatal; } @@ -819,7 +819,7 @@ CpuHotplugEntry ( (VOID **)&mToUnplugApicIds ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __func__, Status)); goto ReleasePluggedApicIds; } @@ -829,7 +829,7 @@ CpuHotplugEntry ( (VOID **)&mToUnplugSelectors ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: MmAllocatePool(): %r\n", __func__, Status)); goto ReleaseToUnplugApicIds; } @@ -874,7 +874,7 @@ CpuHotplugEntry ( DEBUG (( DEBUG_ERROR, "%a: modern CPU hotplug interface: %r\n", - __FUNCTION__, + __func__, Status )); goto ReleasePostSmmPen; @@ -892,7 +892,7 @@ CpuHotplugEntry ( DEBUG (( DEBUG_ERROR, "%a: MmiHandlerRegister(): %r\n", - __FUNCTION__, + __func__, Status )); goto ReleasePostSmmPen; diff --git a/OvmfPkg/CpuHotplugSmm/QemuCpuhp.c b/OvmfPkg/CpuHotplugSmm/QemuCpuhp.c index ec3dc379f3..1687dada4c 100644 --- a/OvmfPkg/CpuHotplugSmm/QemuCpuhp.c +++ b/OvmfPkg/CpuHotplugSmm/QemuCpuhp.c @@ -36,7 +36,7 @@ QemuCpuhpReadCommandData2 ( &CommandData2 ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -61,7 +61,7 @@ QemuCpuhpReadCpuStatus ( &CpuStatus ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -86,7 +86,7 @@ QemuCpuhpReadCommandData ( &CommandData ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -110,7 +110,7 @@ QemuCpuhpWriteCpuSelector ( &Selector ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -132,7 +132,7 @@ QemuCpuhpWriteCpuStatus ( &CpuStatus ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -154,7 +154,7 @@ QemuCpuhpWriteCommand ( &Command ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); ASSERT (FALSE); CpuDeadLoop (); } @@ -266,7 +266,7 @@ QemuCpuhpCollectApicIds ( DEBUG_VERBOSE, "%a: CurrentSelector=%u PendingSelector=%u: " "wrap-around\n", - __FUNCTION__, + __func__, CurrentSelector, PendingSelector )); @@ -291,7 +291,7 @@ QemuCpuhpCollectApicIds ( DEBUG_ERROR, "%a: CurrentSelector=%u CpuStatus=0x%x: " "inconsistent CPU status\n", - __FUNCTION__, + __func__, CurrentSelector, CpuStatus )); @@ -301,7 +301,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: CurrentSelector=%u: insert\n", - __FUNCTION__, + __func__, CurrentSelector )); @@ -317,7 +317,7 @@ QemuCpuhpCollectApicIds ( DEBUG_ERROR, "%a: CurrentSelector=%u CpuStatus=0x%x: " "inconsistent CPU status\n", - __FUNCTION__, + __func__, CurrentSelector, CpuStatus )); @@ -327,7 +327,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: CurrentSelector=%u: fw_remove\n", - __FUNCTION__, + __func__, CurrentSelector )); @@ -341,7 +341,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: CurrentSelector=%u: remove (ignored)\n", - __FUNCTION__, + __func__, CurrentSelector )); @@ -352,7 +352,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: CurrentSelector=%u: no event\n", - __FUNCTION__, + __func__, CurrentSelector )); break; @@ -368,7 +368,7 @@ QemuCpuhpCollectApicIds ( // For unplug events, also save the CurrentSelector. // if (*ExtendCount == ApicIdCount) { - DEBUG ((DEBUG_ERROR, "%a: APIC ID array too small\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: APIC ID array too small\n", __func__)); return EFI_BUFFER_TOO_SMALL; } @@ -377,7 +377,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: ApicId=" FMT_APIC_ID "\n", - __FUNCTION__, + __func__, NewApicId )); if (ExtendSels != NULL) { @@ -399,7 +399,7 @@ QemuCpuhpCollectApicIds ( DEBUG (( DEBUG_VERBOSE, "%a: PluggedCount=%u ToUnplugCount=%u\n", - __FUNCTION__, + __func__, *PluggedCount, *ToUnplugCount )); diff --git a/OvmfPkg/CpuHotplugSmm/Smbase.c b/OvmfPkg/CpuHotplugSmm/Smbase.c index 5d50605893..dc6f4f4b49 100644 --- a/OvmfPkg/CpuHotplugSmm/Smbase.c +++ b/OvmfPkg/CpuHotplugSmm/Smbase.c @@ -62,7 +62,7 @@ SmbaseAllocatePostSmmPen ( DEBUG (( DEBUG_ERROR, "%a: mPostSmmPenSize=%u: %r\n", - __FUNCTION__, + __func__, mPostSmmPenSize, Status )); @@ -77,11 +77,11 @@ SmbaseAllocatePostSmmPen ( &Address ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: AllocatePages(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: AllocatePages(): %r\n", __func__, Status)); return Status; } - DEBUG ((DEBUG_INFO, "%a: Post-SMM Pen at 0x%Lx\n", __FUNCTION__, Address)); + DEBUG ((DEBUG_INFO, "%a: Post-SMM Pen at 0x%Lx\n", __func__, Address)); *PenAddress = (UINT32)Address; return EFI_SUCCESS; } @@ -211,7 +211,7 @@ SmbaseRelocate ( DEBUG (( DEBUG_ERROR, "%a: ApicId=" FMT_APIC_ID " Smbase=0x%Lx: %r\n", - __FUNCTION__, + __func__, ApicId, (UINT64)Smbase, Status @@ -289,7 +289,7 @@ SmbaseRelocate ( DEBUG (( DEBUG_ERROR, "%a: ApicId=" FMT_APIC_ID " ApicIdGate=0x%Lx: %r\n", - __FUNCTION__, + __func__, ApicId, ExchangeResult, Status diff --git a/OvmfPkg/CpuS3DataDxe/CpuS3Data.c b/OvmfPkg/CpuS3DataDxe/CpuS3Data.c index c192a09cf1..289048b75d 100644 --- a/OvmfPkg/CpuS3DataDxe/CpuS3Data.c +++ b/OvmfPkg/CpuS3DataDxe/CpuS3Data.c @@ -127,7 +127,7 @@ CpuS3DataOnEndOfDxe ( ); ASSERT_EFI_ERROR (Status); - DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a\n", __func__)); MtrrGetAllMtrrs (&AcpiCpuDataEx->MtrrTable); // diff --git a/OvmfPkg/Csm/CsmSupportLib/LegacyInterrupt.c b/OvmfPkg/Csm/CsmSupportLib/LegacyInterrupt.c index 5bed2e2b51..410e4e457d 100644 --- a/OvmfPkg/Csm/CsmSupportLib/LegacyInterrupt.c +++ b/OvmfPkg/Csm/CsmSupportLib/LegacyInterrupt.c @@ -190,7 +190,7 @@ LegacyInterruptInstall ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Csm/CsmSupportLib/LegacyRegion.c b/OvmfPkg/Csm/CsmSupportLib/LegacyRegion.c index 4969c88dc3..3c32b75bd6 100644 --- a/OvmfPkg/Csm/CsmSupportLib/LegacyRegion.c +++ b/OvmfPkg/Csm/CsmSupportLib/LegacyRegion.c @@ -484,7 +484,7 @@ LegacyRegionInit ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.c b/OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.c index 094e4c821b..88b6bafee8 100644 --- a/OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.c +++ b/OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.c @@ -393,7 +393,7 @@ EnrollListOfCerts ( if (EFI_ERROR (Status)) { AsciiPrint ( "error: %a(\"%s\", %g): %r\n", - __FUNCTION__, + __func__, VariableName, VendorGuid, Status diff --git a/OvmfPkg/Fdt/FdtPciHostBridgeLib/FdtPciHostBridgeLib.c b/OvmfPkg/Fdt/FdtPciHostBridgeLib/FdtPciHostBridgeLib.c index 14b41a533e..0d116f60dd 100644 --- a/OvmfPkg/Fdt/FdtPciHostBridgeLib/FdtPciHostBridgeLib.c +++ b/OvmfPkg/Fdt/FdtPciHostBridgeLib/FdtPciHostBridgeLib.c @@ -61,7 +61,7 @@ MapGcdMmioSpace ( DEBUG (( DEBUG_ERROR, "%a: failed to add GCD memory space for region [0x%Lx+0x%Lx)\n", - __FUNCTION__, + __func__, Base, Size )); @@ -73,7 +73,7 @@ MapGcdMmioSpace ( DEBUG (( DEBUG_ERROR, "%a: failed to set memory space attributes for region [0x%Lx+0x%Lx)\n", - __FUNCTION__, + __func__, Base, Size )); @@ -143,7 +143,7 @@ ProcessPciHost ( DEBUG (( DEBUG_INFO, "%a: No 'pci-host-ecam-generic' compatible DT node found\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -169,7 +169,7 @@ ProcessPciHost ( DEBUG (( DEBUG_ERROR, "%a: 'reg' property not found or invalid\n", - __FUNCTION__ + __func__ )); return EFI_PROTOCOL_ERROR; } @@ -194,7 +194,7 @@ ProcessPciHost ( DEBUG (( DEBUG_ERROR, "%a: 'bus-range' not found or invalid\n", - __FUNCTION__ + __func__ )); return EFI_PROTOCOL_ERROR; } @@ -212,7 +212,7 @@ ProcessPciHost ( DEBUG (( DEBUG_ERROR, "%a: invalid 'bus-range' and/or 'reg'\n", - __FUNCTION__ + __func__ )); return EFI_PROTOCOL_ERROR; } @@ -224,7 +224,7 @@ ProcessPciHost ( if (EFI_ERROR (Status) || (Len == 0) || (Len % sizeof (DTB_PCI_HOST_RANGE_RECORD) != 0)) { - DEBUG ((DEBUG_ERROR, "%a: 'ranges' not found or invalid\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: 'ranges' not found or invalid\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -251,7 +251,7 @@ ProcessPciHost ( if ((*Mmio32Base > MAX_UINT32) || (*Mmio32Size > MAX_UINT32) || (*Mmio32Base + *Mmio32Size > SIZE_4GB)) { - DEBUG ((DEBUG_ERROR, "%a: MMIO32 space invalid\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: MMIO32 space invalid\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -262,7 +262,7 @@ ProcessPciHost ( DEBUG_ERROR, "%a: unsupported nonzero MMIO32 translation " "0x%Lx\n", - __FUNCTION__, + __func__, Mmio32Translation )); return EFI_UNSUPPORTED; @@ -282,7 +282,7 @@ ProcessPciHost ( DEBUG_ERROR, "%a: unsupported nonzero MMIO64 translation " "0x%Lx\n", - __FUNCTION__, + __func__, Mmio64Translation )); return EFI_UNSUPPORTED; @@ -293,7 +293,7 @@ ProcessPciHost ( } if (*Mmio32Size == 0) { - DEBUG ((DEBUG_ERROR, "%a: MMIO32 space empty\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: MMIO32 space empty\n", __func__)); return EFI_PROTOCOL_ERROR; } @@ -307,7 +307,7 @@ ProcessPciHost ( DEBUG_INFO, "%a: Config[0x%Lx+0x%Lx) Bus[0x%x..0x%x] " "Io[0x%Lx+0x%Lx)@0x%Lx Mem32[0x%Lx+0x%Lx)@0x0 Mem64[0x%Lx+0x%Lx)@0x0\n", - __FUNCTION__, + __func__, ConfigBase, ConfigSize, *BusMin, @@ -370,7 +370,7 @@ PciHostBridgeGetRootBridges ( PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; if (PcdGet64 (PcdPciExpressBaseAddress) == 0) { - DEBUG ((DEBUG_INFO, "%a: PCI host bridge not present\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: PCI host bridge not present\n", __func__)); *Count = 0; return NULL; @@ -390,7 +390,7 @@ PciHostBridgeGetRootBridges ( DEBUG (( DEBUG_ERROR, "%a: failed to discover PCI host bridge: %r\n", - __FUNCTION__, + __func__, Status )); *Count = 0; diff --git a/OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.c b/OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.c index b5a6718146..a3b09e547f 100644 --- a/OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.c +++ b/OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.c @@ -58,7 +58,7 @@ GetPciIoTranslation ( if (EFI_ERROR (Status) || (Len == 0) || (Len % sizeof (DTB_PCI_HOST_RANGE_RECORD) != 0)) { - DEBUG ((DEBUG_ERROR, "%a: 'ranges' not found or invalid\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: 'ranges' not found or invalid\n", __func__)); return RETURN_PROTOCOL_ERROR; } @@ -152,7 +152,7 @@ FdtPciPcdProducerLibConstructor ( DEBUG (( DEBUG_WARN, "%a: 'pci-host-ecam-generic' device encountered with no I/O range\n", - __FUNCTION__ + __func__ )); } } diff --git a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c index 87bc8b6827..779bf5c827 100644 --- a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c +++ b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c @@ -93,7 +93,7 @@ InitializeHighMemDxe ( DEBUG (( DEBUG_WARN, "%a: Region 0x%lx - 0x%lx not found in the GCD memory space map\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1 )); @@ -112,7 +112,7 @@ InitializeHighMemDxe ( DEBUG (( DEBUG_ERROR, "%a: Failed to add System RAM @ 0x%lx - 0x%lx (%r)\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1, Status @@ -129,7 +129,7 @@ InitializeHighMemDxe ( DEBUG (( DEBUG_WARN, "%a: gDS->SetMemorySpaceAttributes() failed on region 0x%lx - 0x%lx (%r)\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1, Status @@ -160,7 +160,7 @@ InitializeHighMemDxe ( DEBUG (( DEBUG_ERROR, "%a: Failed to set System RAM @ 0x%lx - 0x%lx attribute (%r)\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1, Status @@ -169,7 +169,7 @@ InitializeHighMemDxe ( DEBUG (( DEBUG_INFO, "%a: Add System RAM @ 0x%lx - 0x%lx\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1 )); diff --git a/OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.c b/OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.c index 619740e6e7..668090dbea 100644 --- a/OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.c +++ b/OvmfPkg/Fdt/VirtioFdtDxe/VirtioFdtDxe.c @@ -75,7 +75,7 @@ InitializeVirtioFdtDxe ( DEBUG (( DEBUG_ERROR, "%a: GetNodeProperty () failed (Status == %r)\n", - __FUNCTION__, + __func__, Status )); continue; @@ -93,7 +93,7 @@ InitializeVirtioFdtDxe ( sizeof (VIRTIO_TRANSPORT_DEVICE_PATH) ); if (DevicePath == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Out of memory\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Out of memory\n", __func__)); continue; } @@ -117,7 +117,7 @@ InitializeVirtioFdtDxe ( DEBUG_ERROR, "%a: Failed to install the EFI_DEVICE_PATH " "protocol on a new handle (Status == %r)\n", - __FUNCTION__, + __func__, Status )); FreePool (DevicePath); @@ -130,7 +130,7 @@ InitializeVirtioFdtDxe ( DEBUG_ERROR, "%a: Failed to install VirtIO transport @ 0x%Lx " "on handle %p (Status == %r)\n", - __FUNCTION__, + __func__, RegBase, Handle, Status @@ -152,7 +152,7 @@ InitializeVirtioFdtDxe ( DEBUG_ERROR, "%a: Error occurred while iterating DT nodes " "(FindNodeStatus == %r)\n", - __FUNCTION__, + __func__, FindNodeStatus )); } diff --git a/OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c b/OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c index 686d85633e..3092a174bc 100644 --- a/OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c +++ b/OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c @@ -275,7 +275,7 @@ CheckDevice ( DEBUG (( DEBUG_WARN, "%a: 64-bit MMIO BARs may be degraded for PCI 0x%04x:0x%04x (rev %d)\n", - __FUNCTION__, + __func__, (UINT32)VendorId, (UINT32)DeviceId, (UINT8)RevisionId diff --git a/OvmfPkg/IoMmuDxe/CcIoMmu.c b/OvmfPkg/IoMmuDxe/CcIoMmu.c index 7c2843cd23..b83a969006 100644 --- a/OvmfPkg/IoMmuDxe/CcIoMmu.c +++ b/OvmfPkg/IoMmuDxe/CcIoMmu.c @@ -92,7 +92,7 @@ IoMmuMap ( DEBUG (( DEBUG_VERBOSE, "%a: Operation=%a Host=0x%p Bytes=0x%Lx\n", - __FUNCTION__, + __func__, ((Operation >= 0 && Operation < ARRAY_SIZE (mBusMasterOperationName)) ? mBusMasterOperationName[Operation] : @@ -289,7 +289,7 @@ IoMmuMap ( DEBUG (( DEBUG_VERBOSE, "%a: Mapping=0x%p Device(PlainText)=0x%Lx Crypted=0x%Lx Pages=0x%Lx, ReservedMemBitmap=0x%Lx\n", - __FUNCTION__, + __func__, MapInfo, MapInfo->PlainTextAddress, MapInfo->CryptedAddress, @@ -342,7 +342,7 @@ IoMmuUnmapWorker ( DEBUG (( DEBUG_VERBOSE, "%a: Mapping=0x%p MemoryMapLocked=%d\n", - __FUNCTION__, + __func__, Mapping, MemoryMapLocked )); @@ -537,7 +537,7 @@ IoMmuAllocateBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: MemoryType=%u Pages=0x%Lx Attributes=0x%Lx\n", - __FUNCTION__, + __func__, (UINT32)MemoryType, (UINT64)Pages, Attributes @@ -625,7 +625,7 @@ IoMmuAllocateBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: Host=0x%Lx Stash=0x%p\n", - __FUNCTION__, + __func__, PhysicalAddress, StashBuffer )); @@ -663,7 +663,7 @@ IoMmuFreeBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: Host=0x%p Pages=0x%Lx\n", - __FUNCTION__, + __func__, HostAddress, (UINT64)Pages )); @@ -818,7 +818,7 @@ IoMmuExitBoot ( // queue EventToSignal's NotifyFunction after the NotifyFunctions of *all* // events in EFI_EVENT_GROUP_EXIT_BOOT_SERVICES. // - DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a\n", __func__)); gBS->SignalEvent (EventToSignal); } @@ -847,7 +847,7 @@ IoMmuUnmapAllMappings ( LIST_ENTRY *NextNode; MAP_INFO *MapInfo; - DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a\n", __func__)); // // All drivers that had set up IOMMU mappings have halted their respective @@ -933,7 +933,7 @@ InstallIoMmuProtocol ( if (EFI_ERROR (Status)) { mReservedSharedMemSupported = FALSE; } else { - DEBUG ((DEBUG_INFO, "%a: Feature of reserved memory for DMA is supported.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Feature of reserved memory for DMA is supported.\n", __func__)); } return EFI_SUCCESS; diff --git a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c index 83c7c59583..c8f6cf4818 100644 --- a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c +++ b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c @@ -153,7 +153,7 @@ IoMmuInitReservedSharedMem ( DEBUG (( DEBUG_VERBOSE, "%a: ReservedMem (%d pages) address = 0x%llx\n", - __FUNCTION__, + __func__, TotalPages, PhysicalAddress )); @@ -330,7 +330,7 @@ InternalAllocateBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: range-size: %lx, start-address=0x%llx, pages=0x%llx, bits=0x%lx, bitmap: %lx => %lx\n", - __FUNCTION__, + __func__, MemRange->DataSize, *PhysicalAddress, Pages, @@ -401,7 +401,7 @@ IoMmuFreeBounceBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: PlainTextAddress=0x%Lx, bits=0x%Lx, bitmap: %Lx => %Lx\n", - __FUNCTION__, + __func__, MapInfo->PlainTextAddress, MapInfo->ReservedMemBitmap, mReservedMemBitmap, @@ -480,7 +480,7 @@ IoMmuFreeCommonBuffer ( DEBUG (( DEBUG_VERBOSE, "%a: CommonBuffer=0x%Lx, bits=0x%Lx, bitmap: %Lx => %Lx\n", - __FUNCTION__, + __func__, (UINT64)(UINTN)CommonBufferHeader + SIZE_4KB, CommonBufferHeader->ReservedMemBitmap, mReservedMemBitmap, diff --git a/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.c b/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.c index 6d1e1cb05e..150fe07c67 100644 --- a/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.c +++ b/OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.c @@ -62,7 +62,7 @@ AcpiTimerLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.c b/OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.c index c771997a2a..9b3cd05511 100644 --- a/OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.c +++ b/OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.c @@ -59,7 +59,7 @@ AcpiTimerLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); @@ -119,7 +119,7 @@ InternalAcpiGetTimerTick ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c index 01a41a6a45..03d47cf11c 100644 --- a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c +++ b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c @@ -76,7 +76,7 @@ AcpiTimerLibConstructor ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/PeiDxeVirtualMemory.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/PeiDxeVirtualMemory.c index b9c0a5b25a..a1f6e61c1e 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/PeiDxeVirtualMemory.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/PeiDxeVirtualMemory.c @@ -164,7 +164,7 @@ AllocatePageTableMemory ( DEBUG_VERBOSE, "%a:%a: Buffer=0x%Lx Pages=%ld\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Buffer, Pages )); @@ -561,7 +561,7 @@ InternalMemEncryptSevCreateIdentityMap1G ( DEBUG_VERBOSE, "%a:%a: Cr3Base=0x%Lx Physical=0x%Lx Length=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Cr3BaseAddress, PhysicalAddress, (UINT64)Length @@ -606,7 +606,7 @@ InternalMemEncryptSevCreateIdentityMap1G ( DEBUG_ERROR, "%a:%a: bad PML4 for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -713,7 +713,7 @@ SetMemoryEncDec ( DEBUG_VERBOSE, "%a:%a: Cr3Base=0x%Lx Physical=0x%Lx Length=0x%Lx Mode=%a CacheFlush=%u Mmio=%u\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Cr3BaseAddress, PhysicalAddress, (UINT64)Length, @@ -786,7 +786,7 @@ SetMemoryEncDec ( DEBUG_ERROR, "%a:%a: bad PML4 for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -803,7 +803,7 @@ SetMemoryEncDec ( DEBUG_ERROR, "%a:%a: bad PDPE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -824,7 +824,7 @@ SetMemoryEncDec ( DEBUG_VERBOSE, "%a:%a: updated 1GB entry for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); PhysicalAddress += BIT30; @@ -837,7 +837,7 @@ SetMemoryEncDec ( DEBUG_VERBOSE, "%a:%a: splitting 1GB page for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Split1GPageTo2M ( @@ -865,7 +865,7 @@ SetMemoryEncDec ( DEBUG_ERROR, "%a:%a: bad PDE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -892,7 +892,7 @@ SetMemoryEncDec ( DEBUG_VERBOSE, "%a:%a: splitting 2MB page for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Split2MPageTo4K ( @@ -917,7 +917,7 @@ SetMemoryEncDec ( DEBUG_ERROR, "%a:%a: bad PTE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c index 7a8878b1a9..85eb41585b 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/X64/SnpPageStateChangeInternal.c @@ -113,7 +113,7 @@ PvalidateRange ( DEBUG_ERROR, "%a:%a: Failed to %a address 0x%Lx Error code %d\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Validate ? "Validate" : "Invalidate", Address, Ret @@ -237,7 +237,7 @@ InternalSetPageState ( DEBUG_VERBOSE, "%a:%a Address 0x%Lx - 0x%Lx State = %a LargeEntry = %d\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, BaseAddress, EndAddress, State == SevSnpPageShared ? "Shared" : "Private", diff --git a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c index 5b13042512..a01dc98852 100644 --- a/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c +++ b/OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c @@ -180,7 +180,7 @@ AllocatePageTableMemory ( DEBUG_VERBOSE, "%a:%a: Buffer=0x%Lx Pages=%ld\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Buffer, Pages )); @@ -542,7 +542,7 @@ SetOrClearSharedBit ( TdStatus = TdVmCall (TDVMCALL_MAPGPA, PhysicalAddress, Length, 0, 0, NULL); if (TdStatus != 0) { - DEBUG ((DEBUG_ERROR, "%a: TdVmcall(MAPGPA) failed with %llx\n", __FUNCTION__, TdStatus)); + DEBUG ((DEBUG_ERROR, "%a: TdVmcall(MAPGPA) failed with %llx\n", __func__, TdStatus)); ASSERT (FALSE); return EFI_DEVICE_ERROR; } @@ -553,14 +553,14 @@ SetOrClearSharedBit ( if (Mode == ClearSharedBit) { Status = gBS->LocateProtocol (&gEdkiiMemoryAcceptProtocolGuid, NULL, (VOID **)&MemoryAcceptProtocol); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Failed to locate MemoryAcceptProtocol with %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Failed to locate MemoryAcceptProtocol with %r\n", __func__, Status)); ASSERT (FALSE); return Status; } Status = MemoryAcceptProtocol->AcceptMemory (MemoryAcceptProtocol, PhysicalAddress, Length); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Failed to AcceptMemory with %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Failed to AcceptMemory with %r\n", __func__, Status)); ASSERT (FALSE); return Status; } @@ -570,7 +570,7 @@ SetOrClearSharedBit ( DEBUG_VERBOSE, "%a:%a: pte=0x%Lx AddressEncMask=0x%Lx Mode=0x%x MapGPA Status=0x%x\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, *PageTablePointer, AddressEncMask, Mode, @@ -677,7 +677,7 @@ SetMemorySharedOrPrivate ( DEBUG_VERBOSE, "%a:%a: Cr3Base=0x%Lx Physical=0x%Lx Length=0x%Lx Mode=%a\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Cr3BaseAddress, PhysicalAddress, (UINT64)Length, @@ -734,7 +734,7 @@ SetMemorySharedOrPrivate ( DEBUG_ERROR, "%a:%a: bad PML4 for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -751,7 +751,7 @@ SetMemorySharedOrPrivate ( DEBUG_ERROR, "%a:%a: bad PDPE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -776,7 +776,7 @@ SetMemorySharedOrPrivate ( DEBUG_VERBOSE, "%a:%a: updated 1GB entry for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); PhysicalAddress += BIT30; @@ -789,7 +789,7 @@ SetMemorySharedOrPrivate ( DEBUG_VERBOSE, "%a:%a: splitting 1GB page for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Split1GPageTo2M ( @@ -817,7 +817,7 @@ SetMemorySharedOrPrivate ( DEBUG_ERROR, "%a:%a: bad PDE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; @@ -848,7 +848,7 @@ SetMemorySharedOrPrivate ( DEBUG_VERBOSE, "%a:%a: splitting 2MB page for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); @@ -877,7 +877,7 @@ SetMemorySharedOrPrivate ( DEBUG_ERROR, "%a:%a: bad PTE for Physical=0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, PhysicalAddress )); Status = RETURN_NO_MAPPING; diff --git a/OvmfPkg/Library/BasePciCapLib/BasePciCapLib.c b/OvmfPkg/Library/BasePciCapLib/BasePciCapLib.c index 4215e6cdaa..766a2ccb9c 100644 --- a/OvmfPkg/Library/BasePciCapLib/BasePciCapLib.c +++ b/OvmfPkg/Library/BasePciCapLib/BasePciCapLib.c @@ -427,7 +427,7 @@ DebugDumpPciCapList ( DEBUG_VERBOSE, "%a:%a: %a 0x%04x %03u/%03u v0x%x @0x%03x+0x%03x\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (Info.Domain == PciCapNormal ? "Norm" : "Extd"), Info.CapId, Info.Instance, @@ -753,7 +753,7 @@ PciCapListInit ( DEBUG_ERROR, "%a:%a: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return Status; diff --git a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c index 2c1de0039d..9acc6fbe20 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVeHandler.c @@ -265,7 +265,7 @@ TdxMmioReadWrite ( UINT64 TdStatus; if ((MmioSize != 1) && (MmioSize != 2) && (MmioSize != 4) && (MmioSize != 8)) { - DEBUG ((DEBUG_ERROR, "%a: Invalid MmioSize - %d\n", __FUNCTION__, MmioSize)); + DEBUG ((DEBUG_ERROR, "%a: Invalid MmioSize - %d\n", __func__, MmioSize)); return EFI_INVALID_PARAMETER; } @@ -283,7 +283,7 @@ TdxMmioReadWrite ( } if (TdStatus != 0) { - DEBUG ((DEBUG_ERROR, "%a: TdVmcall failed with %llx\n", __FUNCTION__, TdStatus)); + DEBUG ((DEBUG_ERROR, "%a: TdVmcall failed with %llx\n", __func__, TdStatus)); return EFI_ABORTED; } @@ -334,7 +334,7 @@ ParseMmioExitInstructions ( Status = CcInitInstructionData (InstructionData, NULL, Regs); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Initialize InstructionData failed! (%r)\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Initialize InstructionData failed! (%r)\n", __func__, Status)); return Status; } @@ -361,7 +361,7 @@ ParseMmioExitInstructions ( 0); if (InstructionData->Ext.ModRm.Mod == 3) { - DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __FUNCTION__, OpCode)); + DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __func__, OpCode)); return EFI_UNSUPPORTED; } @@ -440,7 +440,7 @@ ParseMmioExitInstructions ( // // NPF on two register operands??? // - DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __FUNCTION__, OpCode)); + DEBUG ((DEBUG_ERROR, "%a: Parse Ext.ModRm.Mod error! (OpCode: 0x%x)\n", __func__, OpCode)); return EFI_UNSUPPORTED; } @@ -558,7 +558,7 @@ ParseMmioExitInstructions ( break; default: - DEBUG ((DEBUG_ERROR, "%a: Invalid MMIO opcode (%x)\n", __FUNCTION__, OpCode)); + DEBUG ((DEBUG_ERROR, "%a: Invalid MMIO opcode (%x)\n", __func__, OpCode)); Status = EFI_UNSUPPORTED; } @@ -606,12 +606,12 @@ MmioExit ( Gpaw = (UINT8)(TdReturnData.TdInfo.Gpaw & 0x3f); TdSharedPageMask = 1ULL << (Gpaw - 1); } else { - DEBUG ((DEBUG_ERROR, "%a: TDCALL failed with status=%llx\n", __FUNCTION__, TdStatus)); + DEBUG ((DEBUG_ERROR, "%a: TDCALL failed with status=%llx\n", __func__, TdStatus)); goto FatalError; } if ((Veinfo->GuestPA & TdSharedPageMask) == 0) { - DEBUG ((DEBUG_ERROR, "%a: EPT-violation #VE on private memory is not allowed!", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: EPT-violation #VE on private memory is not allowed!", __func__)); goto FatalError; } @@ -624,7 +624,7 @@ MmioExit ( DEBUG (( DEBUG_ERROR, "%a: Address is not correct! (%d: 0x%llx != 0x%llx)\n", - __FUNCTION__, + __func__, ParsedInstruction.OpCode, Veinfo->GuestPA, ParsedInstruction.Address diff --git a/OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.c b/OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.c index c751b10679..b99fb350aa 100644 --- a/OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.c +++ b/OvmfPkg/Library/GenericQemuLoadImageLib/GenericQemuLoadImageLib.c @@ -201,7 +201,7 @@ QemuLoadKernelImage ( DEBUG (( Status == EFI_NOT_FOUND ? DEBUG_INFO : DEBUG_ERROR, "%a: LoadImage(): %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -279,7 +279,7 @@ QemuLoadKernelImage ( DEBUG (( DEBUG_ERROR, "%a: kernel command line is not NUL-terminated\n", - __FUNCTION__ + __func__ )); Status = EFI_PROTOCOL_ERROR; goto FreeCommandLine; @@ -330,7 +330,7 @@ QemuLoadKernelImage ( DEBUG (( DEBUG_INFO, "%a: command line: \"%s\"\n", - __FUNCTION__, + __func__, (CHAR16 *)KernelLoadedImage->LoadOptions )); } diff --git a/OvmfPkg/Library/HardwareInfoLib/HardwareInfoDxe.c b/OvmfPkg/Library/HardwareInfoLib/HardwareInfoDxe.c index a74de52871..5a1a69dcc3 100644 --- a/OvmfPkg/Library/HardwareInfoLib/HardwareInfoDxe.c +++ b/OvmfPkg/Library/HardwareInfoLib/HardwareInfoDxe.c @@ -91,7 +91,7 @@ CreateHardwareInfoList ( DEBUG (( EFI_D_ERROR, "%a: Failed to allocate memory for hardware info\n", - __FUNCTION__ + __func__ )); return EFI_OUT_OF_RESOURCES; diff --git a/OvmfPkg/Library/LockBoxLib/LockBoxLib.c b/OvmfPkg/Library/LockBoxLib/LockBoxLib.c index 2000afeeb8..a8af4ea8d0 100644 --- a/OvmfPkg/Library/LockBoxLib/LockBoxLib.c +++ b/OvmfPkg/Library/LockBoxLib/LockBoxLib.c @@ -125,7 +125,7 @@ SaveLockBox ( DEBUG (( DEBUG_VERBOSE, "%a: Guid=%g Buffer=%p Length=0x%x\n", - __FUNCTION__, + __func__, Guid, Buffer, (UINT32)Length @@ -196,7 +196,7 @@ SetLockBoxAttributes ( DEBUG (( DEBUG_VERBOSE, "%a: Guid=%g Attributes=0x%Lx\n", - __FUNCTION__, + __func__, Guid, Attributes )); @@ -253,7 +253,7 @@ UpdateLockBox ( DEBUG (( DEBUG_VERBOSE, "%a: Guid=%g Offset=0x%x Length=0x%x\n", - __FUNCTION__, + __func__, Guid, (UINT32)Offset, (UINT32)Length @@ -315,7 +315,7 @@ RestoreLockBox ( DEBUG (( DEBUG_VERBOSE, "%a: Guid=%g Buffer=%p\n", - __FUNCTION__, + __func__, Guid, Buffer )); @@ -397,7 +397,7 @@ RestoreAllLockBoxInPlace ( DEBUG (( DEBUG_VERBOSE, "%a: Guid=%g Buffer=%p\n", - __FUNCTION__, + __func__, &Header->Guid, Buffer )); diff --git a/OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.c b/OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.c index cad2bd6c96..0424aa5df1 100644 --- a/OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.c +++ b/OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.c @@ -156,7 +156,7 @@ PciHostBridgeUtilityInitRootBridge ( &mRootBridgeDevicePathTemplate ); if (DevicePath == NULL) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, EFI_OUT_OF_RESOURCES)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, EFI_OUT_OF_RESOURCES)); return EFI_OUT_OF_RESOURCES; } @@ -166,7 +166,7 @@ PciHostBridgeUtilityInitRootBridge ( DEBUG (( DEBUG_INFO, "%a: populated root bus %d, with room for %d subordinate bus(es)\n", - __FUNCTION__, + __func__, RootBusNumber, MaxSubBusNumber - RootBusNumber )); @@ -253,7 +253,7 @@ PciHostBridgeUtilityGetRootBridgesBusScan ( DEBUG_ERROR, "%a: invalid bus range with BusMin %Lu and BusMax " "%Lu\n", - __FUNCTION__, + __func__, (UINT64)BusMin, (UINT64)BusMax )); @@ -283,7 +283,7 @@ PciHostBridgeUtilityGetRootBridgesBusScan ( DEBUG_ERROR, "%a: invalid count of extra root buses (%Lu) " "reported by QEMU\n", - __FUNCTION__, + __func__, ExtraRootBridges )); return NULL; @@ -292,7 +292,7 @@ PciHostBridgeUtilityGetRootBridgesBusScan ( DEBUG (( DEBUG_INFO, "%a: %Lu extra root buses reported by QEMU\n", - __FUNCTION__, + __func__, ExtraRootBridges )); } @@ -302,7 +302,7 @@ PciHostBridgeUtilityGetRootBridgesBusScan ( // Bridges = AllocatePool ((1 + (UINTN)ExtraRootBridges) * sizeof *Bridges); if (Bridges == NULL) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, EFI_OUT_OF_RESOURCES)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, EFI_OUT_OF_RESOURCES)); return NULL; } @@ -471,7 +471,7 @@ PciHostBridgeUtilityGetRootBridgesHostProvided ( DEBUG (( DEBUG_ERROR, "%a: Failed to allocate memory for hardware resources info\n", - __FUNCTION__ + __func__ )); return NULL; } @@ -495,7 +495,7 @@ PciHostBridgeUtilityGetRootBridgesHostProvided ( DEBUG_ERROR, "%a: Failed to create hardware info list to retrieve host " "bridges information from fw-cfg\n", - __FUNCTION__ + __func__ )); goto FreeBridges; @@ -514,7 +514,7 @@ PciHostBridgeUtilityGetRootBridgesHostProvided ( DEBUG (( DEBUG_INFO, "%a: Host provided description for %Lu root bridges\n", - __FUNCTION__, + __func__, PciHostBridgeCount )); @@ -523,7 +523,7 @@ PciHostBridgeUtilityGetRootBridgesHostProvided ( // Bridges = AllocatePool (((UINTN)PciHostBridgeCount) * sizeof *Bridges); if (Bridges == NULL) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, EFI_OUT_OF_RESOURCES)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, EFI_OUT_OF_RESOURCES)); goto FreeBridges; } @@ -567,7 +567,7 @@ PciHostBridgeUtilityGetRootBridgesHostProvided ( DEBUG_ERROR, "%a: invalid bus range with BusMin %Lu and BusMax " "%Lu\n", - __FUNCTION__, + __func__, (UINT64)RootBridgeNumber, (UINT64)LastRootBridgeNumber )); diff --git a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c index b444c052d1..e2c1bac5e0 100644 --- a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c +++ b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c @@ -371,7 +371,7 @@ AllocatePageTableMemory ( DEBUG_INFO, "%a:%a: Buffer=0x%Lx Pages=%ld, PageTablePool=%p\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Buffer, Pages, *PageTablePool diff --git a/OvmfPkg/Library/PlatformBmPrintScLib/StatusCodeHandler.c b/OvmfPkg/Library/PlatformBmPrintScLib/StatusCodeHandler.c index 065673d904..18091640d1 100644 --- a/OvmfPkg/Library/PlatformBmPrintScLib/StatusCodeHandler.c +++ b/OvmfPkg/Library/PlatformBmPrintScLib/StatusCodeHandler.c @@ -122,7 +122,7 @@ HandleStatusCode ( DEBUG_ERROR, "%a:%a: malformed Data\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return EFI_INVALID_PARAMETER; } @@ -143,7 +143,7 @@ HandleStatusCode ( DEBUG_ERROR, "%a:%a: failed to get %g:\"%s\": %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, &gEfiGlobalVariableGuid, EFI_BOOT_CURRENT_VARIABLE_NAME, Status @@ -156,7 +156,7 @@ HandleStatusCode ( DEBUG_ERROR, "%a:%a: got %Lu bytes for %g:\"%s\", expected %Lu\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)VariableSize, &gEfiGlobalVariableGuid, EFI_BOOT_CURRENT_VARIABLE_NAME, @@ -180,7 +180,7 @@ HandleStatusCode ( DEBUG_ERROR, "%a:%a: EfiBootManagerVariableToLoadOption(\"%s\"): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, BootOptionName, Status )); @@ -309,7 +309,7 @@ PlatformBmPrintScRegisterHandler ( DEBUG_ERROR, "%a:%a: failed to register status code handler: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return Status; @@ -337,7 +337,7 @@ PlatformBmPrintScRegisterHandler ( "%a:%a: failed to create ExitBootServices() event: " "%r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); StatusCodeRouter->Unregister (HandleStatusCode); diff --git a/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c b/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c index 98f6f07341..a90076c9e6 100644 --- a/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c +++ b/OvmfPkg/Library/PlatformBootManagerLib/BdsPlatform.c @@ -275,7 +275,7 @@ RemoveStaleFvFileOptions ( DEBUG (( EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_VERBOSE, "%a: removing stale Boot#%04x %s: %r\n", - __FUNCTION__, + __func__, (UINT32)BootOptions[Index].OptionNumber, DevicePathString == NULL ? L"" : DevicePathString, Status @@ -479,7 +479,7 @@ PlatformBootManagerBeforeConsole ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: SetVariable(%s, %u): %r\n", - __FUNCTION__, + __func__, EFI_TIME_OUT_VARIABLE_NAME, FrontPageTimeout, Status @@ -632,7 +632,7 @@ ConnectVirtioPciRng ( return EFI_SUCCESS; Error: - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); return Status; } @@ -1283,7 +1283,7 @@ SetPciIntLine ( DEBUG (( DEBUG_ERROR, "%a: PCI host bridge (00:00.0) should have no interrupts!\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); } @@ -1338,7 +1338,7 @@ SetPciIntLine ( DEBUG (( DEBUG_VERBOSE, "%a: [%02x:%02x.%x] %s -> 0x%02x\n", - __FUNCTION__, + __func__, (UINT32)Bus, (UINT32)Device, (UINT32)Function, @@ -1416,7 +1416,7 @@ PciAcpiInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, mHostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/PlatformBootManagerLib/QemuKernel.c b/OvmfPkg/Library/PlatformBootManagerLib/QemuKernel.c index 1e66e3c452..84b25db521 100644 --- a/OvmfPkg/Library/PlatformBootManagerLib/QemuKernel.c +++ b/OvmfPkg/Library/PlatformBootManagerLib/QemuKernel.c @@ -44,7 +44,7 @@ TryRunningQemuKernel ( DEBUG (( DEBUG_ERROR, "%a: QemuStartKernelImage(): %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/Library/PlatformBootManagerLibBhyve/BdsPlatform.c b/OvmfPkg/Library/PlatformBootManagerLibBhyve/BdsPlatform.c index bf2701965f..ac9c02cb1c 100644 --- a/OvmfPkg/Library/PlatformBootManagerLibBhyve/BdsPlatform.c +++ b/OvmfPkg/Library/PlatformBootManagerLibBhyve/BdsPlatform.c @@ -273,7 +273,7 @@ RemoveStaleFvFileOptions ( DEBUG (( EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_VERBOSE, "%a: removing stale Boot#%04x %s: %r\n", - __FUNCTION__, + __func__, (UINT32)BootOptions[Index].OptionNumber, DevicePathString == NULL ? L"" : DevicePathString, Status @@ -586,7 +586,7 @@ ConnectVirtioPciRng ( return EFI_SUCCESS; Error: - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); return Status; } @@ -1156,7 +1156,7 @@ SetPciIntLine ( DEBUG (( DEBUG_ERROR, "%a: PCI host bridge (00:00.0) should have no interrupts!\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); } @@ -1213,7 +1213,7 @@ SetPciIntLine ( DEBUG (( DEBUG_VERBOSE, "%a: [%02x:%02x.%x] %s -> 0x%02x\n", - __FUNCTION__, + __func__, (UINT32)Bus, (UINT32)Device, (UINT32)Function, @@ -1283,7 +1283,7 @@ PciAcpiInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, mHostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/PlatformBootManagerLibGrub/BdsPlatform.c b/OvmfPkg/Library/PlatformBootManagerLibGrub/BdsPlatform.c index a402589206..df8e2fe157 100644 --- a/OvmfPkg/Library/PlatformBootManagerLibGrub/BdsPlatform.c +++ b/OvmfPkg/Library/PlatformBootManagerLibGrub/BdsPlatform.c @@ -280,7 +280,7 @@ RemoveStaleFvFileOptions ( DEBUG (( EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_VERBOSE, "%a: removing stale Boot#%04x %s: %r\n", - __FUNCTION__, + __func__, (UINT32)BootOptions[Index].OptionNumber, DevicePathString == NULL ? L"" : DevicePathString, Status @@ -551,7 +551,7 @@ ConnectVirtioPciRng ( return EFI_SUCCESS; Error: - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, Status)); return Status; } @@ -1157,7 +1157,7 @@ SetPciIntLine ( DEBUG (( DEBUG_ERROR, "%a: PCI host bridge (00:00.0) should have no interrupts!\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); } @@ -1212,7 +1212,7 @@ SetPciIntLine ( DEBUG (( DEBUG_VERBOSE, "%a: [%02x:%02x.%x] %s -> 0x%02x\n", - __FUNCTION__, + __func__, (UINT32)Bus, (UINT32)Device, (UINT32)Function, @@ -1280,7 +1280,7 @@ PciAcpiInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, mHostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/PlatformBootManagerLibGrub/QemuKernel.c b/OvmfPkg/Library/PlatformBootManagerLibGrub/QemuKernel.c index 1e66e3c452..84b25db521 100644 --- a/OvmfPkg/Library/PlatformBootManagerLibGrub/QemuKernel.c +++ b/OvmfPkg/Library/PlatformBootManagerLibGrub/QemuKernel.c @@ -44,7 +44,7 @@ TryRunningQemuKernel ( DEBUG (( DEBUG_ERROR, "%a: QemuStartKernelImage(): %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index aced8535e6..acf90b4e93 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -91,7 +91,7 @@ PlatformQemuUc32BaseInitialization ( DEBUG_VERBOSE, "%a: rounded UC32 base from 0x%x up to 0x%x, for " "an UC32 size of 0x%x\n", - __FUNCTION__, + __func__, PlatformInfoHob->LowMemory, PlatformInfoHob->Uc32Base, PlatformInfoHob->Uc32Size @@ -123,7 +123,7 @@ PlatformGetFirstNonAddressCB ( Candidate = E820Entry->BaseAddr + E820Entry->Length; if (PlatformInfoHob->FirstNonAddress < Candidate) { - DEBUG ((DEBUG_INFO, "%a: FirstNonAddress=0x%Lx\n", __FUNCTION__, Candidate)); + DEBUG ((DEBUG_INFO, "%a: FirstNonAddress=0x%Lx\n", __func__, Candidate)); PlatformInfoHob->FirstNonAddress = Candidate; } } @@ -151,7 +151,7 @@ PlatformGetLowMemoryCB ( } if (PlatformInfoHob->LowMemory < Candidate) { - DEBUG ((DEBUG_INFO, "%a: LowMemory=0x%Lx\n", __FUNCTION__, Candidate)); + DEBUG ((DEBUG_INFO, "%a: LowMemory=0x%Lx\n", __func__, Candidate)); PlatformInfoHob->LowMemory = (UINT32)Candidate; } } @@ -180,7 +180,7 @@ PlatformAddHobCB ( Base = ALIGN_VALUE (Base, (UINT64)EFI_PAGE_SIZE); End = End & ~(UINT64)EFI_PAGE_MASK; if (Base < End) { - DEBUG ((DEBUG_INFO, "%a: HighMemory [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End)); + DEBUG ((DEBUG_INFO, "%a: HighMemory [0x%Lx, 0x%Lx)\n", __func__, Base, End)); PlatformAddMemoryRangeHob (Base, End); } } @@ -188,13 +188,13 @@ PlatformAddHobCB ( break; case EfiAcpiAddressRangeReserved: BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_RESERVED, 0, Base, End - Base); - DEBUG ((DEBUG_INFO, "%a: Reserved [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End)); + DEBUG ((DEBUG_INFO, "%a: Reserved [0x%Lx, 0x%Lx)\n", __func__, Base, End)); break; default: DEBUG (( DEBUG_WARN, "%a: Type %u [0x%Lx, 0x%Lx) (NOT HANDLED)\n", - __FUNCTION__, + __func__, E820Entry->Type, Base, End @@ -241,7 +241,7 @@ PlatformReservationConflictCB ( DEBUG (( DEBUG_INFO, "%a: move mmio: 0x%Lx => %Lx\n", - __FUNCTION__, + __func__, PlatformInfoHob->PcdPciMmio64Base, NewBase )); @@ -495,7 +495,7 @@ PlatformGetFirstNonAddress ( DEBUG (( DEBUG_WARN, "%a: ignoring malformed 64-bit PCI host aperture size from fw_cfg\n", - __FUNCTION__ + __func__ )); break; } @@ -505,7 +505,7 @@ PlatformGetFirstNonAddress ( DEBUG (( DEBUG_INFO, "%a: disabling 64-bit PCI host aperture\n", - __FUNCTION__ + __func__ )); } @@ -534,7 +534,7 @@ PlatformGetFirstNonAddress ( DEBUG (( DEBUG_VERBOSE, "%a: HotPlugMemoryEnd=0x%Lx\n", - __FUNCTION__, + __func__, HotPlugMemoryEnd )); @@ -638,7 +638,7 @@ PlatformAddressWidthFromCpuid ( DEBUG (( DEBUG_INFO, "%a: Signature: '%a', PhysBits: %d, QemuQuirk: %a, Valid: %a\n", - __FUNCTION__, + __func__, Signature, PhysBits, QemuQuirk ? "On" : "Off", @@ -783,7 +783,7 @@ PlatformScanHostProvided64BitPciMmioEnd ( DEBUG (( DEBUG_ERROR, "%a: ignoring malformed hardware information from fw_cfg\n", - __FUNCTION__ + __func__ )); *PciMmioAddressEnd = 0; return Status; @@ -806,7 +806,7 @@ PlatformScanHostProvided64BitPciMmioEnd ( DEBUG (( DEBUG_INFO, "%a: Pci64End=0x%Lx\n", - __FUNCTION__, + __func__, *PciMmioAddressEnd )); @@ -942,7 +942,7 @@ PlatformQemuInitializeRam ( MTRR_SETTINGS MtrrSettings; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a called\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a called\n", __func__)); // // Determine total memory size available diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c index 5cf8af825a..f48bf16ae3 100644 --- a/OvmfPkg/Library/PlatformInitLib/Platform.c +++ b/OvmfPkg/Library/PlatformInitLib/Platform.c @@ -358,7 +358,7 @@ PlatformMiscInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, PlatformInfoHob->HostBridgeDevId )); ASSERT (FALSE); @@ -366,7 +366,7 @@ PlatformMiscInitialization ( } if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) { - DEBUG ((DEBUG_INFO, "%a: Cloud Hypervisor is done.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Cloud Hypervisor is done.\n", __func__)); return; } @@ -489,12 +489,12 @@ PlatformCpuCountBugCheck ( DEBUG (( DEBUG_ERROR, "%a: Present=%u Possible=%u\n", - __FUNCTION__, + __func__, *Present, *Possible )); for (Idx = 0; Idx < ARRAY_SIZE (Message); ++Idx) { - DEBUG ((DEBUG_ERROR, "%a: %a\n", __FUNCTION__, Message[Idx])); + DEBUG ((DEBUG_ERROR, "%a: %a\n", __func__, Message[Idx])); } ParseStatus = QemuFwCfgParseBool ( @@ -505,7 +505,7 @@ PlatformCpuCountBugCheck ( DEBUG (( DEBUG_WARN, "%a: \"%a\" active. You've been warned.\n", - __FUNCTION__, + __func__, CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE )); // @@ -531,7 +531,7 @@ PlatformCpuCountBugCheck ( DEBUG (( DEBUG_WARN, "%a: QEMU v2.7 reset bug: BootCpuCount=%d Present=%u\n", - __FUNCTION__, + __func__, *BootCpuCount, *Present )); @@ -573,7 +573,7 @@ PlatformMaxCpuCountInitialization ( // until PcdCpuApInitTimeOutInMicroSeconds elapses (whichever is reached // first). // - DEBUG ((DEBUG_WARN, "%a: boot CPU count unavailable\n", __FUNCTION__)); + DEBUG ((DEBUG_WARN, "%a: boot CPU count unavailable\n", __func__)); MaxCpuCount = PlatformInfoHob->DefaultMaxCpuNumber; } else { // @@ -626,7 +626,7 @@ PlatformMaxCpuCountInitialization ( // steps. Both cases confirm modern mode. // CmdData2 = IoRead32 (CpuHpBase + QEMU_CPUHP_R_CMD_DATA2); - DEBUG ((DEBUG_VERBOSE, "%a: CmdData2=0x%x\n", __FUNCTION__, CmdData2)); + DEBUG ((DEBUG_VERBOSE, "%a: CmdData2=0x%x\n", __func__, CmdData2)); if (CmdData2 != 0) { // // QEMU doesn't support the modern CPU hotplug interface. Assume that the @@ -635,7 +635,7 @@ PlatformMaxCpuCountInitialization ( DEBUG (( DEBUG_WARN, "%a: modern CPU hotplug interface unavailable\n", - __FUNCTION__ + __func__ )); MaxCpuCount = BootCpuCount; } else { @@ -693,7 +693,7 @@ PlatformMaxCpuCountInitialization ( DEBUG (( DEBUG_INFO, "%a: BootCpuCount=%d MaxCpuCount=%u\n", - __FUNCTION__, + __func__, BootCpuCount, MaxCpuCount )); diff --git a/OvmfPkg/Library/QemuBootOrderLib/ExtraRootBusMap.c b/OvmfPkg/Library/QemuBootOrderLib/ExtraRootBusMap.c index 37d488e01c..c32c3eddd5 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/ExtraRootBusMap.c +++ b/OvmfPkg/Library/QemuBootOrderLib/ExtraRootBusMap.c @@ -227,7 +227,7 @@ CreateExtraRootBusMap ( DEBUG (( DEBUG_VERBOSE, "%a: extra bus position 0x%Lx maps to bus number (UID) 0x%x\n", - __FUNCTION__, + __func__, (UINT64)(Idx + 1), Acpi->UID )); diff --git a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c index cea4b7a099..2fe6ab30c0 100644 --- a/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c +++ b/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c @@ -543,7 +543,7 @@ ParseOfwNode ( DEBUG (( DEBUG_VERBOSE, "%a: DriverName=\"%.*a\" UnitAddress=\"%.*a\" DeviceArguments=\"%.*a\"\n", - __FUNCTION__, + __func__, OfwNode->DriverName.Len, OfwNode->DriverName.Ptr, OfwNode->UnitAddress.Len, @@ -1477,7 +1477,7 @@ TranslateOfwPath ( } if (Status == RETURN_NOT_FOUND) { - DEBUG ((DEBUG_VERBOSE, "%a: no more nodes\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: no more nodes\n", __func__)); return RETURN_NOT_FOUND; } @@ -1496,7 +1496,7 @@ TranslateOfwPath ( break; case RETURN_INVALID_PARAMETER: - DEBUG ((DEBUG_VERBOSE, "%a: parse error\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: parse error\n", __func__)); return RETURN_INVALID_PARAMETER; default: @@ -1512,22 +1512,22 @@ TranslateOfwPath ( ); switch (Status) { case RETURN_SUCCESS: - DEBUG ((DEBUG_VERBOSE, "%a: success: \"%s\"\n", __FUNCTION__, Translated)); + DEBUG ((DEBUG_VERBOSE, "%a: success: \"%s\"\n", __func__, Translated)); break; case RETURN_BUFFER_TOO_SMALL: - DEBUG ((DEBUG_VERBOSE, "%a: buffer too small\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: buffer too small\n", __func__)); break; case RETURN_UNSUPPORTED: - DEBUG ((DEBUG_VERBOSE, "%a: unsupported\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: unsupported\n", __func__)); break; case RETURN_PROTOCOL_ERROR: DEBUG (( DEBUG_VERBOSE, "%a: logic error / system state mismatch\n", - __FUNCTION__ + __func__ )); break; @@ -1604,9 +1604,9 @@ ConnectDevicesFromQemu ( goto FreeFwCfg; } - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __func__)); DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg)); - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __func__)); if (FeaturePcdGet (PcdQemuBootOrderPciTranslation)) { EfiStatus = CreateExtraRootBusMap (&ExtraPciRoots); @@ -1686,7 +1686,7 @@ ConnectDevicesFromQemu ( DEBUG (( DEBUG_INFO, "%a: %Lu OpenFirmware device path(s) connected\n", - __FUNCTION__, + __func__, (UINT64)NumConnected )); Status = RETURN_SUCCESS; @@ -1750,9 +1750,9 @@ StoreQemuBootOrder ( goto FreeFwCfg; } - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __func__)); DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg)); - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __func__)); if (FeaturePcdGet (PcdQemuBootOrderPciTranslation)) { EfiStatus = CreateExtraRootBusMap (&ExtraPciRoots); @@ -1797,7 +1797,7 @@ StoreQemuBootOrder ( L"VMMBootOrder%04x", VariableIndex++ ); - DEBUG ((DEBUG_INFO, "%a: %s = %s\n", __FUNCTION__, VariableName, Translated)); + DEBUG ((DEBUG_INFO, "%a: %s = %s\n", __func__, VariableName, Translated)); gRT->SetVariable ( VariableName, &gVMMBootOrderGuid, @@ -1944,7 +1944,7 @@ Match ( DEBUG (( DEBUG_VERBOSE, "%a: expanded relative device path \"%s\" for prefix matching\n", - __FUNCTION__, + __func__, Converted )); FreePool (Converted); @@ -1958,7 +1958,7 @@ Match ( DEBUG (( DEBUG_VERBOSE, "%a: against \"%s\": %a\n", - __FUNCTION__, + __func__, Converted, Result ? "match" : "no match" )); @@ -2068,7 +2068,7 @@ BootOrderComplete ( DEBUG (( DEBUG_VERBOSE, "%a: keeping \"%s\"\n", - __FUNCTION__, + __func__, Converted )); } @@ -2076,7 +2076,7 @@ BootOrderComplete ( DEBUG (( DEBUG_VERBOSE, "%a: dropping \"%s\"\n", - __FUNCTION__, + __func__, Converted )); } @@ -2211,9 +2211,9 @@ SetBootOrderFromQemu ( goto ErrorFreeFwCfg; } - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg:\n", __func__)); DEBUG ((DEBUG_VERBOSE, "%a\n", FwCfg)); - DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: FwCfg: \n", __func__)); FwCfgPtr = FwCfg; BootOrder.Produced = 0; @@ -2332,13 +2332,13 @@ SetBootOrderFromQemu ( DEBUG (( DEBUG_ERROR, "%a: setting BootOrder: %r\n", - __FUNCTION__, + __func__, Status )); goto ErrorFreeExtraPciRoots; } - DEBUG ((DEBUG_INFO, "%a: setting BootOrder: success\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: setting BootOrder: success\n", __func__)); PruneBootVariables (ActiveOption, ActiveCount); } diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c index 6a810928a0..4250e633b5 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c @@ -103,7 +103,7 @@ QemuFwCfgInitialize ( DEBUG_ERROR, "QemuFwCfgDma %a:%a Failed to locate IOMMU protocol.\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); ASSERT (FALSE); CpuDeadLoop (); @@ -186,7 +186,7 @@ AllocFwCfgDmaAccessBuffer ( DEBUG_ERROR, "%a:%a failed to allocate FW_CFG_DMA_ACCESS\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); ASSERT (FALSE); CpuDeadLoop (); @@ -215,7 +215,7 @@ AllocFwCfgDmaAccessBuffer ( DEBUG_ERROR, "%a:%a failed to Map() FW_CFG_DMA_ACCESS\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); ASSERT (FALSE); CpuDeadLoop (); @@ -228,7 +228,7 @@ AllocFwCfgDmaAccessBuffer ( DEBUG_ERROR, "%a:%a failed to Map() - requested 0x%Lx got 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)sizeof (FW_CFG_DMA_ACCESS), (UINT64)Size )); @@ -263,7 +263,7 @@ FreeFwCfgDmaAccessBuffer ( DEBUG_ERROR, "%a:%a failed to UnMap() Mapping 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)(UINTN)Mapping )); ASSERT (FALSE); @@ -276,7 +276,7 @@ FreeFwCfgDmaAccessBuffer ( DEBUG_ERROR, "%a:%a failed to Free() 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)(UINTN)Access )); ASSERT (FALSE); @@ -320,7 +320,7 @@ MapFwCfgDmaDataBuffer ( DEBUG_ERROR, "%a:%a failed to Map() Address 0x%Lx Size 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)(UINTN)HostAddress, (UINT64)Size )); @@ -334,7 +334,7 @@ MapFwCfgDmaDataBuffer ( DEBUG_ERROR, "%a:%a failed to Map() - requested 0x%x got 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Size, (UINT64)NumberOfBytes )); @@ -360,7 +360,7 @@ UnmapFwCfgDmaDataBuffer ( DEBUG_ERROR, "%a:%a failed to UnMap() Mapping 0x%Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)(UINTN)Mapping )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibMmio.c b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibMmio.c index 583d8a8e9f..115a210759 100644 --- a/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibMmio.c +++ b/OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibMmio.c @@ -134,7 +134,7 @@ QemuFwCfgInitialize ( DEBUG (( DEBUG_WARN, "%a: No 'qemu,fw-cfg-mmio' compatible DT node found (Status == %r)\n", - __FUNCTION__, + __func__, Status )); return EFI_SUCCESS; diff --git a/OvmfPkg/Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c b/OvmfPkg/Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c index 5706fa9be4..f523756438 100644 --- a/OvmfPkg/Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c +++ b/OvmfPkg/Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c @@ -71,7 +71,7 @@ S3SaveStateInstalledNotify ( DEBUG_INFO, "%a: %a: DmaAccess@0x%Lx ScratchBuffer@[0x%Lx+0x%Lx]\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)(UINTN)mDmaAccess, (UINT64)(UINTN)mScratchBuffer, (UINT64)mScratchBufferSize @@ -161,7 +161,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: fw_cfg DMA unavailable\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return RETURN_NOT_FOUND; } @@ -177,7 +177,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: ScratchBufferSize too big: %Lu\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)ScratchBufferSize )); return RETURN_BAD_BUFFER_SIZE; @@ -192,7 +192,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: AllocateReservedPool(): out of resources\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return RETURN_OUT_OF_RESOURCES; } @@ -215,7 +215,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: CreateEvent(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); goto FreeDmaAccess; @@ -231,7 +231,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: RegisterProtocolNotify(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); goto CloseEvent; @@ -256,7 +256,7 @@ QemuFwCfgS3CallWhenBootScriptReady ( DEBUG_ERROR, "%a: %a: SignalEvent(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); goto NullGlobals; @@ -383,7 +383,7 @@ QemuFwCfgS3ScriptWriteBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -409,7 +409,7 @@ QemuFwCfgS3ScriptWriteBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -436,7 +436,7 @@ QemuFwCfgS3ScriptWriteBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -544,7 +544,7 @@ QemuFwCfgS3ScriptReadBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -570,7 +570,7 @@ QemuFwCfgS3ScriptReadBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -597,7 +597,7 @@ QemuFwCfgS3ScriptReadBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -692,7 +692,7 @@ QemuFwCfgS3ScriptSkipBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -718,7 +718,7 @@ QemuFwCfgS3ScriptSkipBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -745,7 +745,7 @@ QemuFwCfgS3ScriptSkipBytes ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; @@ -877,7 +877,7 @@ QemuFwCfgS3ScriptCheckValue ( DEBUG_ERROR, "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return (RETURN_STATUS)Status; diff --git a/OvmfPkg/Library/ResetSystemLib/DxeResetSystemLibMicrovm.c b/OvmfPkg/Library/ResetSystemLib/DxeResetSystemLibMicrovm.c index a31fd0e7bb..ae9d2260d5 100644 --- a/OvmfPkg/Library/ResetSystemLib/DxeResetSystemLibMicrovm.c +++ b/OvmfPkg/Library/ResetSystemLib/DxeResetSystemLibMicrovm.c @@ -29,11 +29,11 @@ DxeResetSystemLibMicrovmConstructor ( EFI_STATUS Status; EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; - DEBUG ((DEBUG_INFO, "%a: start\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: start\n", __func__)); Status = gDS->GetMemorySpaceDescriptor (Address, &Descriptor); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: GetMemorySpaceDescriptor failed\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: GetMemorySpaceDescriptor failed\n", __func__)); return RETURN_UNSUPPORTED; } @@ -43,10 +43,10 @@ DxeResetSystemLibMicrovmConstructor ( Descriptor.Attributes | EFI_MEMORY_RUNTIME ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: SetMemorySpaceAttributes failed\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: SetMemorySpaceAttributes failed\n", __func__)); return RETURN_UNSUPPORTED; } - DEBUG ((DEBUG_INFO, "%a: done\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: done\n", __func__)); return EFI_SUCCESS; } diff --git a/OvmfPkg/Library/ResetSystemLib/ResetSystemLibMicrovm.c b/OvmfPkg/Library/ResetSystemLib/ResetSystemLibMicrovm.c index 44fe929e93..4a4e78cca4 100644 --- a/OvmfPkg/Library/ResetSystemLib/ResetSystemLibMicrovm.c +++ b/OvmfPkg/Library/ResetSystemLib/ResetSystemLibMicrovm.c @@ -25,9 +25,9 @@ MicrovmGedBase ( if (EfiGoneVirtual ()) { EfiConvertPointer (0, &Address); - DEBUG ((DEBUG_INFO, "%a: virtual -> 0x%x\n", __FUNCTION__, Address)); + DEBUG ((DEBUG_INFO, "%a: virtual -> 0x%x\n", __func__, Address)); } else { - DEBUG ((DEBUG_INFO, "%a: physical -> 0x%x\n", __FUNCTION__, Address)); + DEBUG ((DEBUG_INFO, "%a: physical -> 0x%x\n", __func__, Address)); } return (UINTN)Address; @@ -40,7 +40,7 @@ MicrovmReset ( { UINTN Address = MicrovmGedBase (); - DEBUG ((DEBUG_INFO, "%a: microvm reset via ged\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: microvm reset via ged\n", __func__)); MmioWrite8 ( Address + MICROVM_ACPI_GED_REG_RESET, MICROVM_ACPI_GED_RESET_VALUE @@ -55,7 +55,7 @@ MicrovmShutdown ( { UINTN Address = MicrovmGedBase (); - DEBUG ((DEBUG_INFO, "%a: microvm poweroff via ged\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: microvm poweroff via ged\n", __func__)); MmioWrite8 ( Address + MICROVM_ACPI_GED_REG_SLEEP_CTL, (1 << 5) /* enable bit */ | diff --git a/OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.c b/OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.c index c70b4556b7..8df82e161a 100644 --- a/OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.c +++ b/OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.c @@ -294,7 +294,7 @@ IterateVariablesCallbackSetSystemVariable ( DEBUG_WARN, "%a: setting authenticated variable \"%s\" " "failed with EFI_SECURITY_VIOLATION, ignoring\n", - __FUNCTION__, + __func__, VariableName )); Status = EFI_SUCCESS; @@ -303,7 +303,7 @@ IterateVariablesCallbackSetSystemVariable ( DEBUG_WARN, "%a: setting ReadOnly variable \"%s\" " "failed with EFI_WRITE_PROTECTED, ignoring\n", - __FUNCTION__, + __func__, VariableName )); Status = EFI_SUCCESS; diff --git a/OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.c b/OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.c index 69c2d36400..5de3022086 100644 --- a/OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.c +++ b/OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.c @@ -98,7 +98,7 @@ DetectSmbiosVersion ( DEBUG (( DEBUG_INFO, "%a: SMBIOS 3.x DocRev from QEMU: 0x%02x\n", - __FUNCTION__, + __func__, QemuAnchor.V3.DocRev )); PcdStatus = PcdSet8S (PcdSmbiosDocRev, QemuAnchor.V3.DocRev); @@ -112,7 +112,7 @@ DetectSmbiosVersion ( DEBUG (( DEBUG_INFO, "%a: SMBIOS version from QEMU: 0x%04x\n", - __FUNCTION__, + __func__, SmbiosVersion )); PcdStatus = PcdSet16S (PcdSmbiosVersion, SmbiosVersion); diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c index a1dd10c9f2..a009123dae 100644 --- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c +++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c @@ -220,7 +220,7 @@ InitCpuHotEjectData ( RETURN_ERROR (SafeUintnAdd (Size, sizeof (*mCpuHotEjectData), &Size)) || RETURN_ERROR (SafeUintnAdd (Size, sizeof (UINT64) - 1, &Size))) { - DEBUG ((DEBUG_ERROR, "%a: invalid CPU_HOT_EJECT_DATA\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid CPU_HOT_EJECT_DATA\n", __func__)); goto Fatal; } @@ -303,7 +303,7 @@ SmmCpuFeaturesSmmRelocationComplete ( DEBUG (( DEBUG_ERROR, "%a: MemEncryptSevSetPageEncMask(): %r\n", - __FUNCTION__, + __func__, Status )); ASSERT (FALSE); diff --git a/OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.c b/OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.c index e22de4f5d4..e4bec93fed 100644 --- a/OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.c +++ b/OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.c @@ -51,7 +51,7 @@ SetCaCerts ( DEBUG_VERBOSE, "%a:%a: not touching CA cert list\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return; } @@ -83,7 +83,7 @@ SetCaCerts ( DEBUG_ERROR, "%a:%a: failed to delete %g:\"%s\"\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, &gEfiTlsCaCertificateGuid, EFI_TLS_CA_CERTIFICATE_VARIABLE )); @@ -96,7 +96,7 @@ SetCaCerts ( DEBUG_VERBOSE, "%a:%a: applied empty CA cert list\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return; } @@ -107,7 +107,7 @@ SetCaCerts ( DEBUG_ERROR, "%a:%a: failed to allocate HttpsCaCerts\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return; } @@ -127,7 +127,7 @@ SetCaCerts ( DEBUG_ERROR, "%a:%a: failed to set %g:\"%s\": %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, &gEfiTlsCaCertificateGuid, EFI_TLS_CA_CERTIFICATE_VARIABLE, Status @@ -139,7 +139,7 @@ SetCaCerts ( DEBUG_VERBOSE, "%a:%a: stored CA cert list (%Lu byte(s))\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)HttpsCaCertsSize )); @@ -176,7 +176,7 @@ SetCipherSuites ( DEBUG_VERBOSE, "%a:%a: not touching cipher suites\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); return; } @@ -204,7 +204,7 @@ SetCipherSuites ( DEBUG_ERROR, "%a:%a: failed to delete %g:\"%s\"\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, &gEdkiiHttpTlsCipherListGuid, EDKII_HTTP_TLS_CIPHER_LIST_VARIABLE )); @@ -216,7 +216,7 @@ SetCipherSuites ( DEBUG_ERROR, "%a:%a: list of cipher suites must not be empty\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); Status = EFI_INVALID_PARAMETER; goto Done; @@ -228,7 +228,7 @@ SetCipherSuites ( DEBUG_ERROR, "%a:%a: failed to allocate HttpsCiphers\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -249,7 +249,7 @@ SetCipherSuites ( DEBUG_ERROR, "%a:%a: failed to set %g:\"%s\"\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, &gEdkiiHttpTlsCipherListGuid, EDKII_HTTP_TLS_CIPHER_LIST_VARIABLE )); @@ -260,7 +260,7 @@ SetCipherSuites ( DEBUG_VERBOSE, "%a:%a: stored list of cipher suites (%Lu byte(s))\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)HttpsCiphersSize )); diff --git a/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDevice.c b/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDevice.c index 831dc1736d..fac3242257 100644 --- a/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDevice.c +++ b/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDevice.c @@ -85,7 +85,7 @@ VirtioMmioInit ( DEBUG (( DEBUG_INFO, "%a virtio 0.9.5, id %d\n", - __FUNCTION__, + __func__, Device->VirtioDevice.SubSystemDeviceId )); Device->VirtioDevice.Revision = VIRTIO_SPEC_REVISION (0, 9, 5); @@ -94,7 +94,7 @@ VirtioMmioInit ( DEBUG (( DEBUG_INFO, "%a virtio 1.0, id %d\n", - __FUNCTION__, + __func__, Device->VirtioDevice.SubSystemDeviceId )); Device->VirtioDevice.Revision = VIRTIO_SPEC_REVISION (1, 0, 0); diff --git a/OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.c b/OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.c index 248a03e8db..a7ab43ca74 100644 --- a/OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.c +++ b/OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.c @@ -394,7 +394,7 @@ QemuLoadKernelImage ( DEBUG (( DEBUG_ERROR, "%a: QemuLoadLegacyImage(): %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -404,7 +404,7 @@ QemuLoadKernelImage ( return EFI_SUCCESS; default: - DEBUG ((DEBUG_ERROR, "%a: LoadImage(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: LoadImage(): %r\n", __func__, Status)); return Status; } @@ -443,7 +443,7 @@ QemuLoadKernelImage ( DEBUG (( DEBUG_ERROR, "%a: kernel command line is not NUL-terminated\n", - __FUNCTION__ + __func__ )); Status = EFI_PROTOCOL_ERROR; goto FreeCommandLine; @@ -492,7 +492,7 @@ QemuLoadKernelImage ( DEBUG (( DEBUG_INFO, "%a: command line: \"%s\"\n", - __FUNCTION__, + __func__, (CHAR16 *)KernelLoadedImage->LoadOptions )); } diff --git a/OvmfPkg/Library/XenIoMmioLib/XenIoMmioLib.c b/OvmfPkg/Library/XenIoMmioLib/XenIoMmioLib.c index caf4a28e1f..db4973406a 100644 --- a/OvmfPkg/Library/XenIoMmioLib/XenIoMmioLib.c +++ b/OvmfPkg/Library/XenIoMmioLib/XenIoMmioLib.c @@ -91,7 +91,7 @@ XenIoMmioInstall ( &mXenBusRootDevicePathTemplate ); if (!XenBusDevicePath) { - DEBUG ((DEBUG_ERROR, "%a: Out of memory\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Out of memory\n", __func__)); Status = EFI_OUT_OF_RESOURCES; goto FreeXenIo; } @@ -115,7 +115,7 @@ XenIoMmioInstall ( DEBUG_ERROR, "%a: Failed to install the EFI_DEVICE_PATH and " "XENIO_PROTOCOL protocols on handle %p (Status == %r)\n", - __FUNCTION__, + __func__, OutHandle, Status )); diff --git a/OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.c b/OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.c index 40c464ce16..2edd92c754 100644 --- a/OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.c +++ b/OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.c @@ -204,7 +204,7 @@ CacheInitrdFile ( DEBUG (( DEBUG_WARN, "%a: failed to read initrd file - %r 0x%lx 0x%lx\n", - __FUNCTION__, + __func__, Status, (UINT64)ReadSize, FileSize diff --git a/OvmfPkg/LsiScsiDxe/LsiScsi.c b/OvmfPkg/LsiScsiDxe/LsiScsi.c index 1f52b85ed2..86c8c6612d 100644 --- a/OvmfPkg/LsiScsiDxe/LsiScsi.c +++ b/OvmfPkg/LsiScsiDxe/LsiScsi.c @@ -512,7 +512,7 @@ LsiScsiProcessRequest ( DEBUG (( DEBUG_VERBOSE, "%a: dstat: %02X, sist0: %02X, sist1: %02X\n", - __FUNCTION__, + __func__, DStat, SIst0, SIst1 @@ -800,7 +800,7 @@ LsiScsiExitBoot ( LSI_SCSI_DEV *Dev; Dev = Context; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); LsiScsiReset (Dev); } diff --git a/OvmfPkg/MptScsiDxe/MptScsi.c b/OvmfPkg/MptScsiDxe/MptScsi.c index f64ccec24d..348acafcf0 100644 --- a/OvmfPkg/MptScsiDxe/MptScsi.c +++ b/OvmfPkg/MptScsiDxe/MptScsi.c @@ -278,7 +278,7 @@ ReportHostAdapterError ( OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet ) { - DEBUG ((DEBUG_ERROR, "%a: fatal error in scsi request\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: fatal error in scsi request\n", __func__)); Packet->InTransferLength = 0; Packet->OutTransferLength = 0; Packet->SenseDataLength = 0; @@ -509,7 +509,7 @@ MptScsiHandleReply ( Packet->HostAdapterStatus = EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OK; Packet->TargetStatus = EFI_EXT_SCSI_STATUS_TARGET_GOOD; } else if ((Reply & BIT31) != 0) { - DEBUG ((DEBUG_INFO, "%a: Full reply returned\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Full reply returned\n", __func__)); // // When reply MSB is set, we got a full reply. Since we submitted only one // reply frame, we know it's IoReply. @@ -549,7 +549,7 @@ MptScsiHandleReply ( return EFI_DEVICE_ERROR; } } else { - DEBUG ((DEBUG_ERROR, "%a: unexpected reply (%x)\n", __FUNCTION__, Reply)); + DEBUG ((DEBUG_ERROR, "%a: unexpected reply (%x)\n", __func__, Reply)); return ReportHostAdapterError (Packet); } @@ -785,7 +785,7 @@ MptScsiExitBoot ( MPT_SCSI_DEV *Dev; Dev = Context; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); MptScsiReset (Dev); } @@ -940,7 +940,7 @@ MptScsiControllerStart ( DEBUG (( DEBUG_WARN, "%a: failed to enable 64-bit DMA addresses\n", - __FUNCTION__ + __func__ )); } diff --git a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c index 3f9c84cf2b..6b2b6797b3 100644 --- a/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c +++ b/OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.c @@ -572,7 +572,7 @@ GetResourcePadding ( DEBUG (( DEBUG_VERBOSE, "%a: Address=%02x:%02x.%x DevicePath=%s\n", - __FUNCTION__, + __func__, Address->Bus, Address->Device, Address->Function, @@ -613,11 +613,11 @@ GetResourcePadding ( DEBUG_VERBOSE, "%a: BusNumbers=0x%x Io=0x%Lx NonPrefetchable32BitMmio=0x%x\n" "%a: Prefetchable32BitMmio=0x%x Prefetchable64BitMmio=0x%Lx\n", - __FUNCTION__, + __func__, ReservationHint.BusNumbers, ReservationHint.Io, ReservationHint.NonPrefetchable32BitMmio, - __FUNCTION__, + __func__, ReservationHint.Prefetchable32BitMmio, ReservationHint.Prefetchable64BitMmio )); diff --git a/OvmfPkg/PlatformDxe/Platform.c b/OvmfPkg/PlatformDxe/Platform.c index e58e75eb22..cd3bfd554c 100644 --- a/OvmfPkg/PlatformDxe/Platform.c +++ b/OvmfPkg/PlatformDxe/Platform.c @@ -239,7 +239,7 @@ ExtractConfig ( UINTN Size; BOOLEAN AllocatedRequest; - DEBUG ((DEBUG_VERBOSE, "%a: Request=\"%s\"\n", __FUNCTION__, Request)); + DEBUG ((DEBUG_VERBOSE, "%a: Request=\"%s\"\n", __func__, Request)); if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; @@ -321,12 +321,12 @@ ExtractConfig ( DEBUG (( DEBUG_ERROR, "%a: BlockToConfig(): %r, Progress=\"%s\"\n", - __FUNCTION__, + __func__, Status, (Status == EFI_DEVICE_ERROR) ? NULL : *Progress )); } else { - DEBUG ((DEBUG_VERBOSE, "%a: Results=\"%s\"\n", __FUNCTION__, *Results)); + DEBUG ((DEBUG_VERBOSE, "%a: Results=\"%s\"\n", __func__, *Results)); } // @@ -431,7 +431,7 @@ RouteConfig ( DEBUG (( DEBUG_VERBOSE, "%a: Configuration=\"%s\"\n", - __FUNCTION__, + __func__, Configuration )); @@ -481,7 +481,7 @@ RouteConfig ( DEBUG (( DEBUG_ERROR, "%a: ConfigToBlock(): %r, Progress=\"%s\"\n", - __FUNCTION__, + __func__, Status, (Status == EFI_BUFFER_TOO_SMALL) ? NULL : *Progress )); @@ -514,7 +514,7 @@ Callback ( DEBUG (( DEBUG_VERBOSE, "%a: Action=0x%Lx QuestionId=%d Type=%d\n", - __FUNCTION__, + __func__, (UINT64)Action, QuestionId, Type @@ -835,7 +835,7 @@ ExecutePlatformConfig ( DEBUG (( (Status == EFI_NOT_FOUND) ? DEBUG_VERBOSE : DEBUG_ERROR, "%a: failed to load platform config: %r\n", - __FUNCTION__, + __func__, Status )); return Status; diff --git a/OvmfPkg/PlatformPei/ClearCache.c b/OvmfPkg/PlatformPei/ClearCache.c index 9f23f9a428..9e59f31df7 100644 --- a/OvmfPkg/PlatformPei/ClearCache.c +++ b/OvmfPkg/PlatformPei/ClearCache.c @@ -59,7 +59,7 @@ ClearCacheOnMpServicesAvailable ( EFI_PEI_MP_SERVICES_PPI *MpServices; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __func__)); // // Clear cache on all the APs in parallel. @@ -74,7 +74,7 @@ ClearCacheOnMpServicesAvailable ( NULL // ProcedureArgument ); if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) { - DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __func__, Status)); return Status; } @@ -108,7 +108,7 @@ InstallClearCacheCallback ( DEBUG (( DEBUG_ERROR, "%a: failed to set up MP Services callback: %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/PlatformPei/FeatureControl.c b/OvmfPkg/PlatformPei/FeatureControl.c index d8a398cd55..d2ec496b74 100644 --- a/OvmfPkg/PlatformPei/FeatureControl.c +++ b/OvmfPkg/PlatformPei/FeatureControl.c @@ -85,7 +85,7 @@ OnMpServicesAvailable ( PlatformInfoHob = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob); - DEBUG ((DEBUG_VERBOSE, "%a: %a\n", gEfiCallerBaseName, __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: %a\n", gEfiCallerBaseName, __func__)); // // Write the MSR on all the APs in parallel. @@ -100,7 +100,7 @@ OnMpServicesAvailable ( PlatformInfoHob // ProcedureArgument ); if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) { - DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __func__, Status)); return Status; } @@ -154,7 +154,7 @@ InstallFeatureControlCallback ( DEBUG (( DEBUG_ERROR, "%a: failed to set up MP Services callback: %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/PlatformPei/MemDetect.c b/OvmfPkg/PlatformPei/MemDetect.c index 41d186986b..0c755c4940 100644 --- a/OvmfPkg/PlatformPei/MemDetect.c +++ b/OvmfPkg/PlatformPei/MemDetect.c @@ -75,7 +75,7 @@ Q35TsegMbytesInitialization ( DEBUG (( DEBUG_INFO, "%a: QEMU offers an extended TSEG (%d MB)\n", - __FUNCTION__, + __func__, ExtendedTsegMbytes )); PcdStatus = PcdSet16S (PcdQ35TsegMbytes, ExtendedTsegMbytes); @@ -97,7 +97,7 @@ Q35SmramAtDefaultSmbaseInitialization ( DEBUG (( DEBUG_INFO, "%a: SMRAM at default SMBASE not checked due to CSM\n", - __FUNCTION__ + __func__ )); } else { UINTN CtlReg; @@ -111,7 +111,7 @@ Q35SmramAtDefaultSmbaseInitialization ( DEBUG (( DEBUG_INFO, "%a: SMRAM at default SMBASE %a\n", - __FUNCTION__, + __func__, PlatformInfoHob->Q35SmramAtDefaultSmbase ? "found" : "not found" )); } @@ -152,7 +152,7 @@ AddressWidthInitialization ( DEBUG (( DEBUG_INFO, "%a: disabling 64-bit PCI host aperture\n", - __FUNCTION__ + __func__ )); PcdStatus = PcdSet64S (PcdPciMmio64Size, 0); ASSERT_RETURN_ERROR (PcdStatus); @@ -175,7 +175,7 @@ AddressWidthInitialization ( DEBUG (( DEBUG_INFO, "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n", - __FUNCTION__, + __func__, PlatformInfoHob->PcdPciMmio64Base, PlatformInfoHob->PcdPciMmio64Size )); @@ -307,7 +307,7 @@ PublishPeiMemory ( DEBUG (( DEBUG_INFO, "%a: PhysMemAddressWidth=%d PeiMemoryCap=%u KB\n", - __FUNCTION__, + __func__, PlatformInfoHob->PhysMemAddressWidth, PeiMemoryCap >> 10 )); diff --git a/OvmfPkg/PlatformPei/MemTypeInfo.c b/OvmfPkg/PlatformPei/MemTypeInfo.c index eb37febb31..ea049b21cf 100644 --- a/OvmfPkg/PlatformPei/MemTypeInfo.c +++ b/OvmfPkg/PlatformPei/MemTypeInfo.c @@ -100,7 +100,7 @@ RefreshMemTypeInfo ( // If the UEFI variable couldn't be read for some other reason, we // similarly can't use it for udpating mMemoryTypeInformation. // - DEBUG ((DEBUG_ERROR, "%a: GetVariable(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: GetVariable(): %r\n", __func__, Status)); return; } @@ -111,7 +111,7 @@ RefreshMemTypeInfo ( DEBUG (( DEBUG_ERROR, "%a: invalid UEFI variable size %Lu\n", - __FUNCTION__, + __func__, (UINT64)DataSize )); return; @@ -151,7 +151,7 @@ RefreshMemTypeInfo ( DEBUG (( DEBUG_VERBOSE, "%a: Type 0x%x: NumberOfPages 0x%x -> 0x%x\n", - __FUNCTION__, + __func__, HobRecord->Type, HobRecord->NumberOfPages, VariableRecord->NumberOfPages @@ -183,7 +183,7 @@ OnReadOnlyVariable2Available ( IN VOID *Ppi ) { - DEBUG ((DEBUG_VERBOSE, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a\n", __func__)); RefreshMemTypeInfo (Ppi); BuildMemTypeInfoHob (); @@ -222,7 +222,7 @@ MemTypeInfoInitialization ( DEBUG (( DEBUG_ERROR, "%a: failed to set up R/O Variable 2 callback: %r\n", - __FUNCTION__, + __func__, Status )); ASSERT (FALSE); diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index 148240342b..cc9384ba5c 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -114,7 +114,7 @@ MicrovmInitialization ( Status = QemuFwCfgFindFile ("etc/fdt", &FdtItem, &FdtSize); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: no etc/fdt found in fw_cfg, using dummy\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: no etc/fdt found in fw_cfg, using dummy\n", __func__)); FdtItem = 0; FdtSize = sizeof (EmptyFdt); } @@ -122,7 +122,7 @@ MicrovmInitialization ( FdtPages = EFI_SIZE_TO_PAGES (FdtSize); NewBase = AllocatePages (FdtPages); if (NewBase == NULL) { - DEBUG ((DEBUG_INFO, "%a: AllocatePages failed\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: AllocatePages failed\n", __func__)); return; } @@ -135,14 +135,14 @@ MicrovmInitialization ( FdtHobData = BuildGuidHob (&gFdtHobGuid, sizeof (*FdtHobData)); if (FdtHobData == NULL) { - DEBUG ((DEBUG_INFO, "%a: BuildGuidHob failed\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: BuildGuidHob failed\n", __func__)); return; } DEBUG (( DEBUG_INFO, "%a: fdt at 0x%x (size %d)\n", - __FUNCTION__, + __func__, NewBase, FdtSize )); @@ -158,7 +158,7 @@ MiscInitializationForMicrovm ( ASSERT (PlatformInfoHob->HostBridgeDevId == 0xffff); - DEBUG ((DEBUG_INFO, "%a: microvm\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: microvm\n", __func__)); // // Disable A20 Mask // @@ -240,17 +240,17 @@ S3Verification ( DEBUG (( DEBUG_ERROR, "%a: S3Resume2Pei doesn't support X64 PEI + SMM yet.\n", - __FUNCTION__ + __func__ )); DEBUG (( DEBUG_ERROR, "%a: Please disable S3 on the QEMU command line (see the README),\n", - __FUNCTION__ + __func__ )); DEBUG (( DEBUG_ERROR, "%a: or build OVMF with \"OvmfPkgIa32X64.dsc\".\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); CpuDeadLoop (); @@ -273,7 +273,7 @@ Q35BoardVerification ( DEBUG_ERROR, "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; " "only DID=0x%04x (Q35) is supported\n", - __FUNCTION__, + __func__, PlatformInfoHob->HostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); diff --git a/OvmfPkg/PvScsiDxe/PvScsi.c b/OvmfPkg/PvScsiDxe/PvScsi.c index 47cc0ae59b..6ec5040f7e 100644 --- a/OvmfPkg/PvScsiDxe/PvScsi.c +++ b/OvmfPkg/PvScsiDxe/PvScsi.c @@ -904,7 +904,7 @@ PvScsiSetPciAttributes ( DEBUG (( DEBUG_WARN, "%a: failed to enable 64-bit DMA addresses\n", - __FUNCTION__ + __func__ )); } @@ -1279,7 +1279,7 @@ PvScsiExitBoot ( PVSCSI_DEV *Dev; Dev = Context; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); // // Reset the device to stop device usage of the rings. diff --git a/OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.c b/OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.c index d4f3cd9225..3c12085f6c 100644 --- a/OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.c +++ b/OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.c @@ -968,7 +968,7 @@ FetchBlob ( DEBUG (( DEBUG_ERROR, "%a: failed to allocate %Ld bytes for \"%s\"\n", - __FUNCTION__, + __func__, (INT64)Blob->Size, Blob->Name )); @@ -978,7 +978,7 @@ FetchBlob ( DEBUG (( DEBUG_INFO, "%a: loading %Ld bytes for \"%s\"\n", - __FUNCTION__, + __func__, (INT64)Blob->Size, Blob->Name )); @@ -1001,7 +1001,7 @@ FetchBlob ( DEBUG (( DEBUG_VERBOSE, "%a: %Ld bytes remaining for \"%s\" (%d)\n", - __FUNCTION__, + __func__, (INT64)Left, Blob->Name, (INT32)Idx @@ -1051,7 +1051,7 @@ QemuKernelLoaderFsDxeEntrypoint ( Status = gRT->GetTime (&mInitTime, NULL /* Capabilities */); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: GetTime(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: GetTime(): %r\n", __func__, Status)); return Status; } @@ -1101,7 +1101,7 @@ QemuKernelLoaderFsDxeEntrypoint ( DEBUG (( DEBUG_ERROR, "%a: InstallMultipleProtocolInterfaces(): %r\n", - __FUNCTION__, + __func__, Status )); goto FreeBlobs; @@ -1121,7 +1121,7 @@ QemuKernelLoaderFsDxeEntrypoint ( DEBUG (( DEBUG_ERROR, "%a: InstallMultipleProtocolInterfaces(): %r\n", - __FUNCTION__, + __func__, Status )); goto UninstallFileSystemHandle; diff --git a/OvmfPkg/QemuRamfbDxe/QemuRamfb.c b/OvmfPkg/QemuRamfbDxe/QemuRamfb.c index f5113fbc78..5a1044f0dc 100644 --- a/OvmfPkg/QemuRamfbDxe/QemuRamfb.c +++ b/OvmfPkg/QemuRamfbDxe/QemuRamfb.c @@ -189,7 +189,7 @@ QemuRamfbGraphicsOutputSetMode ( DEBUG (( DEBUG_WARN, "%a: clearing the screen failed: %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/QemuVideoDxe/Gop.c b/OvmfPkg/QemuVideoDxe/Gop.c index 7a9fe208c9..b11eed7558 100644 --- a/OvmfPkg/QemuVideoDxe/Gop.c +++ b/OvmfPkg/QemuVideoDxe/Gop.c @@ -37,7 +37,7 @@ QemuVideoCompleteModeInfo ( Info->PixelInformation.BlueMask = 0; Info->PixelInformation.ReservedMask = 0; } else { - DEBUG ((DEBUG_ERROR, "%a: Invalid ColorDepth %u", __FUNCTION__, ModeData->ColorDepth)); + DEBUG ((DEBUG_ERROR, "%a: Invalid ColorDepth %u", __func__, ModeData->ColorDepth)); ASSERT (FALSE); } diff --git a/OvmfPkg/QemuVideoDxe/Initialize.c b/OvmfPkg/QemuVideoDxe/Initialize.c index 2a3cbc65c3..050ae878ec 100644 --- a/OvmfPkg/QemuVideoDxe/Initialize.c +++ b/OvmfPkg/QemuVideoDxe/Initialize.c @@ -310,7 +310,7 @@ QemuVideoBochsEdid ( DEBUG (( DEBUG_INFO, "%a: mmio read failed\n", - __FUNCTION__ + __func__ )); return; } @@ -321,7 +321,7 @@ QemuVideoBochsEdid ( DEBUG (( DEBUG_INFO, "%a: magic check failed\n", - __FUNCTION__ + __func__ )); return; } @@ -329,7 +329,7 @@ QemuVideoBochsEdid ( DEBUG (( DEBUG_INFO, "%a: blob found (extensions: %d)\n", - __FUNCTION__, + __func__, Private->Edid[126] )); @@ -339,7 +339,7 @@ QemuVideoBochsEdid ( DEBUG (( DEBUG_INFO, "%a: no detailed timing descriptor\n", - __FUNCTION__ + __func__ )); return; } @@ -349,7 +349,7 @@ QemuVideoBochsEdid ( DEBUG (( DEBUG_INFO, "%a: default resolution: %dx%d\n", - __FUNCTION__, + __func__, *XRes, *YRes )); @@ -436,7 +436,7 @@ QemuVideoBochsModeSetup ( DEBUG_ERROR, "%a: can't read size of drawable buffer from QXL " "ROM\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -448,7 +448,7 @@ QemuVideoBochsModeSetup ( DEBUG (( DEBUG_INFO, "%a: AvailableFbSize=0x%x\n", - __FUNCTION__, + __func__, AvailableFbSize )); diff --git a/OvmfPkg/QemuVideoDxe/VbeShim.c b/OvmfPkg/QemuVideoDxe/VbeShim.c index 2a048211a8..8f151b96f9 100644 --- a/OvmfPkg/QemuVideoDxe/VbeShim.c +++ b/OvmfPkg/QemuVideoDxe/VbeShim.c @@ -73,12 +73,12 @@ InstallVbeShim ( DEBUG (( DEBUG_WARN, "%a: page 0 protected, not installing VBE shim\n", - __FUNCTION__ + __func__ )); DEBUG (( DEBUG_WARN, "%a: page 0 protection prevents Windows 7 from booting anyway\n", - __FUNCTION__ + __func__ )); return; } @@ -117,7 +117,7 @@ InstallVbeShim ( DEBUG (( DEBUG_INFO, "%a: Video BIOS handler found at %04x:%04x\n", - __FUNCTION__, + __func__, Int0x10->Segment, Int0x10->Offset )); @@ -131,7 +131,7 @@ InstallVbeShim ( DEBUG (( DEBUG_INFO, "%a: failed to allocate page at zero: %r\n", - __FUNCTION__, + __func__, Segment0AllocationStatus )); } else { @@ -162,7 +162,7 @@ InstallVbeShim ( DEBUG (( DEBUG_ERROR, "%a: unknown host bridge device ID: 0x%04x\n", - __FUNCTION__, + __func__, HostBridgeDevId )); ASSERT (FALSE); @@ -324,5 +324,5 @@ InstallVbeShim ( Int0x10->Segment = (UINT16)((UINT32)SegmentC >> 4); Int0x10->Offset = (UINT16)((UINTN)(VbeModeInfo + 1) - SegmentC); - DEBUG ((DEBUG_INFO, "%a: VBE shim installed\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: VBE shim installed\n", __func__)); } diff --git a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c index 2559889638..be4316f320 100644 --- a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/PlatformBm.c @@ -193,7 +193,7 @@ FilterAndProcess ( DEBUG (( DEBUG_VERBOSE, "%a: %g: %r\n", - __FUNCTION__, + __func__, ProtocolGuid, Status )); @@ -264,7 +264,7 @@ IsPciDisplay ( &Pci ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __func__, ReportText, Status)); return FALSE; } @@ -413,7 +413,7 @@ IsVirtioPciRng ( return FALSE; PciError: - DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __FUNCTION__, ReportText, Status)); + DEBUG ((DEBUG_ERROR, "%a: %s: %r\n", __func__, ReportText, Status)); return FALSE; } @@ -440,7 +440,7 @@ Connect ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %s: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -466,7 +466,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: handle %p: device path not found\n", - __FUNCTION__, + __func__, ReportText, Handle )); @@ -478,7 +478,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ConOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -490,7 +490,7 @@ AddOutput ( DEBUG (( DEBUG_ERROR, "%a: %s: adding to ErrOut: %r\n", - __FUNCTION__, + __func__, ReportText, Status )); @@ -500,7 +500,7 @@ AddOutput ( DEBUG (( DEBUG_VERBOSE, "%a: %s: added to ConOut and ErrOut\n", - __FUNCTION__, + __func__, ReportText )); } @@ -701,7 +701,7 @@ RemoveStaleFvFileOptions ( DEBUG (( EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_VERBOSE, "%a: removing stale Boot#%04x %s: %r\n", - __FUNCTION__, + __func__, (UINT32)BootOptions[Index].OptionNumber, DevicePathString == NULL ? L"" : DevicePathString, Status @@ -879,7 +879,7 @@ PlatformBootManagerBeforeConsole ( DEBUG (( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: SetVariable(%s, %u): %r\n", - __FUNCTION__, + __func__, EFI_TIME_OUT_VARIABLE_NAME, FrontPageTimeout, Status diff --git a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c index 736628174f..c1ed425da0 100644 --- a/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c +++ b/OvmfPkg/RiscVVirt/Library/PlatformBootManagerLib/QemuKernel.c @@ -66,7 +66,7 @@ TryRunningQemuKernel ( DEBUG (( DEBUG_ERROR, "%a: QemuStartKernelImage(): %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c index a58b7aae6b..4035ba8d85 100644 --- a/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c +++ b/OvmfPkg/RiscVVirt/Library/PrePiHobListPointerLib/PrePiHobListPointer.c @@ -31,7 +31,7 @@ PrePeiGetHobList ( GetFirmwareContextPointer (&FirmwareContext); if (FirmwareContext == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __func__)); return NULL; } @@ -56,7 +56,7 @@ PrePeiSetHobList ( GetFirmwareContextPointer (&FirmwareContext); if (FirmwareContext == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __func__)); return EFI_NOT_READY; } diff --git a/OvmfPkg/RiscVVirt/Sec/Memory.c b/OvmfPkg/RiscVVirt/Sec/Memory.c index f7a72c7bb4..0e2690c736 100644 --- a/OvmfPkg/RiscVVirt/Sec/Memory.c +++ b/OvmfPkg/RiscVVirt/Sec/Memory.c @@ -97,7 +97,7 @@ InitMmu ( // Set supervisor translation mode to Bare mode // RiscVSetSupervisorAddressTranslationRegister ((UINT64)SATP_MODE_OFF << 60); - DEBUG ((DEBUG_INFO, "%a: Set Supervisor address mode to bare-metal mode.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Set Supervisor address mode to bare-metal mode.\n", __func__)); } /** @@ -276,13 +276,13 @@ MemoryPeimInitialization ( GetFirmwareContextPointer (&FirmwareContext); if (FirmwareContext == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __func__)); return EFI_UNSUPPORTED; } FdtPointer = (VOID *)FirmwareContext->FlattenedDeviceTree; if (FdtPointer == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __func__)); return EFI_UNSUPPORTED; } @@ -306,7 +306,7 @@ MemoryPeimInitialization ( DEBUG (( DEBUG_INFO, "%a: System RAM @ 0x%lx - 0x%lx\n", - __FUNCTION__, + __func__, CurBase, CurBase + CurSize - 1 )); @@ -319,7 +319,7 @@ MemoryPeimInitialization ( DEBUG (( DEBUG_ERROR, "%a: Failed to parse FDT memory node\n", - __FUNCTION__ + __func__ )); } } diff --git a/OvmfPkg/RiscVVirt/Sec/Platform.c b/OvmfPkg/RiscVVirt/Sec/Platform.c index e8fd126cf8..3645c27b0b 100644 --- a/OvmfPkg/RiscVVirt/Sec/Platform.c +++ b/OvmfPkg/RiscVVirt/Sec/Platform.c @@ -43,20 +43,20 @@ PlatformPeimInitialization ( GetFirmwareContextPointer (&FirmwareContext); if (FirmwareContext == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Firmware Context is NULL\n", __func__)); return EFI_UNSUPPORTED; } FdtPointer = (VOID *)FirmwareContext->FlattenedDeviceTree; if (FdtPointer == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Invalid FDT pointer\n", __func__)); return EFI_UNSUPPORTED; } - DEBUG ((DEBUG_INFO, "%a: Build FDT HOB - FDT at address: 0x%x \n", __FUNCTION__, FdtPointer)); + DEBUG ((DEBUG_INFO, "%a: Build FDT HOB - FDT at address: 0x%x \n", __func__, FdtPointer)); Base = FdtPointer; if (fdt_check_header (Base) != 0) { - DEBUG ((DEBUG_ERROR, "%a: Corrupted DTB\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Corrupted DTB\n", __func__)); return EFI_UNSUPPORTED; } @@ -64,7 +64,7 @@ PlatformPeimInitialization ( FdtPages = EFI_SIZE_TO_PAGES (FdtSize); NewBase = AllocatePages (FdtPages); if (NewBase == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Could not allocate memory for DTB\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Could not allocate memory for DTB\n", __func__)); return EFI_UNSUPPORTED; } @@ -72,7 +72,7 @@ PlatformPeimInitialization ( FdtHobData = BuildGuidHob (&gFdtHobGuid, sizeof *FdtHobData); if (FdtHobData == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Could not build FDT Hob\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Could not build FDT Hob\n", __func__)); return EFI_UNSUPPORTED; } diff --git a/OvmfPkg/RiscVVirt/Sec/SecMain.c b/OvmfPkg/RiscVVirt/Sec/SecMain.c index adf73f2eb6..b052048178 100644 --- a/OvmfPkg/RiscVVirt/Sec/SecMain.c +++ b/OvmfPkg/RiscVVirt/Sec/SecMain.c @@ -63,7 +63,7 @@ SecStartup ( DEBUG (( DEBUG_INFO, "%a() BootHartId: 0x%x, DeviceTreeAddress=0x%x\n", - __FUNCTION__, + __func__, BootHartId, DeviceTreeAddress )); diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index e96726d6ec..31da5d0ace 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -386,7 +386,7 @@ DecompressMemFvs ( DEBUG_VERBOSE, "%a: OutputBuffer@%p+0x%x ScratchBuffer@%p+0x%x " "PcdOvmfDecompressionScratchEnd=0x%x\n", - __FUNCTION__, + __func__, OutputBuffer, OutputBufferSize, ScratchBuffer, diff --git a/OvmfPkg/SmmAccess/SmmAccessPei.c b/OvmfPkg/SmmAccess/SmmAccessPei.c index 4be5f2423e..0e57b7804c 100644 --- a/OvmfPkg/SmmAccess/SmmAccessPei.c +++ b/OvmfPkg/SmmAccess/SmmAccessPei.c @@ -263,7 +263,7 @@ SmmAccessPeiEntryPoint ( DEBUG_ERROR, "%a: no SMRAM with host bridge DID=0x%04x; only " "DID=0x%04x (Q35) is supported\n", - __FUNCTION__, + __func__, HostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); @@ -283,7 +283,7 @@ SmmAccessPeiEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: this Q35 implementation lacks SMRAM\n", - __FUNCTION__ + __func__ )); goto WrongConfig; } @@ -378,7 +378,7 @@ SmmAccessPeiEntryPoint ( DEBUG (( DEBUG_VERBOSE, "%a: SMRAM map follows, %d entries\n", - __FUNCTION__, + __func__, (INT32)Count )); DEBUG (( diff --git a/OvmfPkg/SmmControl2Dxe/SmiFeatures.c b/OvmfPkg/SmmControl2Dxe/SmiFeatures.c index daeb7195ae..4bd24bf119 100644 --- a/OvmfPkg/SmmControl2Dxe/SmiFeatures.c +++ b/OvmfPkg/SmmControl2Dxe/SmiFeatures.c @@ -113,7 +113,7 @@ NegotiateSmiFeatures ( DEBUG (( DEBUG_INFO, "%a: SMI feature negotiation unavailable\n", - __FUNCTION__ + __func__ )); return FALSE; } @@ -129,7 +129,7 @@ NegotiateSmiFeatures ( DEBUG (( DEBUG_ERROR, "%a: size mismatch in feature negotiation\n", - __FUNCTION__ + __func__ )); goto FatalError; } @@ -168,7 +168,7 @@ NegotiateSmiFeatures ( DEBUG (( DEBUG_ERROR, "%a: negotiation failed for feature bitmap 0x%Lx\n", - __FUNCTION__, + __func__, mSmiFeatures )); goto FatalError; @@ -179,7 +179,7 @@ NegotiateSmiFeatures ( // If we can't get broadcast SMIs from QEMU, that's acceptable too, // although not optimal. // - DEBUG ((DEBUG_INFO, "%a: SMI broadcast unavailable\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: SMI broadcast unavailable\n", __func__)); } else { // // Configure the traditional AP sync / SMI delivery mode for @@ -192,31 +192,31 @@ NegotiateSmiFeatures ( DEBUG (( DEBUG_ERROR, "%a: PiSmmCpuDxeSmm PCD configuration failed\n", - __FUNCTION__ + __func__ )); goto FatalError; } - DEBUG ((DEBUG_INFO, "%a: using SMI broadcast\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: using SMI broadcast\n", __func__)); } if ((mSmiFeatures & ICH9_LPC_SMI_F_CPU_HOTPLUG) == 0) { - DEBUG ((DEBUG_INFO, "%a: CPU hotplug not negotiated\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: CPU hotplug not negotiated\n", __func__)); } else { DEBUG (( DEBUG_INFO, "%a: CPU hotplug with SMI negotiated\n", - __FUNCTION__ + __func__ )); } if ((mSmiFeatures & ICH9_LPC_SMI_F_CPU_HOT_UNPLUG) == 0) { - DEBUG ((DEBUG_INFO, "%a: CPU hot-unplug not negotiated\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: CPU hot-unplug not negotiated\n", __func__)); } else { DEBUG (( DEBUG_INFO, "%a: CPU hot-unplug with SMI negotiated\n", - __FUNCTION__ + __func__ )); } @@ -292,7 +292,7 @@ AppendFwCfgBootScript ( DEBUG (( DEBUG_VERBOSE, "%a: SMI feature negotiation boot script saved\n", - __FUNCTION__ + __func__ )); return; diff --git a/OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.c b/OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.c index edbf8ac431..e7438b18dd 100644 --- a/OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.c +++ b/OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.c @@ -205,7 +205,7 @@ SmmControl2DxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: this Q35 implementation lacks SMI\n", - __FUNCTION__ + __func__ )); goto FatalError; } @@ -234,7 +234,7 @@ SmmControl2DxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: failed to lock down GBL_SMI_EN\n", - __FUNCTION__ + __func__ )); goto FatalError; } @@ -260,7 +260,7 @@ SmmControl2DxeEntryPoint ( &mS3SaveStateInstalled ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: CreateEvent: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: CreateEvent: %r\n", __func__, Status)); goto FatalError; } @@ -273,7 +273,7 @@ SmmControl2DxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: RegisterProtocolNotify: %r\n", - __FUNCTION__, + __func__, Status )); goto ReleaseEvent; @@ -284,7 +284,7 @@ SmmControl2DxeEntryPoint ( // Status = gBS->SignalEvent (mS3SaveStateInstalled); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: SignalEvent: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: SignalEvent: %r\n", __func__, Status)); goto ReleaseEvent; } } @@ -303,7 +303,7 @@ SmmControl2DxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: InstallMultipleProtocolInterfaces: %r\n", - __FUNCTION__, + __func__, Status )); goto ReleaseEvent; @@ -376,7 +376,7 @@ OnS3SaveStateInstalled ( DEBUG (( DEBUG_ERROR, "%a: EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE: %r\n", - __FUNCTION__, + __func__, Status )); ASSERT (FALSE); @@ -400,14 +400,14 @@ OnS3SaveStateInstalled ( DEBUG (( DEBUG_ERROR, "%a: EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE: %r\n", - __FUNCTION__, + __func__, Status )); ASSERT (FALSE); CpuDeadLoop (); } - DEBUG ((DEBUG_VERBOSE, "%a: chipset boot script saved\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: chipset boot script saved\n", __func__)); // // Append a boot script fragment that re-selects the negotiated SMI features. diff --git a/OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c b/OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c index 96771b1935..65bb1a9268 100644 --- a/OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c +++ b/OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c @@ -49,11 +49,11 @@ Tcg2ConfigPeimEntryPoint ( UINTN Size; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a\n", __func__)); Status = InternalTpm12Detect (); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: TPM1.2 detected\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: TPM1.2 detected\n", __func__)); Size = sizeof (gEfiTpmDeviceInstanceTpm12Guid); Status = PcdSetPtrS ( PcdTpmInstanceGuid, @@ -64,7 +64,7 @@ Tcg2ConfigPeimEntryPoint ( } else { Status = Tpm2RequestUseTpm (); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: TPM2 detected\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: TPM2 detected\n", __func__)); Size = sizeof (gEfiTpmDeviceInstanceTpm20DtpmGuid); Status = PcdSetPtrS ( PcdTpmInstanceGuid, @@ -73,7 +73,7 @@ Tcg2ConfigPeimEntryPoint ( ); ASSERT_EFI_ERROR (Status); } else { - DEBUG ((DEBUG_INFO, "%a: no TPM detected\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: no TPM detected\n", __func__)); // // If no TPM2 was detected, we still need to install // TpmInitializationDonePpi. Namely, Tcg2Pei will exit early upon seeing diff --git a/OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPeim.c b/OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPeim.c index 88bb9e8e04..c671aa21ea 100644 --- a/OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPeim.c +++ b/OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPeim.c @@ -38,7 +38,7 @@ TpmMmioSevDecryptPeimEntryPoint ( RETURN_STATUS DecryptStatus; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a\n", __func__)); // // If SEV is active, MMIO succeeds against an encrypted physical address @@ -60,7 +60,7 @@ TpmMmioSevDecryptPeimEntryPoint ( DEBUG (( DEBUG_INFO, "%a: mapping TPM MMIO address range unencrypted\n", - __FUNCTION__ + __func__ )); DecryptStatus = MemEncryptSevClearMmioPageEncMask ( @@ -73,7 +73,7 @@ TpmMmioSevDecryptPeimEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: failed to map TPM MMIO address range unencrypted\n", - __FUNCTION__ + __func__ )); ASSERT_RETURN_ERROR (DecryptStatus); } diff --git a/OvmfPkg/TdxDxe/TdxAcpiTable.c b/OvmfPkg/TdxDxe/TdxAcpiTable.c index 8a1abe8b1d..5dc27e23ad 100644 --- a/OvmfPkg/TdxDxe/TdxAcpiTable.c +++ b/OvmfPkg/TdxDxe/TdxAcpiTable.c @@ -175,7 +175,7 @@ AlterAcpiTable ( NewMadtTableLength = Table->Length + sizeof (EFI_ACPI_6_4_MULTIPROCESSOR_WAKEUP_STRUCTURE); NewMadtTable = AllocatePool (NewMadtTableLength); if (NewMadtTable == NULL) { - DEBUG ((DEBUG_ERROR, "%a: OUT_OF_SOURCES error.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: OUT_OF_SOURCES error.\n", __func__)); break; } diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c index f9a41f6aab..6b9ef26133 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashDxe.c @@ -422,11 +422,11 @@ NorFlashFvbInitialize ( // Install the Default FVB header if required if (EFI_ERROR (Status)) { // There is no valid header, so time to install one. - DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __func__)); DEBUG (( DEBUG_INFO, "%a: Installing a correct one for this volume.\n", - __FUNCTION__ + __func__ )); // Erase all the NorFlash that is reserved for variable storage diff --git a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c index cc5eefaaf3..5ee98e9b59 100644 --- a/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c +++ b/OvmfPkg/VirtNorFlashDxe/VirtNorFlashFvb.c @@ -74,7 +74,7 @@ InitializeFvAndVariableStoreHeaders ( DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwWorkingBase is not contiguous with NvStorageVariableBase region\n", - __FUNCTION__ + __func__ )); return EFI_INVALID_PARAMETER; } @@ -83,7 +83,7 @@ InitializeFvAndVariableStoreHeaders ( DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwSpareBase is not contiguous with NvStorageFtwWorkingBase region\n", - __FUNCTION__ + __func__ )); return EFI_INVALID_PARAMETER; } @@ -93,7 +93,7 @@ InitializeFvAndVariableStoreHeaders ( DEBUG (( DEBUG_ERROR, "%a: NvStorageVariableSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, + __func__, NvStorageVariableSize )); return EFI_INVALID_PARAMETER; @@ -103,7 +103,7 @@ InitializeFvAndVariableStoreHeaders ( DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwWorkingSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, + __func__, NvStorageFtwWorkingSize )); return EFI_INVALID_PARAMETER; @@ -113,7 +113,7 @@ InitializeFvAndVariableStoreHeaders ( DEBUG (( DEBUG_ERROR, "%a: NvStorageFtwSpareSize is 0x%x, should be atleast one block size\n", - __FUNCTION__, + __func__, NvStorageFtwSpareSize )); return EFI_INVALID_PARAMETER; @@ -124,7 +124,7 @@ InitializeFvAndVariableStoreHeaders ( (NvStorageFtwWorkingBase % Instance->BlockSize != 0) || (NvStorageFtwSpareBase % Instance->BlockSize != 0)) { - DEBUG ((DEBUG_ERROR, "%a: NvStorage Base addresses must be aligned to block size boundaries", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: NvStorage Base addresses must be aligned to block size boundaries", __func__)); return EFI_INVALID_PARAMETER; } @@ -209,7 +209,7 @@ ValidateFvHeader ( DEBUG (( DEBUG_INFO, "%a: No Firmware Volume header present\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -219,7 +219,7 @@ ValidateFvHeader ( DEBUG (( DEBUG_INFO, "%a: Firmware Volume Guid non-compatible\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -230,7 +230,7 @@ ValidateFvHeader ( DEBUG (( DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n", - __FUNCTION__, + __func__, Checksum )); return EFI_NOT_FOUND; @@ -245,7 +245,7 @@ ValidateFvHeader ( DEBUG (( DEBUG_INFO, "%a: Variable Store Guid non-compatible\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } @@ -255,7 +255,7 @@ ValidateFvHeader ( DEBUG (( DEBUG_INFO, "%a: Variable Store Length does not match\n", - __FUNCTION__ + __func__ )); return EFI_NOT_FOUND; } diff --git a/OvmfPkg/VirtioBlkDxe/VirtioBlk.c b/OvmfPkg/VirtioBlkDxe/VirtioBlk.c index cc094cc4dd..74ed52f9da 100644 --- a/OvmfPkg/VirtioBlkDxe/VirtioBlk.c +++ b/OvmfPkg/VirtioBlkDxe/VirtioBlk.c @@ -943,7 +943,7 @@ VirtioBlkInit ( DEBUG (( DEBUG_INFO, "%a: LbaSize=0x%x[B] NumBlocks=0x%Lx[Lba]\n", - __FUNCTION__, + __func__, Dev->BlockIoMedia.BlockSize, Dev->BlockIoMedia.LastBlock + 1 )); @@ -958,14 +958,14 @@ VirtioBlkInit ( DEBUG (( DEBUG_INFO, "%a: FirstAligned=0x%Lx[Lba] PhysBlkSize=0x%x[Lba]\n", - __FUNCTION__, + __func__, Dev->BlockIoMedia.LowestAlignedLba, Dev->BlockIoMedia.LogicalBlocksPerPhysicalBlock )); DEBUG (( DEBUG_INFO, "%a: OptimalTransferLengthGranularity=0x%x[Lba]\n", - __FUNCTION__, + __func__, Dev->BlockIoMedia.OptimalTransferLengthGranularity )); } @@ -1037,7 +1037,7 @@ VirtioBlkExitBoot ( { VBLK_DEV *Dev; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); // // Reset the device. This causes the hypervisor to forget about the virtio // ring. diff --git a/OvmfPkg/VirtioFsDxe/FuseFlush.c b/OvmfPkg/VirtioFsDxe/FuseFlush.c index ff5d6f3f5a..26cc12087b 100644 --- a/OvmfPkg/VirtioFsDxe/FuseFlush.c +++ b/OvmfPkg/VirtioFsDxe/FuseFlush.c @@ -111,7 +111,7 @@ VirtioFsFuseFlush ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu FuseHandle=%Lu " "Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, FuseHandle, diff --git a/OvmfPkg/VirtioFsDxe/FuseFsync.c b/OvmfPkg/VirtioFsDxe/FuseFsync.c index c537b064e6..11a4ab4e77 100644 --- a/OvmfPkg/VirtioFsDxe/FuseFsync.c +++ b/OvmfPkg/VirtioFsDxe/FuseFsync.c @@ -116,7 +116,7 @@ VirtioFsFuseFsyncFileOrDir ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu FuseHandle=%Lu " "IsDir=%d Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, FuseHandle, diff --git a/OvmfPkg/VirtioFsDxe/FuseGetAttr.c b/OvmfPkg/VirtioFsDxe/FuseGetAttr.c index 1dc0349a55..6f6e89c4fd 100644 --- a/OvmfPkg/VirtioFsDxe/FuseGetAttr.c +++ b/OvmfPkg/VirtioFsDxe/FuseGetAttr.c @@ -116,7 +116,7 @@ VirtioFsFuseGetAttr ( DEBUG (( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, CommonResp.Error diff --git a/OvmfPkg/VirtioFsDxe/FuseInit.c b/OvmfPkg/VirtioFsDxe/FuseInit.c index d34fc05a50..590ef441ef 100644 --- a/OvmfPkg/VirtioFsDxe/FuseInit.c +++ b/OvmfPkg/VirtioFsDxe/FuseInit.c @@ -125,7 +125,7 @@ VirtioFsFuseInitSession ( DEBUG (( DEBUG_ERROR, "%a: Label=\"%s\" Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, CommonResp.Error )); diff --git a/OvmfPkg/VirtioFsDxe/FuseLookup.c b/OvmfPkg/VirtioFsDxe/FuseLookup.c index f2bda8a547..277a19fb1f 100644 --- a/OvmfPkg/VirtioFsDxe/FuseLookup.c +++ b/OvmfPkg/VirtioFsDxe/FuseLookup.c @@ -128,7 +128,7 @@ VirtioFsFuseLookup ( DEBUG_VERBOSE : DEBUG_ERROR), "%a: Label=\"%s\" DirNodeId=%Lu Name=\"%a\" Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, DirNodeId, Name, diff --git a/OvmfPkg/VirtioFsDxe/FuseMkDir.c b/OvmfPkg/VirtioFsDxe/FuseMkDir.c index 409e09a418..847d0c0798 100644 --- a/OvmfPkg/VirtioFsDxe/FuseMkDir.c +++ b/OvmfPkg/VirtioFsDxe/FuseMkDir.c @@ -127,7 +127,7 @@ VirtioFsFuseMkDir ( DEBUG_ERROR, "%a: Label=\"%s\" ParentNodeId=%Lu Name=\"%a\" " "Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, ParentNodeId, Name, diff --git a/OvmfPkg/VirtioFsDxe/FuseOpen.c b/OvmfPkg/VirtioFsDxe/FuseOpen.c index 64015bb6cc..99ea5f3b71 100644 --- a/OvmfPkg/VirtioFsDxe/FuseOpen.c +++ b/OvmfPkg/VirtioFsDxe/FuseOpen.c @@ -119,7 +119,7 @@ VirtioFsFuseOpen ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu ReadWrite=%d " "Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, ReadWrite, diff --git a/OvmfPkg/VirtioFsDxe/FuseOpenDir.c b/OvmfPkg/VirtioFsDxe/FuseOpenDir.c index e49c046b9d..11249ef0a8 100644 --- a/OvmfPkg/VirtioFsDxe/FuseOpenDir.c +++ b/OvmfPkg/VirtioFsDxe/FuseOpenDir.c @@ -113,7 +113,7 @@ VirtioFsFuseOpenDir ( DEBUG (( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, CommonResp.Error diff --git a/OvmfPkg/VirtioFsDxe/FuseOpenOrCreate.c b/OvmfPkg/VirtioFsDxe/FuseOpenOrCreate.c index 4d9846ab3b..db586dc76d 100644 --- a/OvmfPkg/VirtioFsDxe/FuseOpenOrCreate.c +++ b/OvmfPkg/VirtioFsDxe/FuseOpenOrCreate.c @@ -146,7 +146,7 @@ VirtioFsFuseOpenOrCreate ( DEBUG_ERROR, "%a: Label=\"%s\" ParentNodeId=%Lu Name=\"%a\" " "Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, ParentNodeId, Name, diff --git a/OvmfPkg/VirtioFsDxe/FuseRead.c b/OvmfPkg/VirtioFsDxe/FuseRead.c index 013dac7e52..882d433045 100644 --- a/OvmfPkg/VirtioFsDxe/FuseRead.c +++ b/OvmfPkg/VirtioFsDxe/FuseRead.c @@ -178,7 +178,7 @@ VirtioFsFuseReadFileOrDir ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu FuseHandle=%Lu " "IsDir=%d Offset=0x%Lx Size=0x%x Data@%p Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, FuseHandle, diff --git a/OvmfPkg/VirtioFsDxe/FuseRelease.c b/OvmfPkg/VirtioFsDxe/FuseRelease.c index c8363158f5..75bb171a13 100644 --- a/OvmfPkg/VirtioFsDxe/FuseRelease.c +++ b/OvmfPkg/VirtioFsDxe/FuseRelease.c @@ -116,7 +116,7 @@ VirtioFsFuseReleaseFileOrDir ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu FuseHandle=%Lu " "IsDir=%d Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, FuseHandle, diff --git a/OvmfPkg/VirtioFsDxe/FuseRename.c b/OvmfPkg/VirtioFsDxe/FuseRename.c index a3a1050506..3ec5363037 100644 --- a/OvmfPkg/VirtioFsDxe/FuseRename.c +++ b/OvmfPkg/VirtioFsDxe/FuseRename.c @@ -130,7 +130,7 @@ VirtioFsFuseRename ( DEBUG_ERROR, "%a: Label=\"%s\" OldParentNodeId=%Lu OldName=\"%a\" " "NewParentNodeId=%Lu NewName=\"%a\" Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, OldParentNodeId, OldName, diff --git a/OvmfPkg/VirtioFsDxe/FuseSetAttr.c b/OvmfPkg/VirtioFsDxe/FuseSetAttr.c index 9d0ea93fd9..719584fa32 100644 --- a/OvmfPkg/VirtioFsDxe/FuseSetAttr.c +++ b/OvmfPkg/VirtioFsDxe/FuseSetAttr.c @@ -164,7 +164,7 @@ VirtioFsFuseSetAttr ( DEBUG (( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId )); diff --git a/OvmfPkg/VirtioFsDxe/FuseStatFs.c b/OvmfPkg/VirtioFsDxe/FuseStatFs.c index d93a62080e..55b4edc5b9 100644 --- a/OvmfPkg/VirtioFsDxe/FuseStatFs.c +++ b/OvmfPkg/VirtioFsDxe/FuseStatFs.c @@ -102,7 +102,7 @@ VirtioFsFuseStatFs ( DEBUG (( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, CommonResp.Error diff --git a/OvmfPkg/VirtioFsDxe/FuseUnlink.c b/OvmfPkg/VirtioFsDxe/FuseUnlink.c index 14cbdec5f5..d83a175dc6 100644 --- a/OvmfPkg/VirtioFsDxe/FuseUnlink.c +++ b/OvmfPkg/VirtioFsDxe/FuseUnlink.c @@ -109,7 +109,7 @@ VirtioFsFuseRemoveFileOrDir ( DEBUG_ERROR, "%a: Label=\"%s\" ParentNodeId=%Lu Name=\"%a\" " "IsDir=%d Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, ParentNodeId, Name, diff --git a/OvmfPkg/VirtioFsDxe/FuseWrite.c b/OvmfPkg/VirtioFsDxe/FuseWrite.c index fe65c0bdbe..98dbd6decc 100644 --- a/OvmfPkg/VirtioFsDxe/FuseWrite.c +++ b/OvmfPkg/VirtioFsDxe/FuseWrite.c @@ -147,7 +147,7 @@ VirtioFsFuseWrite ( DEBUG_ERROR, "%a: Label=\"%s\" NodeId=%Lu FuseHandle=%Lu " "Offset=0x%Lx Size=0x%x Data@%p Errno=%d\n", - __FUNCTION__, + __func__, VirtioFs->Label, NodeId, FuseHandle, diff --git a/OvmfPkg/VirtioFsDxe/Helpers.c b/OvmfPkg/VirtioFsDxe/Helpers.c index f32fb1d48a..bc3c58cf41 100644 --- a/OvmfPkg/VirtioFsDxe/Helpers.c +++ b/OvmfPkg/VirtioFsDxe/Helpers.c @@ -320,7 +320,7 @@ VirtioFsExitBoot ( DEBUG (( DEBUG_VERBOSE, "%a: VirtioFs=0x%p Label=\"%s\"\n", - __FUNCTION__, + __func__, VirtioFsAsVoid, VirtioFs->Label )); diff --git a/OvmfPkg/VirtioFsDxe/SimpleFsOpen.c b/OvmfPkg/VirtioFsDxe/SimpleFsOpen.c index d479f76f5b..a13d4f6a1e 100644 --- a/OvmfPkg/VirtioFsDxe/SimpleFsOpen.c +++ b/OvmfPkg/VirtioFsDxe/SimpleFsOpen.c @@ -378,7 +378,7 @@ VirtioFsSimpleFileOpen ( ("%a: Label=\"%s\" CanonicalPathname=\"%a\" FileName=\"%s\" " "OpenMode=0x%Lx Attributes=0x%Lx: nonsensical request to possibly " "create a file marked read-only, for read-write access\n"), - __FUNCTION__, + __func__, VirtioFs->Label, VirtioFsFile->CanonicalPathname, FileName, @@ -403,7 +403,7 @@ VirtioFsSimpleFileOpen ( ("%a: Label=\"%s\" CanonicalPathname=\"%a\" FileName=\"%s\": " "nonsensical request to open a file or directory relative to a regular " "file\n"), - __FUNCTION__, + __func__, VirtioFs->Label, VirtioFsFile->CanonicalPathname, FileName diff --git a/OvmfPkg/VirtioGpuDxe/Commands.c b/OvmfPkg/VirtioGpuDxe/Commands.c index 4318d3d771..df79a5f8af 100644 --- a/OvmfPkg/VirtioGpuDxe/Commands.c +++ b/OvmfPkg/VirtioGpuDxe/Commands.c @@ -354,7 +354,7 @@ VirtioGpuExitBoot ( { VGPU_DEV *VgpuDev; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); VgpuDev = Context; VgpuDev->VirtIo->SetDeviceStatus (VgpuDev->VirtIo, 0); } @@ -516,7 +516,7 @@ VirtioGpuSendCommandWithReply ( DEBUG (( DEBUG_ERROR, "%a: malformed response to Request=0x%x\n", - __FUNCTION__, + __func__, (UINT32)RequestType )); Status = EFI_PROTOCOL_ERROR; @@ -548,7 +548,7 @@ VirtioGpuSendCommandWithReply ( DEBUG (( DEBUG_ERROR, "%a: Request=0x%x Response=0x%x (expected 0x%x)\n", - __FUNCTION__, + __func__, (UINT32)RequestType, Response->Type, ResponseType diff --git a/OvmfPkg/VirtioGpuDxe/DriverBinding.c b/OvmfPkg/VirtioGpuDxe/DriverBinding.c index 21bf2babc8..80eac08f90 100644 --- a/OvmfPkg/VirtioGpuDxe/DriverBinding.c +++ b/OvmfPkg/VirtioGpuDxe/DriverBinding.c @@ -816,7 +816,7 @@ VirtioGpuDriverBindingStart ( DEBUG (( DEBUG_INFO, "%a: bound VirtIo=%p without producing GOP\n", - __FUNCTION__, + __func__, (VOID *)VgpuDev->VirtIo )); return EFI_SUCCESS; @@ -848,7 +848,7 @@ VirtioGpuDriverBindingStart ( DEBUG (( DEBUG_INFO, "%a: produced GOP %a VirtIo=%p\n", - __FUNCTION__, + __func__, VirtIoBoundJustNow ? "while binding" : "for pre-bound", (VOID *)VgpuDev->VirtIo )); @@ -952,7 +952,7 @@ VirtioGpuDriverBindingStop ( DEBUG (( DEBUG_INFO, "%a: unbinding GOP-less VirtIo=%p\n", - __FUNCTION__, + __func__, (VOID *)VgpuDev->VirtIo )); @@ -1010,7 +1010,7 @@ VirtioGpuDriverBindingStop ( DEBUG (( DEBUG_INFO, "%a: destroying GOP under VirtIo=%p\n", - __FUNCTION__, + __func__, (VOID *)VgpuDev->VirtIo )); UninitVgpuGop (VgpuDev, ControllerHandle, This->DriverBindingHandle); diff --git a/OvmfPkg/VirtioGpuDxe/Gop.c b/OvmfPkg/VirtioGpuDxe/Gop.c index 16e92830d4..f64dfce5f4 100644 --- a/OvmfPkg/VirtioGpuDxe/Gop.c +++ b/OvmfPkg/VirtioGpuDxe/Gop.c @@ -222,7 +222,7 @@ GopNativeResolution ( DEBUG (( DEBUG_INFO, "%a: #%d: %dx%d\n", - __FUNCTION__, + __func__, Index, DisplayInfo.Pmodes[Index].Rectangle.Width, DisplayInfo.Pmodes[Index].Rectangle.Height diff --git a/OvmfPkg/VirtioNetDxe/Events.c b/OvmfPkg/VirtioNetDxe/Events.c index 4c93607a38..75a9644f74 100644 --- a/OvmfPkg/VirtioNetDxe/Events.c +++ b/OvmfPkg/VirtioNetDxe/Events.c @@ -77,7 +77,7 @@ VirtioNetExitBoot ( // VNET_DEV *Dev; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); Dev = Context; if (Dev->Snm.State == EfiSimpleNetworkInitialized) { Dev->VirtIo->SetDeviceStatus (Dev->VirtIo, 0); diff --git a/OvmfPkg/VirtioRngDxe/VirtioRng.c b/OvmfPkg/VirtioRngDxe/VirtioRng.c index aabc7230ab..069aed148a 100644 --- a/OvmfPkg/VirtioRngDxe/VirtioRng.c +++ b/OvmfPkg/VirtioRngDxe/VirtioRng.c @@ -435,7 +435,7 @@ VirtioRngExitBoot ( { VIRTIO_RNG_DEV *Dev; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); // // Reset the device. This causes the hypervisor to forget about the virtio // ring. diff --git a/OvmfPkg/VirtioScsiDxe/VirtioScsi.c b/OvmfPkg/VirtioScsiDxe/VirtioScsi.c index d44f9ebca7..3705f5fc14 100644 --- a/OvmfPkg/VirtioScsiDxe/VirtioScsi.c +++ b/OvmfPkg/VirtioScsiDxe/VirtioScsi.c @@ -1235,7 +1235,7 @@ VirtioScsiExitBoot ( { VSCSI_DEV *Dev; - DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context)); + DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __func__, Context)); // // Reset the device. This causes the hypervisor to forget about the virtio // ring. diff --git a/OvmfPkg/XenAcpiPlatformDxe/Xen.c b/OvmfPkg/XenAcpiPlatformDxe/Xen.c index cc2fa2cdcf..a80a24628c 100644 --- a/OvmfPkg/XenAcpiPlatformDxe/Xen.c +++ b/OvmfPkg/XenAcpiPlatformDxe/Xen.c @@ -299,7 +299,7 @@ InstallXenTables ( // then we're out of sync with the hypervisor, and cannot continue. // if (DsdtTable == NULL) { - DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no DSDT found\n", __func__)); ASSERT (FALSE); CpuDeadLoop (); } diff --git a/OvmfPkg/XenPlatformPei/ClearCache.c b/OvmfPkg/XenPlatformPei/ClearCache.c index 71e63ab868..a37d1d0c0a 100644 --- a/OvmfPkg/XenPlatformPei/ClearCache.c +++ b/OvmfPkg/XenPlatformPei/ClearCache.c @@ -60,7 +60,7 @@ ClearCacheOnMpServicesAvailable ( EFI_PEI_MP_SERVICES_PPI *MpServices; EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __func__)); // // Clear cache on all the APs in parallel. @@ -75,7 +75,7 @@ ClearCacheOnMpServicesAvailable ( NULL // ProcedureArgument ); if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) { - DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __func__, Status)); return Status; } @@ -109,7 +109,7 @@ InstallClearCacheCallback ( DEBUG (( DEBUG_ERROR, "%a: failed to set up MP Services callback: %r\n", - __FUNCTION__, + __func__, Status )); } diff --git a/OvmfPkg/XenPlatformPei/MemDetect.c b/OvmfPkg/XenPlatformPei/MemDetect.c index d412d1f4db..e552e7a55e 100644 --- a/OvmfPkg/XenPlatformPei/MemDetect.c +++ b/OvmfPkg/XenPlatformPei/MemDetect.c @@ -54,7 +54,7 @@ Q35TsegMbytesInitialization ( DEBUG_ERROR, "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; " "only DID=0x%04x (Q35) is supported\n", - __FUNCTION__, + __func__, mHostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); @@ -88,7 +88,7 @@ Q35TsegMbytesInitialization ( DEBUG (( DEBUG_INFO, "%a: QEMU offers an extended TSEG (%d MB)\n", - __FUNCTION__, + __func__, ExtendedTsegMbytes )); PcdStatus = PcdSet16S (PcdQ35TsegMbytes, ExtendedTsegMbytes); @@ -291,7 +291,7 @@ PublishPeiMemory ( DEBUG (( DEBUG_INFO, "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n", - __FUNCTION__, + __func__, mPhysMemAddressWidth, PeiMemoryCap >> 10 )); diff --git a/OvmfPkg/XenPlatformPei/Platform.c b/OvmfPkg/XenPlatformPei/Platform.c index 6c1886c158..c3fdf3d0b8 100644 --- a/OvmfPkg/XenPlatformPei/Platform.c +++ b/OvmfPkg/XenPlatformPei/Platform.c @@ -292,7 +292,7 @@ MiscInitialization ( DEBUG (( DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", - __FUNCTION__, + __func__, mHostBridgeDevId )); ASSERT (FALSE); diff --git a/OvmfPkg/XenPvBlkDxe/BlockFront.c b/OvmfPkg/XenPvBlkDxe/BlockFront.c index 1827cc58e3..5a3ad5e4e5 100644 --- a/OvmfPkg/XenPvBlkDxe/BlockFront.c +++ b/OvmfPkg/XenPvBlkDxe/BlockFront.c @@ -187,13 +187,13 @@ XenPvBlockFrontInitialization ( if (Dev->MediaInfo.CdRom) { Status = XenBusIo->XsBackendRead (XenBusIo, XST_NIL, "params", (VOID **)&Params); if (Status != XENSTORE_STATUS_SUCCESS) { - DEBUG ((DEBUG_ERROR, "%a: Failed to read params (%d)\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Failed to read params (%d)\n", __func__, Status)); goto Error; } if ((AsciiStrLen (Params) == 0) || (AsciiStrCmp (Params, "aio:") == 0)) { FreePool (Params); - DEBUG ((DEBUG_INFO, "%a: Empty cdrom\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Empty cdrom\n", __func__)); goto Error; } From 6ba47ab63f61274e642a79cfb7fa75d15888d914 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:50:06 -0600 Subject: [PATCH 0851/1529] MdeModulePkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout MdeModulePkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c | 38 +++++++++---------- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c | 18 ++++----- MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c | 2 +- MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c | 2 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c | 4 +- .../NonDiscoverablePciDeviceIo.c | 2 +- .../Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c | 8 ++-- .../Bus/Pci/NvmExpressPei/NvmExpressPei.c | 36 +++++++++--------- .../Pci/NvmExpressPei/NvmExpressPeiBlockIo.c | 6 +-- .../Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c | 34 ++++++++--------- .../Pci/NvmExpressPei/NvmExpressPeiPassThru.c | 24 ++++++------ MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c | 2 +- .../Bus/Pci/PciHostBridgeDxe/PciHostBridge.c | 14 +++---- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c | 6 +-- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 12 +++--- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 2 +- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 4 +- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 6 +-- MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c | 2 +- MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c | 2 +- MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c | 6 +-- .../SectionExtraction/CoreSectionExtraction.c | 2 +- .../Core/DxeIplPeim/Ia32/DxeLoadFunc.c | 4 +- .../Core/DxeIplPeim/RiscV64/DxeLoadFunc.c | 4 +- MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c | 2 +- MdeModulePkg/Core/Pei/FwVol/FwVol.c | 2 +- .../DxeCapsuleLibFmp/DxeCapsuleReportLib.c | 2 +- .../PiDxeS3BootScriptLib/BootScriptSave.c | 2 +- .../Library/ResetUtilityLib/ResetUtility.c | 2 +- .../Library/UefiBootManagerLib/BmBoot.c | 2 +- .../UefiBootManagerLib/BmDriverHealth.c | 2 +- .../VarCheckPolicyLib/VarCheckPolicyLib.c | 22 +++++------ .../VariablePolicyLib/VariablePolicyLib.c | 6 +-- .../Universal/CapsulePei/UefiCapsule.c | 8 ++-- .../Universal/CapsulePei/X64/X64Entry.c | 2 +- .../Universal/Disk/PartitionDxe/Udf.c | 10 ++--- MdeModulePkg/Universal/Disk/UdfDxe/File.c | 2 +- .../Disk/UdfDxe/FileSystemOperations.c | 2 +- .../FaultTolerantWrite.c | 6 +-- .../Universal/FaultTolerantWriteDxe/FtwMisc.c | 2 +- MdeModulePkg/Universal/PCD/Dxe/Service.c | 2 +- MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c | 4 +- .../Variable/RuntimeDxe/TcgMorLockDxe.c | 6 +-- .../Variable/RuntimeDxe/TcgMorLockSmm.c | 6 +-- .../Universal/Variable/RuntimeDxe/Variable.c | 6 +-- .../RuntimeDxe/VariableLockRequestToLock.c | 4 +- .../RuntimeDxe/VariablePolicySmmDxe.c | 20 +++++----- 47 files changed, 181 insertions(+), 181 deletions(-) diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c index 0f0198d308..92fb30638e 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c @@ -759,7 +759,7 @@ AhciPioTransfer ( DEBUG_ERROR, "%a: Driver only support a maximum of 0x%x PRDT entries, " "current number of data byte 0x%x is too large, maximum allowed is 0x%x.\n", - __FUNCTION__, + __func__, AHCI_MAX_PRDT_NUMBER, DataCount, AHCI_MAX_PRDT_NUMBER * AHCI_MAX_DATA_PER_PRDT @@ -778,7 +778,7 @@ AhciPioTransfer ( &MapData ); if (EFI_ERROR (Status) || (MapLength != DataCount)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to map data buffer.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to map data buffer.\n", __func__)); return EFI_OUT_OF_RESOURCES; } @@ -860,7 +860,7 @@ AhciPioTransfer ( Offset = FisBaseAddr + AHCI_PIO_FIS_OFFSET; Status = AhciCheckMemSet (Offset, AHCI_FIS_TYPE_MASK, AHCI_FIS_PIO_SETUP); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: PioFisReceived.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: PioFisReceived.\n", __func__)); PioFisReceived = TRUE; } @@ -874,7 +874,7 @@ AhciPioTransfer ( Offset = FisBaseAddr + AHCI_D2H_FIS_OFFSET; Status = AhciCheckMemSet (Offset, AHCI_FIS_TYPE_MASK, AHCI_FIS_REGISTER_D2H); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: D2hFisReceived.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: D2hFisReceived.\n", __func__)); D2hFisReceived = TRUE; } @@ -918,7 +918,7 @@ AhciPioTransfer ( Timeout ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: AhciWaitMemSet (%r)\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: AhciWaitMemSet (%r)\n", __func__, Status)); goto Exit; } @@ -1479,7 +1479,7 @@ IdentifyAtaDevice ( DEBUG (( DEBUG_ERROR, "%a: Not a hard disk device on Port 0x%x PortMultiplierPort 0x%x\n", - __FUNCTION__, + __func__, DeviceData->Port, DeviceData->PortMultiplier )); @@ -1489,7 +1489,7 @@ IdentifyAtaDevice ( DEBUG (( DEBUG_INFO, "%a: Identify Device: Port 0x%x PortMultiplierPort 0x%x\n", - __FUNCTION__, + __func__, DeviceData->Port, DeviceData->PortMultiplier )); @@ -1518,7 +1518,7 @@ IdentifyAtaDevice ( } if (Capacity == 0) { - DEBUG ((DEBUG_ERROR, "%a: Invalid Capacity (0) for ATA device.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Invalid Capacity (0) for ATA device.\n", __func__)); return EFI_UNSUPPORTED; } @@ -1532,7 +1532,7 @@ IdentifyAtaDevice ( DEBUG (( DEBUG_INFO, "%a: PhyLogicSectorSupport = 0x%x\n", - __FUNCTION__, + __func__, PhyLogicSectorSupport )); if ((PhyLogicSectorSupport & (BIT14 | BIT15)) == BIT14) { @@ -1550,20 +1550,20 @@ IdentifyAtaDevice ( // MaxSectorCount = mMaxTransferBlockNumber[DeviceData->Lba48Bit]; if ((Media->BlockSize == 0) || (Media->BlockSize > MAX_UINT32 / MaxSectorCount)) { - DEBUG ((DEBUG_ERROR, "%a: Invalid BlockSize (0x%x).\n", __FUNCTION__, Media->BlockSize)); + DEBUG ((DEBUG_ERROR, "%a: Invalid BlockSize (0x%x).\n", __func__, Media->BlockSize)); return EFI_UNSUPPORTED; } DEBUG (( DEBUG_INFO, "%a: BlockSize = 0x%x, LastBlock = 0x%lx\n", - __FUNCTION__, + __func__, Media->BlockSize, Media->LastBlock )); if ((IdentifyData->trusted_computing_support & BIT0) != 0) { - DEBUG ((DEBUG_INFO, "%a: Found Trust Computing feature support.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Found Trust Computing feature support.\n", __func__)); DeviceData->TrustComputing = TRUE; } @@ -1686,7 +1686,7 @@ AhciModeInitialization ( Status = AhciReset (AhciBar, AHCI_PEI_RESET_TIMEOUT); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: AHCI HBA reset failed with %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: AHCI HBA reset failed with %r.\n", __func__, Status)); return EFI_DEVICE_ERROR; } @@ -1708,7 +1708,7 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Transfer-related data allocation failed with %r.\n", - __FUNCTION__, + __func__, Status )); return EFI_OUT_OF_RESOURCES; @@ -1814,7 +1814,7 @@ AhciModeInitialization ( // Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; AhciAndReg (AhciBar, Offset, (UINT32) ~(AHCI_PORT_CMD_SUD)); - DEBUG ((DEBUG_ERROR, "%a: No device detected at Port %d.\n", __FUNCTION__, Port)); + DEBUG ((DEBUG_ERROR, "%a: No device detected at Port %d.\n", __func__, Port)); continue; } @@ -1844,7 +1844,7 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Port %d device presence detected but phy not ready (TFD=0x%x).\n", - __FUNCTION__, + __func__, Port, Data )); @@ -1866,7 +1866,7 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Error occurred when waiting for the first D2H register FIS - %r\n", - __FUNCTION__, + __func__, Status )); continue; @@ -1876,11 +1876,11 @@ AhciModeInitialization ( if ((Data & AHCI_ATAPI_SIG_MASK) == AHCI_ATA_DEVICE_SIG) { Status = AhciIdentify (Private, Port, 0, PortIndex - 1, &IdentifyData); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: AhciIdentify() failed with %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: AhciIdentify() failed with %r\n", __func__, Status)); continue; } - DEBUG ((DEBUG_INFO, "%a: ATA hard disk found on Port %d.\n", __FUNCTION__, Port)); + DEBUG ((DEBUG_INFO, "%a: ATA hard disk found on Port %d.\n", __func__, Port)); } else { continue; } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c index e33d863d2a..7ea36afa25 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c @@ -156,7 +156,7 @@ AtaAhciInitPrivateData ( // Status = PeiServicesGetBootMode (&BootMode); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to get the current boot mode.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to get the current boot mode.\n", __func__)); return Status; } @@ -168,7 +168,7 @@ AtaAhciInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: The device path is invalid.\n", - __FUNCTION__ + __func__ )); return Status; } @@ -196,7 +196,7 @@ AtaAhciInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: Fail to allocate private data.\n", - __FUNCTION__ + __func__ )); return EFI_OUT_OF_RESOURCES; } @@ -260,7 +260,7 @@ AtaAhciInitPrivateData ( DEBUG (( DEBUG_INFO, "%a: Security Security Command PPI will be produced.\n", - __FUNCTION__ + __func__ )); Private->StorageSecurityPpi.Revision = EDKII_STORAGE_SECURITY_PPI_REVISION; Private->StorageSecurityPpi.GetNumberofDevices = AhciStorageSecurityGetDeviceNo; @@ -329,7 +329,7 @@ AtaAhciInitPrivateDataFromHostControllerPpi ( DEBUG (( DEBUG_ERROR, "%a: Fail to allocate get the device path for Controller %d.\n", - __FUNCTION__, + __func__, Controller )); return Status; @@ -340,7 +340,7 @@ AtaAhciInitPrivateDataFromHostControllerPpi ( DEBUG (( DEBUG_ERROR, "%a: Controller initialization fail for Controller %d with Status - %r.\n", - __FUNCTION__, + __func__, Controller, Status )); @@ -348,7 +348,7 @@ AtaAhciInitPrivateDataFromHostControllerPpi ( DEBUG (( DEBUG_INFO, "%a: Controller %d has been successfully initialized.\n", - __FUNCTION__, + __func__, Controller )); } @@ -471,7 +471,7 @@ AtaAhciInitPrivateDataFromPciDevice ( DEBUG (( DEBUG_INFO, "%a: Failed to init controller, with Status - %r\n", - __FUNCTION__, + __func__, Status )); } @@ -522,7 +522,7 @@ AtaAhciPeimEntry ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - DEBUG ((DEBUG_INFO, "%a: Enters.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Enters.\n", __func__)); PeiServicesNotifyPpi (&mAtaAhciHostControllerNotify); diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c index c5d1f3fffb..5eb2a9ce82 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c @@ -101,7 +101,7 @@ AccessAtaDevice ( DEBUG (( DEBUG_BLKIO, "%a: Blocking AccessAtaDevice, TransferBlockNumber = %x; StartLba = %x\n", - __FUNCTION__, + __func__, TransferBlockNumber, StartLba )); diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c index e903593b01..b4f1a50799 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c @@ -1863,7 +1863,7 @@ EhcDriverBindingStart ( DEBUG (( DEBUG_WARN, "%a: failed to enable 64-bit DMA on 64-bit capable controller @ %p (%r)\n", - __FUNCTION__, + __func__, Controller, Status )); diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c index 6967aabceb..59bbe9fc23 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c @@ -836,7 +836,7 @@ EhciInsertAsyncIntTransfer ( Data = AllocatePool (DataLen); if (Data == NULL) { - DEBUG ((DEBUG_ERROR, "%a: failed to allocate buffer\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: failed to allocate buffer\n", __func__)); return NULL; } @@ -858,7 +858,7 @@ EhciInsertAsyncIntTransfer ( ); if (Urb == NULL) { - DEBUG ((DEBUG_ERROR, "%a: failed to create URB\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: failed to create URB\n", __func__)); gBS->FreePool (Data); return NULL; } diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c index 2fb78d8f96..e31c38deed 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c @@ -1843,7 +1843,7 @@ InitializePciIoProtocol ( DEBUG (( DEBUG_ERROR, "%a: resource count exceeds number of emulated BARs\n", - __FUNCTION__ + __func__ )); ASSERT (FALSE); break; diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c index b33c903412..b6ed7f7031 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c @@ -216,7 +216,7 @@ NvmeRead ( DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", - __FUNCTION__, + __func__, Lba, (UINT64)OrginalBlocks, (UINT64)Blocks, @@ -302,7 +302,7 @@ NvmeWrite ( DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", - __FUNCTION__, + __func__, Lba, (UINT64)OrginalBlocks, (UINT64)Blocks, @@ -817,7 +817,7 @@ NvmeAsyncRead ( DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", - __FUNCTION__, + __func__, Lba, (UINT64)OrginalBlocks, (UINT64)Blocks, @@ -945,7 +945,7 @@ NvmeAsyncWrite ( DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", - __FUNCTION__, + __func__, Lba, (UINT64)OrginalBlocks, (UINT64)Blocks, diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c index 3e6f75345d..38f86487e2 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c @@ -91,7 +91,7 @@ EnumerateNvmeDevNamespace ( NamespaceData ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyNamespace fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyNamespace fail, Status - %r\n", __func__, Status)); goto Exit; } @@ -99,7 +99,7 @@ EnumerateNvmeDevNamespace ( // Validate Namespace // if (NamespaceData->Ncap == 0) { - DEBUG ((DEBUG_INFO, "%a: Namespace ID %d is an inactive one.\n", __FUNCTION__, NamespaceId)); + DEBUG ((DEBUG_INFO, "%a: Namespace ID %d is an inactive one.\n", __func__, NamespaceId)); Status = EFI_DEVICE_ERROR; goto Exit; } @@ -142,7 +142,7 @@ EnumerateNvmeDevNamespace ( DEBUG (( DEBUG_INFO, "%a: Namespace ID %d - BlockSize = 0x%x, LastBlock = 0x%lx\n", - __FUNCTION__, + __func__, NamespaceId, NamespaceInfo->Media.BlockSize, NamespaceInfo->Media.LastBlock @@ -246,14 +246,14 @@ NvmeInitPrivateData ( PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; EFI_PHYSICAL_ADDRESS DeviceAddress; - DEBUG ((DEBUG_INFO, "%a: Enters.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Enters.\n", __func__)); // // Get the current boot mode. // Status = PeiServicesGetBootMode (&BootMode); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to get the current boot mode.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to get the current boot mode.\n", __func__)); return Status; } @@ -265,7 +265,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: The device path is invalid.\n", - __FUNCTION__ + __func__ )); return Status; } @@ -282,7 +282,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: skipped during S3.\n", - __FUNCTION__ + __func__ )); return EFI_SUCCESS; } @@ -295,7 +295,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: Fail to allocate private data.\n", - __FUNCTION__ + __func__ )); return EFI_OUT_OF_RESOURCES; } @@ -313,13 +313,13 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: Fail to allocate DMA buffers.\n", - __FUNCTION__ + __func__ )); return Status; } ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS)(UINTN)Private->Buffer)); - DEBUG ((DEBUG_INFO, "%a: DMA buffer base at 0x%x\n", __FUNCTION__, Private->Buffer)); + DEBUG ((DEBUG_INFO, "%a: DMA buffer base at 0x%x\n", __func__, Private->Buffer)); // // Initialize controller private data @@ -337,7 +337,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: Controller initialization fail with Status - %r.\n", - __FUNCTION__, + __func__, Status )); NvmeFreeDmaResource (Private); @@ -355,7 +355,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_ERROR, "%a: Namespaces discovery fail with Status - %r.\n", - __FUNCTION__, + __func__, Status )); NvmeFreeDmaResource (Private); @@ -414,7 +414,7 @@ NvmeInitPrivateData ( DEBUG (( DEBUG_INFO, "%a: Security Security Command PPI will be produced.\n", - __FUNCTION__ + __func__ )); Private->StorageSecurityPpi.Revision = EDKII_STORAGE_SECURITY_PPI_REVISION; Private->StorageSecurityPpi.GetNumberofDevices = NvmeStorageSecurityGetDeviceNo; @@ -557,7 +557,7 @@ NvmeInitControllerDataFromPciDevice ( DEBUG (( DEBUG_INFO, "%a: Failed to init controller, with Status - %r\n", - __FUNCTION__, + __func__, Status )); } @@ -635,7 +635,7 @@ NvmeInitControllerFromHostControllerPpi ( DEBUG (( DEBUG_ERROR, "%a: Fail to allocate get the device path for Controller %d.\n", - __FUNCTION__, + __func__, Controller )); return Status; @@ -646,7 +646,7 @@ NvmeInitControllerFromHostControllerPpi ( DEBUG (( DEBUG_ERROR, "%a: Controller initialization fail for Controller %d with Status - %r.\n", - __FUNCTION__, + __func__, Controller, Status )); @@ -654,7 +654,7 @@ NvmeInitControllerFromHostControllerPpi ( DEBUG (( DEBUG_INFO, "%a: Controller %d has been successfully initialized.\n", - __FUNCTION__, + __func__, Controller )); } @@ -712,7 +712,7 @@ NvmExpressPeimEntry ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - DEBUG ((DEBUG_INFO, "%a: Enters.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Enters.\n", __func__)); PeiServicesNotifyPpi (&mNvmeHostControllerNotify); diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c index 576481dcee..a61238086c 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c @@ -125,14 +125,14 @@ NvmeRead ( MaxTransferBlocks = MaxTransferBlocks >> 1; if ((Retries > NVME_READ_MAX_RETRY) || (MaxTransferBlocks < 1)) { - DEBUG ((DEBUG_ERROR, "%a: ReadSectors fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: ReadSectors fail, Status - %r\n", __func__, Status)); break; } DEBUG (( DEBUG_BLKIO, "%a: ReadSectors fail, retry with smaller transfer block number - 0x%x\n", - __FUNCTION__, + __func__, MaxTransferBlocks )); continue; @@ -151,7 +151,7 @@ NvmeRead ( DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", - __FUNCTION__, + __func__, Lba, (UINT64)OrginalBlocks, (UINT64)Blocks, diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c index bff5cfd0d5..fc7b684940 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c @@ -138,7 +138,7 @@ NvmeBaseMemPageOffset ( PageSizeList[4] = NVME_PRP_SIZE; /* PRPs */ if (BaseMemIndex > MAX_BASEMEM_COUNT) { - DEBUG ((DEBUG_ERROR, "%a: The input BaseMem index is invalid.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: The input BaseMem index is invalid.\n", __func__)); ASSERT (FALSE); return 0; } @@ -191,7 +191,7 @@ NvmeWaitController ( // Status = NVME_GET_CSTS (Private, &Csts); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CSTS fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CSTS fail, Status - %r\n", __func__, Status)); return Status; } @@ -232,7 +232,7 @@ NvmeDisableController ( // Status = NVME_GET_CC (Private, &Cc); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CC fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CC fail, Status - %r\n", __func__, Status)); goto ErrorExit; } @@ -243,21 +243,21 @@ NvmeDisableController ( // Status = NVME_SET_CC (Private, &Cc); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __func__, Status)); goto ErrorExit; } } Status = NvmeWaitController (Private, FALSE); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __func__, Status)); goto ErrorExit; } return EFI_SUCCESS; ErrorExit: - DEBUG ((DEBUG_ERROR, "%a fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a fail, Status - %r\n", __func__, Status)); return Status; } @@ -289,20 +289,20 @@ NvmeEnableController ( Cc.Iocqes = 4; Status = NVME_SET_CC (Private, &Cc); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NVME_SET_CC fail, Status - %r\n", __func__, Status)); goto ErrorExit; } Status = NvmeWaitController (Private, TRUE); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeWaitController fail, Status - %r\n", __func__, Status)); goto ErrorExit; } return EFI_SUCCESS; ErrorExit: - DEBUG ((DEBUG_ERROR, "%a fail, Status: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a fail, Status: %r\n", __func__, Status)); return Status; } @@ -572,7 +572,7 @@ NvmeControllerInit ( // NVME_GET_CAP (Private, &Private->Cap); if ((Private->Cap.Css & BIT0) == 0) { - DEBUG ((DEBUG_ERROR, "%a: The NVME controller doesn't support NVMe command set.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: The NVME controller doesn't support NVMe command set.\n", __func__)); return EFI_UNSUPPORTED; } @@ -580,7 +580,7 @@ NvmeControllerInit ( // Currently, the driver only supports 4k page size // if ((Private->Cap.Mpsmin + 12) > EFI_PAGE_SHIFT) { - DEBUG ((DEBUG_ERROR, "%a: The driver doesn't support page size other than 4K.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: The driver doesn't support page size other than 4K.\n", __func__)); ASSERT (FALSE); return EFI_UNSUPPORTED; } @@ -599,7 +599,7 @@ NvmeControllerInit ( // Status = NvmeDisableController (Private); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeDisableController fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeDisableController fail, Status - %r\n", __func__, Status)); return Status; } @@ -647,7 +647,7 @@ NvmeControllerInit ( // Status = NvmeEnableController (Private); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeEnableController fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeEnableController fail, Status - %r\n", __func__, Status)); return Status; } @@ -663,7 +663,7 @@ NvmeControllerInit ( Status = NvmeIdentifyController (Private, Private->ControllerData); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyController fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyController fail, Status - %r\n", __func__, Status)); return Status; } @@ -676,7 +676,7 @@ NvmeControllerInit ( DEBUG (( DEBUG_ERROR, "%a: Number of Namespaces field in Identify Controller data not supported by the driver.\n", - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } @@ -686,13 +686,13 @@ NvmeControllerInit ( // Status = NvmeCreateIoCompletionQueue (Private); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Create IO completion queue fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Create IO completion queue fail, Status - %r\n", __func__, Status)); return Status; } Status = NvmeCreateIoSubmissionQueue (Private); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Create IO submission queue fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Create IO submission queue fail, Status - %r\n", __func__, Status)); } return Status; diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c index dc280ec4e3..5081b53cd5 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c @@ -57,7 +57,7 @@ NvmeCreatePrpList ( DEBUG_ERROR, "%a: The implementation only supports PrpList number up to 4." " But %d are needed here.\n", - __FUNCTION__, + __func__, PrpListNo )); return 0; @@ -365,7 +365,7 @@ NvmePassThruExecute ( DEBUG (( DEBUG_ERROR, "%a, Invalid parameter: Packet(%lx)\n", - __FUNCTION__, + __func__, (UINTN)Packet )); return EFI_INVALID_PARAMETER; @@ -375,7 +375,7 @@ NvmePassThruExecute ( DEBUG (( DEBUG_ERROR, "%a, Invalid parameter: NvmeCmd (%lx)/NvmeCompletion(%lx)\n", - __FUNCTION__, + __func__, (UINTN)Packet->NvmeCmd, (UINTN)Packet->NvmeCompletion )); @@ -386,7 +386,7 @@ NvmePassThruExecute ( DEBUG (( DEBUG_ERROR, "%a, Invalid parameter: QueueId(%lx)\n", - __FUNCTION__, + __func__, (UINTN)Packet->QueueType )); return EFI_INVALID_PARAMETER; @@ -407,7 +407,7 @@ NvmePassThruExecute ( DEBUG (( DEBUG_ERROR, "%a: Nsid mismatch (%x, %x)\n", - __FUNCTION__, + __func__, Packet->NvmeCmd->Nsid, NamespaceId )); @@ -425,7 +425,7 @@ NvmePassThruExecute ( // ASSERT (Sq->Psdt == 0); if (Sq->Psdt != 0) { - DEBUG ((DEBUG_ERROR, "%a: Does not support SGL mechanism.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Does not support SGL mechanism.\n", __func__)); return EFI_UNSUPPORTED; } @@ -458,7 +458,7 @@ NvmePassThruExecute ( DEBUG (( DEBUG_ERROR, "%a: Does not support external IO queues creation request.\n", - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } @@ -480,7 +480,7 @@ NvmePassThruExecute ( ); if (EFI_ERROR (Status) || (MapLength != Packet->TransferLength)) { Status = EFI_OUT_OF_RESOURCES; - DEBUG ((DEBUG_ERROR, "%a: Fail to map data buffer.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to map data buffer.\n", __func__)); goto Exit; } @@ -498,7 +498,7 @@ NvmePassThruExecute ( ); if (EFI_ERROR (Status) || (MapLength != Packet->MetadataLength)) { Status = EFI_OUT_OF_RESOURCES; - DEBUG ((DEBUG_ERROR, "%a: Fail to map meta data buffer.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to map meta data buffer.\n", __func__)); goto Exit; } @@ -526,7 +526,7 @@ NvmePassThruExecute ( ); if (Sq->Prp[1] == 0) { Status = EFI_OUT_OF_RESOURCES; - DEBUG ((DEBUG_ERROR, "%a: Create PRP list fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Create PRP list fail, Status - %r\n", __func__, Status)); goto Exit; } } else if ((Offset + Bytes) > EFI_PAGE_SIZE) { @@ -568,7 +568,7 @@ NvmePassThruExecute ( Data32 = ReadUnaligned32 ((UINT32 *)&Private->SqTdbl[QueueId]); Status = NVME_SET_SQTDBL (Private, QueueId, &Data32); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: NVME_SET_SQTDBL fail, Status - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: NVME_SET_SQTDBL fail, Status - %r\n", __func__, Status)); goto Exit; } @@ -591,7 +591,7 @@ NvmePassThruExecute ( // // Timeout occurs for an NVMe command, reset the controller to abort the outstanding command // - DEBUG ((DEBUG_ERROR, "%a: Timeout occurs for the PassThru command.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Timeout occurs for the PassThru command.\n", __func__)); Status = NvmeControllerInit (Private); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c index ba4b099bc5..75c9b344ee 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c @@ -237,7 +237,7 @@ LocatePciExpressCapabilityRegBlock ( DEBUG (( DEBUG_WARN, "%a: [%02x|%02x|%02x] failed to access config space at offset 0x%x\n", - __FUNCTION__, + __func__, PciIoDevice->BusNumber, PciIoDevice->DeviceNumber, PciIoDevice->FunctionNumber, diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c index b20bcd310a..d573e532ba 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c @@ -128,7 +128,7 @@ IntersectIoDescriptor ( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, IntersectionBase, IntersectionEnd, Status @@ -141,7 +141,7 @@ IntersectIoDescriptor ( "%a: %a: desc [%Lx, %Lx) type %u conflicts with " "aperture [%Lx, %Lx)\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length, (UINT32)Descriptor->GcdIoType, @@ -178,7 +178,7 @@ AddIoSpace ( DEBUG_ERROR, "%a: %a: GetIoSpaceMap(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return Status; @@ -299,7 +299,7 @@ IntersectMemoryDescriptor ( EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, IntersectionBase, IntersectionEnd, Status @@ -312,7 +312,7 @@ IntersectMemoryDescriptor ( "%a: %a: desc [%Lx, %Lx) type %u cap %Lx conflicts " "with aperture [%Lx, %Lx) cap %Lx\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length, (UINT32)Descriptor->GcdMemoryType, @@ -353,7 +353,7 @@ AddMemoryMappedIoSpace ( DEBUG_ERROR, "%a: %a: GetMemorySpaceMap(): %r\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); return Status; @@ -955,7 +955,7 @@ NotifyPhase ( DEBUG (( DEBUG_ERROR, "[%a:%d] Translation %lx is not aligned to %lx!\n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, Translation, Alignment diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c index ab2becdd19..8496ce4727 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c @@ -641,7 +641,7 @@ SdMmcPciHcDriverBindingStart ( DEBUG (( DEBUG_INFO, "%a: found SD/MMC override protocol\n", - __FUNCTION__ + __func__ )); } } @@ -676,7 +676,7 @@ SdMmcPciHcDriverBindingStart ( DEBUG (( DEBUG_WARN, "%a: Failed to override capability - %r\n", - __FUNCTION__, + __func__, Status )); continue; @@ -691,7 +691,7 @@ SdMmcPciHcDriverBindingStart ( (VOID *)&Private->Slot[Slot].OperatingParameters ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, "%a: Failed to get operating parameters, using defaults\n", __FUNCTION__)); + DEBUG ((DEBUG_WARN, "%a: Failed to get operating parameters, using defaults\n", __func__)); } } } diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index dd45167a00..aab6815328 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -498,7 +498,7 @@ SdMmcHcReset ( DEBUG (( DEBUG_WARN, "%a: SD/MMC pre reset notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -556,7 +556,7 @@ SdMmcHcReset ( DEBUG (( DEBUG_WARN, "%a: SD/MMC post reset notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); } @@ -942,7 +942,7 @@ SdMmcHcClockSupply ( DEBUG (( DEBUG_ERROR, "%a: SD/MMC switch clock freq post notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -1234,7 +1234,7 @@ SdMmcHcInitHost ( DEBUG (( DEBUG_WARN, "%a: SD/MMC pre init notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -1286,7 +1286,7 @@ SdMmcHcInitHost ( DEBUG (( DEBUG_WARN, "%a: SD/MMC post init notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); } @@ -1375,7 +1375,7 @@ SdMmcHcUhsSignaling ( DEBUG (( DEBUG_ERROR, "%a: SD/MMC uhs signaling notifier callback failed - %r\n", - __FUNCTION__, + __func__, Status )); return Status; diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index d8fa41f68f..62682dd27c 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -2059,7 +2059,7 @@ XhcDriverBindingStart ( DEBUG (( DEBUG_WARN, "%a: failed to enable 64-bit DMA on 64-bit capable controller @ %p (%r)\n", - __FUNCTION__, + __func__, Controller, Status )); diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index 4b7462704a..298fb88b81 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -1495,7 +1495,7 @@ XhciInsertAsyncIntTransfer ( Data = AllocateZeroPool (DataLen); if (Data == NULL) { - DEBUG ((DEBUG_ERROR, "%a: failed to allocate buffer\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: failed to allocate buffer\n", __func__)); return NULL; } @@ -1513,7 +1513,7 @@ XhciInsertAsyncIntTransfer ( Context ); if (Urb == NULL) { - DEBUG ((DEBUG_ERROR, "%a: failed to create URB\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: failed to create URB\n", __func__)); FreePool (Data); return NULL; } diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index 873581d817..670f70caf4 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -2593,7 +2593,7 @@ ScsiDiskInquiryDevice ( DEBUG (( DEBUG_WARN, "%a: invalid PageLength (%u) in Supported VPD Pages page\n", - __FUNCTION__, + __func__, (UINT32)PageLength )); PageLength = 0; @@ -2606,7 +2606,7 @@ ScsiDiskInquiryDevice ( DEBUG (( DEBUG_WARN, "%a: Supported VPD Pages page doesn't start with code 0x%02x\n", - __FUNCTION__, + __func__, EFI_SCSI_PAGE_CODE_SUPPORTED_VPD )); PageLength = 0; @@ -2626,7 +2626,7 @@ ScsiDiskInquiryDevice ( DEBUG (( DEBUG_WARN, "%a: non-ascending code in Supported VPD Pages page @ %u\n", - __FUNCTION__, + __func__, Index )); Index = 0; diff --git a/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c index fb9ae3ce78..cf9d556877 100644 --- a/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c @@ -1095,7 +1095,7 @@ CoreProcessFvImageFile ( DEBUG (( DEBUG_INFO, "%a() FV at 0x%x, FvAlignment required is 0x%x\n", - __FUNCTION__, + __func__, FvHeader, FvAlignment )); diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c index 4683016ed7..0e0f9769b9 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c +++ b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c @@ -315,7 +315,7 @@ DxeMain ( DEBUG (( DEBUG_INFO, "%a: MemoryBaseAddress=0x%Lx MemoryLength=0x%Lx\n", - __FUNCTION__, + __func__, MemoryBaseAddress, MemoryLength )); diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c index b89ab046fa..7cc829b174 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c @@ -838,7 +838,7 @@ InitializeDxeNxMemoryProtectionPolicy ( DEBUG (( DEBUG_INFO, "%a: StackBase = 0x%016lx StackSize = 0x%016lx\n", - __FUNCTION__, + __func__, MemoryHob->AllocDescriptor.MemoryBaseAddress, MemoryHob->AllocDescriptor.MemoryLength )); @@ -864,7 +864,7 @@ InitializeDxeNxMemoryProtectionPolicy ( DEBUG (( DEBUG_INFO, "%a: applying strict permissions to active memory regions\n", - __FUNCTION__ + __func__ )); MergeMemoryMapForProtectionPolicy (MemoryMap, &MemoryMapSize, DescriptorSize); @@ -926,7 +926,7 @@ InitializeDxeNxMemoryProtectionPolicy ( DEBUG (( DEBUG_INFO, "%a: applying strict permissions to inactive memory regions\n", - __FUNCTION__ + __func__ )); CoreAcquireGcdMemoryLock (); diff --git a/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c b/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c index b8d4184b50..2152833ff6 100644 --- a/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c +++ b/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c @@ -1304,7 +1304,7 @@ GetSection ( DEBUG (( DEBUG_ERROR, "%a: recursion aborted due to nesting depth\n", - __FUNCTION__ + __func__ )); // // Map "aborted" to "not found". diff --git a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c index fdeaaa39d8..4bc7b749b0 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c @@ -369,7 +369,7 @@ HandOffToDxeCore ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%lx, Stack Size: 0x%x\n", - __FUNCTION__, + __func__, BaseOfStack, STACK_SIZE )); @@ -457,7 +457,7 @@ HandOffToDxeCore ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%lx, Stack Size: 0x%x\n", - __FUNCTION__, + __func__, BaseOfStack, STACK_SIZE )); diff --git a/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c index f7b57df1c4..b3567d88f7 100644 --- a/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c @@ -36,7 +36,7 @@ HandOffToDxeCore ( // BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (STACK_SIZE)); if (BaseOfStack == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Can't allocate memory for stack.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't allocate memory for stack.", __func__)); ASSERT (FALSE); } @@ -52,7 +52,7 @@ HandOffToDxeCore ( // Status = PeiServicesInstallPpi (&gEndOfPeiSignalPpi); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to signal End of PEI event.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to signal End of PEI event.", __func__)); ASSERT (FALSE); } diff --git a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c index 3552feda8f..d8284f9f4f 100644 --- a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c @@ -101,7 +101,7 @@ DiscoverPeimsAndOrderWithApriori ( DEBUG (( DEBUG_INFO, "%a(): Found 0x%x PEI FFS files in the %dth FV\n", - __FUNCTION__, + __func__, PeimCount, Private->CurrentPeimFvCount )); diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.c b/MdeModulePkg/Core/Pei/FwVol/FwVol.c index 60bbe57332..f7cc94c6eb 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.c +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.c @@ -1494,7 +1494,7 @@ ProcessFvFile ( DEBUG (( DEBUG_INFO, "%a() FV at 0x%x, FvAlignment required is 0x%x\n", - __FUNCTION__, + __func__, FvHeader, FvAlignment )); diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c index efc6b4ce26..a1523428cd 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c @@ -502,7 +502,7 @@ InitCapsuleVariable ( // Locate the VariablePolicy protocol Status = gBS->LocateProtocol (&gEdkiiVariablePolicyProtocolGuid, NULL, (VOID **)&VariablePolicy); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "DxeCapsuleReportLib %a - Could not locate VariablePolicy protocol! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "DxeCapsuleReportLib %a - Could not locate VariablePolicy protocol! %r\n", __func__, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c index 8c7b58b2f9..a6af2e8485 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c @@ -579,7 +579,7 @@ S3BootScriptLibDeinitialize ( return RETURN_SUCCESS; } - DEBUG ((DEBUG_INFO, "%a() in %a module\n", __FUNCTION__, gEfiCallerBaseName)); + DEBUG ((DEBUG_INFO, "%a() in %a module\n", __func__, gEfiCallerBaseName)); if (mEventDxeSmmReadyToLock != NULL) { // diff --git a/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c b/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c index 50131a431f..4ca8425705 100644 --- a/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c +++ b/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c @@ -132,7 +132,7 @@ GetResetPlatformSpecificGuid ( // if ((ResetDataStringSize < DataSize) && ((DataSize - ResetDataStringSize) >= sizeof (GUID))) { ResetSubtypeGuid = (GUID *)((UINT8 *)ResetData + ResetDataStringSize); - DEBUG ((DEBUG_VERBOSE, "%a - Detected reset subtype %g...\n", __FUNCTION__, ResetSubtypeGuid)); + DEBUG ((DEBUG_VERBOSE, "%a - Detected reset subtype %g...\n", __func__, ResetSubtypeGuid)); return ResetSubtypeGuid; } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c index bde22fa659..c3763c4483 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c @@ -1448,7 +1448,7 @@ BmExpandLoadFile ( "%a:%a: failed to allocate reserved pages: " "BufferSize=%Lu LoadFile=\"%s\" FilePath=\"%s\"\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, (UINT64)BufferSize, LoadFileText, FileText diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c b/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c index 46a2fa2016..46a8b780e3 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c @@ -581,7 +581,7 @@ BmRepairAllControllers ( DEBUG (( DEBUG_ERROR, "[%a:%d] Repair failed after %d retries.\n", - __FUNCTION__, + __func__, DEBUG_LINE_NUMBER, ReconnectRepairCount )); diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c index da90f4fc6a..5de46133bb 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c @@ -95,7 +95,7 @@ VarCheckPolicyLibMmiHandler ( // // If either of the pointers are NULL, we can't proceed. if ((CommBuffer == NULL) || (CommBufferSize == NULL)) { - DEBUG ((DEBUG_INFO, "%a - Invalid comm buffer pointers!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a - Invalid comm buffer pointers!\n", __func__)); return EFI_INVALID_PARAMETER; } @@ -105,14 +105,14 @@ VarCheckPolicyLibMmiHandler ( if ((InternalCommBufferSize > VAR_CHECK_POLICY_MM_COMM_BUFFER_SIZE) || !VarCheckPolicyIsBufferOutsideValid ((UINTN)CommBuffer, (UINT64)InternalCommBufferSize)) { - DEBUG ((DEBUG_ERROR, "%a - Invalid CommBuffer supplied! 0x%016lX[0x%016lX]\n", __FUNCTION__, CommBuffer, InternalCommBufferSize)); + DEBUG ((DEBUG_ERROR, "%a - Invalid CommBuffer supplied! 0x%016lX[0x%016lX]\n", __func__, CommBuffer, InternalCommBufferSize)); return EFI_INVALID_PARAMETER; } // If the size does not meet a minimum threshold, we cannot proceed. ExpectedSize = sizeof (VAR_CHECK_POLICY_COMM_HEADER); if (InternalCommBufferSize < ExpectedSize) { - DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __FUNCTION__, InternalCommBufferSize, ExpectedSize)); + DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize)); return EFI_INVALID_PARAMETER; } @@ -128,7 +128,7 @@ VarCheckPolicyLibMmiHandler ( if ((InternalPolicyCommmHeader->Signature != VAR_CHECK_POLICY_COMM_SIG) || (InternalPolicyCommmHeader->Revision != VAR_CHECK_POLICY_COMM_REVISION)) { - DEBUG ((DEBUG_INFO, "%a - Signature or revision are incorrect!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a - Signature or revision are incorrect!\n", __func__)); // We have verified the buffer is not null and have enough size to hold Result field. PolicyCommmHeader->Result = EFI_INVALID_PARAMETER; return EFI_SUCCESS; @@ -157,7 +157,7 @@ VarCheckPolicyLibMmiHandler ( // This add should be safe because these are fixed sizes so far. ExpectedSize += sizeof (VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS); if (InternalCommBufferSize < ExpectedSize) { - DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __FUNCTION__, InternalCommBufferSize, ExpectedSize)); + DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize)); PolicyCommmHeader->Result = EFI_INVALID_PARAMETER; break; } @@ -173,7 +173,7 @@ VarCheckPolicyLibMmiHandler ( // This add should be safe because these are fixed sizes so far. ExpectedSize += sizeof (VARIABLE_POLICY_ENTRY); if (InternalCommBufferSize < ExpectedSize) { - DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __FUNCTION__, InternalCommBufferSize, ExpectedSize)); + DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize)); PolicyCommmHeader->Result = EFI_INVALID_PARAMETER; break; } @@ -186,7 +186,7 @@ VarCheckPolicyLibMmiHandler ( EFI_ERROR (SafeUintnAdd (sizeof (VAR_CHECK_POLICY_COMM_HEADER), PolicyEntry->Size, &ExpectedSize)) || (InternalCommBufferSize < ExpectedSize)) { - DEBUG ((DEBUG_INFO, "%a - Bad policy entry contents!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a - Bad policy entry contents!\n", __func__)); PolicyCommmHeader->Result = EFI_INVALID_PARAMETER; break; } @@ -199,7 +199,7 @@ VarCheckPolicyLibMmiHandler ( // This add should be safe because these are fixed sizes so far. ExpectedSize += sizeof (VAR_CHECK_POLICY_COMM_DUMP_PARAMS) + VAR_CHECK_POLICY_MM_DUMP_BUFFER_SIZE; if (InternalCommBufferSize < ExpectedSize) { - DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __FUNCTION__, InternalCommBufferSize, ExpectedSize)); + DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize)); PolicyCommmHeader->Result = EFI_INVALID_PARAMETER; break; } @@ -298,7 +298,7 @@ VarCheckPolicyLibMmiHandler ( default: // Mark unknown requested command as EFI_UNSUPPORTED. - DEBUG ((DEBUG_INFO, "%a - Invalid command requested! %d\n", __FUNCTION__, PolicyCommmHeader->Command)); + DEBUG ((DEBUG_INFO, "%a - Invalid command requested! %d\n", __func__, PolicyCommmHeader->Command)); PolicyCommmHeader->Result = EFI_UNSUPPORTED; break; } @@ -306,7 +306,7 @@ VarCheckPolicyLibMmiHandler ( DEBUG (( DEBUG_VERBOSE, "%a - Command %d returning %r.\n", - __FUNCTION__, + __func__, PolicyCommmHeader->Command, PolicyCommmHeader->Result )); @@ -349,7 +349,7 @@ VarCheckPolicyLibCommonConstructor ( } // Otherwise, there's not much we can do. else { - DEBUG ((DEBUG_ERROR, "%a - Cannot Initialize VariablePolicyLib! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Cannot Initialize VariablePolicyLib! %r\n", __func__, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c index 82dae67ef5..214f76ab96 100644 --- a/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c +++ b/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c @@ -521,7 +521,7 @@ ValidateSetVariable ( DEBUG (( DEBUG_VERBOSE, "%a - Bad Size. 0x%X <> 0x%X-0x%X\n", - __FUNCTION__, + __func__, DataSize, ActivePolicy->MinSize, ActivePolicy->MaxSize @@ -537,7 +537,7 @@ ValidateSetVariable ( DEBUG (( DEBUG_VERBOSE, "%a - Bad Attributes. 0x%X <> 0x%X:0x%X\n", - __FUNCTION__, + __func__, Attributes, ActivePolicy->AttributesMustHave, ActivePolicy->AttributesCantHave @@ -598,7 +598,7 @@ ValidateSetVariable ( } Exit: - DEBUG ((DEBUG_VERBOSE, "%a - Variable (%g:%s) returning %r.\n", __FUNCTION__, VendorGuid, VariableName, ReturnStatus)); + DEBUG ((DEBUG_VERBOSE, "%a - Variable (%g:%s) returning %r.\n", __func__, VendorGuid, VariableName, ReturnStatus)); return ReturnStatus; } diff --git a/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c b/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c index cdeffa9113..8e26a7d795 100644 --- a/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c +++ b/MdeModulePkg/Universal/CapsulePei/UefiCapsule.c @@ -344,7 +344,7 @@ Thunk32To64 ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%lx, Stack Size: 0x%lx\n", - __FUNCTION__, + __func__, Context->StackBufferBase, Context->StackBufferLength )); @@ -917,7 +917,7 @@ GetScatterGatherHeadEntries ( CapsuleDataPtr64 = 0; if ((ListLength == NULL) || (HeadList == NULL)) { - DEBUG ((DEBUG_ERROR, "%a Invalid parameters. Inputs can't be NULL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a Invalid parameters. Inputs can't be NULL\n", __func__)); ASSERT (ListLength != NULL); ASSERT (HeadList != NULL); return EFI_INVALID_PARAMETER; @@ -1022,7 +1022,7 @@ GetScatterGatherHeadEntries ( } if (ValidIndex == 0) { - DEBUG ((DEBUG_ERROR, "%a didn't find any SG lists in variables\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a didn't find any SG lists in variables\n", __func__)); return EFI_NOT_FOUND; } @@ -1101,7 +1101,7 @@ CapsuleCoalesce ( // Status = GetScatterGatherHeadEntries (&ListLength, &VariableArrayAddress); if (EFI_ERROR (Status) || (VariableArrayAddress == NULL)) { - DEBUG ((DEBUG_ERROR, "%a failed to get Scatter Gather List Head Entries. Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a failed to get Scatter Gather List Head Entries. Status = %r\n", __func__, Status)); goto Done; } diff --git a/MdeModulePkg/Universal/CapsulePei/X64/X64Entry.c b/MdeModulePkg/Universal/CapsulePei/X64/X64Entry.c index 05941f9f8d..4085f371ab 100644 --- a/MdeModulePkg/Universal/CapsulePei/X64/X64Entry.c +++ b/MdeModulePkg/Universal/CapsulePei/X64/X64Entry.c @@ -277,7 +277,7 @@ _ModuleEntryPoint ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%lx, Stack Size: 0x%lx\n", - __FUNCTION__, + __func__, EntrypointContext->StackBufferBase, EntrypointContext->StackBufferLength )); diff --git a/MdeModulePkg/Universal/Disk/PartitionDxe/Udf.c b/MdeModulePkg/Universal/Disk/PartitionDxe/Udf.c index 098e4fec66..6e10defe59 100644 --- a/MdeModulePkg/Universal/Disk/PartitionDxe/Udf.c +++ b/MdeModulePkg/Universal/Disk/PartitionDxe/Udf.c @@ -114,7 +114,7 @@ FindAnchorVolumeDescriptorPointer ( DEBUG (( DEBUG_ERROR, "%a: Media block size 0x%x unable to hold an AVDP.\n", - __FUNCTION__, + __func__, BlockSize )); return EFI_UNSUPPORTED; @@ -140,7 +140,7 @@ FindAnchorVolumeDescriptorPointer ( // Check if read block is a valid AVDP descriptor // if (DescriptorTag->TagIdentifier == UdfAnchorVolumeDescriptorPointer) { - DEBUG ((DEBUG_INFO, "%a: found AVDP at block %d\n", __FUNCTION__, 256)); + DEBUG ((DEBUG_INFO, "%a: found AVDP at block %d\n", __func__, 256)); AvdpsCount++; } @@ -167,7 +167,7 @@ FindAnchorVolumeDescriptorPointer ( DEBUG (( DEBUG_INFO, "%a: found AVDP at block %Ld\n", - __FUNCTION__, + __func__, EndLBA - 256 )); return EFI_SUCCESS; @@ -251,13 +251,13 @@ FindAnchorVolumeDescriptorPointer ( DEBUG (( DEBUG_WARN, "%a: found AVDP at block %Ld\n", - __FUNCTION__, + __func__, LastAvdpBlockNum )); DEBUG (( DEBUG_WARN, "%a: correcting last block from %Ld to %Ld\n", - __FUNCTION__, + __func__, EndLBA, LastAvdpBlockNum )); diff --git a/MdeModulePkg/Universal/Disk/UdfDxe/File.c b/MdeModulePkg/Universal/Disk/UdfDxe/File.c index 6cd197046f..ca2f3e0766 100644 --- a/MdeModulePkg/Universal/Disk/UdfDxe/File.c +++ b/MdeModulePkg/Universal/Disk/UdfDxe/File.c @@ -262,7 +262,7 @@ UdfOpen ( DEBUG (( DEBUG_ERROR, "%a: GetFileSize() fails with status - %r.\n", - __FUNCTION__, + __func__, Status )); goto Error_Get_File_Size; diff --git a/MdeModulePkg/Universal/Disk/UdfDxe/FileSystemOperations.c b/MdeModulePkg/Universal/Disk/UdfDxe/FileSystemOperations.c index 2998c3369c..86020de6e0 100644 --- a/MdeModulePkg/Universal/Disk/UdfDxe/FileSystemOperations.c +++ b/MdeModulePkg/Universal/Disk/UdfDxe/FileSystemOperations.c @@ -298,7 +298,7 @@ GetLongAdLsn ( DEBUG (( DEBUG_ERROR, "%a: Fail to get the Partition Descriptor from the given Long Allocation Descriptor.\n", - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c index 53f9aefb2d..10a67767eb 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c @@ -731,7 +731,7 @@ FtwRestart ( return EFI_ABORTED; } - DEBUG ((DEBUG_INFO, "%a(): success\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a(): success\n", __func__)); return EFI_SUCCESS; } @@ -787,7 +787,7 @@ FtwAbort ( FtwDevice->FtwLastWriteHeader->Complete = FTW_VALID_STATE; - DEBUG ((DEBUG_INFO, "%a(): success\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a(): success\n", __func__)); return EFI_SUCCESS; } @@ -901,7 +901,7 @@ FtwGetLastWrite ( Status = EFI_SUCCESS; } - DEBUG ((DEBUG_INFO, "%a(): success\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a(): success\n", __func__)); return Status; } diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FtwMisc.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FtwMisc.c index f1335870e7..508184f7a0 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FtwMisc.c +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FtwMisc.c @@ -1320,7 +1320,7 @@ InitFtwProtocol ( DEBUG (( DEBUG_INFO, "Ftw: Restart working block update in %a() - %r\n", - __FUNCTION__, + __func__, Status )); FtwAbort (&FtwDevice->FtwInstance); diff --git a/MdeModulePkg/Universal/PCD/Dxe/Service.c b/MdeModulePkg/Universal/PCD/Dxe/Service.c index 5ade8d988b..1ae06a639c 100644 --- a/MdeModulePkg/Universal/PCD/Dxe/Service.c +++ b/MdeModulePkg/Universal/PCD/Dxe/Service.c @@ -1632,7 +1632,7 @@ GetExPcdTokenNumber ( } } - DEBUG ((DEBUG_ERROR, "%a: Failed to find PCD with GUID: %g and token number: %d\n", __FUNCTION__, Guid, ExTokenNumber)); + DEBUG ((DEBUG_ERROR, "%a: Failed to find PCD with GUID: %g and token number: %d\n", __func__, Guid, ExTokenNumber)); ASSERT (FALSE); return 0; diff --git a/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c b/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c index dd077bb0cf..1a86e69d3c 100644 --- a/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c +++ b/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c @@ -1157,7 +1157,7 @@ SmbiosCreateTable ( DEBUG (( DEBUG_INFO, "%a() re-allocate SMBIOS 32-bit table\n", - __FUNCTION__ + __func__ )); if (EntryPointStructure->TableAddress != 0) { // @@ -1329,7 +1329,7 @@ SmbiosCreate64BitTable ( DEBUG (( DEBUG_INFO, "%a() re-allocate SMBIOS 64-bit table\n", - __FUNCTION__ + __func__ )); if (Smbios30EntryPointStructure->TableAddress != 0) { // diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockDxe.c index 88984c31ab..114d0693fe 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockDxe.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockDxe.c @@ -116,7 +116,7 @@ MorLockInitAtEndOfDxe ( // First, we obviously need to locate the VariablePolicy protocol. Status = gBS->LocateProtocol (&gEdkiiVariablePolicyProtocolGuid, NULL, (VOID **)&VariablePolicy); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Could not locate VariablePolicy protocol! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Could not locate VariablePolicy protocol! %r\n", __func__, Status)); return; } @@ -132,7 +132,7 @@ MorLockInitAtEndOfDxe ( VARIABLE_POLICY_TYPE_LOCK_NOW ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Could not lock variable %s! %r\n", __FUNCTION__, MEMORY_OVERWRITE_REQUEST_CONTROL_LOCK_NAME, Status)); + DEBUG ((DEBUG_ERROR, "%a - Could not lock variable %s! %r\n", __func__, MEMORY_OVERWRITE_REQUEST_CONTROL_LOCK_NAME, Status)); } Status = RegisterBasicVariablePolicy ( @@ -146,7 +146,7 @@ MorLockInitAtEndOfDxe ( VARIABLE_POLICY_TYPE_LOCK_NOW ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Could not lock variable %s! %r\n", __FUNCTION__, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, Status)); + DEBUG ((DEBUG_ERROR, "%a - Could not lock variable %s! %r\n", __func__, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, Status)); } return; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockSmm.c index 296afd2ec4..da1105ff07 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/TcgMorLockSmm.c @@ -485,7 +485,7 @@ MorLockInitAtEndOfDxe ( DEBUG (( DEBUG_WARN, "%a: deleting unexpected / unsupported variable %g:%s\n", - __FUNCTION__, + __func__, &gEfiMemoryOverwriteControlDataGuid, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME )); @@ -521,7 +521,7 @@ MorLockInitAtEndOfDxe ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __FUNCTION__, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __func__, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, Status)); ASSERT_EFI_ERROR (Status); } @@ -559,7 +559,7 @@ MorLockInitAtEndOfDxe ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __FUNCTION__, MEMORY_OVERWRITE_REQUEST_CONTROL_LOCK_NAME, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __func__, MEMORY_OVERWRITE_REQUEST_CONTROL_LOCK_NAME, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 3eb7d935b4..7a1331255b 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -2770,7 +2770,7 @@ VariableServiceSetVariable ( DEBUG (( DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", - __FUNCTION__, + __func__, VariableName, VendorGuid )); @@ -2792,7 +2792,7 @@ VariableServiceSetVariable ( DEBUG (( DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", - __FUNCTION__, + __func__, VariableName, VendorGuid )); @@ -2814,7 +2814,7 @@ VariableServiceSetVariable ( DEBUG (( DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", - __FUNCTION__, + __func__, VariableName, VendorGuid )); diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableLockRequestToLock.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableLockRequestToLock.c index d849ee9ce2..f6bb7284f0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableLockRequestToLock.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableLockRequestToLock.c @@ -48,7 +48,7 @@ VariableLockRequestToLock ( EFI_STATUS Status; VARIABLE_POLICY_ENTRY *NewPolicy; - DEBUG ((DEBUG_WARN, "!!! DEPRECATED INTERFACE !!! %a() will go away soon!\n", __FUNCTION__)); + DEBUG ((DEBUG_WARN, "!!! DEPRECATED INTERFACE !!! %a() will go away soon!\n", __func__)); DEBUG ((DEBUG_WARN, "!!! DEPRECATED INTERFACE !!! Please move to use Variable Policy!\n")); DEBUG ((DEBUG_WARN, "!!! DEPRECATED INTERFACE !!! Variable: %g %s\n", VendorGuid, VariableName)); @@ -85,7 +85,7 @@ VariableLockRequestToLock ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __FUNCTION__, VariableName, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to lock variable %s! %r\n", __func__, VariableName, Status)); } if (NewPolicy != NULL) { diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariablePolicySmmDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariablePolicySmmDxe.c index b2094fbcd6..6151a2ba0b 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariablePolicySmmDxe.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariablePolicySmmDxe.c @@ -95,7 +95,7 @@ ProtocolDisableVariablePolicy ( PolicyHeader->Command = VAR_CHECK_POLICY_COMMAND_DISABLE; Status = InternalMmCommunicate (CommHeader, &BufferSize); - DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __func__, Status)); ReleaseLockOnlyAtBootTime (&mMmCommunicationLock); @@ -144,7 +144,7 @@ ProtocolIsVariablePolicyEnabled ( PolicyHeader->Command = VAR_CHECK_POLICY_COMMAND_IS_ENABLED; Status = InternalMmCommunicate (CommHeader, &BufferSize); - DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __func__, Status)); if (!EFI_ERROR (Status)) { Status = PolicyHeader->Result; @@ -197,7 +197,7 @@ ProtocolRegisterVariablePolicy ( DEBUG (( DEBUG_ERROR, "%a - Policy too large for buffer! %r, %d > %d \n", - __FUNCTION__, + __func__, Status, RequiredSize, mMmCommunicationBufferSize @@ -222,7 +222,7 @@ ProtocolRegisterVariablePolicy ( CopyMem (PolicyBuffer, NewPolicy, NewPolicy->Size); Status = InternalMmCommunicate (CommHeader, &BufferSize); - DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __func__, Status)); ReleaseLockOnlyAtBootTime (&mMmCommunicationLock); @@ -278,7 +278,7 @@ DumpVariablePolicyHelper ( CommandParams->PageRequested = PageRequested; Status = InternalMmCommunicate (CommHeader, &BufferSize); - DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __func__, Status)); if (!EFI_ERROR (Status)) { Status = PolicyHeader->Result; @@ -403,7 +403,7 @@ ProtocolLockVariablePolicy ( PolicyHeader->Command = VAR_CHECK_POLICY_COMMAND_LOCK; Status = InternalMmCommunicate (CommHeader, &BufferSize); - DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - MmCommunication returned %r.\n", __func__, Status)); ReleaseLockOnlyAtBootTime (&mMmCommunicationLock); @@ -500,7 +500,7 @@ VariablePolicySmmDxeMain ( // Locate the shared comm buffer to use for sending MM commands. Status = InitMmCommonCommBuffer (&mMmCommunicationBufferSize, &mMmCommunicationBuffer); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to locate a viable MM comm buffer! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to locate a viable MM comm buffer! %r\n", __func__, Status)); ASSERT_EFI_ERROR (Status); return Status; } @@ -508,7 +508,7 @@ VariablePolicySmmDxeMain ( // Locate the MmCommunication protocol. Status = gBS->LocateProtocol (&gEfiMmCommunication2ProtocolGuid, NULL, (VOID **)&mMmCommunication); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmCommunication protocol! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmCommunication protocol! %r\n", __func__, Status)); ASSERT_EFI_ERROR (Status); return Status; } @@ -529,7 +529,7 @@ VariablePolicySmmDxeMain ( NULL ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to install protocol! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to install protocol! %r\n", __func__, Status)); goto Exit; } else { ProtocolInstalled = TRUE; @@ -551,7 +551,7 @@ VariablePolicySmmDxeMain ( &VirtualAddressChangeEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to create VirtualAddressChange event! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to create VirtualAddressChange event! %r\n", __func__, Status)); goto Exit; } else { VirtualAddressChangeRegistered = TRUE; From 60f20070ed50187ef10a902342033ae4b1dbd0d6 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:50:26 -0600 Subject: [PATCH 0852/1529] SecurityPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout SecurityPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- SecurityPkg/HddPassword/HddPasswordDxe.c | 44 +++++++++---------- SecurityPkg/HddPassword/HddPasswordPei.c | 10 ++--- .../Library/AuthVariableLib/AuthService.c | 4 +- .../PeiDxeTpmPlatformHierarchyLib.c | 6 +-- .../PlatformPKProtectionLibVarPolicy.c | 2 +- .../SecureBootVariableLib.c | 38 ++++++++-------- .../UnitTest/SecureBootVariableLibUnitTest.c | 4 +- .../SecureBootVariableProvisionLib.c | 2 +- .../Tcg/Opal/OpalPassword/OpalDriver.c | 24 +++++----- SecurityPkg/Tcg/Opal/OpalPassword/OpalHii.c | 8 ++-- .../Tcg/Opal/OpalPassword/OpalPasswordPei.c | 10 ++--- SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c | 12 ++--- SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c | 10 ++--- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 22 +++++----- SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c | 6 +-- .../SecureBootConfigImpl.c | 2 +- .../SecureBootDefaultKeysDxe.c | 14 +++--- 17 files changed, 109 insertions(+), 109 deletions(-) diff --git a/SecurityPkg/HddPassword/HddPasswordDxe.c b/SecurityPkg/HddPassword/HddPasswordDxe.c index a1a63b67a4..55dfb25886 100644 --- a/SecurityPkg/HddPassword/HddPasswordDxe.c +++ b/SecurityPkg/HddPassword/HddPasswordDxe.c @@ -314,7 +314,7 @@ FreezeLockDevice ( FreeAlignedPages (Asb, EFI_SIZE_TO_PAGES (sizeof (EFI_ATA_STATUS_BLOCK))); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -449,7 +449,7 @@ HddPasswordEndOfDxeEventNotify ( EFI_STATUS Status; ATA_IDENTIFY_DATA IdentifyData; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); mHddPasswordEndOfDxe = TRUE; @@ -503,7 +503,7 @@ HddPasswordEndOfDxeEventNotify ( } } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); gBS->CloseEvent (Event); } @@ -620,7 +620,7 @@ SaveHddPasswordVariable ( UINT8 HashData[SHA256_DIGEST_SIZE]; UINT8 SaltData[PASSWORD_SALT_SIZE]; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); Delete = FALSE; if (!PasswordIsFullZero (Password)) { @@ -765,7 +765,7 @@ SaveHddPasswordVariable ( FreePool (Variable); } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** @@ -791,7 +791,7 @@ GetSavedHddPasswordVariable ( UINTN VariableSize; BOOLEAN Found; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); Variable = NULL; VariableSize = 0; @@ -835,7 +835,7 @@ GetSavedHddPasswordVariable ( DEBUG ((DEBUG_INFO, "The variable node for the HDD password device is not found\n")); } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); return Found; } @@ -864,7 +864,7 @@ ValidateHddPassword ( BOOLEAN HashOk; UINT8 HashData[SHA256_DIGEST_SIZE]; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); if (!GetSavedHddPasswordVariable (ConfigFormEntry, &HddPasswordVariable)) { DEBUG ((DEBUG_INFO, "GetSavedHddPasswordVariable failed\n")); @@ -884,7 +884,7 @@ ValidateHddPassword ( Status = EFI_SUCCESS; } - DEBUG ((DEBUG_INFO, "%a() - exit (%r)\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - exit (%r)\n", __func__, Status)); return Status; } @@ -982,7 +982,7 @@ UnlockHddPassword ( ZeroMem (Buffer, sizeof (Buffer)); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -1080,7 +1080,7 @@ DisableHddPassword ( ZeroMem (Buffer, sizeof (Buffer)); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -1185,7 +1185,7 @@ SetHddPassword ( ZeroMem (Buffer, sizeof (Buffer)); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -1357,7 +1357,7 @@ HddPasswordRequestPassword ( RetryCount = 0; - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); UnicodeSPrint (PopUpString, sizeof (PopUpString), L"Unlock: %s", ConfigFormEntry->HddString); @@ -1541,7 +1541,7 @@ ProcessHddPasswordRequestSetUserPwd ( RetryCount = 0; - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); if (ConfigFormEntry->IfrData.SecurityStatus.Frozen) { DEBUG ((DEBUG_INFO, "%s is frozen, do nothing\n", ConfigFormEntry->HddString)); @@ -1685,7 +1685,7 @@ ProcessHddPasswordRequestSetMasterPwd ( RetryCount = 0; - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); if (ConfigFormEntry->IfrData.SecurityStatus.Frozen) { DEBUG ((DEBUG_INFO, "%s is frozen, do nothing\n", ConfigFormEntry->HddString)); @@ -1812,7 +1812,7 @@ ProcessHddPasswordRequest ( HDD_PASSWORD_REQUEST_VARIABLE *Variable; UINTN VariableSize; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); if (mHddPasswordRequestVariable == NULL) { Status = GetVariable2 ( @@ -1873,7 +1873,7 @@ ProcessHddPasswordRequest ( TempVariable += 1; } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** @@ -1892,7 +1892,7 @@ GetSavedHddPasswordRequest ( HDD_PASSWORD_REQUEST_VARIABLE *Variable; UINTN VariableSize; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); Variable = NULL; VariableSize = 0; @@ -1934,7 +1934,7 @@ GetSavedHddPasswordRequest ( FreePool (Variable); - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** @@ -1956,7 +1956,7 @@ SaveHddPasswordRequest ( HDD_PASSWORD_REQUEST_VARIABLE *NewVariable; UINTN NewVariableSize; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); DEBUG (( DEBUG_INFO, @@ -2047,7 +2047,7 @@ SaveHddPasswordRequest ( FreePool (Variable); } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** @@ -2865,7 +2865,7 @@ HddPasswordDxeInit ( HDD_PASSWORD_VARIABLE_NAME, &mHddPasswordVendorGuid ); - DEBUG ((DEBUG_INFO, "%a(): Lock %s variable (%r)\n", __FUNCTION__, HDD_PASSWORD_VARIABLE_NAME, Status)); + DEBUG ((DEBUG_INFO, "%a(): Lock %s variable (%r)\n", __func__, HDD_PASSWORD_VARIABLE_NAME, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/SecurityPkg/HddPassword/HddPasswordPei.c b/SecurityPkg/HddPassword/HddPasswordPei.c index a1c881599f..c56c00c685 100644 --- a/SecurityPkg/HddPassword/HddPasswordPei.c +++ b/SecurityPkg/HddPassword/HddPasswordPei.c @@ -103,7 +103,7 @@ UnlockDevice ( ZeroMem (Buffer, sizeof (Buffer)); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -186,7 +186,7 @@ FreezeLockDevice ( FreeAlignedPages (Asb, EFI_SIZE_TO_PAGES (sizeof (EFI_ATA_STATUS_BLOCK))); - DEBUG ((DEBUG_INFO, "%a() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a() - %r\n", __func__, Status)); return Status; } @@ -321,11 +321,11 @@ HddPasswordAtaPassThruNotify ( IN VOID *Ppi ) { - DEBUG ((DEBUG_INFO, "%a() - enter at S3 resume\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter at S3 resume\n", __func__)); UnlockHddPassword ((EDKII_PEI_ATA_PASS_THRU_PPI *)Ppi); - DEBUG ((DEBUG_INFO, "%a() - exit at S3 resume\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit at S3 resume\n", __func__)); return EFI_SUCCESS; } @@ -360,7 +360,7 @@ HddPasswordPeiInit ( return EFI_UNSUPPORTED; } - DEBUG ((DEBUG_INFO, "%a: Enters in S3 path.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Enters in S3 path.\n", __func__)); Status = PeiServicesNotifyPpi (&mHddPasswordAtaPassThruPpiNotifyDesc); ASSERT_EFI_ERROR (Status); diff --git a/SecurityPkg/Library/AuthVariableLib/AuthService.c b/SecurityPkg/Library/AuthVariableLib/AuthService.c index 452ed491ea..d81c581d78 100644 --- a/SecurityPkg/Library/AuthVariableLib/AuthService.c +++ b/SecurityPkg/Library/AuthVariableLib/AuthService.c @@ -1126,7 +1126,7 @@ CalculatePrivAuthVarSignChainSHA256Digest ( // Status = X509GetCommonName (SignerCert, SignerCertSize, CertCommonName, &CertCommonNameSize); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a Get SignerCert CommonName failed with status %x\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a Get SignerCert CommonName failed with status %x\n", __func__, Status)); return EFI_ABORTED; } @@ -1134,7 +1134,7 @@ CalculatePrivAuthVarSignChainSHA256Digest ( // Get TopLevelCert tbsCertificate // if (!X509GetTBSCert (TopLevelCert, TopLevelCertSize, &TbsCert, &TbsCertSize)) { - DEBUG ((DEBUG_INFO, "%a Get Top-level Cert tbsCertificate failed!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a Get Top-level Cert tbsCertificate failed!\n", __func__)); return EFI_ABORTED; } diff --git a/SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c b/SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c index b8838766bc..cdb5248aff 100644 --- a/SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c +++ b/SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c @@ -205,7 +205,7 @@ DisableTpmPlatformHierarchy ( // Make sure that we have use of the TPM. Status = Tpm2RequestUseTpm (); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:%a() - Tpm2RequestUseTpm Failed! %r\n", gEfiCallerBaseName, __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a:%a() - Tpm2RequestUseTpm Failed! %r\n", gEfiCallerBaseName, __func__, Status)); ASSERT_EFI_ERROR (Status); return Status; } @@ -224,9 +224,9 @@ DisableTpmPlatformHierarchy ( TPM_RH_PLATFORM, // Hierarchy NO // State ); - DEBUG ((DEBUG_VERBOSE, "%a:%a() - Disable PH = %r\n", gEfiCallerBaseName, __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a:%a() - Disable PH = %r\n", gEfiCallerBaseName, __func__, Status)); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:%a() - Disable PH Failed! %r\n", gEfiCallerBaseName, __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a:%a() - Disable PH Failed! %r\n", gEfiCallerBaseName, __func__, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.c b/SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.c index a264924224..ac18fcd702 100644 --- a/SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.c +++ b/SecurityPkg/Library/PlatformPKProtectionLibVarPolicy/PlatformPKProtectionLibVarPolicy.c @@ -33,7 +33,7 @@ DisablePKProtection ( EFI_STATUS Status; EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy; - DEBUG ((DEBUG_INFO, "%a() Entry...\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() Entry...\n", __func__)); // IMPORTANT NOTE: This operation is sticky and leaves variable protections disabled. // The system *MUST* be reset after performing this operation. diff --git a/SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.c b/SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.c index abca249c65..24599c7a0b 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.c +++ b/SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.c @@ -276,7 +276,7 @@ CreateTimeBasedPayload ( UINTN DescriptorSize; if ((Data == NULL) || (DataSize == NULL) || (Time == NULL)) { - DEBUG ((DEBUG_ERROR, "%a(), invalid arg\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a(), invalid arg\n", __func__)); return EFI_INVALID_PARAMETER; } @@ -292,7 +292,7 @@ CreateTimeBasedPayload ( DescriptorSize = OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo) + OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData); NewData = (UINT8 *)AllocateZeroPool (DescriptorSize + PayloadSize); if (NewData == NULL) { - DEBUG ((DEBUG_ERROR, "%a() Out of resources.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a() Out of resources.\n", __func__)); return EFI_OUT_OF_RESOURCES; } @@ -603,13 +603,13 @@ DeleteSecureBootVariables ( { EFI_STATUS Status, TempStatus; - DEBUG ((DEBUG_INFO, "%a - Attempting to delete the Secure Boot variables.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a - Attempting to delete the Secure Boot variables.\n", __func__)); // // Step 1: Notify that a PK update is coming shortly... Status = DisablePKProtection (); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to signal PK update start! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to signal PK update start! %r\n", __func__, Status)); // Classify this as a PK deletion error. Status = EFI_ABORTED; } @@ -619,7 +619,7 @@ DeleteSecureBootVariables ( // Let's try to nuke the PK, why not... if (!EFI_ERROR (Status)) { Status = DeletePlatformKey (); - DEBUG ((DEBUG_INFO, "%a - PK Delete = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a - PK Delete = %r\n", __func__, Status)); // If the PK is not found, then our work here is done. if (Status == EFI_NOT_FOUND) { Status = EFI_SUCCESS; @@ -646,25 +646,25 @@ DeleteSecureBootVariables ( // the variables anyway. // TempStatus = DeleteKEK (); - DEBUG ((DEBUG_INFO, "%a - KEK Delete = %r\n", __FUNCTION__, TempStatus)); + DEBUG ((DEBUG_INFO, "%a - KEK Delete = %r\n", __func__, TempStatus)); if (EFI_ERROR (TempStatus) && (TempStatus != EFI_NOT_FOUND)) { Status = EFI_ACCESS_DENIED; } TempStatus = DeleteDb (); - DEBUG ((DEBUG_INFO, "%a - db Delete = %r\n", __FUNCTION__, TempStatus)); + DEBUG ((DEBUG_INFO, "%a - db Delete = %r\n", __func__, TempStatus)); if (EFI_ERROR (TempStatus) && (TempStatus != EFI_NOT_FOUND)) { Status = EFI_ACCESS_DENIED; } TempStatus = DeleteDbx (); - DEBUG ((DEBUG_INFO, "%a - dbx Delete = %r\n", __FUNCTION__, TempStatus)); + DEBUG ((DEBUG_INFO, "%a - dbx Delete = %r\n", __func__, TempStatus)); if (EFI_ERROR (TempStatus) && (TempStatus != EFI_NOT_FOUND)) { Status = EFI_ACCESS_DENIED; } TempStatus = DeleteDbt (); - DEBUG ((DEBUG_INFO, "%a - dbt Delete = %r\n", __FUNCTION__, TempStatus)); + DEBUG ((DEBUG_INFO, "%a - dbt Delete = %r\n", __func__, TempStatus)); if (EFI_ERROR (TempStatus) && (TempStatus != EFI_NOT_FOUND)) { Status = EFI_ACCESS_DENIED; } @@ -752,7 +752,7 @@ EnrollFromInput ( DEBUG (( DEBUG_ERROR, "error: %a (\"%s\", %g): %r\n", - __FUNCTION__, + __func__, VariableName, VendorGuid, Status @@ -795,21 +795,21 @@ SetSecureBootVariablesToDefault ( UINT8 *Data; UINTN DataSize; - DEBUG ((DEBUG_INFO, "%a() Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() Entry\n", __func__)); if (SecureBootPayload == NULL) { - DEBUG ((DEBUG_ERROR, "%a - Invalid SecureBoot payload is supplied!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Invalid SecureBoot payload is supplied!\n", __func__)); return EFI_INVALID_PARAMETER; } // // Right off the bat, if SecureBoot is currently enabled, bail. if (IsSecureBootEnabled ()) { - DEBUG ((DEBUG_ERROR, "%a - Cannot set default keys while SecureBoot is enabled!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Cannot set default keys while SecureBoot is enabled!\n", __func__)); return EFI_ABORTED; } - DEBUG ((DEBUG_INFO, "%a - Setting up key %s!\n", __FUNCTION__, SecureBootPayload->SecureBootKeyName)); + DEBUG ((DEBUG_INFO, "%a - Setting up key %s!\n", __func__, SecureBootPayload->SecureBootKeyName)); // // Start running down the list, creating variables in our wake. @@ -834,10 +834,10 @@ SetSecureBootVariablesToDefault ( Data ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DB %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DB %r!\n", __func__, Status)); } } else { - DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DBX %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DBX %r!\n", __func__, Status)); } // Keep it going. Keep it going. dbt if supplied... @@ -851,7 +851,7 @@ SetSecureBootVariablesToDefault ( Data ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DBT %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to enroll DBT %r!\n", __func__, Status)); } } @@ -866,7 +866,7 @@ SetSecureBootVariablesToDefault ( Data ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to enroll KEK %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to enroll KEK %r!\n", __func__, Status)); } } @@ -889,7 +889,7 @@ SetSecureBootVariablesToDefault ( // // Report PK creation errors. if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to update the PK! - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to update the PK! - %r\n", __func__, Status)); Status = EFI_SECURITY_VIOLATION; } } diff --git a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c index e4cdc68bbb..fb9a0a2aba 100644 --- a/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c +++ b/SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.c @@ -82,7 +82,7 @@ MockSetVariable ( DEBUG (( DEBUG_INFO, "%a %s %g %x %x %p\n", - __FUNCTION__, + __func__, VariableName, VendorGuid, Attributes, @@ -139,7 +139,7 @@ MockGetVariable ( DEBUG (( DEBUG_INFO, "%a %s %g %p %x %p\n", - __FUNCTION__, + __func__, VariableName, VendorGuid, Attributes, diff --git a/SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.c b/SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.c index bed1fe8620..d6046c85d2 100644 --- a/SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.c +++ b/SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.c @@ -81,7 +81,7 @@ SecureBootFetchData ( if (Status == EFI_SUCCESS) { RsaPubKey = NULL; if (RsaGetPublicKeyFromX509 (Buffer, Size, &RsaPubKey) == FALSE) { - DEBUG ((DEBUG_ERROR, "%a: Invalid key format: %d\n", __FUNCTION__, KeyIndex)); + DEBUG ((DEBUG_ERROR, "%a: Invalid key format: %d\n", __func__, KeyIndex)); if (EfiSig != NULL) { FreePool (EfiSig); } diff --git a/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c b/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c index f127757ad9..e2e77cbc24 100644 --- a/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c +++ b/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c @@ -491,7 +491,7 @@ OpalEndOfDxeEventNotify ( { OPAL_DRIVER_DEVICE *TmpDev; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); mOpalEndOfDxe = TRUE; @@ -529,7 +529,7 @@ OpalEndOfDxeEventNotify ( // SendBlockSidCommand (); - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); gBS->CloseEvent (Event); } @@ -888,7 +888,7 @@ OpalDriverRequestPassword ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1074,7 +1074,7 @@ ProcessOpalRequestEnableFeature ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1223,7 +1223,7 @@ ProcessOpalRequestDisableUser ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1339,7 +1339,7 @@ ProcessOpalRequestPsidRevert ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1478,7 +1478,7 @@ ProcessOpalRequestRevert ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1646,7 +1646,7 @@ ProcessOpalRequestSecureErase ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1784,7 +1784,7 @@ ProcessOpalRequestSetUserPwd ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -1990,7 +1990,7 @@ ProcessOpalRequestSetAdminPwd ( return; } - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); PopUpString = OpalGetPopUpString (Dev, RequestString); @@ -2182,7 +2182,7 @@ ProcessOpalRequest ( UINTN DevicePathSize; BOOLEAN KeepUserData; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); if (mOpalRequestVariable == NULL) { Status = GetVariable2 ( @@ -2278,7 +2278,7 @@ ProcessOpalRequest ( TempVariable = (OPAL_REQUEST_VARIABLE *)((UINTN)TempVariable + TempVariable->Length); } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** diff --git a/SecurityPkg/Tcg/Opal/OpalPassword/OpalHii.c b/SecurityPkg/Tcg/Opal/OpalPassword/OpalHii.c index c4f96bee8a..8035f44ebe 100644 --- a/SecurityPkg/Tcg/Opal/OpalPassword/OpalHii.c +++ b/SecurityPkg/Tcg/Opal/OpalPassword/OpalHii.c @@ -95,7 +95,7 @@ GetSavedOpalRequest ( EFI_DEVICE_PATH_PROTOCOL *DevicePath; UINTN DevicePathSize; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); Variable = NULL; VariableSize = 0; @@ -141,7 +141,7 @@ GetSavedOpalRequest ( FreePool (Variable); - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** @@ -169,7 +169,7 @@ SaveOpalRequest ( EFI_DEVICE_PATH_PROTOCOL *DevicePath; UINTN DevicePathSize; - DEBUG ((DEBUG_INFO, "%a() - enter\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - enter\n", __func__)); DEBUG (( DEBUG_INFO, @@ -264,7 +264,7 @@ SaveOpalRequest ( FreePool (Variable); } - DEBUG ((DEBUG_INFO, "%a() - exit\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a() - exit\n", __func__)); } /** diff --git a/SecurityPkg/Tcg/Opal/OpalPassword/OpalPasswordPei.c b/SecurityPkg/Tcg/Opal/OpalPassword/OpalPasswordPei.c index c998b50be5..0fb6b1bf41 100644 --- a/SecurityPkg/Tcg/Opal/OpalPassword/OpalPasswordPei.c +++ b/SecurityPkg/Tcg/Opal/OpalPassword/OpalPasswordPei.c @@ -280,7 +280,7 @@ UnlockOpalPassword ( DEBUG (( DEBUG_INFO, "%a() OpalUtilUpdateGlobalLockingRange() Result = 0x%x\n", - __FUNCTION__, + __func__, Result )); } @@ -302,7 +302,7 @@ UnlockOpalPassword ( DEBUG (( DEBUG_INFO, "%a() OpalBlockSid() Result = 0x%x\n", - __FUNCTION__, + __func__, Result )); } @@ -427,11 +427,11 @@ OpalPasswordStorageSecurityPpiNotify ( IN VOID *Ppi ) { - DEBUG ((DEBUG_INFO, "%a entered at S3 resume!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a entered at S3 resume!\n", __func__)); UnlockOpalPasswordDevices ((EDKII_PEI_STORAGE_SECURITY_CMD_PPI *)Ppi); - DEBUG ((DEBUG_INFO, "%a exit at S3 resume!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a exit at S3 resume!\n", __func__)); return EFI_SUCCESS; } @@ -466,7 +466,7 @@ OpalPasswordPeiInit ( return EFI_UNSUPPORTED; } - DEBUG ((DEBUG_INFO, "%a: Enters in S3 path.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Enters in S3 path.\n", __func__)); Status = PeiServicesNotifyPpi (&mOpalPasswordStorageSecurityPpiNotifyDesc); ASSERT_EFI_ERROR (Status); diff --git a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c index e8822cbeb0..76123fc51a 100644 --- a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c +++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c @@ -188,14 +188,14 @@ ExchangeCommonBuffer ( // Step 0: Sanity check for input argument if (TcgNvs == NULL) { - DEBUG ((DEBUG_ERROR, "%a - Input argument is NULL!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Input argument is NULL!\n", __func__)); return EFI_INVALID_PARAMETER; } // Step 1: Grab the common buffer header Status = EfiGetSystemConfigurationTable (&gEdkiiPiSmmCommunicationRegionTableGuid, (VOID **)&PiSmmCommunicationRegionTable); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to locate SMM communciation common buffer - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to locate SMM communciation common buffer - %r!\n", __func__, Status)); return Status; } @@ -215,7 +215,7 @@ ExchangeCommonBuffer ( if (Index >= PiSmmCommunicationRegionTable->NumberOfEntries) { // Could not find one that meets our goal... - DEBUG ((DEBUG_ERROR, "%a - Could not find a common buffer that is big enough for NVS!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Could not find a common buffer that is big enough for NVS!\n", __func__)); return EFI_OUT_OF_RESOURCES; } @@ -236,9 +236,9 @@ ExchangeCommonBuffer ( Status = gBS->LocateProtocol (&gEfiMmCommunicationProtocolGuid, NULL, (VOID **)&MmCommunication); if (!EFI_ERROR (Status)) { Status = MmCommunication->Communicate (MmCommunication, CommHeader, &CommBufferSize); - DEBUG ((DEBUG_INFO, "%a - Communicate() = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a - Communicate() = %r\n", __func__, Status)); } else { - DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmCommunication protocol - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmCommunication protocol - %r\n", __func__, Status)); return Status; } @@ -250,7 +250,7 @@ ExchangeCommonBuffer ( DEBUG (( DEBUG_INFO, "%a Communication returned software SMI value. PP: 0x%x; MC: 0x%x.\n", - __FUNCTION__, + __func__, TcgNvs->PhysicalPresence.SoftwareSmi, TcgNvs->MemoryClear.SoftwareSmi )); diff --git a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c index 26bb5282a5..1caaa4e319 100644 --- a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c +++ b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c @@ -312,10 +312,10 @@ SyncPcrAllocationsAndPcrMask ( NewTpmActivePcrBanks &= BiosHashAlgorithmBitmap; DEBUG ((DEBUG_INFO, "NewTpmActivePcrBanks 0x%08x\n", NewTpmActivePcrBanks)); - DEBUG ((DEBUG_INFO, "%a - Reallocating PCR banks from 0x%X to 0x%X.\n", __FUNCTION__, TpmActivePcrBanks, NewTpmActivePcrBanks)); + DEBUG ((DEBUG_INFO, "%a - Reallocating PCR banks from 0x%X to 0x%X.\n", __func__, TpmActivePcrBanks, NewTpmActivePcrBanks)); if (NewTpmActivePcrBanks == 0) { - DEBUG ((DEBUG_ERROR, "%a - No viable PCRs active! Please set a less restrictive value for PcdTpm2HashMask!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - No viable PCRs active! Please set a less restrictive value for PcdTpm2HashMask!\n", __func__)); ASSERT (FALSE); } else { DEBUG ((DEBUG_ERROR, "Tpm2PcrAllocateBanks (TpmHashAlgorithmBitmap: 0x%08x, NewTpmActivePcrBanks: 0x%08x)\n", TpmHashAlgorithmBitmap, NewTpmActivePcrBanks)); @@ -324,7 +324,7 @@ SyncPcrAllocationsAndPcrMask ( // // We can't do much here, but we hope that this doesn't happen. // - DEBUG ((DEBUG_ERROR, "%a - Failed to reallocate PCRs!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Failed to reallocate PCRs!\n", __func__)); ASSERT_EFI_ERROR (Status); } @@ -342,9 +342,9 @@ SyncPcrAllocationsAndPcrMask ( if ((Tpm2PcrMask & TpmHashAlgorithmBitmap) != Tpm2PcrMask) { NewTpm2PcrMask = Tpm2PcrMask & TpmHashAlgorithmBitmap; - DEBUG ((DEBUG_INFO, "%a - Updating PcdTpm2HashMask from 0x%X to 0x%X.\n", __FUNCTION__, Tpm2PcrMask, NewTpm2PcrMask)); + DEBUG ((DEBUG_INFO, "%a - Updating PcdTpm2HashMask from 0x%X to 0x%X.\n", __func__, Tpm2PcrMask, NewTpm2PcrMask)); if (NewTpm2PcrMask == 0) { - DEBUG ((DEBUG_ERROR, "%a - No viable PCRs supported! Please set a less restrictive value for PcdTpm2HashMask!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - No viable PCRs supported! Please set a less restrictive value for PcdTpm2HashMask!\n", __func__)); ASSERT (FALSE); } diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c index 498fb626bd..c47c582cc8 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -57,7 +57,7 @@ TpmNvsCommunciate ( UINTN TempCommBufferSize; TPM_NVS_MM_COMM_BUFFER *CommParams; - DEBUG ((DEBUG_VERBOSE, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a()\n", __func__)); // // If input is invalid, stop processing this SMI @@ -69,12 +69,12 @@ TpmNvsCommunciate ( TempCommBufferSize = *CommBufferSize; if (TempCommBufferSize != sizeof (TPM_NVS_MM_COMM_BUFFER)) { - DEBUG ((DEBUG_ERROR, "[%a] MM Communication buffer size is invalid for this handler!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "[%a] MM Communication buffer size is invalid for this handler!\n", __func__)); return EFI_ACCESS_DENIED; } if (!IsBufferOutsideMmValid ((UINTN)CommBuffer, TempCommBufferSize)) { - DEBUG ((DEBUG_ERROR, "[%a] - MM Communication buffer in invalid location!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "[%a] - MM Communication buffer in invalid location!\n", __func__)); return EFI_ACCESS_DENIED; } @@ -85,14 +85,14 @@ TpmNvsCommunciate ( Status = EFI_SUCCESS; switch (CommParams->Function) { case TpmNvsMmExchangeInfo: - DEBUG ((DEBUG_VERBOSE, "[%a] - Function requested: MM_EXCHANGE_NVS_INFO\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "[%a] - Function requested: MM_EXCHANGE_NVS_INFO\n", __func__)); CommParams->RegisteredPpSwiValue = mPpSoftwareSmi; CommParams->RegisteredMcSwiValue = mMcSoftwareSmi; mTcgNvs = (TCG_NVS *)(UINTN)CommParams->TargetAddress; break; default: - DEBUG ((DEBUG_INFO, "[%a] - Unknown function %d!\n", __FUNCTION__, CommParams->Function)); + DEBUG ((DEBUG_INFO, "[%a] - Unknown function %d!\n", __func__, CommParams->Function)); Status = EFI_UNSUPPORTED; break; } @@ -301,7 +301,7 @@ InitializeTcgCommon ( Status = gMmst->MmiHandlerRegister (TpmNvsCommunciate, &gTpmNvsMmGuid, &mReadyToLockHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "[%a] Failed to register NVS communicate as root MM handler - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to register NVS communicate as root MM handler - %r!\n", __func__, Status)); goto Cleanup; } @@ -311,7 +311,7 @@ InitializeTcgCommon ( Status = gMmst->MmLocateProtocol (&gEfiSmmSwDispatch2ProtocolGuid, NULL, (VOID **)&SwDispatch); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "[%a] Failed to locate Sw dispatch protocol - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to locate Sw dispatch protocol - %r!\n", __func__, Status)); goto Cleanup; } @@ -319,7 +319,7 @@ InitializeTcgCommon ( Status = SwDispatch->Register (SwDispatch, PhysicalPresenceCallback, &SwContext, &PpSwHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "[%a] Failed to register PP callback as SW MM handler - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to register PP callback as SW MM handler - %r!\n", __func__, Status)); goto Cleanup; } @@ -329,7 +329,7 @@ InitializeTcgCommon ( Status = SwDispatch->Register (SwDispatch, MemoryClearCallback, &SwContext, &McSwHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "[%a] Failed to register MC callback as SW MM handler - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to register MC callback as SW MM handler - %r!\n", __func__, Status)); goto Cleanup; } @@ -342,7 +342,7 @@ InitializeTcgCommon ( ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { // Should not happen - DEBUG ((DEBUG_ERROR, "[%a] Failed to locate SMM variable protocol - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to locate SMM variable protocol - %r!\n", __func__, Status)); goto Cleanup; } @@ -350,7 +350,7 @@ InitializeTcgCommon ( Status = gMmst->MmRegisterProtocolNotify (&gEfiMmReadyToLockProtocolGuid, TcgMmReadyToLock, &NotifyHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "[%a] Failed to register ready to lock notification - %r!\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "[%a] Failed to register ready to lock notification - %r!\n", __func__, Status)); goto Cleanup; } diff --git a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c index b34da724ac..6ca29f5de0 100644 --- a/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c +++ b/SecurityPkg/Tcg/TdTcg2Dxe/TdTcg2Dxe.c @@ -1353,12 +1353,12 @@ TdHashLogExtendEvent ( } if (CcEvent->Header.MrIndex == CC_MR_INDEX_0_MRTD) { - DEBUG ((DEBUG_ERROR, "%a: MRTD cannot be extended in TDVF.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: MRTD cannot be extended in TDVF.\n", __func__)); return EFI_INVALID_PARAMETER; } if (CcEvent->Header.MrIndex >= CC_MR_INDEX_INVALID) { - DEBUG ((DEBUG_ERROR, "%a: MrIndex is invalid. (%d)\n", __FUNCTION__, CcEvent->Header.MrIndex)); + DEBUG ((DEBUG_ERROR, "%a: MrIndex is invalid. (%d)\n", __func__, CcEvent->Header.MrIndex)); return EFI_INVALID_PARAMETER; } @@ -2514,7 +2514,7 @@ DriverEntry ( // // Cc measurement feature is crucial to a td-guest and it shall stop running immediately // when it is failed to be installed. - DEBUG ((DEBUG_ERROR, "%a: CcMeasurement protocol failed to be installed - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: CcMeasurement protocol failed to be installed - %r\n", __func__, Status)); CpuDeadLoop (); } diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c index 4299a6b5e5..0e31502b1b 100644 --- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c +++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c @@ -167,7 +167,7 @@ GetCurrentTime ( DEBUG (( DEBUG_ERROR, "%a(), GetTime() failed, status = '%r'\n", - __FUNCTION__, + __func__, Status )); return Status; diff --git a/SecurityPkg/VariableAuthenticated/SecureBootDefaultKeysDxe/SecureBootDefaultKeysDxe.c b/SecurityPkg/VariableAuthenticated/SecureBootDefaultKeysDxe/SecureBootDefaultKeysDxe.c index 0abde52a05..2f6f3e6796 100644 --- a/SecurityPkg/VariableAuthenticated/SecureBootDefaultKeysDxe/SecureBootDefaultKeysDxe.c +++ b/SecurityPkg/VariableAuthenticated/SecureBootDefaultKeysDxe/SecureBootDefaultKeysDxe.c @@ -42,35 +42,35 @@ SecureBootDefaultKeysEntryPoint ( Status = SecureBootInitPKDefault (); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Cannot initialize PKDefault: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Cannot initialize PKDefault: %r\n", __func__, Status)); return Status; } Status = SecureBootInitKEKDefault (); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Cannot initialize KEKDefault: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Cannot initialize KEKDefault: %r\n", __func__, Status)); return Status; } Status = SecureBootInitDbDefault (); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbDefault: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbDefault: %r\n", __func__, Status)); return Status; } Status = SecureBootInitDbtDefault (); if (Status == EFI_NOT_FOUND) { - DEBUG ((DEBUG_INFO, "%a: dbtDefault not initialized\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: dbtDefault not initialized\n", __func__)); } else if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbtDefault: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbtDefault: %r\n", __func__, Status)); return Status; } Status = SecureBootInitDbxDefault (); if (Status == EFI_NOT_FOUND) { - DEBUG ((DEBUG_INFO, "%a: dbxDefault not initialized\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: dbxDefault not initialized\n", __func__)); } else if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbxDefault: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Cannot initialize dbxDefault: %r\n", __func__, Status)); return Status; } From 4e442bf9a85070331b5ad7aeeb374119ead4d0d5 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:50:52 -0600 Subject: [PATCH 0853/1529] EmbeddedPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout EmbeddedPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Abner Chang --- .../Drivers/ConsolePrefDxe/ConsolePrefDxe.c | 18 +++++++-------- .../Drivers/DtPlatformDxe/DtPlatformDxe.c | 10 ++++----- .../Drivers/FdtClientDxe/FdtClientDxe.c | 22 +++++++++---------- .../NonCoherentDmaLib/NonCoherentDmaLib.c | 2 +- .../RealTimeClockRuntimeDxe/RealTimeClock.c | 2 +- .../Universal/MmcDxe/MmcIdentification.c | 20 ++++++++--------- 6 files changed, 37 insertions(+), 37 deletions(-) diff --git a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c index 07b82892eb..2c2e73e720 100644 --- a/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c +++ b/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.c @@ -116,7 +116,7 @@ RemoveDtStdoutPath ( DEBUG (( DEBUG_INFO, "%a: could not retrieve DT blob - %r\n", - __FUNCTION__, + __func__, Status )); return; @@ -132,7 +132,7 @@ RemoveDtStdoutPath ( DEBUG (( DEBUG_INFO, "%a: Failed to delete 'stdout-path' property: %a\n", - __FUNCTION__, + __func__, fdt_strerror (Error) )); } @@ -190,7 +190,7 @@ RemoveSpcrTable ( DEBUG (( DEBUG_WARN, "%a: failed to uninstall SPCR table - %r\n", - __FUNCTION__, + __func__, Status )); } @@ -224,7 +224,7 @@ OnReadyToBoot ( DEBUG (( DEBUG_ERROR, "%a: variable '%s' could not be read - bailing!\n", - __FUNCTION__, + __func__, CONSOLE_PREF_VARIABLE_NAME )); return; @@ -234,7 +234,7 @@ OnReadyToBoot ( DEBUG (( DEBUG_INFO, "%a: serial console preferred - doing nothing\n", - __FUNCTION__ + __func__ )); return; } @@ -247,7 +247,7 @@ OnReadyToBoot ( DEBUG (( DEBUG_INFO, "%a: no GOP instances found - doing nothing (%r)\n", - __FUNCTION__, + __func__, Status )); return; @@ -296,7 +296,7 @@ ConsolePrefDxeEntryPoint ( DEBUG (( DEBUG_INFO, "%a: no console preference found, defaulting to graphical\n", - __FUNCTION__ + __func__ )); ConsolePref.Console = CONSOLE_PREF_GRAPHICAL; } @@ -308,7 +308,7 @@ ConsolePrefDxeEntryPoint ( DEBUG (( DEBUG_WARN, "%a: invalid value for %s, defaulting to graphical\n", - __FUNCTION__, + __func__, CONSOLE_PREF_VARIABLE_NAME )); ConsolePref.Console = CONSOLE_PREF_GRAPHICAL; @@ -332,7 +332,7 @@ ConsolePrefDxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: gRT->SetVariable () failed - %r\n", - __FUNCTION__, + __func__, Status )); return Status; diff --git a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c index 7f7e8c446c..b94cd4da25 100644 --- a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c +++ b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c @@ -122,7 +122,7 @@ DtPlatformDxeEntryPoint ( DEBUG (( DEBUG_WARN, "%a: no DTB blob could be loaded, defaulting to ACPI (Status == %r)\n", - __FUNCTION__, + __func__, Status )); DtAcpiPref.Pref = DT_ACPI_SELECT_ACPI; @@ -142,7 +142,7 @@ DtPlatformDxeEntryPoint ( DEBUG (( DEBUG_WARN, "%a: no DT/ACPI preference found, defaulting to %a\n", - __FUNCTION__, + __func__, PcdGetBool (PcdDefaultDtPref) ? "DT" : "ACPI" )); DtAcpiPref.Pref = PcdGetBool (PcdDefaultDtPref) ? DT_ACPI_SELECT_DT @@ -157,7 +157,7 @@ DtPlatformDxeEntryPoint ( DEBUG (( DEBUG_WARN, "%a: invalid value for %s, defaulting to %a\n", - __FUNCTION__, + __func__, DT_ACPI_VARIABLE_NAME, PcdGetBool (PcdDefaultDtPref) ? "DT" : "ACPI" )); @@ -197,7 +197,7 @@ DtPlatformDxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: failed to install gEdkiiPlatformHasAcpiGuid as a protocol\n", - __FUNCTION__ + __func__ )); goto FreeDtb; } @@ -211,7 +211,7 @@ DtPlatformDxeEntryPoint ( DEBUG (( DEBUG_ERROR, "%a: failed to install FDT configuration table\n", - __FUNCTION__ + __func__ )); goto FreeDtb; } diff --git a/EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.c b/EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.c index b182c77d19..7da505a313 100644 --- a/EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.c +++ b/EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.c @@ -222,7 +222,7 @@ FindCompatibleNodeReg ( DEBUG (( DEBUG_ERROR, "%a: '%a' compatible node has invalid 'reg' property (size == 0x%x)\n", - __FUNCTION__, + __func__, CompatibleString, *RegSize )); @@ -263,7 +263,7 @@ FindNextMemoryNodeReg ( } if (!IsNodeEnabled (Next)) { - DEBUG ((DEBUG_WARN, "%a: ignoring disabled memory node\n", __FUNCTION__)); + DEBUG ((DEBUG_WARN, "%a: ignoring disabled memory node\n", __func__)); continue; } @@ -279,7 +279,7 @@ FindNextMemoryNodeReg ( DEBUG (( DEBUG_WARN, "%a: ignoring memory node with no 'reg' property\n", - __FUNCTION__ + __func__ )); continue; } @@ -288,7 +288,7 @@ FindNextMemoryNodeReg ( DEBUG (( DEBUG_WARN, "%a: ignoring memory node with invalid 'reg' property (size == 0x%x)\n", - __FUNCTION__, + __func__, *RegSize )); continue; @@ -391,7 +391,7 @@ OnPlatformHasDeviceTree ( DEBUG (( DEBUG_INFO, "%a: exposing DTB @ 0x%p to OS\n", - __FUNCTION__, + __func__, DeviceTreeBase )); Status = gBS->InstallConfigurationTable (&gFdtTableGuid, DeviceTreeBase); @@ -424,7 +424,7 @@ InitializeFdtClientDxe ( DEBUG (( DEBUG_ERROR, "%a: No DTB found @ 0x%p\n", - __FUNCTION__, + __func__, DeviceTreeBase )); return EFI_NOT_FOUND; @@ -432,7 +432,7 @@ InitializeFdtClientDxe ( mDeviceTreeBase = DeviceTreeBase; - DEBUG ((DEBUG_INFO, "%a: DTB @ 0x%p\n", __FUNCTION__, mDeviceTreeBase)); + DEBUG ((DEBUG_INFO, "%a: DTB @ 0x%p\n", __func__, mDeviceTreeBase)); // // Register a protocol notify for the EDKII Platform Has Device Tree @@ -446,7 +446,7 @@ InitializeFdtClientDxe ( &PlatformHasDeviceTreeEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: CreateEvent(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: CreateEvent(): %r\n", __func__, Status)); return Status; } @@ -459,7 +459,7 @@ InitializeFdtClientDxe ( DEBUG (( DEBUG_ERROR, "%a: RegisterProtocolNotify(): %r\n", - __FUNCTION__, + __func__, Status )); goto CloseEvent; @@ -470,7 +470,7 @@ InitializeFdtClientDxe ( // Status = gBS->SignalEvent (PlatformHasDeviceTreeEvent); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: SignalEvent(): %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: SignalEvent(): %r\n", __func__, Status)); goto CloseEvent; } @@ -484,7 +484,7 @@ InitializeFdtClientDxe ( DEBUG (( DEBUG_ERROR, "%a: InstallProtocolInterface(): %r\n", - __FUNCTION__, + __func__, Status )); goto CloseEvent; diff --git a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c index 44a78c947e..e193352fbe 100644 --- a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c +++ b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c @@ -349,7 +349,7 @@ DmaMap ( "%a: Operation type 'MapOperationBusMasterCommonBuffer' is only " "supported\non memory regions that were allocated using " "DmaAllocateBuffer ()\n", - __FUNCTION__ + __func__ )); Status = EFI_UNSUPPORTED; FreeMapInfo: diff --git a/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClock.c b/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClock.c index 7adb732405..17dde432c4 100644 --- a/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClock.c +++ b/EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClock.c @@ -219,7 +219,7 @@ InitializeRealTimeClock ( DEBUG (( DEBUG_WARN, "%a: using default timezone/daylight settings\n", - __FUNCTION__ + __func__ )); mTimeSettings.TimeZone = EFI_UNSPECIFIED_TIMEZONE; diff --git a/EmbeddedPkg/Universal/MmcDxe/MmcIdentification.c b/EmbeddedPkg/Universal/MmcDxe/MmcIdentification.c index 86eb55800e..57388d9f46 100755 --- a/EmbeddedPkg/Universal/MmcDxe/MmcIdentification.c +++ b/EmbeddedPkg/Universal/MmcDxe/MmcIdentification.c @@ -414,13 +414,13 @@ InitializeSdMmcDevice ( Status = MmcHost->SendCommand (MmcHost, MMC_CMD55, CmdArg); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __func__, Status)); return Status; } Status = MmcHost->ReceiveResponse (MmcHost, MMC_RESPONSE_TYPE_R1, Response); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __func__, Status)); return Status; } @@ -473,18 +473,18 @@ InitializeSdMmcDevice ( CmdArg = CreateSwitchCmdArgument (0, 0, 0); Status = MmcHost->SendCommand (MmcHost, MMC_CMD6, CmdArg); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __func__, Status)); return Status; } else { Status = MmcHost->ReadBlockData (MmcHost, 0, SWITCH_CMD_DATA_LENGTH, Buffer); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): ReadBlockData Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): ReadBlockData Error and Status = %r\n", __func__, Status)); return Status; } } if (!(Buffer[3] & SD_HIGH_SPEED_SUPPORTED)) { - DEBUG ((DEBUG_INFO, "%a : High Speed not supported by Card\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a : High Speed not supported by Card\n", __func__)); } else { Speed = SD_HIGH_SPEED; @@ -492,12 +492,12 @@ InitializeSdMmcDevice ( CmdArg = CreateSwitchCmdArgument (1, 0, 1); Status = MmcHost->SendCommand (MmcHost, MMC_CMD6, CmdArg); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __func__, Status)); return Status; } else { Status = MmcHost->ReadBlockData (MmcHost, 0, SWITCH_CMD_DATA_LENGTH, Buffer); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): ReadBlockData Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): ReadBlockData Error and Status = %r\n", __func__, Status)); return Status; } @@ -513,14 +513,14 @@ InitializeSdMmcDevice ( CmdArg = MmcHostInstance->CardInfo.RCA << 16; Status = MmcHost->SendCommand (MmcHost, MMC_CMD55, CmdArg); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD55): Error and Status = %r\n", __func__, Status)); return Status; } /* Width: 4 */ Status = MmcHost->SendCommand (MmcHost, MMC_CMD6, 2); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (MMC_CMD6): Error and Status = %r\n", __func__, Status)); return Status; } } @@ -528,7 +528,7 @@ InitializeSdMmcDevice ( if (MMC_HOST_HAS_SETIOS (MmcHost)) { Status = MmcHost->SetIos (MmcHost, Speed, BUSWIDTH_4, EMMCBACKWARD); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a (SetIos): Error and Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a (SetIos): Error and Status = %r\n", __func__, Status)); return Status; } } From 04ff563c5eb7fc415bfcfcf3ef85be579378e62a Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:51:09 -0600 Subject: [PATCH 0854/1529] RedfishPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout RedfishPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Ard Biesheuvel Reviewed-by: Nickle Wang --- .../PlatformHostInterfaceBmcUsbNicLib.c | 36 +++++------ .../RedfishPlatformCredentialIpmiLib.c | 28 ++++----- .../PrivateLibrary/RedfishLib/RedfishLib.c | 2 +- .../RedfishLib/edk2libredfish/src/service.c | 4 +- .../RedfishConfigHandlerCommon.c | 6 +- .../RedfishConfigHandlerDriver.c | 20 +++--- .../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 62 +++++++++---------- .../RedfishHostInterfaceDxe.c | 14 ++--- .../RedfishRestExDxe/RedfishRestExImpl.c | 14 ++--- 9 files changed, 93 insertions(+), 93 deletions(-) diff --git a/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c index 122473dbe4..4bd01850af 100644 --- a/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c +++ b/RedfishPkg/Library/PlatformHostInterfaceBmcUsbNicLib/PlatformHostInterfaceBmcUsbNicLib.c @@ -37,7 +37,7 @@ ProbeRedfishCredentialBootstrap ( UINT32 ResponseSize; BOOLEAN ReturnBool; - DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n", __func__)); // // IPMI callout to NetFn 2C, command 02 @@ -65,10 +65,10 @@ ProbeRedfishCredentialBootstrap ( (ResponseData.CompletionCode == REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED) )) { - DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is supported\n", __FUNCTION__)); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is supported\n", __func__)); ReturnBool = TRUE; } else { - DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is not supported\n", __FUNCTION__)); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, " Redfish Credentail Bootstrapping is not supported\n", __func__)); ReturnBool = FALSE; } @@ -94,7 +94,7 @@ RedfishPlatformHostInterfaceDeviceDescriptor ( HOST_INTERFACE_BMC_USB_NIC_INFO *ThisInstance; REDFISH_INTERFACE_DATA *InterfaceData; - DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n", __func__)); if (IsListEmpty (&mBmcUsbNic)) { return EFI_NOT_FOUND; @@ -166,7 +166,7 @@ RedfishPlatformHostInterfaceProtocolData ( UINT8 HostNameLength; CHAR8 *HostNameString; - DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n", __func__)); if (IsListEmpty (&mBmcUsbNic) || (IndexOfProtocolData > 0)) { return EFI_NOT_FOUND; @@ -300,7 +300,7 @@ RetrievedBmcUsbNicInfo ( IPMI_LAN_VLAN_ID *LanVlanId; EFI_USB_DEVICE_DESCRIPTOR UsbDeviceDescriptor; - DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n", __func__)); if (IsListEmpty (&mBmcUsbNic)) { return EFI_NOT_FOUND; @@ -605,7 +605,7 @@ HostInterfaceIpmiCheckMacAddress ( EFI_MAC_ADDRESS IpmiLanChannelMacAddress; BOOLEAN AlreadyCached; - DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __func__)); GetLanConfigReps = NULL; AlreadyCached = FALSE; @@ -823,7 +823,7 @@ UsbNicSearchUsbIo ( EFI_DEVICE_PATH_PROTOCOL *ThisUsbDevicePath; EFI_DEVICE_PATH_PROTOCOL *ThisUsbDevicePathEnd; - DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __func__)); DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "Device path on the EFI handle which has UsbIo and SNP instaleld on it.\n")); DevicePathStr = ConvertDevicePathToText (UsbDevicePath, FALSE, FALSE); if (DevicePathStr != NULL) { @@ -987,7 +987,7 @@ IdentifyUsbNicBmcChannel ( EFI_USB_IO_PROTOCOL *UsbIo; HOST_INTERFACE_BMC_USB_NIC_INFO *BmcUsbNic; - DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __func__)); Status = gBS->HandleProtocol ( Handle, &gEfiSimpleNetworkProtocolGuid, @@ -1074,7 +1074,7 @@ CheckBmcUsbNicOnHandles ( return EFI_INVALID_PARAMETER; } - DEBUG ((DEBUG_INFO, "%a: Entry, #%d SNP handle\n", __FUNCTION__, HandleNumer)); + DEBUG ((DEBUG_INFO, "%a: Entry, #%d SNP handle\n", __func__, HandleNumer)); GotOneUsbNIc = FALSE; for (Index = 0; Index < HandleNumer; Index++) { @@ -1084,7 +1084,7 @@ CheckBmcUsbNicOnHandles ( (VOID **)&DevicePath ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, " Failed to locate SNP on %d handle.\n", __FUNCTION__, Index)); + DEBUG ((DEBUG_ERROR, " Failed to locate SNP on %d handle.\n", __func__, Index)); continue; } @@ -1137,7 +1137,7 @@ CheckBmcUsbNic ( UINTN BufferSize; EFI_HANDLE *HandleBuffer; - DEBUG ((DEBUG_INFO, "%a: Entry, the registration key - 0x%08x.\n", __FUNCTION__, Registration)); + DEBUG ((DEBUG_INFO, "%a: Entry, the registration key - 0x%08x.\n", __func__, Registration)); Handle = NULL; Status = EFI_SUCCESS; @@ -1213,7 +1213,7 @@ PlatformHostInterfaceSnpCallback ( IN VOID *Context ) { - DEBUG ((DEBUG_INFO, "%a: Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry.\n", __func__)); CheckBmcUsbNic (mPlatformHostInterfaceSnpRegistration); return; @@ -1241,7 +1241,7 @@ RedfishPlatformHostInterfaceNotification ( { EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: Entry\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n", __func__)); *InformationReadinessGuid = NULL; InitializeListHead (&mBmcUsbNic); @@ -1257,7 +1257,7 @@ RedfishPlatformHostInterfaceNotification ( } if (Status == EFI_NOT_FOUND) { - DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%a: BMC USB NIC is not found. Register the notification.\n", __FUNCTION__)); + DEBUG ((DEBUG_REDFISH_HOST_INTERFACE, "%a: BMC USB NIC is not found. Register the notification.\n", __func__)); // Register the notification of SNP installation. Status = gBS->CreateEvent ( @@ -1268,7 +1268,7 @@ RedfishPlatformHostInterfaceNotification ( &mPlatformHostInterfaceSnpEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to create event for the installation of SNP protocol.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to create event for the installation of SNP protocol.", __func__)); return Status; } @@ -1278,7 +1278,7 @@ RedfishPlatformHostInterfaceNotification ( &mPlatformHostInterfaceSnpRegistration ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to register event for the installation of SNP protocol.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to register event for the installation of SNP protocol.", __func__)); return Status; } @@ -1286,6 +1286,6 @@ RedfishPlatformHostInterfaceNotification ( return EFI_SUCCESS; } - DEBUG ((DEBUG_ERROR, "%a: Something wrong when look for BMC USB NIC.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Something wrong when look for BMC USB NIC.\n", __func__)); return Status; } diff --git a/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c index dacb09bb23..3b34dafbaf 100644 --- a/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c +++ b/RedfishPkg/Library/RedfishPlatformCredentialIpmiLib/RedfishPlatformCredentialIpmiLib.c @@ -63,10 +63,10 @@ LibStopRedfishService ( // Status = SetBootstrapAccountCredentialsToVariable (NULL, NULL, TRUE); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: fail to remove bootstrap credential: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: fail to remove bootstrap credential: %r\n", __func__, Status)); } - DEBUG ((DEBUG_INFO, "%a: bootstrap credential service stopped\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: bootstrap credential service stopped\n", __func__)); return EFI_SUCCESS; } @@ -153,7 +153,7 @@ GetBootstrapAccountCredentials ( return EFI_INVALID_PARAMETER; } - DEBUG ((DEBUG_VERBOSE, "%a: Disable bootstrap control: 0x%x\n", __FUNCTION__, DisableBootstrapControl)); + DEBUG ((DEBUG_VERBOSE, "%a: Disable bootstrap control: 0x%x\n", __func__, DisableBootstrapControl)); // // IPMI callout to NetFn 2C, command 02 @@ -183,19 +183,19 @@ GetBootstrapAccountCredentials ( ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: IPMI transaction failure. Returning\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: IPMI transaction failure. Returning\n", __func__)); return Status; } else { if (ResponseData.CompletionCode != IPMI_COMP_CODE_NORMAL) { if (ResponseData.CompletionCode == REDFISH_IPMI_COMP_CODE_BOOTSTRAP_CREDENTIAL_DISABLED) { - DEBUG ((DEBUG_ERROR, "%a: bootstrap credential support was disabled\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: bootstrap credential support was disabled\n", __func__)); return EFI_ACCESS_DENIED; } - DEBUG ((DEBUG_ERROR, "%a: Completion code = 0x%x. Returning\n", __FUNCTION__, ResponseData.CompletionCode)); + DEBUG ((DEBUG_ERROR, "%a: Completion code = 0x%x. Returning\n", __func__, ResponseData.CompletionCode)); return EFI_PROTOCOL_ERROR; } else if (ResponseData.GroupExtensionId != REDFISH_IPMI_GROUP_EXTENSION) { - DEBUG ((DEBUG_ERROR, "%a: Group Extension Response = 0x%x. Returning\n", __FUNCTION__, ResponseData.GroupExtensionId)); + DEBUG ((DEBUG_ERROR, "%a: Group Extension Response = 0x%x. Returning\n", __func__, ResponseData.GroupExtensionId)); return EFI_DEVICE_ERROR; } else { if (BootstrapUsername != NULL) { @@ -216,7 +216,7 @@ GetBootstrapAccountCredentials ( } } - DEBUG ((DEBUG_INFO, "%a: get bootstrap credential via IPMI: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: get bootstrap credential via IPMI: %r\n", __func__, Status)); return Status; } @@ -269,7 +269,7 @@ GetBootstrapAccountCredentialsFromVariable ( } if (DataSize != sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE)) { - DEBUG ((DEBUG_ERROR, "%a: data corruption. returned size: %d != structure size: %d\n", __FUNCTION__, DataSize, sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE))); + DEBUG ((DEBUG_ERROR, "%a: data corruption. returned size: %d != structure size: %d\n", __func__, DataSize, sizeof (BOOTSTRAP_CREDENTIALS_VARIABLE))); FreePool (Data); return EFI_NOT_FOUND; } @@ -284,7 +284,7 @@ GetBootstrapAccountCredentialsFromVariable ( FreePool (Data); - DEBUG ((DEBUG_INFO, "%a: get bootstrap credential from variable\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: get bootstrap credential from variable\n", __func__)); return EFI_SUCCESS; } @@ -412,7 +412,7 @@ LibCredentialGetAuthInfo ( DisableCredentialService = PcdGetBool (PcdRedfishDisableBootstrapCredentialService); if (mRedfishServiceStopped) { - DEBUG ((DEBUG_ERROR, "%a: credential service is stopped due to security reason\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: credential service is stopped due to security reason\n", __func__)); return EFI_ACCESS_DENIED; } @@ -441,17 +441,17 @@ LibCredentialGetAuthInfo ( // Status = GetBootstrapAccountCredentials (DisableCredentialService, *UserId, USERNAME_MAX_SIZE, *Password, PASSWORD_MAX_SIZE); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: fail to get bootstrap credential: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: fail to get bootstrap credential: %r\n", __func__, Status)); return Status; } if (DisableCredentialService) { - DEBUG ((DEBUG_INFO, "%a: credential bootstrapping control disabled\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: credential bootstrapping control disabled\n", __func__)); } Status = SetBootstrapAccountCredentialsToVariable (*UserId, *Password, FALSE); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: fail to cache bootstrap credential: %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: fail to cache bootstrap credential: %r\n", __func__, Status)); } return EFI_SUCCESS; diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c index 51a85a7336..0a0a4e6458 100644 --- a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c +++ b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c @@ -1101,7 +1101,7 @@ RedfishIsValidOdataType ( } } - DEBUG ((DEBUG_INFO, "%a: This Odata type is not in the list.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: This Odata type is not in the list.\n", __func__)); return FALSE; } diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c index cbd4330a0e..206094d87d 100644 --- a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c +++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c @@ -521,7 +521,7 @@ getUriFromService ( // Status = DecodeResponseContent (ContentEncodedHeader->FieldValue, &ResponseMsg.Body, &ResponseMsg.BodyLength); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Failed to decompress the response content %r\n.", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Failed to decompress the response content %r\n.", __func__, Status)); ret = NULL; goto ON_EXIT; } @@ -656,7 +656,7 @@ patchUriFromService ( // Status = EncodeRequestContent ((CHAR8 *)HTTP_CONTENT_ENCODING_GZIP, (CHAR8 *)content, (VOID **)&EncodedContent, &EncodedContentLen); if (Status == EFI_INVALID_PARAMETER) { - DEBUG ((DEBUG_ERROR, "%a: Error to encode content.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Error to encode content.\n", __func__)); ret = NULL; goto ON_EXIT; } else if (Status == EFI_UNSUPPORTED) { diff --git a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c index 96aac125ee..b51b558a48 100644 --- a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c +++ b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerCommon.c @@ -122,7 +122,7 @@ RedfishConfigCommonInit ( // Status = gBS->LocateProtocol (&gEdkIIRedfishCredentialProtocolGuid, NULL, (VOID **)&gCredential); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: No Redfish Credential Protocol is installed on system.", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: No Redfish Credential Protocol is installed on system.", __func__)); return Status; } @@ -138,7 +138,7 @@ RedfishConfigCommonInit ( &gEndOfDxeEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to register End Of DXE event.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to register End Of DXE event.", __func__)); return Status; } @@ -156,7 +156,7 @@ RedfishConfigCommonInit ( if (EFI_ERROR (Status)) { gBS->CloseEvent (gEndOfDxeEvent); gEndOfDxeEvent = NULL; - DEBUG ((DEBUG_ERROR, "%a: Fail to register Exit Boot Service event.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to register Exit Boot Service event.", __func__)); return Status; } diff --git a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c index 96ac70f418..993ad338b6 100644 --- a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c +++ b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c @@ -372,7 +372,7 @@ RedfishDiscoverProtocolInstalled ( EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *ThisNetworkInterface; EFI_REDFISH_DISCOVERED_TOKEN *ThisRedfishDiscoveredToken; - DEBUG ((DEBUG_INFO, "%a: New network interface is installed on system by EFI Redfish discover driver.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: New network interface is installed on system by EFI Redfish discover driver.\n", __func__)); BufferSize = sizeof (EFI_HANDLE); Status = gBS->LocateHandle ( @@ -383,7 +383,7 @@ RedfishDiscoverProtocolInstalled ( &HandleBuffer ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Can't locate handle with EFI_REDFISH_DISCOVER_PROTOCOL installed.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't locate handle with EFI_REDFISH_DISCOVER_PROTOCOL installed.\n", __func__)); } gRedfishDiscoverActivated = TRUE; @@ -403,7 +403,7 @@ RedfishDiscoverProtocolInstalled ( if (EFI_ERROR (Status)) { gEfiRedfishDiscoverProtocol = NULL; gRedfishDiscoverActivated = FALSE; - DEBUG ((DEBUG_ERROR, "%a: Can't locate EFI_REDFISH_DISCOVER_PROTOCOL.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't locate EFI_REDFISH_DISCOVER_PROTOCOL.\n", __func__)); return; } } @@ -422,13 +422,13 @@ RedfishDiscoverProtocolInstalled ( &gNetworkInterfaceInstances ); if (EFI_ERROR (Status) || (gNumberOfNetworkInterfaces == 0)) { - DEBUG ((DEBUG_ERROR, "%a: No network interfaces found on the handle.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: No network interfaces found on the handle.\n", __func__)); return; } gRedfishDiscoveredToken = AllocateZeroPool (gNumberOfNetworkInterfaces * sizeof (EFI_REDFISH_DISCOVERED_TOKEN)); if (gRedfishDiscoveredToken == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Not enough memory for EFI_REDFISH_DISCOVERED_TOKEN.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Not enough memory for EFI_REDFISH_DISCOVERED_TOKEN.\n", __func__)); return; } @@ -449,7 +449,7 @@ RedfishDiscoverProtocolInstalled ( &ThisRedfishDiscoveredToken->Event ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Failed to create event for Redfish discovered token.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Failed to create event for Redfish discovered token.\n", __func__)); goto ErrorReturn; } @@ -472,7 +472,7 @@ RedfishDiscoverProtocolInstalled ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Acquire Redfish service fail.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Acquire Redfish service fail.\n", __func__)); goto ErrorReturn; } @@ -556,7 +556,7 @@ RedfishConfigHandlerDriverEntryPoint ( &gEfiRedfishDiscoverProtocolEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to create event for the installation of EFI_REDFISH_DISCOVER_PROTOCOL.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to create event for the installation of EFI_REDFISH_DISCOVER_PROTOCOL.", __func__)); return Status; } @@ -566,7 +566,7 @@ RedfishConfigHandlerDriverEntryPoint ( &gEfiRedfishDiscoverRegistration ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to register event for the installation of EFI_REDFISH_DISCOVER_PROTOCOL.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to register event for the installation of EFI_REDFISH_DISCOVER_PROTOCOL.", __func__)); return Status; } @@ -593,7 +593,7 @@ RedfishConfigHandlerDriverEntryPoint ( gExitBootServiceEvent = NULL; gBS->CloseEvent (gEfiRedfishDiscoverProtocolEvent); gEfiRedfishDiscoverProtocolEvent = NULL; - DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI Binding Protocol of EFI Redfish Config driver.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI Binding Protocol of EFI Redfish Config driver.", __func__)); return Status; } diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c index f64c79088f..583c6f78e1 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c @@ -196,13 +196,13 @@ Tcp4GetSubnetInfo ( Tcp4Option.EnableNagle = TRUE; Status = Tcp4->Configure (Tcp4, &Tcp4CfgData); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Can't get subnet information\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't get subnet information\n", __func__)); return Status; } Status = Tcp4->GetModeData (Tcp4, NULL, NULL, &IpModedata, NULL, NULL); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __func__)); return Status; } @@ -265,12 +265,12 @@ Tcp6GetSubnetInfo ( ZeroMem ((VOID *)&IpModedata, sizeof (EFI_IP6_MODE_DATA)); Status = Tcp6->GetModeData (Tcp6, NULL, NULL, &IpModedata, NULL, NULL); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't get IP mode data information\n", __func__)); return Status; } if (IpModedata.AddressCount == 0) { - DEBUG ((DEBUG_INFO, "%a: No IPv6 address configured.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: No IPv6 address configured.\n", __func__)); Instance->SubnetAddrInfoIPv6Number = 0; return EFI_SUCCESS; } @@ -282,7 +282,7 @@ Tcp6GetSubnetInfo ( Instance->SubnetAddrInfoIPv6 = AllocateZeroPool (IpModedata.AddressCount * sizeof (EFI_IP6_ADDRESS_INFO)); if (Instance->SubnetAddrInfoIPv6 == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Failed to allocate memory for IPv6 subnet address information\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Failed to allocate memory for IPv6 subnet address information\n", __func__)); return EFI_OUT_OF_RESOURCES; } @@ -529,7 +529,7 @@ DiscoverRedfishHostInterface ( IP4_COPY_ADDRESS ((VOID *)&Instance->HostSubnetMask.v4, (VOID *)Data->HostIpMask); if (EFI_IP4_EQUAL (&Instance->HostIpAddress.v4, &mZeroIp4Addr)) { - DEBUG ((DEBUG_ERROR, "%a: invalid host IP address: zero address\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid host IP address: zero address\n", __func__)); // // Invalid IP address detected. Change address format to Unknown and use system default address. // @@ -537,7 +537,7 @@ DiscoverRedfishHostInterface ( } if (!IP4_IS_VALID_NETMASK (EFI_IP4 (Instance->HostSubnetMask.v4))) { - DEBUG ((DEBUG_ERROR, "%a: invalid subnet mask address\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid subnet mask address\n", __func__)); // // Invalid subnet mast address detected. Change address format to Unknown and use system default address. // @@ -551,14 +551,14 @@ DiscoverRedfishHostInterface ( IP4_COPY_ADDRESS ((VOID *)&Instance->TargetIpAddress.v4, (VOID *)Data->RedfishServiceIpAddress); if (EFI_IP4_EQUAL (&Instance->TargetIpAddress.v4, &mZeroIp4Addr)) { - DEBUG ((DEBUG_ERROR, "%a: invalid service IP address: zero address\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: invalid service IP address: zero address\n", __func__)); } } else { IP6_COPY_ADDRESS ((VOID *)&Instance->TargetIpAddress.v6, (VOID *)Data->RedfishServiceIpAddress); } if (Instance->HostIntfValidation) { - DEBUG ((DEBUG_ERROR, "%a:Send UPnP unicast SSDP to validate this Redfish Host Interface is not supported.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Send UPnP unicast SSDP to validate this Redfish Host Interface is not supported.\n", __func__)); Status = EFI_UNSUPPORTED; } else { // @@ -682,7 +682,7 @@ AddAndSignalNewRedfishService ( RestExOpened = FALSE; DeleteRestEx = FALSE; - DEBUG ((DEBUG_INFO, "%a:Add this instance to Redfish instance list.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a:Add this instance to Redfish instance list.\n", __func__)); if (Uuid != NULL) { Char16Uuid = (CHAR16 *)AllocateZeroPool (AsciiStrSize ((const CHAR8 *)Uuid) * sizeof (CHAR16)); @@ -846,7 +846,7 @@ AddAndSignalNewRedfishService ( if (!InfoRefresh) { Status = CreateRestExInstance (Instance, Instance->DiscoverToken); // Create REST EX child. if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:Can't create REST EX child instance.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Can't create REST EX child instance.\n", __func__)); goto ON_EXIT; } @@ -906,7 +906,7 @@ AddAndSignalNewRedfishService ( (EFI_REST_EX_CONFIG_DATA)(UINT8 *)RestExHttpConfigData ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:REST EX configured..\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:REST EX configured..\n", __func__)); DeleteRestEx = TRUE; goto EXIT_FREE_ALL; } @@ -927,7 +927,7 @@ AddAndSignalNewRedfishService ( Status = gBS->SignalEvent (Instance->DiscoverToken->Event); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:No event to signal!\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:No event to signal!\n", __func__)); } } @@ -997,13 +997,13 @@ NetworkInterfaceGetSubnetInfo ( Instance ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a:Failed to get Subnet infomation.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Failed to get Subnet infomation.\n", __func__)); return Status; } else { - DEBUG ((DEBUG_INFO, "%a:MAC address: %s\n", __FUNCTION__, Instance->StrMacAddr)); + DEBUG ((DEBUG_INFO, "%a:MAC address: %s\n", __func__, Instance->StrMacAddr)); if (CheckIsIpVersion6 (Instance)) { if (Instance->SubnetAddrInfoIPv6Number == 0) { - DEBUG ((DEBUG_ERROR, "%a: There is no Subnet infomation for IPv6 network interface.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: There is no Subnet infomation for IPv6 network interface.\n", __func__)); return EFI_NOT_FOUND; } @@ -1184,13 +1184,13 @@ RedfishServiceAcquireService ( UINTN NetworkInterfacesIndex; EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *TargetNetworkInterfaceInternal; - DEBUG ((DEBUG_INFO, "%a:Entry.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a:Entry.\n", __func__)); // // Validate parameters. // if ((ImageHandle == NULL) || (Token == NULL) || ((Flags & ~EFI_REDFISH_DISCOVER_VALIDATION) == 0)) { - DEBUG ((DEBUG_ERROR, "%a:Invalid parameters.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Invalid parameters.\n", __func__)); return EFI_INVALID_PARAMETER; } @@ -1208,7 +1208,7 @@ RedfishServiceAcquireService ( TargetNetworkInterfaceInternal = (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *)GetFirstNode (&mEfiRedfishDiscoverNetworkInterface); NumNetworkInterfaces = NumberOfNetworkInterface (); if (NumNetworkInterfaces == 0) { - DEBUG ((DEBUG_ERROR, "%a:No network interface on platform.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:No network interface on platform.\n", __func__)); return EFI_UNSUPPORTED; } } @@ -1219,10 +1219,10 @@ RedfishServiceAcquireService ( NewInstance = FALSE; Instance = GetInstanceByOwner (ImageHandle, TargetNetworkInterfaceInternal, Flags & ~EFI_REDFISH_DISCOVER_VALIDATION); // Check if we can re-use previous instance. if (Instance == NULL) { - DEBUG ((DEBUG_INFO, "%a:Create new EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a:Create new EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE.\n", __func__)); Instance = (EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE *)AllocateZeroPool (sizeof (EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE)); if (Instance == NULL) { - DEBUG ((DEBUG_ERROR, "%a:Memory allocation fail.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Memory allocation fail.\n", __func__)); } InitializeListHead (&Instance->Entry); @@ -1238,14 +1238,14 @@ RedfishServiceAcquireService ( } if (TargetNetworkInterfaceInternal->StrMacAddr != NULL) { - DEBUG ((DEBUG_INFO, "%a:Acquire Redfish service on network interface MAC address:%s.\n", __FUNCTION__, TargetNetworkInterfaceInternal->StrMacAddr)); + DEBUG ((DEBUG_INFO, "%a:Acquire Redfish service on network interface MAC address:%s.\n", __func__, TargetNetworkInterfaceInternal->StrMacAddr)); } else { - DEBUG ((DEBUG_INFO, "%a:WARNING: No MAC address on this network interface.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a:WARNING: No MAC address on this network interface.\n", __func__)); } Instance->DiscoverToken = Token; // Always use the latest Token passed by caller. if ((Flags & EFI_REDFISH_DISCOVER_HOST_INTERFACE) != 0) { - DEBUG ((DEBUG_INFO, "%a:Redfish HOST interface discovery.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a:Redfish HOST interface discovery.\n", __func__)); Instance->HostIntfValidation = FALSE; if ((Flags & EFI_REDFISH_DISCOVER_VALIDATION) != 0) { Instance->HostIntfValidation = TRUE; @@ -1255,12 +1255,12 @@ RedfishServiceAcquireService ( } if ((Flags & EFI_REDFISH_DISCOVER_SSDP) != 0) { - DEBUG ((DEBUG_ERROR, "%a:Redfish service discovery through SSDP is not supported\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:Redfish service discovery through SSDP is not supported\n", __func__)); return EFI_UNSUPPORTED; } else { if (EFI_ERROR (Status1) && EFI_ERROR (Status2)) { FreePool ((VOID *)Instance); - DEBUG ((DEBUG_ERROR, "%a:Something wrong on Redfish service discovery Status1=%x, Status2=%x.\n", __FUNCTION__, Status1, Status2)); + DEBUG ((DEBUG_ERROR, "%a:Something wrong on Redfish service discovery Status1=%x, Status2=%x.\n", __func__, Status1, Status2)); } else { if (NewInstance) { InsertTailList (&mRedfishDiscoverList, &Instance->Entry); @@ -1326,7 +1326,7 @@ RedfishServiceReleaseService ( EFI_REDFISH_DISCOVERED_INTERNAL_LIST *DiscoveredRedfishInstance; if (IsListEmpty (&mRedfishInstanceList)) { - DEBUG ((DEBUG_ERROR, "%a:No any discovered Redfish service.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a:No any discovered Redfish service.\n", __func__)); return EFI_NOT_FOUND; } @@ -1535,7 +1535,7 @@ TestForRequiredProtocols ( ); if (EFI_ERROR (Status)) { if (Index == ListCount - 1) { - DEBUG ((DEBUG_ERROR, "%a: all required protocols are found on this controller handle: %p.\n", __FUNCTION__, ControllerHandle)); + DEBUG ((DEBUG_ERROR, "%a: all required protocols are found on this controller handle: %p.\n", __func__, ControllerHandle)); return EFI_SUCCESS; } } @@ -1706,7 +1706,7 @@ BuildupNetworkInterface ( if (!NewNetworkInterfaceInstalled) { NetworkInterface = GetTargetNetworkInterfaceInternalByController (ControllerHandle); if (NetworkInterface == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Can't find network interface by ControllerHandle\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Can't find network interface by ControllerHandle\n", __func__)); return Status; } } @@ -1720,10 +1720,10 @@ BuildupNetworkInterface ( (VOID *)&mRedfishDiscover ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI_REDFISH_DISCOVER_PROTOCOL\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI_REDFISH_DISCOVER_PROTOCOL\n", __func__)); } } else { - DEBUG ((DEBUG_INFO, "%a: Not REST EX, continue with next\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Not REST EX, continue with next\n", __func__)); Index++; if (Index == (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL))) { break; diff --git a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c index 872cf3ae06..45fc6e2182 100644 --- a/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c +++ b/RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c @@ -59,11 +59,11 @@ RedfishCreateSmbiosTable42 ( Status = RedfishPlatformHostInterfaceDeviceDescriptor (&DeviceType, &DeviceDescriptor); if (EFI_ERROR (Status)) { if (Status == EFI_NOT_FOUND) { - DEBUG ((DEBUG_ERROR, "%a: No Redfish host interface descriptor is provided on this platform.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: No Redfish host interface descriptor is provided on this platform.", __func__)); return EFI_NOT_FOUND; } - DEBUG ((DEBUG_ERROR, "%a: Fail to get device descriptor, %r.", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Fail to get device descriptor, %r.", __func__, Status)); return Status; } @@ -71,7 +71,7 @@ RedfishCreateSmbiosTable42 ( (DeviceType != REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2) ) { - DEBUG ((DEBUG_ERROR, "%a: Only support either protocol type 04h or 05h as Redfish host interface.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Only support either protocol type 04h or 05h as Redfish host interface.", __func__)); return EFI_UNSUPPORTED; } @@ -98,7 +98,7 @@ RedfishCreateSmbiosTable42 ( } if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Fail to get Redfish host interafce protocol type data.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to get Redfish host interafce protocol type data.", __func__)); if (ProtocolRecords != NULL) { FreePool (ProtocolRecords); } @@ -124,7 +124,7 @@ RedfishCreateSmbiosTable42 ( } else { NewProtocolRecords = ReallocatePool (CurrentProtocolsDataLength, NewProtocolsDataLength, (VOID *)ProtocolRecords); if (NewProtocolRecords == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Fail to allocate memory for Redfish host interface protocol data.", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Fail to allocate memory for Redfish host interface protocol data.", __func__)); FreePool (ProtocolRecords); FreePool (ProtocolRecord); return EFI_OUT_OF_RESOURCES; @@ -258,7 +258,7 @@ PlatformHostInterfaceInformationReady ( IN VOID *Context ) { - DEBUG ((DEBUG_INFO, "%a: Platform Redfish Host Interface informtion is ready\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Platform Redfish Host Interface informtion is ready\n", __func__)); RedfishCreateSmbiosTable42 (); @@ -290,7 +290,7 @@ RedfishHostInterfaceDxeEntryPoint ( EFI_STATUS Status; EFI_GUID *ReadyGuid; - DEBUG ((DEBUG_INFO, "%a: Entry\n.", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Entry\n.", __func__)); // // Check if the Redfish Host Interface depends on diff --git a/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c b/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c index 75b3f1fab8..41f2b29c83 100644 --- a/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c +++ b/RedfishPkg/RedfishRestExDxe/RedfishRestExImpl.c @@ -28,17 +28,17 @@ ResetHttpTslSession ( { EFI_STATUS Status; - DEBUG ((DEBUG_INFO, "%a: TCP connection is finished. Could be TSL session closure, reset HTTP instance for the new TLS session.\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: TCP connection is finished. Could be TSL session closure, reset HTTP instance for the new TLS session.\n", __func__)); Status = Instance->HttpIo.Http->Configure (Instance->HttpIo.Http, NULL); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Error to reset HTTP instance.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Error to reset HTTP instance.\n", __func__)); return Status; } Status = Instance->HttpIo.Http->Configure (Instance->HttpIo.Http, &((EFI_REST_EX_HTTP_CONFIG_DATA *)Instance->ConfigData)->HttpConfigData); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Error to re-initiate HTTP instance.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Error to re-initiate HTTP instance.\n", __func__)); } return Status; @@ -70,7 +70,7 @@ RedfishCheckHttpReceiveStatus ( ReturnStatus = EFI_SUCCESS; } else if (HttpIoReceiveStatus != EFI_CONNECTION_FIN) { if ((Instance->Flags & RESTEX_INSTANCE_FLAGS_TCP_ERROR_RETRY) == 0) { - DEBUG ((DEBUG_ERROR, "%a: TCP error, reset HTTP session.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: TCP error, reset HTTP session.\n", __func__)); Instance->Flags |= RESTEX_INSTANCE_FLAGS_TCP_ERROR_RETRY; gBS->Stall (500); Status = ResetHttpTslSession (Instance); @@ -78,20 +78,20 @@ RedfishCheckHttpReceiveStatus ( return EFI_NOT_READY; } - DEBUG ((DEBUG_ERROR, "%a: Reset HTTP instance fail.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Reset HTTP instance fail.\n", __func__)); } ReturnStatus = EFI_DEVICE_ERROR; } else { if ((Instance->Flags & RESTEX_INSTANCE_FLAGS_TLS_RETRY) != 0) { - DEBUG ((DEBUG_ERROR, "%a: REST_EX Send and receive fail even with a new TLS session.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: REST_EX Send and receive fail even with a new TLS session.\n", __func__)); ReturnStatus = EFI_DEVICE_ERROR; } Instance->Flags |= RESTEX_INSTANCE_FLAGS_TLS_RETRY; Status = ResetHttpTslSession (Instance); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Reset HTTP instance fail.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Reset HTTP instance fail.\n", __func__)); ReturnStatus = EFI_DEVICE_ERROR; } From 0b21da1ee7602c117139b4c89459ca82b0e046ac Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:51:30 -0600 Subject: [PATCH 0855/1529] ArmPlatformPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout ArmPlatformPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c index 5821dc1958..b8e7fbe38d 100644 --- a/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c +++ b/ArmPlatformPkg/Drivers/SP805WatchdogDxe/SP805Watchdog.c @@ -397,7 +397,7 @@ SP805Initialize ( DEBUG (( DEBUG_ERROR, "%a: failed to register watchdog interrupt - %r\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -406,7 +406,7 @@ SP805Initialize ( DEBUG (( DEBUG_WARN, "%a: no interrupt specified, running in RESET mode only\n", - __FUNCTION__ + __func__ )); } From baec629005cc4a19e3b5b5b7bcf41daa97336c75 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:51:51 -0600 Subject: [PATCH 0856/1529] UnitTestFrameworkPkg: Update to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout UnitTestFrameworkPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- .../UnitTestBootLibUsbClass.c | 12 ++++----- .../Library/UnitTestLib/Log.c | 2 +- .../Library/UnitTestLib/UnitTestLib.c | 4 +-- .../UnitTestPersistenceLibSimpleFileSystem.c | 26 +++++++++---------- .../UnitTestResultReportLib.c | 2 +- .../UnitTestResultReportLibConOut.c | 2 +- .../UnitTestResultReportLibDebugLib.c | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c index ebb42186a5..b9b2d23eb1 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -61,7 +61,7 @@ SetBootNextDevice ( DpEnd = AppendDevicePathNode (NULL, NULL); if (DpEnd == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __func__)); Status = EFI_OUT_OF_RESOURCES; goto CLEANUP; } @@ -72,7 +72,7 @@ SetBootNextDevice ( (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp ); if (Dp == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __func__)); Status = EFI_OUT_OF_RESOURCES; goto CLEANUP; } @@ -88,15 +88,15 @@ SetBootNextDevice ( OptionalDataSize ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __func__, Status)); goto CLEANUP; } NewOptionValid = TRUE; - DEBUG ((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); + DEBUG ((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __func__)); Status = EfiBootManagerLoadOptionToVariable (&NewOption); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __func__, Status)); goto CLEANUP; } @@ -111,7 +111,7 @@ SetBootNextDevice ( &(BootNextValue) ); - DEBUG ((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __func__, Status)); CLEANUP: if (Dp != NULL) { diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index 3998aafdf8..19eb8ee0db 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -118,7 +118,7 @@ UnitTestLogInit ( // Make sure that you're cooking with gas. // if (Test == NULL) { - DEBUG ((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a called with invalid Test parameter\n", __func__)); return; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 5b442ed122..322ea15b15 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -274,7 +274,7 @@ InitUnitTestFramework ( // // Don't actually report it as an error, but emit a warning. // - DEBUG ((DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __func__)); Status = EFI_SUCCESS; } } @@ -856,7 +856,7 @@ SaveFrameworkState ( // Status = SaveUnitTestCache (FrameworkHandle, Header, Header->SaveStateSize); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Could not save state! %r\n", __func__, Status)); Status = EFI_DEVICE_ERROR; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c index d7a62145da..b59991683f 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c @@ -61,7 +61,7 @@ GetCacheFileDevicePath ( (VOID **)&LoadedImage ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __func__, Status)); return NULL; } @@ -91,7 +91,7 @@ GetCacheFileDevicePath ( // Make sure we didn't get any weird data. // if (DirectorySlashOffset == 0) { - DEBUG ((DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __func__)); goto Exit; } @@ -112,7 +112,7 @@ GetCacheFileDevicePath ( // Let's check and make sure that's right. // if (AppPath[DirectorySlashOffset] != L'\\') { - DEBUG ((DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __func__)); goto Exit; } @@ -202,7 +202,7 @@ DoesCacheExist ( FreePool (FileDevicePath); } - DEBUG ((DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR (Status))); + DEBUG ((DEBUG_VERBOSE, "%a - Returning %d\n", __func__, !EFI_ERROR (Status))); return (!EFI_ERROR (Status)); } @@ -263,7 +263,7 @@ SaveUnitTestCache ( // Status = ShellDeleteFile (&FileHandle); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a failed to delete file %r\n", __func__, Status)); } } @@ -277,7 +277,7 @@ SaveUnitTestCache ( 0 ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __func__, Status)); goto Exit; } @@ -285,7 +285,7 @@ SaveUnitTestCache ( // Write the data to the file. // WriteCount = SaveStateSize; - DEBUG ((DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount)); + DEBUG ((DEBUG_INFO, "%a - Writing %d bytes to file...\n", __func__, WriteCount)); Status = ShellWriteFile ( FileHandle, &WriteCount, @@ -293,9 +293,9 @@ SaveUnitTestCache ( ); if (EFI_ERROR (Status) || (WriteCount != SaveStateSize)) { - DEBUG ((DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Writing to file failed! %r\n", __func__, Status)); } else { - DEBUG ((DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a - SUCCESS!\n", __func__)); } // @@ -368,7 +368,7 @@ LoadUnitTestCache ( 0 ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __func__, Status)); goto Exit; } else { IsFileOpened = TRUE; @@ -379,7 +379,7 @@ LoadUnitTestCache ( // Status = ShellGetFileSize (FileHandle, &LargeFileSize); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __func__, Status)); goto Exit; } @@ -390,7 +390,7 @@ LoadUnitTestCache ( *SaveStateSize = FileSize; Buffer = AllocatePool (FileSize); if (Buffer == NULL) { - DEBUG ((DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __func__, Status)); Status = EFI_OUT_OF_RESOURCES; goto Exit; } @@ -400,7 +400,7 @@ LoadUnitTestCache ( // Status = ShellReadFile (FileHandle, &FileSize, Buffer); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __func__, Status)); } Exit: diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c index d088b927a6..5e2973beb3 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -102,7 +102,7 @@ GetStringForFailureType ( // // Return last entry if no match found. // - DEBUG ((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + DEBUG ((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __func__, (UINT32)Failure)); return mFailureTypeStrings[Index].String; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c index aba00fe7b9..3bcbf557a1 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c @@ -25,7 +25,7 @@ ReportPrint ( VA_START (Marker, Format); Length = UnicodeVSPrintAsciiFormat (String, sizeof (String), Format, Marker); if (Length == 0) { - DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __func__)); } else { gST->ConOut->OutputString (gST->ConOut, String); } diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c index ac330861fd..eb78554f91 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c @@ -24,7 +24,7 @@ ReportPrint ( VA_START (Marker, Format); Length = AsciiVSPrint (String, sizeof (String), Format, Marker); if (Length == 0) { - DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __func__)); } else { DEBUG ((DEBUG_INFO, String)); } From 76fd10c1e126e990797692f0591e96777493b7ff Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:52:17 -0600 Subject: [PATCH 0857/1529] PrmPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout PrmPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- PrmPkg/Application/PrmInfo/PrmInfo.c | 6 +-- .../DxePrmContextBufferLib.c | 10 ++--- .../UnitTest/DxePrmContextBufferLibUnitTest.c | 2 +- .../DxePrmModuleDiscoveryLib.c | 14 +++--- .../Library/DxePrmPeCoffLib/DxePrmPeCoffLib.c | 40 ++++++++--------- PrmPkg/PrmConfigDxe/PrmConfigDxe.c | 44 +++++++++---------- PrmPkg/PrmLoaderDxe/PrmLoaderDxe.c | 22 +++++----- PrmPkg/PrmSsdtInstallDxe/PrmSsdtInstallDxe.c | 4 +- 8 files changed, 71 insertions(+), 71 deletions(-) diff --git a/PrmPkg/Application/PrmInfo/PrmInfo.c b/PrmPkg/Application/PrmInfo/PrmInfo.c index 0cde2fad3b..d7ce0d03be 100644 --- a/PrmPkg/Application/PrmInfo/PrmInfo.c +++ b/PrmPkg/Application/PrmInfo/PrmInfo.c @@ -493,7 +493,7 @@ ExecutePrmHandlerByGuid ( DEBUG_ERROR, "%a - %a: An error occurred creating a context buffer for handler %g\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, HandlerContext->Guid )); } @@ -628,7 +628,7 @@ ParseParameterList ( DEBUG_ERROR, "%a - %a: An error occurred during PRM module discovery (%r)\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); ReturnStatus = Status; @@ -719,7 +719,7 @@ UefiMain ( DEBUG_ERROR, "%a - %a: An error occurred parsing user-provided arguments (%r)\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, Status )); } diff --git a/PrmPkg/Library/DxePrmContextBufferLib/DxePrmContextBufferLib.c b/PrmPkg/Library/DxePrmContextBufferLib/DxePrmContextBufferLib.c index 3036aa503e..a6ad141556 100644 --- a/PrmPkg/Library/DxePrmContextBufferLib/DxePrmContextBufferLib.c +++ b/PrmPkg/Library/DxePrmContextBufferLib/DxePrmContextBufferLib.c @@ -40,7 +40,7 @@ FindContextBufferInModuleBuffers ( { UINTN Index; - DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __func__)); if ((HandlerGuid == NULL) || (ModuleContextBuffers == NULL) || (ContextBuffer == NULL)) { return EFI_INVALID_PARAMETER; @@ -89,7 +89,7 @@ GetModuleContextBuffers ( PRM_CONFIG_PROTOCOL *PrmConfigProtocol; CONST PRM_CONTEXT_BUFFER *PrmContextBuffer; - DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __func__)); if ((Guid == NULL) || (PrmModuleContextBuffers == NULL)) { return EFI_INVALID_PARAMETER; @@ -122,7 +122,7 @@ GetModuleContextBuffers ( DEBUG_INFO, " %a %a: Found a PRM configuration protocol for PRM module %g.\n", _DBGMSGID_, - __FUNCTION__, + __func__, Guid )); @@ -143,7 +143,7 @@ GetModuleContextBuffers ( DEBUG_INFO, " %a %a: Could not locate a PRM configuration protocol for PRM handler %g.\n", _DBGMSGID_, - __FUNCTION__, + __func__, Guid )); @@ -176,7 +176,7 @@ GetContextBuffer ( EFI_STATUS Status; CONST PRM_MODULE_CONTEXT_BUFFERS *ContextBuffers; - DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __func__)); if ((PrmHandlerGuid == NULL) || (PrmContextBuffer == NULL)) { return EFI_INVALID_PARAMETER; diff --git a/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTest.c b/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTest.c index fdc32993b8..212c4cf6aa 100644 --- a/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTest.c +++ b/PrmPkg/Library/DxePrmContextBufferLib/UnitTest/DxePrmContextBufferLibUnitTest.c @@ -384,7 +384,7 @@ VerifyGetModuleContextBuffers ( UT_ASSERT_TRUE (CompareGuid (TestContext->ExpectedModuleGuid, &ContextBuffers->ModuleGuid)); UT_LOG_INFO ( "%a: Searching by %a GUID ({%g}) returned ContextBuffers at 0x%x\n", - __FUNCTION__, + __func__, ((TestContext->GuidSearchType == ByModuleGuid) ? "module" : "handler"), TestContext->Guid, (UINTN)ContextBuffers diff --git a/PrmPkg/Library/DxePrmModuleDiscoveryLib/DxePrmModuleDiscoveryLib.c b/PrmPkg/Library/DxePrmModuleDiscoveryLib/DxePrmModuleDiscoveryLib.c index e6bea47bc5..efd9f231ba 100644 --- a/PrmPkg/Library/DxePrmModuleDiscoveryLib/DxePrmModuleDiscoveryLib.c +++ b/PrmPkg/Library/DxePrmModuleDiscoveryLib/DxePrmModuleDiscoveryLib.c @@ -48,7 +48,7 @@ GetNextPrmModuleEntry ( PRM_MODULE_IMAGE_CONTEXT_LIST_ENTRY *CurrentListEntry; PRM_MODULE_IMAGE_CONTEXT_LIST_ENTRY *ForwardListEntry; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); if (ModuleImageContext == NULL) { return EFI_INVALID_PARAMETER; @@ -94,7 +94,7 @@ CreateNewPrmModuleImageContextListEntry ( { PRM_MODULE_IMAGE_CONTEXT_LIST_ENTRY *PrmModuleImageContextListEntry; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); PrmModuleImageContextListEntry = AllocateZeroPool (sizeof (*PrmModuleImageContextListEntry)); if (PrmModuleImageContextListEntry == NULL) { @@ -105,7 +105,7 @@ CreateNewPrmModuleImageContextListEntry ( DEBUG_INFO, " %a %a: Allocated PrmModuleImageContextListEntry at 0x%x of size 0x%x bytes.\n", _DBGMSGID_, - __FUNCTION__, + __func__, (UINTN)PrmModuleImageContextListEntry, sizeof (*PrmModuleImageContextListEntry) )); @@ -186,7 +186,7 @@ DiscoverPrmModules ( EFI_MMRAM_DESCRIPTOR *MmramRanges; UINTN MmramRangeCount; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); PrmHandlerCount = 0; PrmModuleCount = 0; @@ -203,7 +203,7 @@ DiscoverPrmModules ( &HandleBuffer ); if (EFI_ERROR (Status) && (HandleCount == 0)) { - DEBUG ((DEBUG_ERROR, "%a %a: No LoadedImageProtocol instances found!\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a %a: No LoadedImageProtocol instances found!\n", _DBGMSGID_, __func__)); return EFI_NOT_FOUND; } @@ -255,7 +255,7 @@ DiscoverPrmModules ( DEBUG_WARN, "%a %a: ImageHandle 0x%016lx is not a valid PE/COFF image. It cannot be considered a PRM module.\n", _DBGMSGID_, - __FUNCTION__, + __func__, (EFI_PHYSICAL_ADDRESS)(UINTN)LoadedImageProtocol->ImageBase )); continue; @@ -304,7 +304,7 @@ DiscoverPrmModules ( InsertTailList (&mPrmModuleList, &PrmModuleImageContextListEntry->Link); PrmHandlerCount += TempPrmModuleImageContext.ExportDescriptor->Header.NumberPrmHandlers; PrmModuleCount++; - DEBUG ((DEBUG_INFO, "%a %a: New PRM Module inserted into list to be processed.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a: New PRM Module inserted into list to be processed.\n", _DBGMSGID_, __func__)); } if (HandlerCount != NULL) { diff --git a/PrmPkg/Library/DxePrmPeCoffLib/DxePrmPeCoffLib.c b/PrmPkg/Library/DxePrmPeCoffLib/DxePrmPeCoffLib.c index d535c2c105..15792777b7 100644 --- a/PrmPkg/Library/DxePrmPeCoffLib/DxePrmPeCoffLib.c +++ b/PrmPkg/Library/DxePrmPeCoffLib/DxePrmPeCoffLib.c @@ -51,7 +51,7 @@ GetPrmModuleExportDescriptorTable ( UINT32 *ExportAddressTable; PRM_MODULE_EXPORT_DESCRIPTOR_STRUCT *TempExportDescriptor; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); if ((ImageExportDirectory == NULL) || (PeCoffLoaderImageContext == NULL) || @@ -67,7 +67,7 @@ GetPrmModuleExportDescriptorTable ( DEBUG_INFO, " %a %a: %d exported names found in this image.\n", _DBGMSGID_, - __FUNCTION__, + __func__, ImageExportDirectory->NumberOfNames )); @@ -85,7 +85,7 @@ GetPrmModuleExportDescriptorTable ( DEBUG_INFO, " %a %a: Export Name[0x%x] - %a.\n", _DBGMSGID_, - __FUNCTION__, + __func__, Index, CurrentExportName )); @@ -101,29 +101,29 @@ GetPrmModuleExportDescriptorTable ( DEBUG_INFO, " %a %a: PRM Module Export Descriptor found. Ordinal = %d.\n", _DBGMSGID_, - __FUNCTION__, + __func__, PrmModuleExportDescriptorOrdinal )); if (PrmModuleExportDescriptorOrdinal >= ImageExportDirectory->NumberOfFunctions) { - DEBUG ((DEBUG_ERROR, "%a %a: The PRM Module Export Descriptor ordinal value is invalid.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a %a: The PRM Module Export Descriptor ordinal value is invalid.\n", _DBGMSGID_, __func__)); return EFI_NOT_FOUND; } TempExportDescriptor = (PRM_MODULE_EXPORT_DESCRIPTOR_STRUCT *)((UINTN)CurrentImageAddress + ExportAddressTable[PrmModuleExportDescriptorOrdinal]); if (TempExportDescriptor->Header.Signature == PRM_MODULE_EXPORT_DESCRIPTOR_SIGNATURE) { *ExportDescriptor = TempExportDescriptor; - DEBUG ((DEBUG_INFO, " %a %a: PRM Module Export Descriptor found at 0x%x.\n", _DBGMSGID_, __FUNCTION__, (UINTN)ExportDescriptor)); + DEBUG ((DEBUG_INFO, " %a %a: PRM Module Export Descriptor found at 0x%x.\n", _DBGMSGID_, __func__, (UINTN)ExportDescriptor)); } else { DEBUG (( DEBUG_INFO, " %a %a: PRM Module Export Descriptor found at 0x%x but signature check failed.\n", _DBGMSGID_, - __FUNCTION__, + __func__, (UINTN)TempExportDescriptor )); } - DEBUG ((DEBUG_INFO, " %a %a: Exiting export iteration since export descriptor found.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a: Exiting export iteration since export descriptor found.\n", _DBGMSGID_, __func__)); return EFI_SUCCESS; } } @@ -194,7 +194,7 @@ GetExportDirectoryInPeCoffImage ( DEBUG_WARN, "%a %a: The machine type for this image is not valid for a PRM module.\n", _DBGMSGID_, - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } @@ -208,7 +208,7 @@ GetExportDirectoryInPeCoffImage ( // Check the PE/COFF Header Signature. Determine if the image is valid and/or a TE image. // if (OptionalHeaderPtrUnion.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { - DEBUG ((DEBUG_ERROR, "%a %a: The PE signature is not valid for the current image.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a %a: The PE signature is not valid for the current image.\n", _DBGMSGID_, __func__)); return EFI_UNSUPPORTED; } @@ -237,18 +237,18 @@ GetExportDirectoryInPeCoffImage ( // // The directory address overflows // - DEBUG ((DEBUG_ERROR, "%a %a: The export directory entry in this image results in overflow.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a %a: The export directory entry in this image results in overflow.\n", _DBGMSGID_, __func__)); return EFI_UNSUPPORTED; } else { - DEBUG ((DEBUG_INFO, "%a %a: Export Directory Entry found in the image at 0x%x.\n", _DBGMSGID_, __FUNCTION__, (UINTN)OptionalHeaderPtrUnion.Pe32)); - DEBUG ((DEBUG_INFO, " %a %a: Directory Entry Virtual Address = 0x%x.\n", _DBGMSGID_, __FUNCTION__, DirectoryEntry->VirtualAddress)); + DEBUG ((DEBUG_INFO, "%a %a: Export Directory Entry found in the image at 0x%x.\n", _DBGMSGID_, __func__, (UINTN)OptionalHeaderPtrUnion.Pe32)); + DEBUG ((DEBUG_INFO, " %a %a: Directory Entry Virtual Address = 0x%x.\n", _DBGMSGID_, __func__, DirectoryEntry->VirtualAddress)); ExportDirectory = (EFI_IMAGE_EXPORT_DIRECTORY *)((UINTN)Image + DirectoryEntry->VirtualAddress); DEBUG (( DEBUG_INFO, " %a %a: Export Directory Table found successfully at 0x%x. Name address = 0x%x. Name = %a.\n", _DBGMSGID_, - __FUNCTION__, + __func__, (UINTN)ExportDirectory, ((UINTN)Image + ExportDirectory->Name), (CHAR8 *)((UINTN)Image + ExportDirectory->Name) @@ -287,7 +287,7 @@ GetImageVersionInPeCoffImage ( EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION OptionalHeaderPtrUnion; UINT16 Magic; - DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a - Entry.\n", _DBGMSGID_, __func__)); if ((Image == NULL) || (PeCoffLoaderImageContext == NULL) || (ImageMajorVersion == NULL) || (ImageMinorVersion == NULL)) { return EFI_INVALID_PARAMETER; @@ -320,7 +320,7 @@ GetImageVersionInPeCoffImage ( DEBUG_WARN, "%a %a: The machine type for this image is not valid for a PRM module.\n", _DBGMSGID_, - __FUNCTION__ + __func__ )); return EFI_UNSUPPORTED; } @@ -333,7 +333,7 @@ GetImageVersionInPeCoffImage ( // Check the PE/COFF Header Signature. Determine if the image is valid and/or a TE image. // if (OptionalHeaderPtrUnion.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { - DEBUG ((DEBUG_ERROR, "%a %a: The PE signature is not valid for the current image.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a %a: The PE signature is not valid for the current image.\n", _DBGMSGID_, __func__)); return EFI_UNSUPPORTED; } @@ -351,8 +351,8 @@ GetImageVersionInPeCoffImage ( *ImageMinorVersion = OptionalHeaderPtrUnion.Pe32Plus->OptionalHeader.MinorImageVersion; } - DEBUG ((DEBUG_INFO, " %a %a - Image Major Version: 0x%02x.\n", _DBGMSGID_, __FUNCTION__, *ImageMajorVersion)); - DEBUG ((DEBUG_INFO, " %a %a - Image Minor Version: 0x%02x.\n", _DBGMSGID_, __FUNCTION__, *ImageMinorVersion)); + DEBUG ((DEBUG_INFO, " %a %a - Image Major Version: 0x%02x.\n", _DBGMSGID_, __func__, *ImageMajorVersion)); + DEBUG ((DEBUG_INFO, " %a %a - Image Minor Version: 0x%02x.\n", _DBGMSGID_, __func__, *ImageMinorVersion)); return EFI_SUCCESS; } @@ -404,7 +404,7 @@ GetExportEntryAddress ( ASSERT (CurrentExportOrdinal < ImageExportDirectory->NumberOfFunctions); if (CurrentExportOrdinal >= ImageExportDirectory->NumberOfFunctions) { - DEBUG ((DEBUG_ERROR, " %a %a: The export ordinal value is invalid.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, " %a %a: The export ordinal value is invalid.\n", _DBGMSGID_, __func__)); break; } diff --git a/PrmPkg/PrmConfigDxe/PrmConfigDxe.c b/PrmPkg/PrmConfigDxe/PrmConfigDxe.c index c175ee2183..550ee64b4c 100644 --- a/PrmPkg/PrmConfigDxe/PrmConfigDxe.c +++ b/PrmPkg/PrmConfigDxe/PrmConfigDxe.c @@ -71,7 +71,7 @@ SetRuntimeMemoryRangeAttributes ( UINTN Index; EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); if ((RuntimeMmioRanges == NULL) || (RuntimeMmioRanges->Count == 0)) { return; @@ -82,14 +82,14 @@ SetRuntimeMemoryRangeAttributes ( DEBUG_INFO, " %a %a: Runtime MMIO Range [%d].\n", _DBGMSGID_, - __FUNCTION__, + __func__, Index )); DEBUG (( DEBUG_INFO, " %a %a: Physical address = 0x%016x. Length = 0x%x.\n", _DBGMSGID_, - __FUNCTION__, + __func__, RuntimeMmioRanges->Range[Index].PhysicalBaseAddress, RuntimeMmioRanges->Range[Index].Length )); @@ -141,7 +141,7 @@ SetRuntimeMemoryRangeAttributes ( DEBUG_ERROR, " %a %a: Error [%r] finding descriptor for runtime memory range 0x%016x.\n", _DBGMSGID_, - __FUNCTION__, + __func__, Status, RuntimeMmioRanges->Range[Index].PhysicalBaseAddress )); @@ -163,12 +163,12 @@ SetRuntimeMemoryRangeAttributes ( DEBUG_ERROR, " %a %a: Error [%r] setting descriptor for runtime memory range 0x%016x.\n", _DBGMSGID_, - __FUNCTION__, + __func__, Status, RuntimeMmioRanges->Range[Index].PhysicalBaseAddress )); } else { - DEBUG ((DEBUG_INFO, " %a %a: Successfully set runtime attribute for the MMIO range.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a: Successfully set runtime attribute for the MMIO range.\n", _DBGMSGID_, __func__)); } } } @@ -189,7 +189,7 @@ StoreVirtualMemoryAddressChangePointers ( EFI_HANDLE *HandleBuffer; PRM_CONFIG_PROTOCOL *PrmConfigProtocol; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); RangeIndex = 0; @@ -199,7 +199,7 @@ StoreVirtualMemoryAddressChangePointers ( DEBUG_ERROR, " %a %a: Memory allocation for runtime MMIO pointer array failed.\n", _DBGMSGID_, - __FUNCTION__ + __func__ )); ASSERT (FALSE); return; @@ -232,7 +232,7 @@ StoreVirtualMemoryAddressChangePointers ( DEBUG_ERROR, " %a %a: Index out of bounds - Actual count (%d) of runtime MMIO ranges exceeds maximum count (%d).\n", _DBGMSGID_, - __FUNCTION__, + __func__, RangeIndex + 1, mMaxRuntimeMmioRangeCount )); @@ -248,7 +248,7 @@ StoreVirtualMemoryAddressChangePointers ( DEBUG_INFO, " %a %a: %d MMIO ranges buffers saved for future virtual memory conversion.\n", _DBGMSGID_, - __FUNCTION__, + __func__, RangeIndex )); } @@ -277,12 +277,12 @@ ValidatePrmDataBuffer ( } if (PrmDataBuffer->Header.Signature != PRM_DATA_BUFFER_HEADER_SIGNATURE) { - DEBUG ((DEBUG_ERROR, " %a %a: The PRM data buffer signature is invalid. PRM module.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, " %a %a: The PRM data buffer signature is invalid. PRM module.\n", _DBGMSGID_, __func__)); return EFI_NOT_FOUND; } if (PrmDataBuffer->Header.Length < sizeof (PRM_DATA_BUFFER_HEADER)) { - DEBUG ((DEBUG_ERROR, " %a %a: The PRM data buffer length is invalid.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, " %a %a: The PRM data buffer length is invalid.\n", _DBGMSGID_, __func__)); return EFI_BUFFER_TOO_SMALL; } @@ -311,12 +311,12 @@ ValidatePrmContextBuffer ( } if (PrmContextBuffer->Signature != PRM_CONTEXT_BUFFER_SIGNATURE) { - DEBUG ((DEBUG_ERROR, " %a %a: The PRM context buffer signature is invalid.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, " %a %a: The PRM context buffer signature is invalid.\n", _DBGMSGID_, __func__)); return EFI_NOT_FOUND; } if (IsZeroGuid (&PrmContextBuffer->HandlerGuid)) { - DEBUG ((DEBUG_ERROR, " %a %a: The PRM context buffer GUID is zero.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_ERROR, " %a %a: The PRM context buffer GUID is zero.\n", _DBGMSGID_, __func__)); return EFI_NOT_FOUND; } @@ -325,7 +325,7 @@ ValidatePrmContextBuffer ( DEBUG_ERROR, " %a %a: Error in static buffer for PRM handler %g.\n", _DBGMSGID_, - __FUNCTION__, + __func__, &PrmContextBuffer->HandlerGuid )); return EFI_NOT_FOUND; @@ -387,7 +387,7 @@ PrmConfigEndOfDxeNotification ( PRM_CONTEXT_BUFFER *CurrentContextBuffer; PRM_CONFIG_PROTOCOL *PrmConfigProtocol; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); HandleBuffer = NULL; Status = gBS->LocateHandleBuffer ( @@ -413,11 +413,11 @@ PrmConfigEndOfDxeNotification ( DEBUG_INFO, " %a %a: Found PRM configuration protocol for PRM module %g.\n", _DBGMSGID_, - __FUNCTION__, + __func__, &PrmConfigProtocol->ModuleContextBuffers.ModuleGuid )); - DEBUG ((DEBUG_INFO, " %a %a: Validating module context buffers...\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a: Validating module context buffers...\n", _DBGMSGID_, __func__)); for (BufferIndex = 0; BufferIndex < PrmConfigProtocol->ModuleContextBuffers.BufferCount; BufferIndex++) { CurrentContextBuffer = &(PrmConfigProtocol->ModuleContextBuffers.Buffer[BufferIndex]); @@ -427,20 +427,20 @@ PrmConfigEndOfDxeNotification ( DEBUG_ERROR, " %a %a: Context buffer validation failed for PRM handler %g.\n", _DBGMSGID_, - __FUNCTION__, + __func__, CurrentContextBuffer->HandlerGuid )); } } - DEBUG ((DEBUG_INFO, " %a %a: Module context buffer validation complete.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, " %a %a: Module context buffer validation complete.\n", _DBGMSGID_, __func__)); if (PrmConfigProtocol->ModuleContextBuffers.RuntimeMmioRanges != NULL) { DEBUG (( DEBUG_INFO, " %a %a: Found %d PRM runtime MMIO ranges.\n", _DBGMSGID_, - __FUNCTION__, + __func__, PrmConfigProtocol->ModuleContextBuffers.RuntimeMmioRanges->Count )); SetRuntimeMemoryRangeAttributes (PrmConfigProtocol->ModuleContextBuffers.RuntimeMmioRanges); @@ -478,7 +478,7 @@ PrmConfigEntryPoint ( EFI_STATUS Status; EFI_EVENT Event; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); // // Register a notification function to change memory attributes at end of DXE diff --git a/PrmPkg/PrmLoaderDxe/PrmLoaderDxe.c b/PrmPkg/PrmLoaderDxe/PrmLoaderDxe.c index 5a223d783d..477c24c8b8 100644 --- a/PrmPkg/PrmLoaderDxe/PrmLoaderDxe.c +++ b/PrmPkg/PrmLoaderDxe/PrmLoaderDxe.c @@ -73,7 +73,7 @@ ProcessPrmModules ( UINT64 HandlerPhysicalAddress; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); if (PrmAcpiDescriptionTable == NULL) { return EFI_INVALID_PARAMETER; @@ -89,19 +89,19 @@ ProcessPrmModules ( DEBUG_ERROR, " %a %a: The Platform GUID in the DSC file must be set to a unique non-zero value.\n", _DBGMSGID_, - __FUNCTION__ + __func__ )); ASSERT (!CompareGuid (&gEdkiiDscPlatformGuid, &gZeroGuid)); } - DEBUG ((DEBUG_INFO, " %a %a: %d total PRM modules to process.\n", _DBGMSGID_, __FUNCTION__, mPrmModuleCount)); - DEBUG ((DEBUG_INFO, " %a %a: %d total PRM handlers to process.\n", _DBGMSGID_, __FUNCTION__, mPrmHandlerCount)); + DEBUG ((DEBUG_INFO, " %a %a: %d total PRM modules to process.\n", _DBGMSGID_, __func__, mPrmModuleCount)); + DEBUG ((DEBUG_INFO, " %a %a: %d total PRM handlers to process.\n", _DBGMSGID_, __func__, mPrmHandlerCount)); PrmAcpiDescriptionTableBufferSize = (UINT32)(OFFSET_OF (PRM_ACPI_DESCRIPTION_TABLE, PrmModuleInfoStructure) + (OFFSET_OF (PRM_MODULE_INFORMATION_STRUCT, HandlerInfoStructure) * mPrmModuleCount) + (sizeof (PRM_HANDLER_INFORMATION_STRUCT) * mPrmHandlerCount) ); - DEBUG ((DEBUG_INFO, " %a %a: Total PRM ACPI table size: 0x%x.\n", _DBGMSGID_, __FUNCTION__, PrmAcpiDescriptionTableBufferSize)); + DEBUG ((DEBUG_INFO, " %a %a: Total PRM ACPI table size: 0x%x.\n", _DBGMSGID_, __func__, PrmAcpiDescriptionTableBufferSize)); PrmAcpiTable = AllocateZeroPool ((UINTN)PrmAcpiDescriptionTableBufferSize); if (PrmAcpiTable == NULL) { @@ -139,7 +139,7 @@ ProcessPrmModules ( DEBUG_INFO, " %a %a: PRM Module - %a with %d handlers.\n", _DBGMSGID_, - __FUNCTION__, + __func__, (CHAR8 *)((UINTN)CurrentImageAddress + CurrentImageExportDirectory->Name), CurrentExportDescriptorStruct->Header.NumberPrmHandlers )); @@ -212,7 +212,7 @@ ProcessPrmModules ( DEBUG_INFO, " %a %a: Found %a handler physical address at 0x%016x.\n", _DBGMSGID_, - __FUNCTION__, + __func__, CurrentExportDescriptorHandlerName, CurrentHandlerInfoStruct->PhysicalAddress )); @@ -279,7 +279,7 @@ PublishPrmAcpiTable ( &TableKey ); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a %a: The PRMT ACPI table was installed successfully.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a: The PRMT ACPI table was installed successfully.\n", _DBGMSGID_, __func__)); } } @@ -316,7 +316,7 @@ PrmLoaderEndOfDxeNotification ( EFI_STATUS Status; PRM_ACPI_DESCRIPTION_TABLE *PrmAcpiDescriptionTable; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); Status = DiscoverPrmModules (&mPrmModuleCount, &mPrmHandlerCount); ASSERT_EFI_ERROR (Status); @@ -354,7 +354,7 @@ PrmLoaderEntryPoint ( EFI_STATUS Status; EFI_EVENT EndOfDxeEvent; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); // // Discover and process installed PRM modules at the End of DXE @@ -369,7 +369,7 @@ PrmLoaderEntryPoint ( &EndOfDxeEvent ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a %a: EndOfDxe callback registration failed! %r.\n", _DBGMSGID_, __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "%a %a: EndOfDxe callback registration failed! %r.\n", _DBGMSGID_, __func__, Status)); ASSERT_EFI_ERROR (Status); } diff --git a/PrmPkg/PrmSsdtInstallDxe/PrmSsdtInstallDxe.c b/PrmPkg/PrmSsdtInstallDxe/PrmSsdtInstallDxe.c index e8bf4cfb8f..80ad7d3758 100644 --- a/PrmPkg/PrmSsdtInstallDxe/PrmSsdtInstallDxe.c +++ b/PrmPkg/PrmSsdtInstallDxe/PrmSsdtInstallDxe.c @@ -42,7 +42,7 @@ InstallPrmSsdt ( EFI_ACPI_TABLE_PROTOCOL *AcpiTableProtocol; EFI_ACPI_DESCRIPTION_HEADER *Ssdt; - DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a - Entry.\n", _DBGMSGID_, __func__)); if (OemId == NULL) { return EFI_INVALID_PARAMETER; @@ -61,7 +61,7 @@ InstallPrmSsdt ( &SsdtSize ); ASSERT_EFI_ERROR (Status); - DEBUG ((DEBUG_INFO, "%a %a: SSDT loaded...\n", _DBGMSGID_, __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a %a: SSDT loaded...\n", _DBGMSGID_, __func__)); // // Update OEM ID in the SSDT From 500ef0a3acd329e47c4b1ca9f8b826d3a6e28af9 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:52:42 -0600 Subject: [PATCH 0858/1529] StandaloneMmPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout StandaloneMmPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- .../Arm/SetPermissions.c | 22 +++++++++---------- .../X86StandaloneMmMemLibInternal.c | 2 +- .../StandaloneMmPeCoffExtraActionLib.c | 16 +++++++------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/Arm/SetPermissions.c b/StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/Arm/SetPermissions.c index 8f2833a135..5c6bd0e1d7 100644 --- a/StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/Arm/SetPermissions.c +++ b/StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/Arm/SetPermissions.c @@ -80,7 +80,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_ERROR, "%a: ImageContext->ImageRead () failed (Status = %r)\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -89,7 +89,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Section %d of image at 0x%lx has 0x%x permissions\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress, SectionHeader.Characteristics @@ -97,7 +97,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Section %d of image at 0x%lx has %a name\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress, SectionHeader.Name @@ -105,7 +105,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Section %d of image at 0x%lx has 0x%x address\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress, ImageContext->ImageAddress + SectionHeader.VirtualAddress @@ -113,7 +113,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Section %d of image at 0x%lx has 0x%x data\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress, SectionHeader.PointerToRawData @@ -133,7 +133,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Mapping section %d of image at 0x%lx with RW-XN permissions\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress )); @@ -141,7 +141,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Mapping section %d of image at 0x%lx with RO-XN permissions\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress )); @@ -150,7 +150,7 @@ UpdateMmFoundationPeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Ignoring section %d of image at 0x%lx with 0x%x permissions\n", - __FUNCTION__, + __func__, Index, ImageContext->ImageAddress, SectionHeader.Characteristics @@ -251,7 +251,7 @@ GetPeCoffSectionInformation ( DEBUG (( DEBUG_ERROR, "%a: PeCoffLoaderGetImageInfo () failed (Status == %r)\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -266,7 +266,7 @@ GetPeCoffSectionInformation ( DEBUG (( DEBUG_WARN, "%a: non-TE Image at 0x%lx has SectionAlignment < 4 KB (%lu)\n", - __FUNCTION__, + __func__, ImageContext->ImageAddress, ImageContext->SectionAlignment )); @@ -296,7 +296,7 @@ GetPeCoffSectionInformation ( DEBUG (( DEBUG_ERROR, "%a: TmpContext->ImageRead () failed (Status = %r)\n", - __FUNCTION__, + __func__, Status )); return Status; diff --git a/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c b/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c index c309d1bc6a..0b4b1174de 100644 --- a/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c +++ b/StandaloneMmPkg/Library/StandaloneMmMemLib/X86StandaloneMmMemLibInternal.c @@ -95,7 +95,7 @@ MmMemLibInternalPopulateMmramRanges ( EFI_MMRAM_DESCRIPTOR *MmramDescriptors; HobStart = GetHobList (); - DEBUG ((DEBUG_INFO, "%a - 0x%x\n", __FUNCTION__, HobStart)); + DEBUG ((DEBUG_INFO, "%a - 0x%x\n", __func__, HobStart)); // // Extract MM Core Private context from the Hob. If absent search for diff --git a/StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/AArch64/StandaloneMmPeCoffExtraActionLib.c b/StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/AArch64/StandaloneMmPeCoffExtraActionLib.c index 426fd8dd74..492252843e 100644 --- a/StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/AArch64/StandaloneMmPeCoffExtraActionLib.c +++ b/StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/AArch64/StandaloneMmPeCoffExtraActionLib.c @@ -55,7 +55,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_ERROR, "%a: PeCoffLoaderGetImageInfo () failed (Status = %r)\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -68,7 +68,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: ignoring XIP TE image at 0x%lx\n", - __FUNCTION__, + __func__, ImageContext->ImageAddress )); return RETURN_SUCCESS; @@ -84,7 +84,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_WARN, "%a: non-TE Image at 0x%lx has SectionAlignment < 4 KB (%lu)\n", - __FUNCTION__, + __func__, ImageContext->ImageAddress, TmpContext.SectionAlignment )); @@ -114,7 +114,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_ERROR, "%a: TmpContext.ImageRead () failed (Status = %r)\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -156,7 +156,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_ERROR, "%a: TmpContext.ImageRead () failed (Status = %r)\n", - __FUNCTION__, + __func__, Status )); return Status; @@ -169,7 +169,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Mapping section %d of image at 0x%lx with RO-XN permissions and size 0x%x\n", - __FUNCTION__, + __func__, Index, Base, SectionHeader.Misc.VirtualSize @@ -179,7 +179,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_WARN, "%a: Mapping section %d of image at 0x%lx with RW-XN permissions and size 0x%x\n", - __FUNCTION__, + __func__, Index, Base, SectionHeader.Misc.VirtualSize @@ -189,7 +189,7 @@ UpdatePeCoffPermissions ( DEBUG (( DEBUG_INFO, "%a: Mapping section %d of image at 0x%lx with RO-X permissions and size 0x%x\n", - __FUNCTION__, + __func__, Index, Base, SectionHeader.Misc.VirtualSize From 8f69ab67ae712eaa9280e7c78d6cc7c1c625fc6a Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:53:10 -0600 Subject: [PATCH 0859/1529] CryptoPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout CryptoPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- CryptoPkg/Library/TlsLib/TlsConfig.c | 8 ++++---- CryptoPkg/Library/TlsLib/TlsProcess.c | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Library/TlsLib/TlsConfig.c b/CryptoPkg/Library/TlsLib/TlsConfig.c index 60559de4a7..fdda73690a 100644 --- a/CryptoPkg/Library/TlsLib/TlsConfig.c +++ b/CryptoPkg/Library/TlsLib/TlsConfig.c @@ -331,7 +331,7 @@ TlsSetCipherList ( DEBUG_VERBOSE, "%a:%a: skipping CipherId=0x%04x\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, CipherId[Index] )); // @@ -380,7 +380,7 @@ TlsSetCipherList ( DEBUG_ERROR, "%a:%a: no CipherId could be mapped\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); Status = EFI_UNSUPPORTED; goto FreeMappedCipher; @@ -441,7 +441,7 @@ TlsSetCipherList ( DEBUG_VERBOSE, "%a:%a: CipherString={\n", gEfiCallerBaseName, - __FUNCTION__ + __func__ )); for (CipherStringPosition = CipherString; CipherStringPosition < CipherString + FullLength; @@ -610,7 +610,7 @@ TlsSetVerifyHost ( "%a:%a: parsed \"%a\" as an IPv%c address " "literal\n", gEfiCallerBaseName, - __FUNCTION__, + __func__, HostName, (UINTN)((BinaryAddressSize == NS_IN6ADDRSZ) ? '6' : '4') )); diff --git a/CryptoPkg/Library/TlsLib/TlsProcess.c b/CryptoPkg/Library/TlsLib/TlsProcess.c index a803d86c4f..db296053fd 100644 --- a/CryptoPkg/Library/TlsLib/TlsProcess.c +++ b/CryptoPkg/Library/TlsLib/TlsProcess.c @@ -127,7 +127,7 @@ TlsDoHandshake ( DEBUG (( DEBUG_ERROR, "%a SSL_HANDSHAKE_ERROR State=0x%x SSL_ERROR_%a\n", - __FUNCTION__, + __func__, SSL_get_state (TlsConn->Ssl), Ret == SSL_ERROR_SSL ? "SSL" : Ret == SSL_ERROR_SYSCALL ? "SYSCALL" : "ZERO_RETURN" )); @@ -141,7 +141,7 @@ TlsDoHandshake ( DEBUG (( DEBUG_ERROR, "%a ERROR 0x%x=L%x:F%x:R%x\n", - __FUNCTION__, + __func__, ErrorCode, ERR_GET_LIB (ErrorCode), ERR_GET_FUNC (ErrorCode), From 7e0b4a0ef92ae823f845d8366a189567788559b0 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:53:26 -0600 Subject: [PATCH 0860/1529] NetworkPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout NetworkPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel --- NetworkPkg/HttpDxe/HttpsSupport.c | 16 ++++++++-------- NetworkPkg/IScsiDxe/IScsiMisc.c | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/NetworkPkg/HttpDxe/HttpsSupport.c b/NetworkPkg/HttpDxe/HttpsSupport.c index ad611e7c38..7330be42c0 100644 --- a/NetworkPkg/HttpDxe/HttpsSupport.c +++ b/NetworkPkg/HttpDxe/HttpsSupport.c @@ -436,7 +436,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: truncated EFI_SIGNATURE_LIST header\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -447,7 +447,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: SignatureListSize too small for EFI_SIGNATURE_LIST\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -456,7 +456,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: truncated EFI_SIGNATURE_LIST body\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -465,7 +465,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: only X509 certificates are supported\n", - __FUNCTION__ + __func__ )); Status = EFI_UNSUPPORTED; goto FreeCACert; @@ -475,7 +475,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: SignatureHeaderSize must be 0 for X509\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -484,7 +484,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: SignatureSize too small for EFI_SIGNATURE_DATA\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -495,7 +495,7 @@ TlsConfigCertificate ( DEBUG (( DEBUG_ERROR, "%a: EFI_SIGNATURE_DATA array not a multiple of SignatureSize\n", - __FUNCTION__ + __func__ )); goto FreeCACert; } @@ -505,7 +505,7 @@ TlsConfigCertificate ( } if (CertCount == 0) { - DEBUG ((DEBUG_ERROR, "%a: no X509 certificates provided\n", __FUNCTION__)); + DEBUG ((DEBUG_ERROR, "%a: no X509 certificates provided\n", __func__)); goto FreeCACert; } diff --git a/NetworkPkg/IScsiDxe/IScsiMisc.c b/NetworkPkg/IScsiDxe/IScsiMisc.c index b3ea90158f..78dc5c73d3 100644 --- a/NetworkPkg/IScsiDxe/IScsiMisc.c +++ b/NetworkPkg/IScsiDxe/IScsiMisc.c @@ -875,7 +875,7 @@ IScsiCreateAttempts ( DEBUG_ERROR, "%a: Failed to set 'InitialAttemptOrder' with Guid (%g): " "%r\n", - __FUNCTION__, + __func__, &gIScsiConfigGuid, Status )); @@ -926,7 +926,7 @@ IScsiCreateAttempts ( DEBUG_ERROR, "%a: Failed to set variable (mPrivate->PortString) with Guid (%g): " "%r\n", - __FUNCTION__, + __func__, &gEfiIScsiInitiatorNameProtocolGuid, Status )); From 5f8f38661103d8c4ef4e100f47c3597a952ad719 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:53:42 -0600 Subject: [PATCH 0861/1529] SourceLevelDebugPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout SourceLevelDebugPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Dxe.c | 4 ++-- .../DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Pei.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Dxe.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Dxe.c index 4490526273..d37fb991f1 100644 --- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Dxe.c +++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Dxe.c @@ -186,7 +186,7 @@ Usb3DxeSmmReadyToLockNotify ( { USB3_DEBUG_PORT_HANDLE *Instance; - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); Instance = GetUsb3DebugPortInstance (); ASSERT (Instance != NULL); @@ -290,7 +290,7 @@ Usb3PciIoNotify ( // // Found the PciIo for USB3 debug port. // - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); if (Usb3GetIoMmu () != NULL) { Instance = GetUsb3DebugPortInstance (); ASSERT (Instance != NULL); diff --git a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Pei.c b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Pei.c index 15842a317e..aa04442918 100644 --- a/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Pei.c +++ b/SourceLevelDebugPkg/Library/DebugCommunicationLibUsb3/DebugCommunicationLibUsb3Pei.c @@ -35,7 +35,7 @@ Usb3IoMmuPpiNotify ( { USB3_DEBUG_PORT_HANDLE *Instance; - DEBUG ((DEBUG_INFO, "%a()\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a()\n", __func__)); Instance = GetUsb3DebugPortInstance (); ASSERT (Instance != NULL); From af48a616e405c1d3664859687635c52524f03757 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:54:02 -0600 Subject: [PATCH 0862/1529] EmulatorPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout EmulatorPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Abner Chang Reviewed-by: Ray Ni --- .../RedfishPlatformHostInterfaceLib.c | 2 +- EmulatorPkg/Win/Host/WinPacketFilter.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c b/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c index 4361bd4170..4332caa710 100644 --- a/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c +++ b/EmulatorPkg/Library/RedfishPlatformHostInterfaceLib/RedfishPlatformHostInterfaceLib.c @@ -538,7 +538,7 @@ RedfishPlatformHostInterfaceConstructor ( EFI_STATUS Status; Status = GetRedfishRecordFromVariable (&mRedfishOverIpProtocolData, &mRedfishProtocolDataSize); - DEBUG ((DEBUG_INFO, "%a: GetRedfishRecordFromVariable() - %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_INFO, "%a: GetRedfishRecordFromVariable() - %r\n", __func__, Status)); if (!EFI_ERROR (Status)) { DumpRedfishIpProtocolData (mRedfishOverIpProtocolData, mRedfishProtocolDataSize); } diff --git a/EmulatorPkg/Win/Host/WinPacketFilter.c b/EmulatorPkg/Win/Host/WinPacketFilter.c index 21859897c8..a71c7e8c13 100644 --- a/EmulatorPkg/Win/Host/WinPacketFilter.c +++ b/EmulatorPkg/Win/Host/WinPacketFilter.c @@ -966,7 +966,7 @@ WintNtInitializeNetUtilityData ( goto ErrorReturn; } - DEBUG ((DEBUG_INFO, "%a, total %d interface(s) found\n", __FUNCTION__, InterfaceCount)); + DEBUG ((DEBUG_INFO, "%a, total %d interface(s) found\n", __func__, InterfaceCount)); // // Active interface index is set to first interface if given instance does // not exist. From ab8ec634ad5fbd9448a8e5f44a16ecdc04f3d16a Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:54:18 -0600 Subject: [PATCH 0863/1529] UefiPayloadPkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout UefiPayloadPkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Gua Guo Reviewed-by: James Lu --- UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c | 4 ++-- UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c b/UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c index 790e6109c0..5727475414 100644 --- a/UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c +++ b/UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c @@ -135,7 +135,7 @@ InitRootBridge ( &mRootBridgeDevicePathTemplate ); if (DevicePath == NULL) { - DEBUG ((DEBUG_ERROR, "%a: %r\n", __FUNCTION__, EFI_OUT_OF_RESOURCES)); + DEBUG ((DEBUG_ERROR, "%a: %r\n", __func__, EFI_OUT_OF_RESOURCES)); return EFI_OUT_OF_RESOURCES; } @@ -145,7 +145,7 @@ InitRootBridge ( DEBUG (( DEBUG_INFO, "%a: populated root bus %d, with room for %d subordinate bus(es)\n", - __FUNCTION__, + __func__, RootBusNumber, MaxSubBusNumber - RootBusNumber )); diff --git a/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c b/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c index c66e56aee1..61a9f01ec9 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c +++ b/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c @@ -355,7 +355,7 @@ HandOffToDxeCore ( DEBUG (( DEBUG_INFO, "%a() Stack Base: 0x%lx, Stack Size: 0x%x\n", - __FUNCTION__, + __func__, BaseOfStack, STACK_SIZE )); From 2249efb2188cd6253c9b15d8a200332b02291392 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 13:54:35 -0600 Subject: [PATCH 0864/1529] FmpDevicePkg: Update code to be more C11 compliant by using __func__ __FUNCTION__ is a pre-standard extension that gcc and Visual C++ among others support, while __func__ was standardized in C99. Since it's more standard, replace __FUNCTION__ with __func__ throughout FmpDevicePkg. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney Reviewed-by: Ard Biesheuvel Reviewed-by: Wei6 Xu --- FmpDevicePkg/FmpDxe/VariableSupport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FmpDevicePkg/FmpDxe/VariableSupport.c b/FmpDevicePkg/FmpDxe/VariableSupport.c index 541e5e0f5f..5126c5e2d5 100644 --- a/FmpDevicePkg/FmpDxe/VariableSupport.c +++ b/FmpDevicePkg/FmpDxe/VariableSupport.c @@ -832,7 +832,7 @@ LockAllFmpVariables ( // Locate the VariablePolicy protocol. Status = gBS->LocateProtocol (&gEdkiiVariablePolicyProtocolGuid, NULL, (VOID **)&VariablePolicy); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "FmpDxe %a - Could not locate VariablePolicy protocol! %r\n", __FUNCTION__, Status)); + DEBUG ((DEBUG_ERROR, "FmpDxe %a - Could not locate VariablePolicy protocol! %r\n", __func__, Status)); return Status; } From 276015dfdc49cabba6493fb8ecb836609ddb047b Mon Sep 17 00:00:00 2001 From: "Lin, MillerX" Date: Mon, 10 Apr 2023 11:41:01 +0800 Subject: [PATCH 0865/1529] ShellPkg: Update smbiosview type 0/4/17/41 with SMBIOS 3.5 fields Signed-off-by: MillerX Lin Cc: Ray Ni Cc: Zhichao Gao Reviewed-by: Zhichao Gao --- .../SmbiosView/PrintInfo.c | 152 +++++++++--------- .../SmbiosView/SmbiosViewStrings.uni | 28 ++-- 2 files changed, 89 insertions(+), 91 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c index 2611601230..1811cf0c44 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c @@ -335,10 +335,10 @@ SmbiosPrintStructure ( // BIOS Information (Type 0) // case 0: - PRINT_PENDING_STRING (Struct, Type0, Vendor); - PRINT_PENDING_STRING (Struct, Type0, BiosVersion); - PRINT_STRUCT_VALUE_H (Struct, Type0, BiosSegment); - PRINT_PENDING_STRING (Struct, Type0, BiosReleaseDate); + ShellPrintEx (-1, -1, L"Vendor: %a\n", LibGetSmbiosString (Struct, Struct->Type0->Vendor)); + ShellPrintEx (-1, -1, L"BIOS Version: %a\n", LibGetSmbiosString (Struct, Struct->Type0->BiosVersion)); + ShellPrintEx (-1, -1, L"BIOS Starting Address Segment: 0x%x\n", Struct->Type0->BiosSegment); + ShellPrintEx (-1, -1, L"BIOS Release Date: %a\n", LibGetSmbiosString (Struct, Struct->Type0->BiosReleaseDate)); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_BIOS_SIZE), gShellDebug1HiiHandle, 64 * (Struct->Type0->BiosSize + 1)); DisplayBiosCharacteristics (ReadUnaligned64 ((UINT64 *)(UINTN)&(Struct->Type0->BiosCharacteristics)), Option); @@ -352,10 +352,10 @@ SmbiosPrintStructure ( } if (AE_SMBIOS_VERSION (0x2, 0x4) && (Struct->Hdr->Length > 0x14)) { - PRINT_STRUCT_VALUE (Struct, Type0, SystemBiosMajorRelease); - PRINT_STRUCT_VALUE (Struct, Type0, SystemBiosMinorRelease); - PRINT_STRUCT_VALUE (Struct, Type0, EmbeddedControllerFirmwareMajorRelease); - PRINT_STRUCT_VALUE (Struct, Type0, EmbeddedControllerFirmwareMinorRelease); + ShellPrintEx (-1, -1, L"System BIOS Major Release: %u\n", Struct->Type0->SystemBiosMajorRelease); + ShellPrintEx (-1, -1, L"System BIOS Minor Release: %u\n", Struct->Type0->SystemBiosMinorRelease); + ShellPrintEx (-1, -1, L"Embedded Controller Firmware Major Release: %u\n", Struct->Type0->EmbeddedControllerFirmwareMajorRelease); + ShellPrintEx (-1, -1, L"Embedded Controller Firmware Minor Release: %u\n", Struct->Type0->EmbeddedControllerFirmwareMinorRelease); } if (AE_SMBIOS_VERSION (0x3, 0x1) && (Struct->Hdr->Length > 0x18)) { @@ -470,48 +470,49 @@ SmbiosPrintStructure ( // Processor Information (Type 4) // case 4: - PRINT_SMBIOS_STRING (Struct, Struct->Type4->Socket, SocketDesignation) + ShellPrintEx (-1, -1, L"Socket Designation: %a\n", LibGetSmbiosString (Struct, Struct->Type4->Socket)); DisplayProcessorType (Struct->Type4->ProcessorType, Option); - if (AE_SMBIOS_VERSION (0x2, 0x6) && (Struct->Hdr->Length > 0x28) && - (Struct->Type4->ProcessorFamily == 0xFE)) - { - // - // Get family from ProcessorFamily2 field - // - DisplayProcessorFamily2 (Struct->Type4->ProcessorFamily2, Option); - } else { - DisplayProcessorFamily (Struct->Type4->ProcessorFamily, Option); - } - - PRINT_PENDING_STRING (Struct, Type4, ProcessorManufacturer); - PRINT_BIT_FIELD (Struct, Type4, ProcessorId, 8); - PRINT_PENDING_STRING (Struct, Type4, ProcessorVersion); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY), gShellDebug1HiiHandle); + DisplayProcessorFamily (Struct->Type4->ProcessorFamily, Option); + ShellPrintEx (-1, -1, L"Processor Manufacturer: %a\n", LibGetSmbiosString (Struct, Struct->Type4->ProcessorManufacturer)); + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_ID), gShellDebug1HiiHandle, 8); + DumpHex (0, 0, 8, &(Struct->Type4->ProcessorId)); + ShellPrintEx (-1, -1, L"Processor Version: %a\n", LibGetSmbiosString (Struct, Struct->Type4->ProcessorVersion)); DisplayProcessorVoltage (*(UINT8 *)&(Struct->Type4->Voltage), Option); - PRINT_STRUCT_VALUE (Struct, Type4, ExternalClock); - PRINT_STRUCT_VALUE (Struct, Type4, MaxSpeed); - PRINT_STRUCT_VALUE (Struct, Type4, CurrentSpeed); + ShellPrintEx (-1, -1, L"External Clock: %u\n", Struct->Type4->ExternalClock); + ShellPrintEx (-1, -1, L"Max Speed: %u\n", Struct->Type4->MaxSpeed); + ShellPrintEx (-1, -1, L"Current Speed: %u\n", Struct->Type4->CurrentSpeed); DisplayProcessorStatus (Struct->Type4->Status, Option); DisplayProcessorUpgrade (Struct->Type4->ProcessorUpgrade, Option); - PRINT_STRUCT_VALUE_H (Struct, Type4, L1CacheHandle); - PRINT_STRUCT_VALUE_H (Struct, Type4, L2CacheHandle); - PRINT_STRUCT_VALUE_H (Struct, Type4, L3CacheHandle); + ShellPrintEx (-1, -1, L"L1 Cache Handle: 0x%x\n", Struct->Type4->L1CacheHandle); + ShellPrintEx (-1, -1, L"L2 Cache Handle: 0x%x\n", Struct->Type4->L2CacheHandle); + ShellPrintEx (-1, -1, L"L3 Cache Handle: 0x%x\n", Struct->Type4->L3CacheHandle); if (AE_SMBIOS_VERSION (0x2, 0x3) && (Struct->Hdr->Length > 0x20)) { - PRINT_PENDING_STRING (Struct, Type4, SerialNumber); - PRINT_PENDING_STRING (Struct, Type4, AssetTag); - PRINT_PENDING_STRING (Struct, Type4, PartNumber); + ShellPrintEx (-1, -1, L"Serial Number: %a\n", LibGetSmbiosString (Struct, Struct->Type4->SerialNumber)); + ShellPrintEx (-1, -1, L"Asset Tag: %a\n", LibGetSmbiosString (Struct, Struct->Type4->AssetTag)); + ShellPrintEx (-1, -1, L"Part Number: %a\n", LibGetSmbiosString (Struct, Struct->Type4->PartNumber)); } if (AE_SMBIOS_VERSION (0x2, 0x5) && (Struct->Hdr->Length > 0x23)) { - PRINT_STRUCT_VALUE (Struct, Type4, CoreCount); - PRINT_STRUCT_VALUE (Struct, Type4, EnabledCoreCount); - PRINT_STRUCT_VALUE (Struct, Type4, ThreadCount); + ShellPrintEx (-1, -1, L"Core Count: %u\n", Struct->Type4->CoreCount); + ShellPrintEx (-1, -1, L"Core Enabled: %u\n", Struct->Type4->EnabledCoreCount); + ShellPrintEx (-1, -1, L"Thread Count: %u\n", Struct->Type4->ThreadCount); DisplayProcessorCharacteristics (Struct->Type4->ProcessorCharacteristics, Option); } + if (AE_SMBIOS_VERSION (0x2, 0x6) && (Struct->Hdr->Length > 0x28)) { + ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY2), gShellDebug1HiiHandle); + if (Struct->Type4->ProcessorFamily2 >= 0x100) { + DisplayProcessorFamily2 (Struct->Type4->ProcessorFamily2, Option); + } else { + DisplayProcessorFamily ((UINT8)Struct->Type4->ProcessorFamily2, Option); + } + } + if ((SmbiosMajorVersion >= 0x3) && (Struct->Hdr->Length > 0x2A)) { - PRINT_STRUCT_VALUE (Struct, Type4, CoreCount2); - PRINT_STRUCT_VALUE (Struct, Type4, EnabledCoreCount2); - PRINT_STRUCT_VALUE (Struct, Type4, ThreadCount2); + ShellPrintEx (-1, -1, L"Core Count 2: %u\n", Struct->Type4->CoreCount2); + ShellPrintEx (-1, -1, L"Core Enabled 2: %u\n", Struct->Type4->EnabledCoreCount2); + ShellPrintEx (-1, -1, L"Thread Count 2: %u\n", Struct->Type4->ThreadCount2); } break; @@ -829,68 +830,68 @@ SmbiosPrintStructure ( // Memory Device (Type 17) // case 17: - PRINT_STRUCT_VALUE_H (Struct, Type17, MemoryArrayHandle); - PRINT_STRUCT_VALUE_H (Struct, Type17, MemoryErrorInformationHandle); - PRINT_STRUCT_VALUE_H (Struct, Type17, TotalWidth); - PRINT_STRUCT_VALUE_H (Struct, Type17, DataWidth); + ShellPrintEx (-1, -1, L"Physical Memory Array Handle: 0x%x\n", Struct->Type17->MemoryArrayHandle); + ShellPrintEx (-1, -1, L"Memory Error Information Handle: 0x%x\n", Struct->Type17->MemoryErrorInformationHandle); + ShellPrintEx (-1, -1, L"Total Width: 0x%x\n", Struct->Type17->TotalWidth); + ShellPrintEx (-1, -1, L"Data Width: 0x%x\n", Struct->Type17->DataWidth); PRINT_STRUCT_VALUE (Struct, Type17, Size); DisplayMemoryDeviceFormFactor (Struct->Type17->FormFactor, Option); - PRINT_STRUCT_VALUE_H (Struct, Type17, DeviceSet); - PRINT_PENDING_STRING (Struct, Type17, DeviceLocator); - PRINT_PENDING_STRING (Struct, Type17, BankLocator); + ShellPrintEx (-1, -1, L"Device Set: 0x%x\n", Struct->Type17->DeviceSet); + ShellPrintEx (-1, -1, L"Device Locator: %a\n", LibGetSmbiosString (Struct, Struct->Type17->DeviceLocator)); + ShellPrintEx (-1, -1, L"Bank Locator: %a\n", LibGetSmbiosString (Struct, Struct->Type17->BankLocator)); DisplayMemoryDeviceType (Struct->Type17->MemoryType, Option); DisplayMemoryDeviceTypeDetail (ReadUnaligned16 ((UINT16 *)(UINTN)&(Struct->Type17->TypeDetail)), Option); PRINT_STRUCT_VALUE_H (Struct, Type17, Speed); PRINT_PENDING_STRING (Struct, Type17, Manufacturer); - PRINT_PENDING_STRING (Struct, Type17, SerialNumber); - PRINT_PENDING_STRING (Struct, Type17, AssetTag); - PRINT_PENDING_STRING (Struct, Type17, PartNumber); + ShellPrintEx (-1, -1, L"Serial Number: %a\n", LibGetSmbiosString (Struct, Struct->Type17->SerialNumber)); + ShellPrintEx (-1, -1, L"Asset Tag: %a\n", LibGetSmbiosString (Struct, Struct->Type17->AssetTag)); + ShellPrintEx (-1, -1, L"Part Number: %a\n", LibGetSmbiosString (Struct, Struct->Type17->PartNumber)); if (AE_SMBIOS_VERSION (0x2, 0x6) && (Struct->Hdr->Length > 0x1B)) { PRINT_STRUCT_VALUE_H (Struct, Type17, Attributes); } if (AE_SMBIOS_VERSION (0x2, 0x7) && (Struct->Hdr->Length > 0x1C)) { - PRINT_STRUCT_VALUE (Struct, Type17, ExtendedSize); - PRINT_STRUCT_VALUE_H (Struct, Type17, ConfiguredMemoryClockSpeed); + ShellPrintEx (-1, -1, L"Extended Size: %u\n", Struct->Type17->ExtendedSize); + ShellPrintEx (-1, -1, L"Configured Memory Speed: 0x%x\n", Struct->Type17->ConfiguredMemoryClockSpeed); } if (AE_SMBIOS_VERSION (0x2, 0x8) && (Struct->Hdr->Length > 0x22)) { - PRINT_STRUCT_VALUE (Struct, Type17, MinimumVoltage); - PRINT_STRUCT_VALUE (Struct, Type17, MaximumVoltage); - PRINT_STRUCT_VALUE (Struct, Type17, ConfiguredVoltage); + ShellPrintEx (-1, -1, L"Minimum voltage: %u\n", Struct->Type17->MinimumVoltage); + ShellPrintEx (-1, -1, L"Maximum voltage: %u\n", Struct->Type17->MaximumVoltage); + ShellPrintEx (-1, -1, L"Configured voltage: %u\n", Struct->Type17->ConfiguredVoltage); } if (AE_SMBIOS_VERSION (0x3, 0x2)) { if (Struct->Hdr->Length > 0x28) { DisplayMemoryDeviceMemoryTechnology (Struct->Type17->MemoryTechnology, Option); DisplayMemoryDeviceMemoryOperatingModeCapability (Struct->Type17->MemoryOperatingModeCapability.Uint16, Option); - PRINT_PENDING_STRING (Struct, Type17, FirmwareVersion); - PRINT_STRUCT_VALUE_H (Struct, Type17, ModuleManufacturerID); - PRINT_STRUCT_VALUE_H (Struct, Type17, ModuleProductID); - PRINT_STRUCT_VALUE_H (Struct, Type17, MemorySubsystemControllerManufacturerID); - PRINT_STRUCT_VALUE_H (Struct, Type17, MemorySubsystemControllerProductID); + ShellPrintEx (-1, -1, L"Firmware Version: %a\n", LibGetSmbiosString (Struct, Struct->Type17->FirmwareVersion)); + ShellPrintEx (-1, -1, L"Module Manufacturer ID: 0x%x\n", Struct->Type17->ModuleManufacturerID); + ShellPrintEx (-1, -1, L"Module Product ID: 0x%x\n", Struct->Type17->ModuleProductID); + ShellPrintEx (-1, -1, L"Memory Subsystem Controller Manufacturer ID: 0x%x\n", Struct->Type17->MemorySubsystemControllerManufacturerID); + ShellPrintEx (-1, -1, L"Memory Subsystem Controller Product ID: 0x%x\n", Struct->Type17->MemorySubsystemControllerProductID); } if (Struct->Hdr->Length > 0x34) { - PRINT_STRUCT_VALUE_LH (Struct, Type17, NonVolatileSize); + ShellPrintEx (-1, -1, L"Non-volatile Size: 0x%lx\n", Struct->Type17->NonVolatileSize); } if (Struct->Hdr->Length > 0x3C) { - PRINT_STRUCT_VALUE_LH (Struct, Type17, VolatileSize); + ShellPrintEx (-1, -1, L"Volatile Size: 0x%lx\n", Struct->Type17->VolatileSize); } if (Struct->Hdr->Length > 0x44) { - PRINT_STRUCT_VALUE_LH (Struct, Type17, CacheSize); + ShellPrintEx (-1, -1, L"Cache Size: 0x%lx\n", Struct->Type17->CacheSize); } if (Struct->Hdr->Length > 0x4C) { - PRINT_STRUCT_VALUE_LH (Struct, Type17, LogicalSize); + ShellPrintEx (-1, -1, L"Logical Size: 0x%lx\n", Struct->Type17->LogicalSize); } } if (AE_SMBIOS_VERSION (0x3, 0x3) && (Struct->Hdr->Length > 0x54)) { - PRINT_STRUCT_VALUE_H (Struct, Type17, ExtendedSpeed); - PRINT_STRUCT_VALUE_H (Struct, Type17, ExtendedConfiguredMemorySpeed); + ShellPrintEx (-1, -1, L"Extended Speed: 0x%x\n", Struct->Type17->ExtendedSpeed); + ShellPrintEx (-1, -1, L"Extended Configured Memory Speed: 0x%x\n", Struct->Type17->ExtendedConfiguredMemorySpeed); } break; @@ -1258,13 +1259,13 @@ SmbiosPrintStructure ( // Onboard Devices Extended Information (Type 41) // case 41: - PRINT_PENDING_STRING (Struct, Type41, ReferenceDesignation); + ShellPrintEx (-1, -1, L"Reference Designation: %a\n", LibGetSmbiosString (Struct, Struct->Type41->ReferenceDesignation)); ShellPrintEx (-1, -1, (((Struct->Type41->DeviceType) & 0x80) != 0) ? L"Device Enabled\n" : L"Device Disabled\n"); DisplayOnboardDeviceTypes ((Struct->Type41->DeviceType) & 0x7F, Option); - PRINT_STRUCT_VALUE_H (Struct, Type41, DeviceTypeInstance); - PRINT_STRUCT_VALUE_H (Struct, Type41, SegmentGroupNum); - PRINT_STRUCT_VALUE_H (Struct, Type41, BusNum); - PRINT_STRUCT_VALUE_H (Struct, Type41, DevFuncNum); + ShellPrintEx (-1, -1, L"Device Type Instance: 0x%x\n", Struct->Type41->DeviceTypeInstance); + ShellPrintEx (-1, -1, L"Segment Group Number: 0x%x\n", Struct->Type41->SegmentGroupNum); + ShellPrintEx (-1, -1, L"Bus Number: 0x%x\n", Struct->Type41->BusNum); + ShellPrintEx (-1, -1, L"Device/Function Number: 0x%x\n", Struct->Type41->DevFuncNum); break; // @@ -1606,10 +1607,6 @@ DisplayProcessorFamily ( UINT8 Option ) { - // - // Print prompt message - // - ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY), gShellDebug1HiiHandle); // // Print option // @@ -2411,6 +2408,10 @@ DisplayProcessorFamily ( Print (L"i960\n"); break; + case 0xFE: + Print (L"Indicator to obtain the processor family from the Processor Family 2 field\n"); + break; + default: ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_UNDEFINED_PROC_FAMILY), gShellDebug1HiiHandle); } @@ -2432,11 +2433,6 @@ DisplayProcessorFamily2 ( IN UINT8 Option ) { - // - // Print prompt message - // - ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY), gShellDebug1HiiHandle); - // // Print option // diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni index 05f7a61d9d..73f7b2ab19 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni @@ -88,8 +88,8 @@ #string STR_SMBIOSVIEW_PRINTINFO_FORMATTED_AREA #language en-US "Formatted Area: \r\n" #string STR_SMBIOSVIEW_PRINTINFO_INTER_ACHOR #language en-US "Inter Anchor: %a\r\n" #string STR_SMBIOSVIEW_PRINTINFO_INTER_CHECKSUM #language en-US "Inter Checksum: 0x%x\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_FORMAT_PART_LEN #language en-US "Format part Len : %d\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_STRUCT_HANDLE #language en-US "Structure Handle: %d\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_FORMAT_PART_LEN #language en-US "Length: %d\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_STRUCT_HANDLE #language en-US "Handle: %d\r\n" #string STR_SMBIOSVIEW_PRINTINFO_BOOTUP_STATE #language en-US "Bootup state " #string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_STATE #language en-US "Power Supply State " #string STR_SMBIOSVIEW_PRINTINFO_THERMAL_STATE #language en-US "Thermal state " @@ -168,6 +168,8 @@ #string STR_SMBIOSVIEW_PRINTINFO_MCFG_ENABLED #language en-US "Manufacturing mode is enabled\r\n" #string STR_SMBIOSVIEW_PRINTINFO_BITS_RSVD_FOR_FUTURE #language en-US " Bits %d:7 are reserved for future assignment\r\n" #string STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY #language en-US "Processor Family: " +#string STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_ID #language en-US "Processor ID\r\nsize=%d:\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_PROCESSOR_FAMILY2 #language en-US "Processor Family 2: " #string STR_SMBIOSVIEW_PRINTINFO_OTHER #language en-US "Other\r\n" #string STR_SMBIOSVIEW_PRINTINFO_UNKNOWN #language en-US "Unknown\r\n" #string STR_SMBIOSVIEW_PRINTINFO_INTEL386_PROCESSOR #language en-US "Intel386(TM) Processor\r\n" @@ -255,7 +257,7 @@ #string STR_SMBIOSVIEW_PRINTINFO_RSVD_FOR_SPEC_K5 #language en-US "Reserved for specific K5 versions\r\n" #string STR_SMBIOSVIEW_PRINTINFO_RSVD_FOR_SPEC_PENTIUM #language en-US "Reserved for specific Pentium(R) Processor versions\r\n" #string STR_SMBIOSVIEW_PRINTINFO_UNDEFINED_PROC_FAMILY #language en-US "Undefined processor family and type\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_PROC_INFO #language en-US "Processor Information - Voltage:\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_PROC_INFO #language en-US "Voltage:\r\n" #string STR_SMBIOSVIEW_PRINTINFO_PROC_CURRENT_VOLTAGE #language en-US "Processor current voltage = (%d/10)V\r\n" #string STR_SMBIOSVIEW_PRINTINFO_5V_SUPOPRTED #language en-US " 5V is supported\r\n" #string STR_SMBIOSVIEW_PRINTINFO_33V_SUPPORTED #language en-US " 3.3V is supported\r\n" @@ -271,7 +273,7 @@ #string STR_SMBIOSVIEW_PRINTINFO_BIT13_NOT_ZERO #language en-US "Error, reserved BIT 13 must be zero\r\n" #string STR_SMBIOSVIEW_PRINTINFO_BIT14_NOT_ZERO #language en-US "Error, reserved BIT 14 must be zero\r\n" #string STR_SMBIOSVIEW_PRINTINFO_BIT15_NOT_ZERO #language en-US "Error, reserved BIT 15 must be zero\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_PROC_STATUS #language en-US "Processor Status:\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_PROC_STATUS #language en-US "Status:\r\n" #string STR_SMBIOSVIEW_PRINTINFO_CPU_SOCKET_POPULATED #language en-US "CPU Socket Populated\r\n" #string STR_SMBIOSVIEW_PRINTINFO_CPU_SOCKET_UNPOPULATED #language en-US "CPU Socket Unpopulated\r\n" #string STR_SMBIOSVIEW_PRINTINFO_CPU_ENABLED #language en-US "CPU Enabled\r\n" @@ -382,8 +384,8 @@ #string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_NOT_PRESENT #language en-US "Power supply is not present\r\n" #string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_REPLACE #language en-US "Power supply is hot replaceable\r\n" #string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_NOT_REPLACE #language en-US "Power supply is not hot replaceable\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_BIOS_SIZE #language en-US "BiosSize: %d KB\r\n" -#string STR_SMBIOSVIEW_PRINTINFO_EXTENDED_BIOS_SIZE #language en-US "ExtendedBiosSize: %d %s\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_BIOS_SIZE #language en-US "BIOS ROM Size: %d KB\r\n" +#string STR_SMBIOSVIEW_PRINTINFO_EXTENDED_BIOS_SIZE #language en-US "Extended BIOS ROM Size: %d %s\r\n" #string STR_SMBIOSVIEW_QUERYTABLE_NO_INFO #language en-US "No Info" #string STR_SMBIOSVIEW_QUERYTABLE_RSVD_BITS_SET #language en-US "\r\nIt also has reserved bits set 1 --- reserved bits: 0x%x" #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_WAKEUP_TYPE #language en-US "System Wakeup Type:" @@ -419,7 +421,7 @@ #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_HEIGHT #language en-US "System Slot Height: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PHYSICAL_WIDTH #language en-US "System Slot Physical Width: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PITCH #language en-US "System Slot Pitch: %d\r\n" -#string STR_SMBIOSVIEW_QUERYTABLE_ONBOARD_DEVICE_TYPE #language en-US "Onboard Device Type: " +#string STR_SMBIOSVIEW_QUERYTABLE_ONBOARD_DEVICE_TYPE #language en-US "Device Type: " #string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_EVENT_LOG_TYPE #language en-US "System Event Log Type: " #string STR_SMBIOSVIEW_QUERYTABLE_EVENT_LOG_VAR_DATA_FORMAT #language en-US "Event Log Variable Data Format Types: " #string STR_SMBIOSVIEW_QUERYTABLE_POST_RESULTS_BITMAP #language en-US "POST Results Bitmap - First DWORD:\r\n" @@ -431,11 +433,11 @@ #string STR_SMBIOSVIEW_QUERYTABLE_PHYS_MEM_ARRAY_LOCATION #language en-US "Physical Memory Array Location: " #string STR_SMBIOSVIEW_QUERYTABLE_PHYS_MEM_ARRAY_USE #language en-US "Physical Memory Array Use: " #string STR_SMBIOSVIEW_QUERYTABLE_PHYS_MEM_ARRAY_ERROR #language en-US "Physical Memory Array Error Correction Types: " -#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_FORM_FACTOR #language en-US "Memory Device - Form Factor: " -#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_TYPE #language en-US "Memory Device - Type: " -#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_TYPE_DETAIL #language en-US "Memory Device - Type Detail: " -#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_MEMORY_TECHNOLOGY #language en-US "Memory Device - Memory Technology: " -#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_MEM_OPER_MODE_CAPA #language en-US "Memory Device - Memory Operating Mode Capability: " +#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_FORM_FACTOR #language en-US "Form Factor: " +#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_TYPE #language en-US "Memory Type: " +#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_TYPE_DETAIL #language en-US "Type Detail: " +#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_MEMORY_TECHNOLOGY #language en-US "Memory Technology: " +#string STR_SMBIOSVIEW_QUERYTABLE_MEM_DEVICE_MEM_OPER_MODE_CAPA #language en-US "Memory Operating Mode Capability: " #string STR_SMBIOSVIEW_QUERYTABLE_MEM_ERROR_INFO #language en-US "32-bit Memory Error Information - Type: " #string STR_SMBIOSVIEW_QUERYTABLE_MEM_ERROR_GRANULARITY #language en-US "Memory Error - Error granularity: " #string STR_SMBIOSVIEW_QUERYTABLE_MEM_ERROR_OP #language en-US "Memory Error - Error Operation: " @@ -454,7 +456,7 @@ #string STR_SMBIOSVIEW_QUERYTABLE_MEM_CHANNEL_TYPE #language en-US "Memory Channel Type:" #string STR_SMBIOSVIEW_QUERYTABLE_BMC_INTERFACE_TYPE #language en-US "BMC Interface Type:" #string STR_SMBIOSVIEW_QUERYTABLE_MC_HOST_INTERFACE_TYPE #language en-US "MC Host Interface Type:" -#string STR_SMBIOSVIEW_QUERYTABLE_STRUCT_TYPE #language en-US "Structure Type:" +#string STR_SMBIOSVIEW_QUERYTABLE_STRUCT_TYPE #language en-US "Type:" #string STR_SMBIOSVIEW_QUERYTABLE_PROCESSOR_ARCH_TYPE #language en-US "Processor Architecture Type:" #string STR_SMBIOSVIEW_SMBIOSVIEW_ONE_VAR_ARGV #language en-US "%s " #string STR_SMBIOSVIEW_SMBIOSVIEW_QUERY_STRUCT_COND #language en-US "Query Structure, conditions are:\r\n" From 732ec259b3c0423591f9c241a69765c18499a86b Mon Sep 17 00:00:00 2001 From: Yu Pu Date: Tue, 1 Nov 2022 15:58:42 +0800 Subject: [PATCH 0866/1529] UefiCpuLib: Remove UefiCpuLib. Because UefiCpuPkg/UefiCpuLib is merged to MdePkg/CpuLib and all modules are updated to not depend on this library, remove it completely. Cc: Eric Dong Cc: Ray Ni Cc: Rahul Kumar Signed-off-by: Yu Pu Reviewed-by: Ray Ni Signed-off-by: Zhiguang Liu --- UefiCpuPkg/Include/Library/UefiCpuLib.h | 16 --------- .../Library/BaseUefiCpuLib/BaseUefiCpuLib.inf | 35 ------------------- .../Library/BaseUefiCpuLib/BaseUefiCpuLib.uni | 16 --------- .../BaseUefiCpuLib/BaseUefiCpuLibNull.c | 18 ---------- UefiCpuPkg/UefiCpuPkg.dec | 5 --- UefiCpuPkg/UefiCpuPkg.dsc | 2 -- 6 files changed, 92 deletions(-) delete mode 100644 UefiCpuPkg/Include/Library/UefiCpuLib.h delete mode 100644 UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf delete mode 100644 UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.uni delete mode 100644 UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c diff --git a/UefiCpuPkg/Include/Library/UefiCpuLib.h b/UefiCpuPkg/Include/Library/UefiCpuLib.h deleted file mode 100644 index ab6982db6e..0000000000 --- a/UefiCpuPkg/Include/Library/UefiCpuLib.h +++ /dev/null @@ -1,16 +0,0 @@ -/** @file - Public header file for UEFI CPU library class. - - This library class defines some routines that are generic for IA32 family CPU - to be UEFI specification compliant. - - Copyright (c) 2009 - 2021, Intel Corporation. All rights reserved.
- Copyright (c) 2020, AMD Inc. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UEFI_CPU_LIB_H__ -#define __UEFI_CPU_LIB_H__ - -#endif diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf deleted file mode 100644 index 9f8b62d87a..0000000000 --- a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf +++ /dev/null @@ -1,35 +0,0 @@ -## @file -# This library defines some routines that are generic for IA32 family CPU. -# -# The library routines are UEFI specification compliant. -# -# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-# Copyright (c) 2020, AMD Inc. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseUefiCpuLib - MODULE_UNI_FILE = BaseUefiCpuLib.uni - FILE_GUID = 34C24FD7-7A90-45c2-89FD-946473D9CE98 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiCpuLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - BaseUefiCpuLibNull.c - -[Packages] - MdePkg/MdePkg.dec - UefiCpuPkg/UefiCpuPkg.dec - -[LibraryClasses] - BaseLib diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.uni b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.uni deleted file mode 100644 index 83c96cea67..0000000000 --- a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.uni +++ /dev/null @@ -1,16 +0,0 @@ -// /** @file -// This library defines some routines that are generic for IA32 family CPU. -// -// The library routines are UEFI specification compliant. -// -// Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
-// -// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "Defines generic routines for IA32 family CPUs." - -#string STR_MODULE_DESCRIPTION #language en-US "The library routines comply with the UEFI Specification." - diff --git a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c b/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c deleted file mode 100644 index e29d2e892c..0000000000 --- a/UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLibNull.c +++ /dev/null @@ -1,18 +0,0 @@ -/** @file -This library contains a dummy function to pass build. - -Copyright (c) 2022, Intel Corporation. All rights reserved. - -SPDX-License-Identifier: BSD-2-Clause-Patent -**/ -#include - -/** - Dummy function. -**/ -VOID -Dummy ( - VOID - ) -{ -} diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 2115aa4387..a5528277ff 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -18,11 +18,6 @@ Include [LibraryClasses] - ## @libraryclass Defines some routines that are generic for IA32 family CPU - ## to be UEFI specification compliant. - ## - UefiCpuLib|Include/Library/UefiCpuLib.h - ## @libraryclass Defines some routines that are used to register/manage/program ## CPU features. ## diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc index d85d56916f..593c11cc74 100644 --- a/UefiCpuPkg/UefiCpuPkg.dsc +++ b/UefiCpuPkg/UefiCpuPkg.dsc @@ -31,7 +31,6 @@ SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf @@ -136,7 +135,6 @@ UefiCpuPkg/CpuIo2Smm/CpuIo2StandaloneMm.inf UefiCpuPkg/CpuMpPei/CpuMpPei.inf UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf - UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf UefiCpuPkg/Library/BaseXApicLib/BaseXApicLib.inf UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf From 35e6df57229fad959c3d571d88ce30af4f021704 Mon Sep 17 00:00:00 2001 From: Benjamin Doron Date: Fri, 31 Mar 2023 16:41:25 -0400 Subject: [PATCH 0867/1529] UefiPayloadPkg: Always build MemoryTypeInformation HOB for DXE GCD MemoryType information assists GCD with defragmenting the memory map. When the DXE core starts, GCD adds memory descriptors for the resource descriptors HOBs. This allocates heap space which can be reused later as the bins by memory type. It seems memory allocation prefers low ranges. It seems "below 4G" is an artifact of this heap reuse. However, the memory type information determines the DXE core's `MinimalMemorySizeNeeded`, determining which system memory descriptor HOB may be used by DXE. Furthermore, it's important that the memory type information be correct, for an S4 memory map. Therefore, follow other bootloaders, such as [MinPlatform][1], and do this unconditionally. As of [edk2-stable202011][2], it was. [1]: https://github.com/tianocore/edk2-platforms/blob/b6f96743891be51541184bf61dd2970c008e2c43/Platform/Intel/MinPlatformPkg/PlatformInit/PlatformInitPei/PlatformInitPreMem.c#L164-L201 [2]: https://github.com/tianocore/edk2/blob/edk2-stable202011/UefiPayloadPkg/BlSupportPei/BlSupportPei.c#L462-L466 Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Reviewed-by: Sean Rhodes Signed-off-by: Benjamin Doron --- .../UefiPayloadEntry/UefiPayloadEntry.c | 36 +++++-------------- .../UefiPayloadEntry/UefiPayloadEntry.inf | 2 -- UefiPayloadPkg/UefiPayloadPkg.dec | 3 -- UefiPayloadPkg/UefiPayloadPkg.dsc | 2 -- 4 files changed, 8 insertions(+), 35 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c index 780348eadf..030a5baed9 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c +++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c @@ -19,30 +19,6 @@ EFI_MEMORY_TYPE_INFORMATION mDefaultMemoryTypeInformation[] = { { EfiMaxMemoryType, 0 } }; -/** - Function to reserve memory below 4GB for EDKII Modules. - - This causes the DXE to dispatch everything under 4GB and allows Operating - System's that require EFI_LOADED_IMAGE to be under 4GB to start. - e.g. Xen hypervisor used in Qubes. -**/ -VOID -ForceModulesBelow4G ( - VOID - ) -{ - DEBUG ((DEBUG_INFO, "Building hob to restrict memory resorces to below 4G.\n")); - - // - // Create Memory Type Information HOB - // - BuildGuidDataHob ( - &gEfiMemoryTypeInformationGuid, - mDefaultMemoryTypeInformation, - sizeof (mDefaultMemoryTypeInformation) - ); -} - /** Callback function to build resource descriptor HOB @@ -472,10 +448,14 @@ _ModuleEntryPoint ( // Build other HOBs required by DXE BuildGenericHob (); - // Create a HOB to make resources for EDKII modules below 4G - if (!FixedPcdGetBool (PcdDispatchModuleAbove4GMemory)) { - ForceModulesBelow4G (); - } + // + // Create Memory Type Information HOB + // + BuildGuidDataHob ( + &gEfiMemoryTypeInformationGuid, + mDefaultMemoryTypeInformation, + sizeof (mDefaultMemoryTypeInformation) + ); // Load the DXE Core Status = LoadDxeCore (&DxeCoreEntryPoint); diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf index d47e8e76cf..e2af8a4b7c 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf +++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf @@ -96,5 +96,3 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy ## SOMETIMES_CONSUMES - gUefiPayloadPkgTokenSpaceGuid.PcdDispatchModuleAbove4GMemory - diff --git a/UefiPayloadPkg/UefiPayloadPkg.dec b/UefiPayloadPkg/UefiPayloadPkg.dec index 7d61d6eeae..2ed7351370 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dec +++ b/UefiPayloadPkg/UefiPayloadPkg.dec @@ -82,9 +82,6 @@ gUefiPayloadPkgTokenSpaceGuid.PcdSystemMemoryUefiRegionSize|0x04000000|UINT32|0x gUefiPayloadPkgTokenSpaceGuid.PcdPcdDriverFile|{ 0x57, 0x72, 0xcf, 0x80, 0xab, 0x87, 0xf9, 0x47, 0xa3, 0xfe, 0xD5, 0x0B, 0x76, 0xd8, 0x95, 0x41 }|VOID*|0x00000018 -# Above 4G Memory -gUefiPayloadPkgTokenSpaceGuid.PcdDispatchModuleAbove4GMemory|TRUE|BOOLEAN|0x00000019 - # Boot Manager Key gUefiPayloadPkgTokenSpaceGuid.PcdBootManagerEscape|FALSE|BOOLEAN|0x00000020 diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index bca5d3f335..9847f189ff 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -34,7 +34,6 @@ DEFINE SECURITY_STUB_ENABLE = TRUE DEFINE SMM_SUPPORT = FALSE DEFINE PLATFORM_BOOT_TIMEOUT = 3 - DEFINE ABOVE_4G_MEMORY = TRUE DEFINE BOOT_MANAGER_ESCAPE = FALSE DEFINE ATA_ENABLE = TRUE DEFINE SD_ENABLE = TRUE @@ -442,7 +441,6 @@ !endif gEfiMdeModulePkgTokenSpaceGuid.PcdSdMmcGenericTimeoutValue|$(SD_MMC_TIMEOUT) - gUefiPayloadPkgTokenSpaceGuid.PcdDispatchModuleAbove4GMemory|$(ABOVE_4G_MEMORY) gUefiPayloadPkgTokenSpaceGuid.PcdBootManagerEscape|$(BOOT_MANAGER_ESCAPE) gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1800000 From a67a84e3a19977b59abff0bc20e19a450cc40d7b Mon Sep 17 00:00:00 2001 From: Sean Rhodes Date: Tue, 4 Apr 2023 20:30:30 +0100 Subject: [PATCH 0868/1529] UefiPayloadPkg: Update default memory type information for S4 Copied values from OVMF, these are sufficient for a debug build. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Reviewed-by: Sean Rhodes Signed-off-by: Benjamin Doron Signed-off-by: Sean Rhodes --- UefiPayloadPkg/UefiPayloadPkg.dec | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.dec b/UefiPayloadPkg/UefiPayloadPkg.dec index 2ed7351370..a23a7b5a78 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dec +++ b/UefiPayloadPkg/UefiPayloadPkg.dec @@ -71,11 +71,11 @@ gUefiPayloadPkgTokenSpaceGuid.PcdBootloaderParameter|0|UINT64|0x10000004 gUefiPayloadPkgTokenSpaceGuid.PcdShellFile|{ 0x83, 0xA5, 0x04, 0x7C, 0x3E, 0x9E, 0x1c, 0x4f, 0xAD, 0x65, 0xE0, 0x52, 0x68, 0xD0, 0xB4, 0xD1 }|VOID*|0x10000005 ## Used to help reduce fragmentation in the EFI memory map -gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0x08|UINT32|0x10000012 +gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0x19|UINT32|0x10000012 gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0x04|UINT32|0x10000013 -gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0x04|UINT32|0x00000014 -gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|0xC0|UINT32|0x00000015 -gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0x80|UINT32|0x00000016 +gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0x08|UINT32|0x00000014 +gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|0x100|UINT32|0x00000015 +gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0x100|UINT32|0x00000016 # Size of the region used by UEFI in permanent memory gUefiPayloadPkgTokenSpaceGuid.PcdSystemMemoryUefiRegionSize|0x04000000|UINT32|0x00000017 From 3b6e3077b95eaee34de94eb42c3f2d0ee4224e76 Mon Sep 17 00:00:00 2001 From: Jeff Brasen Date: Fri, 24 Mar 2023 01:42:17 +0000 Subject: [PATCH 0869/1529] OvmfPkg/VirtioMmioDeviceLib: virtio 1.0: Fix SetQueueAlignment. Nothing to do here for virtio 1.0 devices Signed-off-by: Jeff Brasen Reviewed-by: Gerd Hoffmann --- .../Library/VirtioMmioDeviceLib/VirtioMmioDeviceFunctions.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceFunctions.c b/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceFunctions.c index 8bdf1e1fc3..de2c5fa2a6 100644 --- a/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceFunctions.c +++ b/OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceFunctions.c @@ -144,7 +144,9 @@ VirtioMmioSetQueueAlignment ( Device = VIRTIO_MMIO_DEVICE_FROM_VIRTIO_DEVICE (This); - VIRTIO_CFG_WRITE (Device, VIRTIO_MMIO_OFFSET_QUEUE_ALIGN, Alignment); + if (Device->Version == VIRTIO_MMIO_DEVICE_VERSION_0_95) { + VIRTIO_CFG_WRITE (Device, VIRTIO_MMIO_OFFSET_QUEUE_ALIGN, Alignment); + } return EFI_SUCCESS; } From 4cc33faaa31eed1ba517b47f3086363a1034882d Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Tue, 14 Feb 2023 09:58:29 -0700 Subject: [PATCH 0870/1529] MdePkg: Add new JedecJep106Lib to fetch JEDEC JEP106 manufacturer Add a new library, JedecJep106Lib which provides a service to return the JEDEC JEP106 manufacturer string given the code and continuation bytes values. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney --- MdePkg/Include/Library/JedecJep106Lib.h | 29 + .../Library/JedecJep106Lib/JedecJep106Lib.c | 1839 +++++++++++++++++ .../Library/JedecJep106Lib/JedecJep106Lib.inf | 25 + MdePkg/MdePkg.dec | 3 + MdePkg/MdePkg.dsc | 2 + 5 files changed, 1898 insertions(+) create mode 100644 MdePkg/Include/Library/JedecJep106Lib.h create mode 100644 MdePkg/Library/JedecJep106Lib/JedecJep106Lib.c create mode 100644 MdePkg/Library/JedecJep106Lib/JedecJep106Lib.inf diff --git a/MdePkg/Include/Library/JedecJep106Lib.h b/MdePkg/Include/Library/JedecJep106Lib.h new file mode 100644 index 0000000000..de8904360d --- /dev/null +++ b/MdePkg/Include/Library/JedecJep106Lib.h @@ -0,0 +1,29 @@ +/** @file + Provides JEDEC JEP-106 Manufacturer functions. + + Copyright (c) 2022, Qualcomm Innovation Center, Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef JEDEC_JEP106_LIB_H_ +#define JEDEC_JEP106_LIB_H_ + +/** + Looks up the JEP-106 manufacturer. + + @param Code Last non-zero byte of the manufacturer's ID code. + @param ContinuationBytes Number of continuation bytes indicated in JEP-106. + + @return The manufacturer string, or NULL if an error occurred or the + combination of Code and ContinuationBytes are not valid. + +**/ +CONST CHAR8 * +EFIAPI +Jep106GetManufacturerName ( + IN UINT8 Code, + IN UINT8 ContinuationBytes + ); + +#endif /* JEDEC_JEP106_LIB_H_ */ diff --git a/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.c b/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.c new file mode 100644 index 0000000000..f97a074d5c --- /dev/null +++ b/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.c @@ -0,0 +1,1839 @@ +/** @file + Provides JEDEC JEP-106 Manufacturer functions. + + Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +typedef struct { + UINT8 Code; + CONST CHAR8 *Manufacturer; +} JEDEC_MANUFACTURERS; + +// From JEP106BE, published Jan 2022. +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank1[] = { + { 0x01, "AMD" }, + { 0x02, "AMI" }, + { 0x83, "Fairchild" }, + { 0x04, "Fujitsu" }, + { 0x85, "GTE" }, + { 0x86, "Harris" }, + { 0x07, "Hitachi" }, + { 0x08, "Inmos" }, + { 0x89, "Intel" }, + { 0x8A, "I.T.T." }, + { 0x0B, "Intersil" }, + { 0x8C, "Monolithic Technologies" }, + { 0x0D, "Mostek" }, + { 0x0E, "Freescale (Motorola)" }, + { 0x8F, "National" }, + { 0x10, "NEC" }, + { 0x91, "RCA" }, + { 0x92, "Raytheon" }, + { 0x13, "Conexant (Rockwell)" }, + { 0x94, "Seeq" }, + { 0x15, "NXP (Philips)" }, + { 0x16, "Synertek" }, + { 0x97, "Texas Instruments" }, + { 0x98, "Kioxia Corporation" }, + { 0x19, "Xicor" }, + { 0x1A, "Zilog" }, + { 0x9B, "Eurotechnique" }, + { 0x1C, "Mitsubishi" }, + { 0x9D, "Lucent (AT&T)" }, + { 0x9E, "Exel" }, + { 0x1F, "Atmel" }, + { 0x20, "STMicroelectronics" }, + { 0xA1, "Lattice Semi" }, + { 0xA2, "NCR" }, + { 0x23, "Wafer Scale Integration" }, + { 0xA4, "IBM" }, + { 0x25, "Tristar" }, + { 0x26, "Visic" }, + { 0xA7, "Intl. CMOS Technology" }, + { 0xA8, "SSSI" }, + { 0x29, "Microchip Technology" }, + { 0x2A, "Ricoh Ltd." }, + { 0xAB, "VLSI" }, + { 0x2C, "Micron Technology" }, + { 0xAD, "SK Hynix" }, + { 0xAE, "OKI Semiconductor" }, + { 0x2F, "ACTEL" }, + { 0xB0, "Sharp" }, + { 0x31, "Catalyst" }, + { 0x32, "Panasonic" }, + { 0xB3, "IDT" }, + { 0x34, "Cypress" }, + { 0xB5, "DEC" }, + { 0xB6, "LSI Logic" }, + { 0x37, "Zarlink (Plessy)" }, + { 0x38, "UTMC" }, + { 0xB9, "Thinking Machine" }, + { 0xBA, "Thomson CSF" }, + { 0x3B, "Integrated CMOS (Vertex)" }, + { 0xBC, "Honeywell" }, + { 0x3D, "Tektronic" }, + { 0x3E, "Oracle Corporation" }, + { 0xBF, "Silicon Storage Technology" }, + { 0x40, "ProMos/Mosel Vitelic" }, + { 0xC1, "Infineon (Siemens)" }, + { 0xC2, "Macronix" }, + { 0x43, "Xerox" }, + { 0xC4, "Plus Logic" }, + { 0x45, "Western Digital Technologies Inc" }, + { 0x46, "Elan Circuit Tech" }, + { 0xC7, "European Silicon Str." }, + { 0xC8, "Apple Computer" }, + { 0x49, "Xilinx" }, + { 0x4A, "Compaq" }, + { 0xCB, "Protocol Engines" }, + { 0x4C, "SCI" }, + { 0xCD, "Seiko Instruments" }, + { 0xCE, "Samsung" }, + { 0x4F, "I3 Design System" }, + { 0xD0, "Klic" }, + { 0x51, "Crosspoint Solutions" }, + { 0x52, "Alliance Semiconductor" }, + { 0xD3, "Tandem" }, + { 0x54, "Hewlett-Packard" }, + { 0xD5, "Integrated Silicon Solutions" }, + { 0xD6, "Brooktree" }, + { 0x57, "New Media" }, + { 0x58, "MHS Electronic" }, + { 0xD9, "Performance Semi" }, + { 0xDA, "Winbond Electronic" }, + { 0x5B, "Kawasaki Steel" }, + { 0xDC, "Bright Micro" }, + { 0x5D, "TECMAR" }, + { 0x5E, "Exar" }, + { 0xDF, "PCMCIA" }, + { 0xE0, "LG Semi (Goldstar)" }, + { 0x61, "Northern Telecom" }, + { 0x62, "Sanyo" }, + { 0xE3, "Array Microsystems" }, + { 0x64, "Crystal Semiconductor" }, + { 0xE5, "Analog Devices" }, + { 0xE6, "PMC-Sierra" }, + { 0x67, "Asparix" }, + { 0x68, "Convex Computer" }, + { 0xE9, "Quality Semiconductor" }, + { 0xEA, "Nimbus Technology" }, + { 0x6B, "Transwitch" }, + { 0xEC, "Micronas (ITT Intermetal)" }, + { 0x6D, "Cannon" }, + { 0x6E, "Altera" }, + { 0xEF, "NEXCOM" }, + { 0x70, "Qualcomm" }, + { 0xF1, "Sony" }, + { 0xF2, "Cray Research" }, + { 0x73, "AMS(Austria Micro)" }, + { 0xF4, "Vitesse" }, + { 0x75, "Aster Electronics" }, + { 0x76, "Bay Networks (Synoptic)" }, + { 0xF7, "Zentrum/ZMD" }, + { 0xF8, "TRW" }, + { 0x79, "Thesys" }, + { 0x7A, "Solbourne Computer" }, + { 0xFB, "Allied-Signal" }, + { 0x7C, "Dialog Semiconductor" }, + { 0xFD, "Media Vision" }, + { 0xFE, "Numonyx Corporation" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank2[] = { + { 0x01, "Cirrus Logic" }, + { 0x02, "National Instruments" }, + { 0x83, "ILC Data Device" }, + { 0x04, "Alcatel Mietec" }, + { 0x85, "Micro Linear" }, + { 0x86, "Univ. of NC" }, + { 0x07, "JTAG Technologies" }, + { 0x08, "BAE Systems (Loral)" }, + { 0x89, "Nchip" }, + { 0x8A, "Galileo Tech" }, + { 0x0B, "Bestlink Systems" }, + { 0x8C, "Graychip" }, + { 0x0D, "GENNUM" }, + { 0x0E, "VideoLogic" }, + { 0x8F, "Robert Bosch" }, + { 0x10, "Chip Express" }, + { 0x91, "DATARAM" }, + { 0x92, "United Microelectronics Corp." }, + { 0x13, "TCSI" }, + { 0x94, "Smart Modular" }, + { 0x15, "Hughes Aircraft" }, + { 0x16, "Lanstar Semiconductor" }, + { 0x97, "Qlogic" }, + { 0x98, "Kingston" }, + { 0x19, "Music Semi" }, + { 0x1A, "Ericsson Components" }, + { 0x9B, "SPaSE" }, + { 0x1C, "Eon Silicon Devices" }, + { 0x9D, "Integrated Silicon Solution (ISSI)" }, + { 0x9E, "DoD" }, + { 0x1F, "Integ. Memories Tech." }, + { 0x20, "Corollary Inc." }, + { 0xA1, "Dallas Semiconductor" }, + { 0xA2, "Omnivision" }, + { 0x23, "EIV (Switzerland)" }, + { 0xA4, "Novatel Wireless" }, + { 0x25, "Zarlink (Mitel)" }, + { 0x26, "Clearpoint" }, + { 0xA7, "Cabletron" }, + { 0xA8, "STEC (Silicon Tech)" }, + { 0x29, "Vanguard" }, + { 0x2A, "Hagiwara Sys-Com" }, + { 0xAB, "Vantis" }, + { 0x2C, "Celestica" }, + { 0xAD, "Century" }, + { 0xAE, "Hal Computers" }, + { 0x2F, "Rohm Company Ltd." }, + { 0xB0, "Juniper Networks" }, + { 0x31, "Libit Signal Processing" }, + { 0x32, "Mushkin Enhanced Memory" }, + { 0xB3, "Tundra Semiconductor" }, + { 0x34, "Adaptec Inc." }, + { 0xB5, "Lighspeed Semi" }, + { 0xB6, "ZSP Corp." }, + { 0x37, "AMIC Technology" }, + { 0x38, "Adobe Systems" }, + { 0xB9, "Dynachip" }, + { 0xBA, "PNY Technologies, Inc." }, + { 0x3B, "Newport Digital" }, + { 0xBC, "MMC Network" }, + { 0x3D, "T Square" }, + { 0x3E, "Seiko Epson" }, + { 0xBF, "Broadcom" }, + { 0x40, "Viking Components" }, + { 0xC1, "V3 Semiconductor" }, + { 0xC2, "Flextronics (Orbit Semiconductor)" }, + { 0x43, "Suwa Electronics" }, + { 0xC4, "Transmeta" }, + { 0x45, "Micron CMS" }, + { 0x46, "American Computer & Digital Components Inc." }, + { 0xC7, "Enhance 3000 Inc." }, + { 0xC8, "Tower Semiconductor" }, + { 0x49, "CPU Design" }, + { 0x4A, "Price Point" }, + { 0xCB, "Maxim Integrated Product" }, + { 0x4C, "Tellabs" }, + { 0xCD, "Centaur Technology" }, + { 0xCE, "Unigen Corporation" }, + { 0x4F, "Transcent Information" }, + { 0xD0, "Memory Card Technology" }, + { 0x51, "CKD Corporation Ltd." }, + { 0x52, "Capital Instruments, Inc." }, + { 0xD3, "Aica Kogyo, Ltd." }, + { 0x54, "Linvex Technology" }, + { 0xD5, "MSC Vertriebs GmbH" }, + { 0xD6, "AKM Company, Ltd." }, + { 0x57, "Dynamem, Inc." }, + { 0x58, "NERA ASA" }, + { 0xD9, "GSI Technology" }, + { 0xDA, "Dane-Elec (C Memory)" }, + { 0x5B, "Acorn Computers" }, + { 0xDC, "Lara Technology" }, + { 0x5D, "Oak Technology, Inc." }, + { 0x5E, "Itec Memory" }, + { 0xDF, "Tanisys Technology" }, + { 0xE0, "Truevision" }, + { 0x61, "Wintec Industries" }, + { 0x62, "Super PC Memory" }, + { 0xE3, "MGV Memory" }, + { 0x64, "Galvantech" }, + { 0xE5, "Gadzoox Networks" }, + { 0xE6, "Multi Dimensional Cons." }, + { 0x67, "Gatefield" }, + { 0x68, "Integrated Memory System" }, + { 0xE9, "Triscend" }, + { 0xEA, "XaQti" }, + { 0x6B, "Goldenram" }, + { 0xEC, "Clear Logic" }, + { 0x6D, "Cimaron Communications" }, + { 0x6E, "Nippon Steel Semi. Corp." }, + { 0xEF, "Advantage Memory" }, + { 0x70, "AMCC" }, + { 0xF1, "LeCroy" }, + { 0xF2, "Yamaha Corporation" }, + { 0x73, "Digital Microwave" }, + { 0xF4, "NetLogic Microsystems" }, + { 0x75, "MIMOS Semiconductor" }, + { 0x76, "Advanced Fiber" }, + { 0xF7, "BF Goodrich Data" }, + { 0xF8, "Epigram" }, + { 0x79, "Acbel Polytech Inc." }, + { 0x7A, "Apacer Technology" }, + { 0xFB, "Admor Memory" }, + { 0x7C, "FOXCONN" }, + { 0xFD, "Quadratics Superconductor" }, + { 0xFE, "3COM" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank3[] = { + { 0x01, "Camintonn Corporation" }, + { 0x02, "ISOA Incorporated" }, + { 0x83, "Agate Semiconductor" }, + { 0x04, "ADMtek Incorporated" }, + { 0x85, "HYPERTEC" }, + { 0x86, "Adhoc Technologies" }, + { 0x07, "MOSAID Technologies" }, + { 0x08, "Ardent Technologies" }, + { 0x89, "Switchcore" }, + { 0x8A, "Cisco Systems Inc" }, + { 0x0B, "Allayer Technologies" }, + { 0x8C, "WorkX AG (Wichman)" }, + { 0x0D, "Oasis Semiconductor" }, + { 0x0E, "Novanet Semiconductor" }, + { 0x8F, "E-M Solutions" }, + { 0x10, "Power General" }, + { 0x91, "Advanced Hardware Arch." }, + { 0x92, "Inova Semiconductors GmbH" }, + { 0x13, "Telocity" }, + { 0x94, "Delkin Devices" }, + { 0x15, "Symagery Microsystems" }, + { 0x16, "C-Port Corporation" }, + { 0x97, "SiberCore Technologies" }, + { 0x98, "Southland Microsystems" }, + { 0x19, "Malleable Technologies" }, + { 0x1A, "Kendin Communications" }, + { 0x9B, "Great Technology Microcomputer" }, + { 0x1C, "Sanmina Corporation" }, + { 0x9D, "HADCO Corporation" }, + { 0x9E, "Corsair" }, + { 0x1F, "Actrans System Inc" }, + { 0x20, "ALPHA Technologies" }, + { 0xA1, "Silicon Laboratories Inc (Cygnal)" }, + { 0xA2, "Artesyn Technologies" }, + { 0x23, "Align Manufacturing" }, + { 0xA4, "Peregrine Technologies" }, + { 0x25, "Chameleon Systems" }, + { 0x26, "Aplus Flash Technology" }, + { 0xA7, "MIPS Technologies" }, + { 0xA8, "Chrysalis ITS" }, + { 0x29, "ADTEC Corporation" }, + { 0x2A, "Kentron Technologies" }, + { 0xAB, "Win Technologies" }, + { 0x2C, "Tezzaron Semiconductor" }, + { 0xAD, "Extreme Packet Devices" }, + { 0xAE, "RF Micro Devices" }, + { 0x2F, "Siemens AG" }, + { 0xB0, "Sarnoff Corporation" }, + { 0x31, "Itautec SA" }, + { 0x32, "Radiata Inc" }, + { 0xB3, "Benchmark Elect. (AVEX)" }, + { 0x34, "Legend" }, + { 0xB5, "SpecTek Incorporated" }, + { 0xB6, "Hi/fn" }, + { 0x37, "Enikia Incorporated" }, + { 0x38, "SwitchOn Networks" }, + { 0xB9, "AANetcom Incorporated" }, + { 0xBA, "Micro Memory Bank" }, + { 0x3B, "ESS Technology" }, + { 0xBC, "Virata Corporation" }, + { 0x3D, "Excess Bandwidth" }, + { 0x3E, "West Bay Semiconductor" }, + { 0xBF, "DSP Group" }, + { 0x40, "Newport Communications" }, + { 0xC1, "Chip2Chip Incorporated" }, + { 0xC2, "Phobos Corporation" }, + { 0x43, "Intellitech Corporation" }, + { 0xC4, "Nordic VLSI ASA" }, + { 0x45, "Ishoni Networks" }, + { 0x46, "Silicon Spice" }, + { 0xC7, "Alchemy Semiconductor" }, + { 0xC8, "Agilent Technologies" }, + { 0x49, "Centillium Communications" }, + { 0x4A, "W.L. Gore" }, + { 0xCB, "HanBit Electronics" }, + { 0x4C, "GlobeSpan" }, + { 0xCD, "Element 14" }, + { 0xCE, "Pycon" }, + { 0x4F, "Saifun Semiconductors" }, + { 0xD0, "Sibyte Incorporated" }, + { 0x51, "MetaLink Technologies" }, + { 0x52, "Feiya Technology" }, + { 0xD3, "I & C Technology" }, + { 0x54, "Shikatronics" }, + { 0xD5, "Elektrobit" }, + { 0xD6, "Megic" }, + { 0x57, "Com-Tier" }, + { 0x58, "Malaysia Micro Solutions" }, + { 0xD9, "Hyperchip" }, + { 0xDA, "Gemstone Communications" }, + { 0x5B, "Anadigm (Anadyne)" }, + { 0xDC, "3ParData" }, + { 0x5D, "Mellanox Technologies" }, + { 0x5E, "Tenx Technologies" }, + { 0xDF, "Helix AG" }, + { 0xE0, "Domosys" }, + { 0x61, "Skyup Technology" }, + { 0x62, "HiNT Corporation" }, + { 0xE3, "Chiaro" }, + { 0x64, "MDT Technologies GmbH" }, + { 0xE5, "Exbit Techology A/S" }, + { 0xE6, "Integrated Technology Express" }, + { 0x67, "AVED Memory" }, + { 0x68, "Legerity" }, + { 0xE9, "Jasmine Networks" }, + { 0xEA, "Caspian Networks" }, + { 0x6B, "nCUBE" }, + { 0xEC, "Silicon Access Networks" }, + { 0x6D, "FDK Corporation" }, + { 0x6E, "High Bandwidth Access" }, + { 0xEF, "MultiLink Technology" }, + { 0x70, "BRECIS" }, + { 0xF1, "World Wide Packets" }, + { 0xF2, "APW" }, + { 0x73, "Chicory Systems" }, + { 0xF4, "Xstream Logic" }, + { 0x75, "Fast-Chip" }, + { 0x76, "Zucotto Wireless" }, + { 0xF7, "Realchip" }, + { 0xF8, "Galaxy Power" }, + { 0x79, "eSilicon" }, + { 0x7A, "Morphics Technology" }, + { 0xFB, "Accelerant Networks" }, + { 0x7C, "Silicon Wave" }, + { 0xFD, "SandCraft" }, + { 0xFE, "Elpida" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank4[] = { + { 0x01, "Solectron" }, + { 0x02, "Optosys Technologies" }, + { 0x83, "Buffalo (Formerly Melco)" }, + { 0x04, "TriMedia Technologies" }, + { 0x85, "Cyan Technologies" }, + { 0x86, "Global Locate" }, + { 0x07, "Optilion" }, + { 0x08, "Terago Communications" }, + { 0x89, "Ikanos Communications" }, + { 0x8A, "Princeton Technology" }, + { 0x0B, "Nanya Technology" }, + { 0x8C, "Elite Flash Storage" }, + { 0x0D, "Mysticom" }, + { 0x0E, "LightSand Communications" }, + { 0x8F, "ATI Technologies" }, + { 0x10, "Agere Systems" }, + { 0x91, "NeoMagic" }, + { 0x92, "AuroraNetics" }, + { 0x13, "Golden Empire" }, + { 0x94, "Mushkin" }, + { 0x15, "Tioga Technologies" }, + { 0x16, "Netlist" }, + { 0x97, "TeraLogic" }, + { 0x98, "Cicada Semiconductor" }, + { 0x19, "Centon Electronics" }, + { 0x1A, "Tyco Electronics" }, + { 0x9B, "Magis Works" }, + { 0x1C, "Zettacom" }, + { 0x9D, "Cogency Semiconductor" }, + { 0x9E, "Chipcon AS" }, + { 0x1F, "Aspex Technology" }, + { 0x20, "F5 Networks" }, + { 0xA1, "Programmable Silicon Solutions" }, + { 0xA2, "ChipWrights" }, + { 0x23, "Acorn Networks" }, + { 0xA4, "Quicklogic" }, + { 0x25, "Kingmax Semiconductor" }, + { 0x26, "BOPS" }, + { 0xA7, "Flasys" }, + { 0xA8, "BitBlitz Communications" }, + { 0x29, "eMemory Technology" }, + { 0x2A, "Procket Networks" }, + { 0xAB, "Purple Ray" }, + { 0x2C, "Trebia Networks" }, + { 0xAD, "Delta Electronics" }, + { 0xAE, "Onex Communications" }, + { 0x2F, "Ample Communcations" }, + { 0xB0, "Memory Experts Intl" }, + { 0x31, "Astute Networks" }, + { 0x32, "Azanda Network Devices" }, + { 0xB3, "Dibcom" }, + { 0x34, "Tekmos" }, + { 0xB5, "API NetWorks" }, + { 0xB6, "Bay Microsystems" }, + { 0x37, "Firecron Ltd" }, + { 0x38, "Resonext Communications" }, + { 0xB9, "Tachsys Technologies" }, + { 0xBA, "Equator Technology" }, + { 0x3B, "Concept Computer" }, + { 0xBC, "SILCOM" }, + { 0x3D, "3Dlabs" }, + { 0x3E, "c't Magazine" }, + { 0xBF, "Sanera Systems" }, + { 0x40, "Silicon Packets" }, + { 0xC1, "Viasystems Group" }, + { 0xC2, "Simtek" }, + { 0x43, "Semicon Devices Singapore" }, + { 0xC4, "Satron Handelsges" }, + { 0x45, "Improv Systems" }, + { 0x46, "INDUSYS GmbH" }, + { 0xC7, "Corrent" }, + { 0xC8, "Infrant Technologies" }, + { 0x49, "Ritek Corp" }, + { 0x4A, "empowerTel Networks" }, + { 0xCB, "Hypertec" }, + { 0x4C, "Cavium Networks" }, + { 0xCD, "PLX Technology" }, + { 0xCE, "Massana Design" }, + { 0x4F, "Intrinsity" }, + { 0xD0, "Valence Semiconductor" }, + { 0x51, "Terawave Communications" }, + { 0x52, "IceFyre Semiconductor" }, + { 0xD3, "Primarion" }, + { 0x54, "Picochip Designs Ltd" }, + { 0xD5, "Silverback Systems" }, + { 0xD6, "Jade Star Technologies" }, + { 0x57, "Pijnenburg Securealink" }, + { 0x58, "takeMS - Ultron AG" }, + { 0xD9, "Cambridge Silicon Radio" }, + { 0xDA, "Swissbit" }, + { 0x5B, "Nazomi Communications" }, + { 0xDC, "eWave System" }, + { 0x5D, "Rockwell Collins" }, + { 0x5E, "Picocel Co Ltd (Paion)" }, + { 0xDF, "Alphamosaic Ltd" }, + { 0xE0, "Sandburst" }, + { 0x61, "SiCon Video" }, + { 0x62, "NanoAmp Solutions" }, + { 0xE3, "Ericsson Technology" }, + { 0x64, "PrairieComm" }, + { 0xE5, "Mitac International" }, + { 0xE6, "Layer N Networks" }, + { 0x67, "MtekVision (Atsana)" }, + { 0x68, "Allegro Networks" }, + { 0xE9, "Marvell Semiconductors" }, + { 0xEA, "Netergy Microelectronic" }, + { 0x6B, "NVIDIA" }, + { 0xEC, "Internet Machines" }, + { 0x6D, "Memorysolution GmbH" }, + { 0x6E, "Litchfield Communication" }, + { 0xEF, "Accton Technology" }, + { 0x70, "Teradiant Networks" }, + { 0xF1, "Scalio Chip" }, + { 0xF2, "Cortina Systems" }, + { 0x73, "RAM Components" }, + { 0xF4, "Raqia Networks" }, + { 0x75, "ClearSpeed" }, + { 0x76, "Matsushita Battery" }, + { 0xF7, "Xelerated" }, + { 0xF8, "SimpleTech" }, + { 0x79, "Utron Technology" }, + { 0x7A, "Astec International" }, + { 0xFB, "AVM gmbH" }, + { 0x7C, "Redux Communications" }, + { 0xFD, "Dot Hill Systems" }, + { 0xFE, "TeraChip" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank5[] = { + { 0x01, "T-RAM Incorporated" }, + { 0x02, "Innovics Wireless" }, + { 0x83, "Teknovus" }, + { 0x04, "KeyEye Communications" }, + { 0x85, "Runcom Technologies" }, + { 0x86, "RedSwitch" }, + { 0x07, "Dotcast" }, + { 0x08, "Silicon Mountain Memory" }, + { 0x89, "Signia Technologies" }, + { 0x8A, "Pixim" }, + { 0x0B, "Galazar Networks" }, + { 0x8C, "White Electronic Designs" }, + { 0x0D, "Patriot Scientific" }, + { 0x0E, "Neoaxiom Corporation" }, + { 0x8F, "3Y Power Technology" }, + { 0x10, "Scaleo Chip" }, + { 0x91, "Potentia Power Systems" }, + { 0x92, "C-guys Incorporated" }, + { 0x13, "Digital Communications Technology Inc" }, + { 0x94, "Silicon-Based Technology" }, + { 0x15, "Fulcrum Microsystems" }, + { 0x16, "Positivo Informatica Ltd" }, + { 0x97, "XIOtech Corporation" }, + { 0x98, "PortalPlayer" }, + { 0x19, "Zhiying Software" }, + { 0x1A, "ParkerVision Inc" }, + { 0x9B, "Phonex Broadband" }, + { 0x1C, "Skyworks Solutions" }, + { 0x9D, "Entropic Communications" }, + { 0x9E, "I'M Intelligent Memory Ltd" }, + { 0x1F, "Zensys A/S " }, + { 0x20, "Legend Silicon Corp" }, + { 0xA1, "Sci-worx GmbH" }, + { 0xA2, "SMSC (Standard Microsystems)" }, + { 0x23, "Renesas Electronics" }, + { 0xA4, "Raza Microelectronics" }, + { 0x25, "Phyworks" }, + { 0x26, "MediaTek" }, + { 0xA7, "Non-cents Productions" }, + { 0xA8, "US Modular" }, + { 0x29, "Wintegra Ltd" }, + { 0x2A, "Mathstar" }, + { 0xAB, "StarCore" }, + { 0x2C, "Oplus Technologies" }, + { 0xAD, "Mindspeed" }, + { 0xAE, "Just Young Computer" }, + { 0x2F, "Radia Communications" }, + { 0xB0, "OCZ" }, + { 0x31, "Emuzed" }, + { 0x32, "LOGIC Devices" }, + { 0xB3, "Inphi Corporation" }, + { 0x34, "Quake Technologies" }, + { 0xB5, "Vixel" }, + { 0xB6, "SolusTek" }, + { 0x37, "Kongsberg Maritime" }, + { 0x38, "Faraday Technology" }, + { 0xB9, "Altium Ltd" }, + { 0xBA, "Insyte" }, + { 0x3B, "ARM Ltd" }, + { 0xBC, "DigiVision" }, + { 0x3D, "Vativ Technologies" }, + { 0x3E, "Endicott Interconnect Technologies" }, + { 0xBF, "Pericom" }, + { 0x40, "Bandspeed" }, + { 0xC1, "LeWiz Communications" }, + { 0xC2, "CPU Technology" }, + { 0x43, "Ramaxel Technology" }, + { 0xC4, "DSP Group" }, + { 0x45, "Axis Communications" }, + { 0x46, "Legacy Electronics" }, + { 0xC7, "Chrontel" }, + { 0xC8, "Powerchip Semiconductor" }, + { 0x49, "MobilEye Technologies" }, + { 0x4A, "Excel Semiconductor" }, + { 0xCB, "A-DATA Technology " }, + { 0x4C, "VirtualDigm" }, + { 0xCD, "G Skill Intl" }, + { 0xCE, "Quanta Computer" }, + { 0x4F, "Yield Microelectronics" }, + { 0xD0, "Afa Technologies" }, + { 0x51, "KINGBOX Technology Co Ltd" }, + { 0x52, "Ceva" }, + { 0xD3, "iStor Networks" }, + { 0x54, "Advance Modules" }, + { 0xD5, "Microsoft" }, + { 0xD6, "Open-Silicon" }, + { 0x57, "Goal Semiconductor" }, + { 0x58, "ARC International" }, + { 0xD9, "Simmtec" }, + { 0xDA, "Metanoia" }, + { 0x5B, "Key Stream" }, + { 0xDC, "Lowrance Electronics" }, + { 0x5D, "Adimos" }, + { 0x5E, "SiGe Semiconductor" }, + { 0xDF, "Fodus Communications" }, + { 0xE0, "Credence Systems Corp" }, + { 0x61, "Genesis Microchip Inc" }, + { 0x62, "Vihana Inc" }, + { 0xE3, "WIS Technologies" }, + { 0x64, "GateChange Technologies" }, + { 0xE5, "High Density Devices AS" }, + { 0xE6, "Synopsys" }, + { 0x67, "Gigaram" }, + { 0x68, "Enigma Semiconductor Inc" }, + { 0xE9, "Century Micro Inc" }, + { 0xEA, "Icera Semiconductor" }, + { 0x6B, "Mediaworks Integrated Systems" }, + { 0xEC, "O'Neil Product Development" }, + { 0x6D, "Supreme Top Technology Ltd" }, + { 0x6E, "MicroDisplay Corporation" }, + { 0xEF, "Team Group Inc" }, + { 0x70, "Sinett Corporation" }, + { 0xF1, "Toshiba Corporation" }, + { 0xF2, "Tensilica" }, + { 0x73, "SiRF Technology" }, + { 0xF4, "Bacoc Inc" }, + { 0x75, "SMaL Camera Technologies" }, + { 0x76, "Thomson SC" }, + { 0xF7, "Airgo Networks" }, + { 0xF8, "Wisair Ltd" }, + { 0x79, "SigmaTel" }, + { 0x7A, "Arkados" }, + { 0xFB, "Compete IT gmbH Co KG" }, + { 0x7C, "Eudar Technology Inc" }, + { 0xFD, "Focus Enhancements" }, + { 0xFE, "Xyratex" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank6[] = { + { 0x01, "Specular Networks" }, + { 0x02, "Patriot Memory (PDP Systems)" }, + { 0x83, "U-Chip Technology Corp " }, + { 0x04, "Silicon Optix" }, + { 0x85, "Greenfield Networks" }, + { 0x86, "CompuRAM GmbH" }, + { 0x07, "Stargen Inc" }, + { 0x08, "NetCell Corporation" }, + { 0x89, "Excalibrus Technologies Ltd" }, + { 0x8A, "SCM Microsystems" }, + { 0x0B, "Xsigo Systems Inc" }, + { 0x8C, "CHIPS & Systems Inc" }, + { 0x0D, "Tier 1 Multichip Solutions" }, + { 0x0E, "CWRL Labs" }, + { 0x8F, "Teradici" }, + { 0x10, "Gigaram Inc" }, + { 0x91, "g2 Microsystems" }, + { 0x92, "PowerFlash Semiconductor" }, + { 0x13, "P.A. Semi Inc" }, + { 0x94, "NovaTech Solutions S.A. " }, + { 0x15, "c2 Microsystems Inc" }, + { 0x16, "Level5 Networks" }, + { 0x97, "COS Memory AG " }, + { 0x98, "Innovasic Semiconductor" }, + { 0x19, "02IC Co Ltd " }, + { 0x1A, "Tabula Inc" }, + { 0x9B, "Crucial Technology" }, + { 0x1C, "Chelsio Communications" }, + { 0x9D, "Solarflare Communications" }, + { 0x9E, "Xambala Inc" }, + { 0x1F, "EADS Astrium" }, + { 0x20, "Terra Semiconductor Inc" }, + { 0xA1, "Imaging Works Inc " }, + { 0xA2, "Astute Networks Inc" }, + { 0x23, "Tzero" }, + { 0xA4, "Emulex" }, + { 0x25, "Power-One" }, + { 0x26, "Pulse~LINK Inc" }, + { 0xA7, "Hon Hai Precision Industry" }, + { 0xA8, "White Rock Networks Inc" }, + { 0x29, "Telegent Systems USA Inc " }, + { 0x2A, "Atrua Technologies Inc" }, + { 0xAB, "Acbel Polytech Inc" }, + { 0x2C, "eRide Inc" }, + { 0xAD, "ULi Electronics Inc" }, + { 0xAE, "Magnum Semiconductor Inc" }, + { 0x2F, "neoOne Technology Inc" }, + { 0xB0, "Connex Technology Inc" }, + { 0x31, "Stream Processors Inc" }, + { 0x32, "Focus Enhancements" }, + { 0xB3, "Telecis Wireless Inc" }, + { 0x34, "uNav Microelectronics" }, + { 0xB5, "Tarari Inc" }, + { 0xB6, "Ambric Inc" }, + { 0x37, "Newport Media Inc" }, + { 0x38, "VMTS" }, + { 0xB9, "Enuclia Semiconductor Inc" }, + { 0xBA, "Virtium Technology Inc" }, + { 0x3B, "Solid State System Co Ltd " }, + { 0xBC, "Kian Tech LLC" }, + { 0x3D, "Artimi" }, + { 0x3E, "Power Quotient International" }, + { 0xBF, "Avago Technologies" }, + { 0x40, "ADTechnology" }, + { 0xC1, "Sigma Designs" }, + { 0xC2, "SiCortex Inc" }, + { 0x43, "Ventura Technology Group" }, + { 0xC4, "eASIC" }, + { 0x45, "M.H.S. SAS" }, + { 0x46, "Micro Star International" }, + { 0xC7, "Rapport Inc" }, + { 0xC8, "Makway International" }, + { 0x49, "Broad Reach Engineering Co" }, + { 0x4A, "Semiconductor Mfg Intl Corp" }, + { 0xCB, "SiConnect" }, + { 0x4C, "FCI USA Inc" }, + { 0xCD, "Validity Sensors" }, + { 0xCE, "Coney Technology Co Ltd" }, + { 0x4F, "Spans Logic" }, + { 0xD0, "Neterion Inc" }, + { 0x51, "Qimonda" }, + { 0x52, "New Japan Radio Co Ltd" }, + { 0xD3, "Velogix" }, + { 0x54, "Montalvo Systems" }, + { 0xD5, "iVivity Inc" }, + { 0xD6, "Walton Chaintech" }, + { 0x57, "AENEON" }, + { 0x58, "Lorom Industrial Co Ltd" }, + { 0xD9, "Radiospire Networks" }, + { 0xDA, "Sensio Technologies Inc " }, + { 0x5B, "Nethra Imaging" }, + { 0xDC, "Hexon Technology Pte Ltd" }, + { 0x5D, "CompuStocx (CSX)" }, + { 0x5E, "Methode Electronics Inc" }, + { 0xDF, "Connect One Ltd" }, + { 0xE0, "Opulan Technologies" }, + { 0x61, "Septentrio NV" }, + { 0x62, "Goldenmars Technology Inc" }, + { 0xE3, "Kreton Corporation" }, + { 0x64, "Cochlear Ltd" }, + { 0xE5, "Altair Semiconductor" }, + { 0xE6, "NetEffect Inc" }, + { 0x67, "Spansion Inc" }, + { 0x68, "Taiwan Semiconductor Mfg" }, + { 0xE9, "Emphany Systems Inc" }, + { 0xEA, "ApaceWave Technologies" }, + { 0x6B, "Mobilygen Corporation" }, + { 0xEC, "Tego" }, + { 0x6D, "Cswitch Corporation" }, + { 0x6E, "Haier (Beijing) IC Design Co" }, + { 0xEF, "MetaRAM" }, + { 0x70, "Axel Electronics Co Ltd" }, + { 0xF1, "Tilera Corporation" }, + { 0xF2, "Aquantia" }, + { 0x73, "Vivace Semiconductor" }, + { 0xF4, "Redpine Signals" }, + { 0x75, "Octalica" }, + { 0x76, "InterDigital Communications" }, + { 0xF7, "Avant Technology" }, + { 0xF8, "Asrock Inc" }, + { 0x79, "Availink" }, + { 0x7A, "Quartics Inc" }, + { 0xFB, "Element CXI" }, + { 0x7C, "Innovaciones Microelectronicas" }, + { 0xFD, "VeriSilicon Microelectronics" }, + { 0xFE, "W5 Networks" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank7[] = { + { 0x01, "MOVEKING" }, + { 0x02, "Mavrix Technology Inc" }, + { 0x83, "CellGuide Ltd" }, + { 0x04, "Faraday Technology" }, + { 0x85, "Diablo Technologies Inc" }, + { 0x86, "Jennic" }, + { 0x07, "Octasic" }, + { 0x08, "Molex Incorporated" }, + { 0x89, "3Leaf Networks" }, + { 0x8A, "Bright Micron Technology" }, + { 0x0B, "Netxen" }, + { 0x8C, "NextWave Broadband Inc" }, + { 0x0D, "DisplayLink" }, + { 0x0E, "ZMOS Technology" }, + { 0x8F, "Tec-Hill" }, + { 0x10, "Multigig Inc" }, + { 0x91, "Amimon" }, + { 0x92, "Euphonic Technologies Inc" }, + { 0x13, "BRN Phoenix" }, + { 0x94, "InSilica" }, + { 0x15, "Ember Corporation" }, + { 0x16, "Avexir Technologies Corporation" }, + { 0x97, "Echelon Corporation" }, + { 0x98, "Edgewater Computer Systems" }, + { 0x19, "XMOS Semiconductor Ltd " }, + { 0x1A, "GENUSION Inc" }, + { 0x9B, "Memory Corp NV " }, + { 0x1C, "SiliconBlue Technologies" }, + { 0x9D, "Rambus Inc" }, + { 0x9E, "Andes Technology Corporation" }, + { 0x1F, "Coronis Systems" }, + { 0x20, "Achronix Semiconductor" }, + { 0xA1, "Siano Mobile Silicon Ltd" }, + { 0xA2, "Semtech Corporation" }, + { 0x23, "Pixelworks Inc" }, + { 0xA4, "Gaisler Research AB" }, + { 0x25, "Teranetics" }, + { 0x26, "Toppan Printing Co Ltd " }, + { 0xA7, "Kingxcon" }, + { 0xA8, "Silicon Integrated Systems" }, + { 0x29, "I-O Data Device Inc" }, + { 0x2A, "NDS Americas Inc" }, + { 0xAB, "Solomon Systech Limited" }, + { 0x2C, "On Demand Microelectronics" }, + { 0xAD, "Amicus Wireless Inc" }, + { 0xAE, "SMARDTV SNC" }, + { 0x2F, "Comsys Communication Ltd" }, + { 0xB0, "Movidia Ltd" }, + { 0x31, "Javad GNSS Inc" }, + { 0x32, "Montage Technology Group" }, + { 0xB3, "Trident Microsystems" }, + { 0x34, "Super Talent" }, + { 0xB5, "Optichron Inc" }, + { 0xB6, "Future Waves UK Ltd" }, + { 0x37, "SiBEAM Inc" }, + { 0x38, "InicoreInc" }, + { 0xB9, "Virident Systems" }, + { 0xBA, "M2000 Inc" }, + { 0x3B, "ZeroG Wireless Inc" }, + { 0xBC, "Gingle Technology Co Ltd" }, + { 0x3D, "Space Micro Inc" }, + { 0x3E, "Wilocity" }, + { 0xBF, "Novafora Inc" }, + { 0x40, "iKoa Corporation" }, + { 0xC1, "ASint Technology" }, + { 0xC2, "Ramtron" }, + { 0x43, "Plato Networks Inc" }, + { 0xC4, "IPtronics AS" }, + { 0x45, "Infinite-Memories" }, + { 0x46, "Parade Technologies Inc " }, + { 0xC7, "Dune Networks" }, + { 0xC8, "GigaDevice Semiconductor" }, + { 0x49, "Modu Ltd" }, + { 0x4A, "CEITEC" }, + { 0xCB, "Northrop Grumman" }, + { 0x4C, "XRONET Corporation" }, + { 0xCD, "Sicon Semiconductor AB" }, + { 0xCE, "Atla Electronics Co Ltd" }, + { 0x4F, "TOPRAM Technology" }, + { 0xD0, "Silego Technology Inc" }, + { 0x51, "Kinglife" }, + { 0x52, "Ability Industries Ltd" }, + { 0xD3, "Silicon Power Computer & Communications" }, + { 0x54, "Augusta Technology Inc" }, + { 0xD5, "Nantronics Semiconductors" }, + { 0xD6, "Hilscher Gesellschaft" }, + { 0x57, "Quixant Ltd" }, + { 0x58, "Percello Ltd" }, + { 0xD9, "NextIO Inc" }, + { 0xDA, "Scanimetrics Inc" }, + { 0x5B, "FS-Semi Company Ltd" }, + { 0xDC, "Infinera Corporation" }, + { 0x5D, "SandForce Inc" }, + { 0x5E, "Lexar Media" }, + { 0xDF, "Teradyne Inc" }, + { 0xE0, "Memory Exchange Corp" }, + { 0x61, "Suzhou Smartek Electronics" }, + { 0x62, "Avantium Corporation" }, + { 0xE3, "ATP Electronics Inc" }, + { 0x64, "Valens Semiconductor Ltd" }, + { 0xE5, "Agate Logic Inc" }, + { 0xE6, "Netronome" }, + { 0x67, "Zenverge Inc" }, + { 0x68, "N-trig Ltd" }, + { 0xE9, "SanMax Technologies Inc" }, + { 0xEA, "Contour Semiconductor Inc" }, + { 0x6B, "TwinMOS" }, + { 0xEC, "Silicon Systems Inc" }, + { 0x6D, "V-Color Technology Inc" }, + { 0x6E, "Certicom Corporation" }, + { 0xEF, "JSC ICC Milandr" }, + { 0x70, "PhotoFast Global Inc" }, + { 0xF1, "InnoDisk Corporation" }, + { 0xF2, "Muscle Power" }, + { 0x73, "Energy Micro" }, + { 0xF4, "Innofidei" }, + { 0x75, "CopperGate Communications" }, + { 0x76, "Holtek Semiconductor Inc" }, + { 0xF7, "Myson Century Inc" }, + { 0xF8, "FIDELIX" }, + { 0x79, "Red Digital Cinema" }, + { 0x7A, "Densbits Technology" }, + { 0xFB, "Zempro" }, + { 0x7C, "MoSys" }, + { 0xFD, "Provigent" }, + { 0xFE, "Triad Semiconductor Inc" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank8[] = { + { 0x01, "Siklu Communication Ltd" }, + { 0x02, "A Force Manufacturing Ltd" }, + { 0x83, "Strontium" }, + { 0x04, "ALi Corp (Abilis Systems)" }, + { 0x85, "Siglead Inc" }, + { 0x86, "Ubicom Inc" }, + { 0x07, "Unifosa Corporation" }, + { 0x08, "Stretch Inc" }, + { 0x89, "Lantiq Deutschland GmbH" }, + { 0x8A, "Visipro." }, + { 0x0B, "EKMemory" }, + { 0x8C, "Microelectronics Institute ZTE" }, + { 0x0D, "u-blox AG" }, + { 0x0E, "Carry Technology Co Ltd" }, + { 0x8F, "Nokia" }, + { 0x10, "King Tiger Technology" }, + { 0x91, "Sierra Wireless" }, + { 0x92, "HT Micron" }, + { 0x13, "Albatron Technology Co Ltd" }, + { 0x94, "Leica Geosystems AG " }, + { 0x15, "BroadLight" }, + { 0x16, "AEXEA" }, + { 0x97, "ClariPhy Communications Inc" }, + { 0x98, "Green Plug" }, + { 0x19, "Design Art Networks" }, + { 0x1A, "Mach Xtreme Technology Ltd " }, + { 0x9B, "ATO Solutions Co Ltd" }, + { 0x1C, "Ramsta" }, + { 0x9D, "Greenliant Systems Ltd" }, + { 0x9E, "Teikon" }, + { 0x1F, "Antec Hadron" }, + { 0x20, "NavCom Technology Inc " }, + { 0xA1, "Shanghai Fudan Microelectronics" }, + { 0xA2, "Calxeda Inc" }, + { 0x23, "JSC EDC Electronics" }, + { 0xA4, "Kandit Technology Co Ltd" }, + { 0x25, "Ramos Technology" }, + { 0x26, "Goldenmars Technology" }, + { 0xA7, "XeL Technology Inc" }, + { 0xA8, "Newzone Corporation" }, + { 0x29, "ShenZhen MercyPower Tech" }, + { 0x2A, "Nanjing Yihuo Technology" }, + { 0xAB, "Nethra Imaging Inc " }, + { 0x2C, "SiTel Semiconductor BV" }, + { 0xAD, "SolidGear Corporation" }, + { 0xAE, "Topower Computer Ind Co Ltd " }, + { 0x2F, "Wilocity" }, + { 0xB0, "Profichip GmbH" }, + { 0x31, "Gerad Technologies" }, + { 0x32, "Ritek Corporation" }, + { 0xB3, "Gomos Technology Limited" }, + { 0x34, "Memoright Corporation" }, + { 0xB5, "D-Broad Inc" }, + { 0xB6, "HiSilicon Technologies" }, + { 0x37, "Syndiant Inc." }, + { 0x38, "Enverv Inc" }, + { 0xB9, "Cognex" }, + { 0xBA, "Xinnova Technology Inc" }, + { 0x3B, "Ultron AG" }, + { 0xBC, "Concord Idea Corporation" }, + { 0x3D, "AIM Corporation" }, + { 0x3E, "Lifetime Memory Products" }, + { 0xBF, "Ramsway" }, + { 0x40, "Recore Systems B.V." }, + { 0xC1, "Haotian Jinshibo Science Tech" }, + { 0xC2, "Being Advanced Memory" }, + { 0x43, "Adesto Technologies" }, + { 0xC4, "Giantec Semiconductor Inc" }, + { 0x45, "HMD Electronics AG" }, + { 0x46, "Gloway International (HK)" }, + { 0xC7, "Kingcore" }, + { 0xC8, "Anucell Technology Holding" }, + { 0x49, "Accord Software & Systems Pvt. Ltd" }, + { 0x4A, "Active-Semi Inc" }, + { 0xCB, "Denso Corporation" }, + { 0x4C, "TLSI Inc" }, + { 0xCD, "Qidan" }, + { 0xCE, "Mustang" }, + { 0x4F, "Orca Systems" }, + { 0xD0, "Passif Semiconductor" }, + { 0x51, "GigaDevice Semiconductor (Beijing) Inc" }, + { 0x52, "Memphis Electronic" }, + { 0xD3, "Beckhoff Automation GmbH" }, + { 0x54, "Harmony Semiconductor Corp" }, + { 0xD5, "Air Computers SRL" }, + { 0xD6, "TMT Memory" }, + { 0x57, "Eorex Corporation" }, + { 0x58, "Xingtera" }, + { 0xD9, "Netsol" }, + { 0xDA, "Bestdon Technology Co Ltd" }, + { 0x5B, "Baysand Inc" }, + { 0xDC, "Uroad Technology Co Ltd" }, + { 0x5D, "Wilk Elektronik S.A." }, + { 0x5E, "AAI" }, + { 0xDF, "Harman" }, + { 0xE0, "Berg Microelectronics Inc" }, + { 0x61, "ASSIA Inc" }, + { 0x62, "Visiontek Products LLC" }, + { 0xE3, "OCMEMORY" }, + { 0x64, "Welink Solution Inc" }, + { 0xE5, "Shark Gaming" }, + { 0xE6, "Avalanche Technology" }, + { 0x67, "R&D Center ELVEES OJSC" }, + { 0x68, "KingboMars Technology Co Ltd" }, + { 0xE9, "High Bridge Solutions Industria Eletronica" }, + { 0xEA, "Transcend Technology Co Ltd" }, + { 0x6B, "Everspin Technologies" }, + { 0xEC, "Hon-Hai Precision" }, + { 0x6D, "Smart Storage Systems" }, + { 0x6E, "Toumaz Group" }, + { 0xEF, "Zentel Electronics Corporation" }, + { 0x70, "Panram International Corporation" }, + { 0xF1, "Silicon Space Technology" }, + { 0xF2, "LITE-ON IT Corporation" }, + { 0x73, "Inuitive" }, + { 0xF4, "HMicro" }, + { 0x75, "BittWare Inc" }, + { 0x76, "GLOBALFOUNDRIES" }, + { 0xF7, "ACPI Digital Co Ltd" }, + { 0xF8, "Annapurna Labs" }, + { 0x79, "AcSiP Technology Corporation" }, + { 0x7A, "Idea! Electronic Systems" }, + { 0xFB, "Gowe Technology Co Ltd " }, + { 0x7C, "Hermes Testing Solutions Inc" }, + { 0xFD, "Positivo BGH" }, + { 0xFE, "Intelligence Silicon Technology" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank9[] = { + { 0x01, "3D PLUS" }, + { 0x02, "Diehl Aerospace" }, + { 0x83, "Fairchild" }, + { 0x04, "Mercury Systems" }, + { 0x85, "Sonics Inc" }, + { 0x86, "Emerson Automation Solutions" }, + { 0x07, "Shenzhen Jinge Information Co Ltd" }, + { 0x08, "SCWW" }, + { 0x89, "Silicon Motion Inc" }, + { 0x8A, "Anurag" }, + { 0x0B, "King Kong" }, + { 0x8C, "FROM30 Co Ltd" }, + { 0x0D, "Gowin Semiconductor Corp" }, + { 0x0E, "Fremont Micro Devices Ltd" }, + { 0x8F, "Ericsson Modems" }, + { 0x10, "Exelis" }, + { 0x91, "Satixfy Ltd" }, + { 0x92, "Galaxy Microsystems Ltd" }, + { 0x13, "Gloway International Co Ltd" }, + { 0x94, "Lab" }, + { 0x15, "Smart Energy Instruments" }, + { 0x16, "Approved Memory Corporation" }, + { 0x97, "Axell Corporation" }, + { 0x98, "Essencore Limited" }, + { 0x19, "Phytium" }, + { 0x1A, "Xi'an UniIC Semiconductors Co Ltd" }, + { 0x9B, "Ambiq Micro" }, + { 0x1C, "eveRAM Technology Inc" }, + { 0x9D, "Infomax" }, + { 0x9E, "Butterfly Network Inc" }, + { 0x1F, "Shenzhen City Gcai Electronics" }, + { 0x20, "Stack Devices Corporation" }, + { 0xA1, "ADK Media Group" }, + { 0xA2, "TSP Global Co Ltd" }, + { 0x23, "HighX" }, + { 0xA4, "Shenzhen Elicks Technology" }, + { 0x25, "XinKai/Silicon Kaiser" }, + { 0x26, "Google Inc" }, + { 0xA7, "Dasima International Development" }, + { 0xA8, "Leahkinn Technology Limited" }, + { 0x29, "HIMA Paul Hildebrandt GmbH Co KG" }, + { 0x2A, "Keysight Technologies" }, + { 0xAB, "Techcomp International (Fastable)" }, + { 0x2C, "Ancore Technology Corporation" }, + { 0xAD, "Nuvoton" }, + { 0xAE, "Korea Uhbele International Group Ltd" }, + { 0x2F, "Ikegami Tsushinki Co Ltd" }, + { 0xB0, "RelChip Inc" }, + { 0x31, "Baikal Electronics" }, + { 0x32, "Nemostech Inc" }, + { 0xB3, "Memorysolution GmbH" }, + { 0x34, "Silicon Integrated Systems Corporation" }, + { 0xB5, "Xiede" }, + { 0xB6, "BRC" }, + { 0x37, "Flash Chi" }, + { 0x38, "Jone" }, + { 0xB9, "GCT Semiconductor Inc" }, + { 0xBA, "Hong Kong Zetta Device Technology" }, + { 0x3B, "Unimemory Technology(s) Pte Ltd" }, + { 0xBC, "Cuso" }, + { 0x3D, "Kuso" }, + { 0x3E, "Uniquify Inc" }, + { 0xBF, "Skymedi Corporation" }, + { 0x40, "Core Chance Co Ltd" }, + { 0xC1, "Tekism Co Ltd" }, + { 0xC2, "Seagate Technology PLC" }, + { 0x43, "Hong Kong Gaia Group Co Limited" }, + { 0xC4, "Gigacom Semiconductor LLC" }, + { 0x45, "V2 Technologies" }, + { 0x46, "TLi" }, + { 0xC7, "Neotion" }, + { 0xC8, "Lenovo" }, + { 0x49, "Shenzhen Zhongteng Electronic Corp Ltd" }, + { 0x4A, "Compound Photonics" }, + { 0xCB, "in2H2 inc" }, + { 0x4C, "Shenzhen Pango Microsystems Co Ltd" }, + { 0xCD, "Vasekey" }, + { 0xCE, "Cal-Comp Industria de Semicondutores" }, + { 0x4F, "Eyenix Co Ltd" }, + { 0xD0, "Heoriady" }, + { 0x51, "Accelerated Memory Production Inc" }, + { 0x52, "INVECAS Inc" }, + { 0xD3, "AP Memory" }, + { 0x54, "Douqi Technology" }, + { 0xD5, "Etron Technology Inc" }, + { 0xD6, "Indie Semiconductor" }, + { 0x57, "Socionext Inc" }, + { 0x58, "HGST" }, + { 0xD9, "EVGA" }, + { 0xDA, "Audience Inc" }, + { 0x5B, "EpicGear" }, + { 0xDC, "Vitesse Enterprise Co" }, + { 0x5D, "Foxtronn International Corporation" }, + { 0x5E, "Bretelon Inc" }, + { 0xDF, "Graphcore" }, + { 0xE0, "Eoplex Inc" }, + { 0x61, "MaxLinear Inc" }, + { 0x62, "ETA Devices" }, + { 0xE3, "LOKI" }, + { 0x64, "IMS Electronics Co Ltd" }, + { 0xE5, "Dosilicon Co Ltd" }, + { 0xE6, "Dolphin Integration" }, + { 0x67, "Shenzhen Mic Electronics Technolog" }, + { 0x68, "Boya Microelectronics Inc" }, + { 0xE9, "Geniachip (Roche)" }, + { 0xEA, "Axign" }, + { 0x6B, "Kingred Electronic Technology Ltd" }, + { 0xEC, "Chao Yue Zhuo Computer Business Dept." }, + { 0x6D, "Guangzhou Si Nuo Electronic Technology." }, + { 0x6E, "Crocus Technology Inc" }, + { 0xEF, "Creative Chips GmbH" }, + { 0x70, "GE Aviation Systems LLC." }, + { 0xF1, "Asgard" }, + { 0xF2, "Good Wealth Technology Ltd" }, + { 0x73, "TriCor Technologies" }, + { 0xF4, "Nova-Systems GmbH" }, + { 0x75, "JUHOR" }, + { 0x76, "Zhuhai Douke Commerce Co Ltd" }, + { 0xF7, "DSL Memory" }, + { 0xF8, "Anvo-Systems Dresden GmbH" }, + { 0x79, "Realtek" }, + { 0x7A, "AltoBeam" }, + { 0xFB, "Wave Computing" }, + { 0x7C, "Beijing TrustNet Technology Co Ltd" }, + { 0xFD, "Innovium Inc" }, + { 0xFE, "Starsway Technology Limited" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank10[] = { + { 0x01, "Weltronics Co LTD" }, + { 0x02, "VMware Inc" }, + { 0x83, "Hewlett Packard Enterprise" }, + { 0x04, "INTENSO" }, + { 0x85, "Puya Semiconductor" }, + { 0x86, "MEMORFI" }, + { 0x07, "MSC Technologies GmbH" }, + { 0x08, "Txrui" }, + { 0x89, "SiFive Inc" }, + { 0x8A, "Spreadtrum Communications" }, + { 0x0B, "XTX Technology Limited" }, + { 0x8C, "UMAX Technology" }, + { 0x0D, "Shenzhen Yong Sheng Technology" }, + { 0x0E, "SNOAMOO (Shenzhen Kai Zhuo Yue)" }, + { 0x8F, "Daten Tecnologia LTDA" }, + { 0x10, "Shenzhen XinRuiYan Electronics" }, + { 0x91, "Eta Compute" }, + { 0x92, "Energous" }, + { 0x13, "Raspberry Pi Trading Ltd" }, + { 0x94, "Shenzhen Chixingzhe Tech Co Ltd" }, + { 0x15, "Silicon Mobility" }, + { 0x16, "IQ-Analog Corporation" }, + { 0x97, "Uhnder Inc" }, + { 0x98, "Impinj" }, + { 0x19, "DEPO Computers" }, + { 0x1A, "Nespeed Sysems" }, + { 0x9B, "Yangtze Memory Technologies Co Ltd" }, + { 0x1C, "MemxPro Inc" }, + { 0x9D, "Tammuz Co Ltd" }, + { 0x9E, "Allwinner Technology" }, + { 0x1F, "Shenzhen City Futian District Qing Xuan Tong Computer Trading Firm" }, + { 0x20, "XMC" }, + { 0xA1, "Teclast" }, + { 0xA2, "Maxsun" }, + { 0x23, "Haiguang Integrated Circuit Design" }, + { 0xA4, "RamCENTER Technology" }, + { 0x25, "Phison Electronics Corporation" }, + { 0x26, "Guizhou Huaxintong Semi-Conductor" }, + { 0xA7, "Network Intelligence" }, + { 0xA8, "Continental Technology (Holdings)" }, + { 0x29, "Guangzhou Huayan Suning Electronic" }, + { 0x2A, "Guangzhou Zhouji Electronic Co Ltd" }, + { 0xAB, "Shenzhen Giant Hui Kang Tech Co Ltd" }, + { 0x2C, "Shenzhen Yilong Innovative Co Ltd" }, + { 0xAD, "Neo Forza" }, + { 0xAE, "Lyontek Inc" }, + { 0x2F, "Shanghai Kuxin Microelectronics Ltd" }, + { 0xB0, "Shenzhen Larix Technology Co Ltd " }, + { 0x31, "Qbit Semiconductor Ltd" }, + { 0x32, "Insignis Technology Corporation" }, + { 0xB3, "Lanson Memory Co Ltd" }, + { 0x34, "Shenzhen Superway Electronics Co Ltd" }, + { 0xB5, "Canaan-Creative Co Ltd" }, + { 0xB6, "Black Diamond Memory" }, + { 0x37, "Shenzhen City Parker Baking Electronics" }, + { 0x38, "Shenzhen Baihong Technology Co Ltd" }, + { 0xB9, "GEO Semiconductors" }, + { 0xBA, "OCPC" }, + { 0x3B, "Artery Technology Co Ltd" }, + { 0xBC, "Jinyu" }, + { 0x3D, "ShenzhenYing Chi Technology Development" }, + { 0x3E, "Shenzhen Pengcheng Xin Technology" }, + { 0xBF, "Pegasus Semiconductor (Shanghai) Co" }, + { 0x40, "Mythic Inc" }, + { 0xC1, "Elmos Semiconductor AG" }, + { 0xC2, "Kllisre" }, + { 0x43, "Shenzhen Winconway Technology" }, + { 0xC4, "Shenzhen Xingmem Technology Corp" }, + { 0x45, "Gold Key Technology Co Ltd" }, + { 0x46, "Habana Labs Ltd" }, + { 0xC7, "Hoodisk Electronics Co Ltd" }, + { 0xC8, "SemsoTai (SZ) Technology Co Ltd" }, + { 0x49, "OM Nanotech Pvt. Ltd" }, + { 0x4A, "Shenzhen Zhifeng Weiye Technology" }, + { 0xCB, "Xinshirui (Shenzhen) Electronics Co" }, + { 0x4C, "Guangzhou Zhong Hao Tian Electronic" }, + { 0xCD, "Shenzhen Longsys Electronics Co Ltd" }, + { 0xCE, "Deciso B.V." }, + { 0x4F, "Puya Semiconductor (Shenzhen)" }, + { 0xD0, "Shenzhen Veineda Technology Co Ltd" }, + { 0x51, "Antec Memory" }, + { 0x52, "Cortus SAS" }, + { 0xD3, "Dust Leopard" }, + { 0x54, "MyWo AS" }, + { 0xD5, "J&A Information Inc" }, + { 0xD6, "Shenzhen JIEPEI Technology Co Ltd" }, + { 0x57, "Heidelberg University" }, + { 0x58, "Flexxon PTE Ltd" }, + { 0xD9, "Wiliot" }, + { 0xDA, "Raysun Electronics International Ltd" }, + { 0x5B, "Aquarius Production Company LLC" }, + { 0xDC, "MACNICA DHW LTDA" }, + { 0x5D, "Intelimem" }, + { 0x5E, "Zbit Semiconductor Inc" }, + { 0xDF, "Shenzhen Technology Co Ltd" }, + { 0xE0, "Signalchip" }, + { 0x61, "Shenzen Recadata Storage Technology" }, + { 0x62, "Hyundai Technology" }, + { 0xE3, "Shanghai Fudi Investment Development" }, + { 0x64, "Aixi Technology" }, + { 0xE5, "Tecon MT" }, + { 0xE6, "Onda Electric Co Ltd" }, + { 0x67, "Jinshen" }, + { 0x68, "Kimtigo Semiconductor (HK) Limited" }, + { 0xE9, "IIT Madras" }, + { 0xEA, "Shenshan (Shenzhen) Electronic" }, + { 0x6B, "Hefei Core Storage Electronic Limited" }, + { 0xEC, "Colorful Technology Ltd" }, + { 0x6D, "Visenta (Xiamen) Technology Co Ltd" }, + { 0x6E, "Roa Logic BV" }, + { 0xEF, "NSITEXE Inc" }, + { 0x70, "Hong Kong Hyunion Electronics" }, + { 0xF1, "ASK Technology Group Limited" }, + { 0xF2, "GIGA-BYTE Technology Co Ltd" }, + { 0x73, "Terabyte Co Ltd" }, + { 0xF4, "Hyundai Inc" }, + { 0x75, "EXCELERAM" }, + { 0x76, "PsiKick" }, + { 0xF7, "Netac Technology Co Ltd" }, + { 0xF8, "PCCOOLER" }, + { 0x79, "Jiangsu Huacun Electronic Technology" }, + { 0x7A, "Shenzhen Micro Innovation Industry" }, + { 0xFB, "Beijing Tongfang Microelectronics Co" }, + { 0x7C, "XZN Storage Technology" }, + { 0xFD, "ChipCraft Sp. z.o.o." }, + { 0xFE, "ALLFLASH Technology Limited" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank11[] = { + { 0x01, "Foerd Technology Co Ltd" }, + { 0x02, "KingSpec" }, + { 0x83, "Codasip GmbH" }, + { 0x04, "SL Link Co Ltd" }, + { 0x85, "Shenzhen Kefu Technology Co Limited" }, + { 0x86, "Shenzhen ZST Electronics Technology" }, + { 0x07, "Kyokuto Electronic Inc" }, + { 0x08, "Warrior Technology" }, + { 0x89, "TRINAMIC Motion Control GmbH & Co" }, + { 0x8A, "PixelDisplay Inc" }, + { 0x0B, "Shenzhen Futian District Bo Yueda Elec" }, + { 0x8C, "Richtek Power" }, + { 0x0D, "Shenzhen LianTeng Electronics Co Ltd" }, + { 0x0E, "AITC Memory" }, + { 0x8F, "UNIC Memory Technology Co Ltd" }, + { 0x10, "Shenzhen Huafeng Science Technology" }, + { 0x91, "CXMT" }, + { 0x92, "Guangzhou Xinyi Heng Computer Trading Firm" }, + { 0x13, "SambaNova Systems" }, + { 0x94, "V-GEN" }, + { 0x15, "Jump Trading" }, + { 0x16, "Ampere Computing" }, + { 0x97, "Shenzhen Zhongshi Technology Co Ltd" }, + { 0x98, "Shenzhen Zhongtian Bozhong Technology" }, + { 0x19, "Tri-Tech International" }, + { 0x1A, "Silicon Intergrated Systems Corporation" }, + { 0x9B, "Shenzhen HongDingChen Information" }, + { 0x1C, "Plexton Holdings Limited" }, + { 0x9D, "AMS (Jiangsu Advanced Memory Semi)" }, + { 0x9E, "Wuhan Jing Tian Interconnected Tech Co" }, + { 0x1F, "Axia Memory Technology" }, + { 0x20, "Chipset Technology Holding Limited" }, + { 0xA1, "Shenzhen Xinshida Technology Co Ltd" }, + { 0xA2, "Shenzhen Chuangshifeida Technology" }, + { 0x23, "Guangzhou MiaoYuanJi Technology" }, + { 0xA4, "ADVAN Inc" }, + { 0x25, "Shenzhen Qianhai Weishengda Electronic Commerce Company Ltd" }, + { 0x26, "Guangzhou Guang Xie Cheng Trading" }, + { 0xA7, "StarRam International Co Ltd" }, + { 0xA8, "Shen Zhen XinShenHua Tech Co Ltd" }, + { 0x29, "UltraMemory Inc" }, + { 0x2A, "New Coastline Global Tech Industry Co" }, + { 0xAB, "Sinker" }, + { 0x2C, "Diamond" }, + { 0xAD, "PUSKILL" }, + { 0xAE, "Guangzhou Hao Jia Ye Technology Co" }, + { 0x2F, "Ming Xin Limited" }, + { 0xB0, "Barefoot Networks" }, + { 0x31, "Biwin Semiconductor (HK) Co Ltd" }, + { 0x32, "UD INFO Corporation" }, + { 0xB3, "Trek Technology (S) PTE Ltd" }, + { 0x34, "Xiamen Kingblaze Technology Co Ltd" }, + { 0xB5, "Shenzhen Lomica Technology Co Ltd" }, + { 0xB6, "Nuclei System Technology Co Ltd" }, + { 0x37, "Wuhan Xun Zhan Electronic Technology" }, + { 0x38, "Shenzhen Ingacom Semiconductor Ltd" }, + { 0xB9, "Zotac Technology Ltd" }, + { 0xBA, "Foxline" }, + { 0x3B, "Shenzhen Farasia Science Technology" }, + { 0xBC, "Efinix Inc" }, + { 0x3D, "Hua Nan San Xian Technology Co Ltd" }, + { 0x3E, "Goldtech Electronics Co Ltd" }, + { 0xBF, "Shanghai Han Rong Microelectronics Co" }, + { 0x40, "Shenzhen Zhongguang Yunhe Trading" }, + { 0xC1, "Smart Shine(QingDao) Microelectronics" }, + { 0xC2, "Thermaltake Technology Co Ltd" }, + { 0x43, "Shenzhen O'Yang Maile Technology Ltd" }, + { 0xC4, "UPMEM" }, + { 0x45, "Chun Well Technology Holding Limited" }, + { 0x46, "Astera Labs Inc" }, + { 0xC7, "Winconway" }, + { 0xC8, "Advantech Co Ltd" }, + { 0x49, "Chengdu Fengcai Electronic Technology" }, + { 0x4A, "The Boeing Company" }, + { 0xCB, "Blaize Inc" }, + { 0x4C, "Ramonster Technology Co Ltd" }, + { 0xCD, "Wuhan Naonongmai Technology Co Ltd" }, + { 0xCE, "Shenzhen Hui ShingTong Technology" }, + { 0x4F, "Yourlyon" }, + { 0xD0, "Fabu Technology" }, + { 0x51, "Shenzhen Yikesheng Technology Co Ltd" }, + { 0x52, "NOR-MEM" }, + { 0xD3, "Cervoz Co Ltd" }, + { 0x54, "Bitmain Technologies Inc." }, + { 0xD5, "Facebook Inc" }, + { 0xD6, "Shenzhen Longsys Electronics Co Ltd" }, + { 0x57, "Guangzhou Siye Electronic Technology" }, + { 0x58, "Silergy" }, + { 0xD9, "Adamway" }, + { 0xDA, "PZG" }, + { 0x5B, "Shenzhen King Power Electronics" }, + { 0xDC, "Guangzhou ZiaoFu Tranding Co Ltd" }, + { 0x5D, "Shenzhen SKIHOTAR Semiconductor" }, + { 0x5E, "PulseRain Technology" }, + { 0xDF, "Seeker Technology Limited" }, + { 0xE0, "Shenzhen OSCOO Tech Co Ltd" }, + { 0x61, "Shenzhen Yze Technology Co Ltd" }, + { 0x62, "Shenzhen Jieshuo Electronic Commerce" }, + { 0xE3, "Gazda" }, + { 0x64, "Hua Wei Technology Co Ltd" }, + { 0xE5, "Esperanto Technologies" }, + { 0xE6, "JinSheng Electronic (Shenzhen) Co Ltd" }, + { 0x67, "Shenzhen Shi Bolunshuai Technology" }, + { 0x68, "Shanghai Rei Zuan Information Tech" }, + { 0xE9, "Fraunhofer IIS" }, + { 0xEA, "Kandou Bus SA" }, + { 0x6B, "Acer" }, + { 0xEC, "Artmem Technology Co Ltd" }, + { 0x6D, "Gstar Semiconductor Co Ltd" }, + { 0x6E, "ShineDisk" }, + { 0xEF, "Shenzhen CHN Technology Co Ltd" }, + { 0x70, "UnionChip Semiconductor Co Ltd" }, + { 0xF1, "Tanbassh" }, + { 0xF2, "Shenzhen Tianyu Jieyun Intl Logistics" }, + { 0x73, "MCLogic Inc" }, + { 0xF4, "Eorex Corporation" }, + { 0x75, "Arm Technology (China) Co Ltd" }, + { 0x76, "Lexar Co Limited" }, + { 0xF7, "QinetiQ Group plc" }, + { 0xF8, "Exascend" }, + { 0x79, "Hong Kong Hyunion Electronics Co Ltd" }, + { 0x7A, "Shenzhen Banghong Electronics Co Ltd" }, + { 0xFB, "MBit Wireless Inc" }, + { 0x7C, "Hex Five Security Inc" }, + { 0xFD, "ShenZhen Juhor Precision Tech Co Ltd" }, + { 0xFE, "Shenzhen Reeinno Technology Co Ltd" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank12[] = { + { 0x01, "ABIT Electronics (Shenzhen) Co Ltd" }, + { 0x02, "Semidrive" }, + { 0x83, "MyTek Electronics Corp" }, + { 0x04, "Wxilicon Technology Co Ltd" }, + { 0x85, "Shenzhen Meixin Electronics Ltd" }, + { 0x86, "Ghost Wolf" }, + { 0x07, "LiSion Technologies Inc" }, + { 0x08, "Power Active Co Ltd" }, + { 0x89, "Pioneer High Fidelity Taiwan Co. Ltd" }, + { 0x8A, "LuoSilk" }, + { 0x0B, "Shenzhen Chuangshifeida Technology" }, + { 0x8C, "Black Sesame Technologies Inc" }, + { 0x0D, "Jiangsu Xinsheng Intelligent Technology" }, + { 0x0E, "MLOONG" }, + { 0x8F, "Quadratica LLC" }, + { 0x10, "Anpec Electronics" }, + { 0x91, "Xi'an Morebeck Semiconductor Tech Co" }, + { 0x92, "Kingbank Technology Co Ltd" }, + { 0x13, "ITRenew Inc" }, + { 0x94, "Shenzhen Eaget Innovation Tech Ltd" }, + { 0x15, "Jazer" }, + { 0x16, "Xiamen Semiconductor Investment Group" }, + { 0x97, "Guangzhou Longdao Network Tech Co" }, + { 0x98, "Shenzhen Futian SEC Electronic Market" }, + { 0x19, "Allegro Microsystems LLC" }, + { 0x1A, "Hunan RunCore Innovation Technology" }, + { 0x9B, "C-Corsa Technology" }, + { 0x1C, "Zhuhai Chuangfeixin Technology Co Ltd" }, + { 0x9D, "Beijing InnoMem Technologies Co Ltd" }, + { 0x9E, "YooTin" }, + { 0x1F, "Shenzhen Pengxiong Technology Co Ltd" }, + { 0x20, "Dongguan Yingbang Commercial Trading Co" }, + { 0xA1, "Shenzhen Ronisys Electronics Co Ltd" }, + { 0xA2, "Hongkong Xinlan Guangke Co Ltd" }, + { 0x23, "Apex Microelectronics Co Ltd" }, + { 0xA4, "Beijing Hongda Jinming Technology Co Ltd" }, + { 0x25, "Ling Rui Technology (Shenzhen) Co Ltd" }, + { 0x26, "Hongkong Hyunion Electronics Co Ltd" }, + { 0xA7, "Starsystems Inc" }, + { 0xA8, "Shenzhen Yingjiaxun Industrial Co Ltd" }, + { 0x29, "Dongguan Crown Code Electronic Commerce" }, + { 0x2A, "Monolithic Power Systems Inc" }, + { 0xAB, "WuHan SenNaiBo E-Commerce Co Ltd" }, + { 0x2C, "Hangzhou Hikstorage Technology Co" }, + { 0xAD, "Shenzhen Goodix Technology Co Ltd" }, + { 0xAE, "Aigo Electronic Technology Co Ltd" }, + { 0x2F, "Hefei Konsemi Storage Technology Co Ltd" }, + { 0xB0, "Cactus Technologies Limited" }, + { 0x31, "DSIN" }, + { 0x32, "Blu Wireless Technology" }, + { 0xB3, "Nanjing UCUN Technology Inc" }, + { 0x34, "Acacia Communications" }, + { 0xB5, "Beijinjinshengyihe Technology Co Ltd" }, + { 0xB6, "Zyzyx" }, + { 0x37, "-HEAD Semiconductor Co Ltd" }, + { 0x38, "Shenzhen Hystou Technology Co Ltd" }, + { 0xB9, "Syzexion" }, + { 0xBA, "Kembona" }, + { 0x3B, "Qingdao Thunderobot Technology Co Ltd" }, + { 0xBC, "Morse Micro" }, + { 0x3D, "Shenzhen Envida Technology Co Ltd" }, + { 0x3E, "UDStore Solution Limited" }, + { 0xBF, "Shunlie" }, + { 0x40, "Shenzhen Xin Hong Rui Tech Ltd" }, + { 0xC1, "Shenzhen Yze Technology Co Ltd" }, + { 0xC2, "Shenzhen Huang Pu He Xin Technology" }, + { 0x43, "Xiamen Pengpai Microelectronics Co Ltd" }, + { 0xC4, "JISHUN" }, + { 0x45, "Shenzhen WODPOSIT Technology Co" }, + { 0x46, "Unistar" }, + { 0xC7, "UNICORE Electronic (Suzhou) Co Ltd" }, + { 0xC8, "Axonne Inc" }, + { 0x49, "Shenzhen SOVERECA Technology Co" }, + { 0x4A, "Dire Wolf" }, + { 0xCB, "Whampoa Core Technology Co Ltd" }, + { 0x4C, "CSI Halbleiter GmbH" }, + { 0xCD, "ONE Semiconductor" }, + { 0xCE, "SimpleMachines Inc" }, + { 0x4F, "Shenzhen Chengyi Qingdian Electronic" }, + { 0xD0, "Shenzhen Xinlianxin Network Technology" }, + { 0x51, "Vayyar Imaging Ltd" }, + { 0x52, "Paisen Network Technology Co Ltd" }, + { 0xD3, "Shenzhen Fengwensi Technology Co Ltd" }, + { 0x54, "Caplink Technology Limited" }, + { 0xD5, "JJT Solution Co Ltd" }, + { 0xD6, "HOSIN Global Electronics Co Ltd" }, + { 0x57, "Shenzhen KingDisk Century Technology" }, + { 0x58, "SOYO" }, + { 0xD9, "DIT Technology Co Ltd" }, + { 0xDA, "iFound" }, + { 0x5B, "Aril Computer Company" }, + { 0xDC, "ASUS" }, + { 0x5D, "Shenzhen Ruiyingtong Technology Co" }, + { 0x5E, "HANA Micron" }, + { 0xDF, "RANSOR" }, + { 0xE0, "Axiado Corporation" }, + { 0x61, "Tesla Corporation" }, + { 0x62, "Pingtouge (Shanghai) Semiconductor Co" }, + { 0xE3, "S3Plus Technologies SA" }, + { 0x64, "Integrated Silicon Solution Israel Ltd" }, + { 0xE5, "GreenWaves Technologies" }, + { 0xE6, "NUVIA Inc" }, + { 0x67, "Guangzhou Shuvrwine Technology Co" }, + { 0x68, "Shenzhen Hangshun Chip Technology" }, + { 0xE9, "Chengboliwei Electronic Business" }, + { 0xEA, "Kowin Memory Technology Co Ltd" }, + { 0x6B, "Euronet Technology Inc" }, + { 0xEC, "SCY" }, + { 0x6D, "Shenzhen Xinhongyusheng Electrical" }, + { 0x6E, "PICOCOM" }, + { 0xEF, "Shenzhen Toooogo Memory Technology" }, + { 0x70, "VLSI Solution" }, + { 0xF1, "Costar Electronics Inc" }, + { 0xF2, "Shenzhen Huatop Technology Co Ltd" }, + { 0x73, "Inspur Electronic Information Industry" }, + { 0xF4, "Shenzhen Boyuan Computer Technology" }, + { 0x75, "Beijing Welldisk Electronics Co Ltd" }, + { 0x76, "Suzhou EP Semicon Co Ltd" }, + { 0xF7, "Zhejiang Dahua Memory Technology" }, + { 0xF8, "Virtu Financial" }, + { 0x79, "Datotek International Co Ltd" }, + { 0x7A, "Telecom and Microelectronics Industries" }, + { 0xFB, "Echow Technology Ltd" }, + { 0x7C, "APEX-INFO" }, + { 0xFD, "Yingpark" }, + { 0xFE, "Shenzhen Bigway Tech Co Ltd" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank13[] = { + { 0x01, "Beijing Haawking Technology Co Ltd" }, + { 0x02, "Open HW Group" }, + { 0x83, "HICC" }, + { 0x04, "ncoder AG" }, + { 0x85, "ThinkTech Information Technology Co" }, + { 0x86, "Shenzhen Chixingzhe Technology Co Ltd" }, + { 0x07, "Biao Ram Technology Co Ltd" }, + { 0x08, "Shenzhen Kaizhuoyue Electronics Co Ltd" }, + { 0x89, "Shenzhen YC Storage Technology Co Ltd" }, + { 0x8A, "Shenzhen Chixingzhe Technology Co" }, + { 0x0B, "Wink Semiconductor (Shenzhen) Co Ltd" }, + { 0x8C, "AISTOR" }, + { 0x0D, "Palma Ceia SemiDesign" }, + { 0x0E, "EM Microelectronic-Marin SA" }, + { 0x8F, "Shenzhen Monarch Memory Technology" }, + { 0x10, "Reliance Memory Inc" }, + { 0x91, "Jesis" }, + { 0x92, "Espressif Systems (Shanghai) Co Ltd" }, + { 0x13, "Shenzhen Sati Smart Technology Co Ltd" }, + { 0x94, "NeuMem Co Ltd" }, + { 0x15, "Lifelong" }, + { 0x16, "Beijing Oitech Technology Co Ltd" }, + { 0x97, "Groupe LDLC" }, + { 0x98, "Semidynamics Technology Services SLU" }, + { 0x19, "swordbill" }, + { 0x1A, "YIREN" }, + { 0x9B, "Shenzhen Yinxiang Technology Co Ltd" }, + { 0x1C, "PoweV Electronic Technology Co Ltd" }, + { 0x9D, "LEORICE" }, + { 0x9E, "Waymo LLC" }, + { 0x1F, "Ventana Micro Systems" }, + { 0x20, "Hefei Guangxin Microelectronics Co Ltd" }, + { 0xA1, "Shenzhen Sooner Industrial Co Ltd" }, + { 0xA2, "Horizon Robotics" }, + { 0x23, "Tangem AG" }, + { 0xA4, "FuturePath Technology (Shenzhen) Co" }, + { 0x25, "RC Module" }, + { 0x26, "Timetec International Inc" }, + { 0xA7, "ICMAX Technologies Co Limited" }, + { 0xA8, "Lynxi Technologies Ltd Co" }, + { 0x29, "Guangzhou Taisupanke Computer Equipment" }, + { 0x2A, "Ceremorphic Inc" }, + { 0xAB, "Biwin Storage Technology Co Ltd" }, + { 0x2C, "Beijing ESWIN Computing Technology" }, + { 0xAD, "WeForce Co Ltd" }, + { 0xAE, "Shenzhen Fanxiang Information Technology" }, + { 0x2F, "Unisoc" }, + { 0xB0, "YingChu" }, + { 0x31, "GUANCUN" }, + { 0x32, "IPASON" }, + { 0xB3, "Ayar Labs" }, + { 0x34, "Amazon" }, + { 0xB5, "Shenzhen Xinxinshun Technology Co" }, + { 0xB6, "Galois Inc" }, + { 0x37, "Ubilite Inc" }, + { 0x38, "Shenzhen Quanxing Technology Co Ltd" }, + { 0xB9, "Group RZX Technology LTDA" }, + { 0xBA, "Yottac Technology (XI'AN) Cooperation" }, + { 0x3B, "Shenzhen RuiRen Technology Co Ltd" }, + { 0xBC, "Group Star Technology Co Ltd" }, + { 0x3D, "RWA (Hong Kong) Ltd" }, + { 0x3E, "Genesys Logic Inc" }, + { 0xBF, "T3 Robotics Inc." }, + { 0x40, "Biostar Microtech International Corp" }, + { 0xC1, "Shenzhen SXmicro Technology Co Ltd" }, + { 0xC2, "Shanghai Yili Computer Technology Co" }, + { 0x43, "Zhixin Semicoducotor Co Ltd" }, + { 0xC4, "uFound" }, + { 0x45, "Aigo Data Security Technology Co. Ltd" }, + { 0x46, ".GXore Technologies" }, + { 0xC7, "Shenzhen Pradeon Intelligent Technology" }, + { 0xC8, "Power LSI" }, + { 0x49, "PRIME" }, + { 0x4A, "Shenzhen Juyang Innovative Technology" }, + { 0xCB, "CERVO" }, + { 0x4C, "SiEngine Technology Co., Ltd." }, + { 0xCD, "Beijing Unigroup Tsingteng MicroSystem" }, + { 0xCE, "Brainsao GmbH" }, + { 0x4F, "Credo Technology Group Ltd" }, + { 0xD0, "Shanghai Biren Technology Co Ltd" }, + { 0x51, "Nucleu Semiconductor" }, + { 0x52, "Shenzhen Guangshuo Electronics Co Ltd" }, + { 0xD3, "ZhongsihangTechnology Co Ltd" }, + { 0x54, "Suzhou Mainshine Electronic Co Ltd." }, + { 0xD5, "Guangzhou Riss Electronic Technology" }, + { 0xD6, "Shenzhen Cloud Security Storage Co" }, + { 0x57, "ROG" }, + { 0x58, "Perceive" }, + { 0xD9, "e-peas" }, + { 0xDA, "Fraunhofer IPMS" }, + { 0x5B, "Shenzhen Daxinlang Electronic Tech Co" }, + { 0xDC, "Abacus Peripherals Private Limited" }, + { 0x5D, "OLOy Technology" }, + { 0x5E, "Wuhan P&S Semiconductor Co Ltd" }, + { 0xDF, "Sitrus Technology" }, + { 0xE0, "AnHui Conner Storage Co Ltd" }, + { 0x61, "Rochester Electronics" }, + { 0x62, "Wuxi Petabyte Technologies Co Ltd" }, + { 0xE3, "Star Memory" }, + { 0x64, "Agile Memory Technology Co Ltd" }, + { 0xE5, "MEJEC" }, + { 0xE6, "Rockchip Electronics Co Ltd" }, + { 0x67, "Dongguan Guanma e-commerce Co Ltd" }, + { 0x68, "Rayson Hi-Tech (SZ) Limited" }, + { 0xE9, "MINRES Technologies GmbH" }, + { 0xEA, "Himax Technologies Inc" }, + { 0x6B, "Shenzhen Cwinner Technology Co Ltd" }, + { 0xEC, "Tecmiyo" }, + { 0x6D, "Shenzhen Suhuicun Technology Co Ltd " }, + { 0x6E, "Vickter Electronics Co. Ltd." }, + { 0xEF, "lowRISC" }, + { 0x70, "EXEGate FZE" }, + { 0xF1, "Shenzhen 9 Chapter Technologies Co" }, + { 0xF2, "Addlink" }, + { 0x73, "Starsway" }, + { 0xF4, "Pensando Systems Inc." }, + { 0x75, "AirDisk" }, + { 0x76, "Shenzhen Speedmobile Technology Co" }, + { 0xF7, "PEZY Computing" }, + { 0xF8, "Extreme Engineering Solutions Inc" }, + { 0x79, "Shangxin Technology Co Ltd" }, + { 0x7A, "Shanghai Zhaoxin Semiconductor Co" }, + { 0xFB, "Xsight Labs Ltd" }, + { 0x7C, "Hangzhou Hikstorage Technology Co" }, + { 0xFD, "Dell Technologies" }, + { 0xFE, "Guangdong StarFive Technology Co" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS Jep106ManufacturersBank14[] = { + { 0x01, "TECOTON" }, + { 0x02, "Abko Co Ltd" }, + { 0x83, "Shenzhen Feisrike Technology Co Ltd" }, + { 0x04, "Shenzhen Sunhome Electronics Co Ltd" }, + { 0x85, "Global Mixed-mode Technology Inc" }, + { 0x86, "Shenzhen Weien Electronics Co. Ltd." }, + { 0x07, "Shenzhen Cooyes Technology Co Ltd" }, + { 0x08, "Keymos Electronics Co., Limited" }, + { 0x89, "E-Rockic Technology Company Limited" }, + { 0x8A, "Aerospace Science Memory Shenzhen" }, + { 0x0B, "Shenzhen Quanji Technology Co Ltd" }, + { 0x8C, "Dukosi" }, + { 0x0D, "Maxell Corporation of America" }, + { 0x0E, "Shenshen Xinxintao Electronics Co Ltd" }, + { 0x8F, "Zhuhai Sanxia Semiconductor Co Ltd" }, + { 0x10, "Groq Inc" }, + { 0x91, "AstraTek" }, + { 0x92, "Shenzhen Xinyuze Technology Co Ltd" }, + { 0x13, "All Bit Semiconductor" }, + { 0x94, "ACFlow" }, + { 0x15, "Shenzhen Sipeed Technology Co Ltd" }, + { 0x16, "Linzhi Hong Kong Co Limited" }, + { 0x97, "Supreme Wise Limited" }, + { 0x98, "Blue Cheetah Analog Design Inc" }, + { 0x19, "Hefei Laiku Technology Co Ltd" }, + { 0x1A, "Zord" }, + { 0x9B, "SBO Hearing A/S" }, + { 0x1C, "Regent Sharp International Limited" }, + { 0x9D, "Permanent Potential Limited" }, + { 0x9E, "Creative World International Limited" }, + { 0x1F, "Base Creation International Limited" }, + { 0x20, "Shenzhen Zhixin Chuanglian Technology" }, + { 0xA1, "Protected Logic Corporation" }, + { 0xA2, "Sabrent" }, + { 0x23, "Union Memory" }, + { 0xA4, "NEUCHIPS Corporation" }, + { 0x25, "Ingenic Semiconductor Co Ltd" }, + { 0x26, "SiPearl" }, + { 0xA7, "Shenzhen Actseno Information Technology" }, + { 0xA8, "RIVAI Technologies (Shenzhen) Co Ltd" }, + { 0x29, "Shenzhen Sunny Technology Co Ltd" }, + { 0x2A, "Cott Electronics Ltd" }, + { 0xAB, "Shanghai Synsense Technologies Co Ltd" }, + { 0x2C, "Shenzhen Jintang Fuming Optoelectronics" }, + { 0xAD, "CloudBEAR LLC" }, + { 0xAE, "Emzior, LLC" }, + { 0x2F, "Ehiway Microelectronic Science Tech Co" }, + { 0xB0, "UNIM Innovation Technology (Wu XI)" }, + { 0x31, "GDRAMARS" }, + { 0x32, "Meminsights Technology" }, + { 0xB3, "Zhuzhou Hongda Electronics Corp Ltd" }, + { 0x34, "Luminous Computing Inc" }, + { 0xB5, "PROXMEM" }, + { 0xB6, "Draper Labs" }, + { 0x37, "ORICO Technologies Co. Ltd." }, + { 0x38, "Space Exploration Technologies Corp" }, + { 0xB9, "AONDEVICES Inc" }, + { 0xFF, "" } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED +STATIC CONST JEDEC_MANUFACTURERS *Jep106Manufacturers[] = { + Jep106ManufacturersBank1, + Jep106ManufacturersBank2, + Jep106ManufacturersBank3, + Jep106ManufacturersBank4, + Jep106ManufacturersBank5, + Jep106ManufacturersBank6, + Jep106ManufacturersBank7, + Jep106ManufacturersBank8, + Jep106ManufacturersBank9, + Jep106ManufacturersBank10, + Jep106ManufacturersBank11, + Jep106ManufacturersBank12, + Jep106ManufacturersBank13, + Jep106ManufacturersBank14 +}; + +/** + Looks up the JEP-106 manufacturer. + + @param Code Last non-zero byte of the manufacturer's ID code. + @param ContinuationBytes Number of continuation bytes indicated in JEP-106. + + @return The manufacturer string, or NULL if an error occurred or the + combination of Code and ContinuationBytes isn't valid. + +**/ +CONST CHAR8 * +EFIAPI +Jep106GetManufacturerName ( + IN UINT8 Code, + IN UINT8 ContinuationBytes + ) +{ + UINTN Index; + CONST JEDEC_MANUFACTURERS *ManufacturersBank; + + Index = 0; + + if (ContinuationBytes >= ARRAY_SIZE (Jep106Manufacturers)) { + return NULL; + } + + ManufacturersBank = Jep106Manufacturers[ContinuationBytes]; + + while (ManufacturersBank[Index].Code != 0xFF) { + if (ManufacturersBank[Index].Code == Code) { + return ManufacturersBank[Index].Manufacturer; + } + + Index++; + } + + return NULL; +} diff --git a/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.inf b/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.inf new file mode 100644 index 0000000000..b49e2ba720 --- /dev/null +++ b/MdePkg/Library/JedecJep106Lib/JedecJep106Lib.inf @@ -0,0 +1,25 @@ +## @file +# Instance of JEDEC JEP106 Library +# +# JedecJep106Lib fetches the manufacturer string given the JEP106 +# Code and Continuation Bytes. +# +# Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x0001001d + BASE_NAME = JedecJep106Lib + FILE_GUID = d48d43d7-ba31-4463-9433-ccb233cf0df7 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = JedecJep106Lib + +[Sources] + JedecJep106Lib.c + +[Packages] + MdePkg/MdePkg.dec diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index a46f28fff4..e70182bf7f 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -259,6 +259,9 @@ # UnitTestLib|Include/Library/UnitTestLib.h + ## @libraryclass Provides service to get the manufacturer given JEP106 bytes. + JedecJep106Lib|Include/Library/JedecJep106Lib.h + ## @libraryclass Extension to BaseLib for host based unit tests that allows a # subset of BaseLib services to be hooked for emulation. # diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index 0ac7618b46..152c02991a 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -136,6 +136,8 @@ MdePkg/Library/CcProbeLibNull/CcProbeLibNull.inf MdePkg/Library/SmmCpuRendezvousLibNull/SmmCpuRendezvousLibNull.inf + MdePkg/Library/JedecJep106Lib/JedecJep106Lib.inf + [Components.IA32, Components.X64, Components.ARM, Components.AARCH64] # # Add UEFI Target Based Unit Tests From 3eee54c4f6b04605a427eadfb91dcd2142a06d02 Mon Sep 17 00:00:00 2001 From: Sam Kaynor Date: Wed, 5 Apr 2023 04:11:16 +0800 Subject: [PATCH 0871/1529] ShellPkg: UefiShellDebug1CommandsLib: Uefi Config Tables in Dmem.c Added entries for UEFI Config Tables not present in current Dmem output. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Sam Kaynor Reviewed-by: Sunny Wang Reviewed-by: Zhichao Gao Reviewed-by: Samer El-Haj-Mahmoud --- .../Library/UefiShellDebug1CommandsLib/Dmem.c | 99 +++++++++++++++++-- .../UefiShellDebug1CommandsLib.inf | 9 ++ .../UefiShellDebug1CommandsLib.uni | 28 ++++-- 3 files changed, 123 insertions(+), 13 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dmem.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dmem.c index c52c212a56..a609971f34 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Dmem.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Dmem.c @@ -10,9 +10,15 @@ #include "UefiShellDebug1CommandsLib.h" #include +#include #include #include #include +#include +#include +#include +#include +#include /** Make a printable character. @@ -108,6 +114,18 @@ ShellCommandRunDmem ( UINT64 SalTableAddress; UINT64 SmbiosTableAddress; UINT64 MpsTableAddress; + UINT64 DtbTableAddress; + UINT64 MemoryAttributesTableAddress; + UINT64 RtPropertiesTableAddress; + UINT64 SystemResourceTableAddress; + UINT64 DebugImageInfoTableAddress; + UINT64 ImageExecutionTableAddress; + UINT64 JsonConfigDataTableAddress; + UINT64 JsonCapsuleDataTableAddress; + UINT64 JsonCapsuleResultTableAddress; + UINT64 MemoryRangeCapsuleAddress; + UINT64 HiiDatabaseExportBufferAddress; + UINT64 ConformanceProfileTableAddress; UINTN TableWalker; ShellStatus = SHELL_SUCCESS; @@ -168,11 +186,23 @@ ShellCommandRunDmem ( ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DMEM_HEADER_ROW), gShellDebug1HiiHandle, (UINT64)(UINTN)Address, Size); DumpHex (2, (UINTN)Address, (UINTN)Size, Address); if (Address == (VOID *)gST) { - Acpi20TableAddress = 0; - AcpiTableAddress = 0; - SalTableAddress = 0; - SmbiosTableAddress = 0; - MpsTableAddress = 0; + Acpi20TableAddress = 0; + AcpiTableAddress = 0; + SalTableAddress = 0; + SmbiosTableAddress = 0; + MpsTableAddress = 0; + DtbTableAddress = 0; + MemoryAttributesTableAddress = 0; + RtPropertiesTableAddress = 0; + SystemResourceTableAddress = 0; + DebugImageInfoTableAddress = 0; + ImageExecutionTableAddress = 0; + JsonConfigDataTableAddress = 0; + JsonCapsuleDataTableAddress = 0; + JsonCapsuleResultTableAddress = 0; + MemoryRangeCapsuleAddress = 0; + HiiDatabaseExportBufferAddress = 0; + ConformanceProfileTableAddress = 0; for (TableWalker = 0; TableWalker < gST->NumberOfTableEntries; TableWalker++) { if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiAcpi20TableGuid)) { Acpi20TableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; @@ -198,6 +228,51 @@ ShellCommandRunDmem ( MpsTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; continue; } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiMemoryAttributesTableGuid)) { + MemoryAttributesTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiRtPropertiesTableGuid)) { + RtPropertiesTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiSystemResourceTableGuid)) { + SystemResourceTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiDebugImageInfoTableGuid)) { + DebugImageInfoTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiImageSecurityDatabaseGuid)) { + ImageExecutionTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiJsonConfigDataTableGuid)) { + JsonConfigDataTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiJsonCapsuleDataTableGuid)) { + JsonCapsuleDataTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiJsonCapsuleResultTableGuid)) { + JsonCapsuleResultTableAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } + + if (CompareGuid (&gST->ConfigurationTable[TableWalker].VendorGuid, &gEfiHiiDatabaseProtocolGuid)) { + HiiDatabaseExportBufferAddress = (UINT64)(UINTN)gST->ConfigurationTable[TableWalker].VendorTable; + continue; + } } ShellPrintHiiEx ( @@ -218,7 +293,19 @@ ShellCommandRunDmem ( AcpiTableAddress, Acpi20TableAddress, MpsTableAddress, - SmbiosTableAddress + SmbiosTableAddress, + DtbTableAddress, + MemoryAttributesTableAddress, + RtPropertiesTableAddress, + SystemResourceTableAddress, + DebugImageInfoTableAddress, + ImageExecutionTableAddress, + JsonConfigDataTableAddress, + JsonCapsuleDataTableAddress, + JsonCapsuleResultTableAddress, + MemoryRangeCapsuleAddress, + HiiDatabaseExportBufferAddress, + ConformanceProfileTableAddress ); } } else { diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf index 74ad5facf6..3741dac5d9 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf @@ -121,6 +121,7 @@ gEfiBlockIoProtocolGuid ## SOMETIMES_CONSUMES gEfiSimplePointerProtocolGuid ## SOMETIMES_CONSUMES gEfiCpuIo2ProtocolGuid ## SOMETIMES_CONSUMES + gEfiHiiDatabaseProtocolGuid ## SOMETIMES_CONSUMES [Guids] gEfiGlobalVariableGuid ## SOMETIMES_CONSUMES ## GUID @@ -130,3 +131,11 @@ gEfiAcpi10TableGuid ## SOMETIMES_CONSUMES ## SystemTable gEfiAcpi20TableGuid ## SOMETIMES_CONSUMES ## SystemTable gShellDebug1HiiGuid ## SOMETIMES_CONSUMES ## HII + gEfiMemoryAttributesTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiRtPropertiesTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiSystemResourceTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiDebugImageInfoTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiImageSecurityDatabaseGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiJsonConfigDataTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiJsonCapsuleDataTableGuid ## SOMETIMES_CONSUMES ## SystemTable + gEfiJsonCapsuleResultTableGuid ## SOMETIMES_CONSUMES ## SystemTable diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni index 4fedc0d149..4041f0cd48 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.uni @@ -107,13 +107,27 @@ "---------------------------------------------\r\n" "System: Table Structure size %08x revision %08x\r\n" "ConIn (%016LX) ConOut (%016LX) StdErr (%016LX)\r\n" - "Runtime Services %016LX\r\n" - "Boot Services %016LX\r\n" - "SAL System Table %016LX\r\n" - "ACPI Table %016LX\r\n" - "ACPI 2.0 Table %016LX\r\n" - "MPS Table %016LX\r\n" - "SMBIOS Table %016LX\r\n" + "Runtime Services %016LX\r\n" + "Boot Services %016LX\r\n" + "SAL System Table %016LX\r\n" + "ACPI Table %016LX\r\n" + "ACPI 2.0 Table %016LX\r\n" + "MPS Table %016LX\r\n" + "SMBIOS Table %016LX\r\n" + "DTB Table %016LX\r\n" + "Memory Attribute Table %016LX\r\n" + "RT Properties Table %016LX\r\n" + "System Resource Table %016LX\r\n" + "Debug Image Info Table %016LX\r\n" + "Image Execution Info Table %016LX\r\n" + "Json Config Data Table %016LX\r\n" + "Json Capsule Data Table %016LX\r\n" + "Json Capsule Results Table %016LX\r\n" + "Memory Range Capsule %016LX\r\n" + "Hii Database Export Buffer %016LX\r\n" + "Conformance Profile Table %016LX\r\n" + + #string STR_LOAD_PCI_ROM_RES #language en-US "Image '%B%s%N' load result: %r\r\n" #string STR_LOADPCIROM_CORRUPT #language en-US "%H%s%N: File '%B%s%N' Image %d is corrupt.\r\n" From d8508ba132eef5aed7af9bb85e0806e28fab3db1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Corvin=20K=C3=B6hne?= Date: Tue, 6 Dec 2022 08:29:08 +0100 Subject: [PATCH 0872/1529] Maintainer.txt: add myself as reviewer for bhyve's OvmfPkg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Corvin Köhne Reviewed-by: Rebecca Cran Reviewed-by: Peter Grehan Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney --- Maintainers.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Maintainers.txt b/Maintainers.txt index 2f8671147a..455afdbc69 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -462,6 +462,7 @@ F: OvmfPkg/Library/ResetSystemLib/BaseResetShutdownBhyve.c F: OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibBhyve.inf R: Rebecca Cran [bcran] R: Peter Grehan [grehan-freebsd] +R: Corvin Köhne [corvink] OvmfPkg: cloudhv-related modules F: OvmfPkg/CloudHv/ From f41daa45c88c4b840b7cd36efe4321a96394b25f Mon Sep 17 00:00:00 2001 From: "devel@edk2.groups.io" Date: Thu, 1 Dec 2022 04:41:58 -0800 Subject: [PATCH 0873/1529] MdeModulePkg/RegularExpressionDxe: Fix GCC build error Fix GCC build error on AARCH64 system. Cc: Jian J Wang Cc: Liming Gao Cc: Michael D Kinney Cc: Nick Ramirez Signed-off-by: Nickle Wang Reviewed-by: Michael D Kinney --- .../Universal/RegularExpressionDxe/OnigurumaUefiPort.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h index 3dc207da3e..248109b0c9 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h +++ b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h @@ -4,6 +4,7 @@ (C) Copyright 2014-2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -36,11 +37,9 @@ typedef INTN intptr_t; #define offsetof OFFSET_OF #endif -#ifdef MDE_CPU_IA32 +#if defined (MDE_CPU_IA32) || defined (MDE_CPU_ARM) || defined (MDE_CPU_EBC) #define SIZEOF_VOIDP 4 -#endif - -#ifdef MDE_CPU_X64 +#else #define SIZEOF_VOIDP 8 #endif From 7903a46df99f6e274bf412e28eeb1e8a5538e203 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 17:36:32 -0600 Subject: [PATCH 0874/1529] BaseTools: Update PatchCheck.py to check for __FUNCTION__ New code should use the C99 macro __func__ instead of the pre-Standard macro __FUNCTION__. Update PatchCheck.py to reject patches with the latter. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney --- BaseTools/Scripts/PatchCheck.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 5d17d99a12..900226f18f 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -491,6 +491,12 @@ def check_added_line(self, line): 'but DEBUG_' + mo.group(1) + ' is now recommended', line) + rp_file = os.path.realpath(self.filename) + rp_script = os.path.realpath(__file__) + if line.find('__FUNCTION__') != -1 and rp_file != rp_script: + self.added_line_error('__FUNCTION__ was used, but __func__ ' + 'is now recommended', line) + split_diff_re = re.compile(r''' (?P ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $ From fde65628101040bf07c5dc6c6f5a788c536218a5 Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Thu, 6 Apr 2023 17:58:54 -0600 Subject: [PATCH 0875/1529] BaseTools: Update SetupGit.py to add new 'fp' alias for patch formatting To help people format patches with the correct options, add an alias named 'fp' to SetupGit.py that runs format-patch with '-M --stat=1000 --stat-graph-width=20'. Signed-off-by: Rebecca Cran Reviewed-by: Michael D Kinney --- BaseTools/Scripts/SetupGit.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/BaseTools/Scripts/SetupGit.py b/BaseTools/Scripts/SetupGit.py index 91814199bf..5f93124967 100644 --- a/BaseTools/Scripts/SetupGit.py +++ b/BaseTools/Scripts/SetupGit.py @@ -57,6 +57,8 @@ # Set of options to be set identically for all repositories OPTIONS = [ + {'section': 'alias', 'option': 'fp', + 'value': 'format-patch -M --stat=1000 --stat-graph-width=20'}, {'section': 'am', 'option': 'keepcr', 'value': True}, {'section': 'am', 'option': 'signoff', 'value': True}, {'section': 'cherry-pick', 'option': 'signoff', 'value': True}, From 0a90aa7c8c0afe3a12ad70e600e9e72a2d758dad Mon Sep 17 00:00:00 2001 From: Pedro Falcato Date: Fri, 16 Dec 2022 20:31:27 +0000 Subject: [PATCH 0876/1529] edk2: Add .git-blame-ignore-revs file Add a .git-blame-ignore-revs file containing the hashes of every uncrustify format commit as retrieved in: git log --oneline --no-abbrev-commit | grep "uncrustify" This file can be used by tools (such as GitHub[1]) to ignore certain revisions when git blame-ing a file. It can also be trivially usable locally by doing something akin to: git config blame.ignoreRevsFile .git-blame-ignore-revs It may also be desirable in the future to add more commits to it. Signed-off-by: Pedro Falcato Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Reviewed-by: Michael D Kinney [1]: https://github.blog/changelog/2022-03-24-ignore-commits-in-the-blame-view-beta/ --- .git-blame-ignore-revs | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..b426add80c --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,52 @@ +# PrmPkg: Apply uncrustify changes +a298a84478053872ed9da660a75f182ce81b8ddc +# UnitTestFrameworkPkg: Apply uncrustify changes +7c0ad2c33810ead45b7919f8f8d0e282dae52e71 +# UefiPayloadPkg: Apply uncrustify changes +e5efcf8be8a1bf59aa98875787475e3144ee4cef +# UefiCpuPkg: Apply uncrustify changes +053e878bfb5c9d5eca779789b62891add30b14ba +# StandaloneMmPkg: Apply uncrustify changes +91415a36ae7aaeabb2bbab3762f39544f9aed683 +# SourceLevelDebugPkg: Apply uncrustify changes +c1e126b1196de75e0a4cda21e4551ea9bb05e059 +# SignedCapsulePkg: Apply uncrustify changes +b87864896714cf3062a7bc6d577d8fbd62d105e5 +# ShellPkg: Apply uncrustify changes +47d20b54f9a65b08aa602a1866c1b59a69088dfc +# SecurityPkg: Apply uncrustify changes +c411b485b63a671a1e276700cff025c73997233c +# RedfishPkg: Apply uncrustify changes +39de741e2dcb8f11e9b4438e37224797643d8451 +# PcAtChipsetPkg: Apply uncrustify changes +5220bd211df890f2672c23c050082862cd1e82d6 +# OvmfPkg: Apply uncrustify changes +ac0a286f4d747a4c6c603a7b225917293cbe1e9f +# NetworkPkg: Apply uncrustify changes +d1050b9dff1cace252aff86630bfdb59dff5f507 +# MdePkg: Apply uncrustify changes +2f88bd3a1296c522317f1c21377876de63de5be7 +# MdeModulePkg: Apply uncrustify changes +1436aea4d5707e672672a11bda72be2c63c936c3 +# IntelFsp2WrapperPkg: Apply uncrustify changes +7c7184e201a90a1d2376e615e55e3f4074731468 +# IntelFsp2Pkg: Apply uncrustify changes +111f2228ddf487b0ac3491e416bb3dcdcfa4f979 +# FmpDevicePkg: Apply uncrustify changes +45ce0a67bb4ee80f27da93777c623f51f344f23b +# FatPkg: Apply uncrustify changes +bcdcc4160d7460c46c08c9395aae81be44ef23a9 +# EmulatorPkg: Apply uncrustify changes +a550d468a6ca577d9e9c57a0eafcf2fc9fbb8c97 +# EmbeddedPkg: Apply uncrustify changes +e7108d0e9655b1795c94ac372b0449f28dd907df +# DynamicTablesPkg: Apply uncrustify changes +731c67e1d77b7741a91762d17659fc9fbcb9e305 +# CryptoPkg: Apply uncrustify changes +7c342378317039e632d9a1a5d4cf7c21aec8cb7a +# ArmVirtPkg: Apply uncrustify changes +2b16a4fb91b9b31c0d152588f5ac51080c6c0763 +# ArmPlatformPkg: Apply uncrustify changes +40b0b23ed34f48c26d711d3e4613a4bb35eeadff +# ArmPkg: Apply uncrustify changes +429309e0c6b74792d679681a8edd0d5ae0ff850c From eee3d21e69f9ec58610e70b3101a779443821c41 Mon Sep 17 00:00:00 2001 From: "Duggapu, Chinni B" Date: Sun, 16 Apr 2023 21:22:56 -0700 Subject: [PATCH 0877/1529] IntelFsp2Pkg/Tools: Enhance PathFv.py to patch Fd file directly https://bugzilla.tianocore.org/show_bug.cgi?id=4412 After shrinking the FSP (FV) component using FMMT, Image size in FSP info header is not in sync with the FV length in FV header. This enhancement helps to patch the FSP image size offset with correct length & can be used to patch any offset directly on the FSP Component Fd. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Cc: Ted Kuo Signed-off-by: Duggapu Chinni B Reviewed-by: Ted Kuo Reviewed-by: Chasel Chiu --- IntelFsp2Pkg/Tools/PatchFv.py | 14 ++++++++++++- .../Tools/UserManuals/PatchFvUserManual.md | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/IntelFsp2Pkg/Tools/PatchFv.py b/IntelFsp2Pkg/Tools/PatchFv.py index eb130049b5..73ab877c71 100644 --- a/IntelFsp2Pkg/Tools/PatchFv.py +++ b/IntelFsp2Pkg/Tools/PatchFv.py @@ -165,6 +165,17 @@ def createDicts (self, fvDir, fvNames): if not os.path.isdir(fvDir): raise Exception ("'%s' is not a valid directory!" % fvDir) + # + # if user provided fd name as a input, skip rest of the flow to + # patch fd directly + # + fdFile = os.path.join(fvDir,fvNames + ".fd") + if os.path.exists(fdFile): + print("Tool identified Fd file as a input to patch '%s'" %fdFile) + self.fdFile = fdFile + self.fdSize = os.path.getsize(fdFile) + return 0 + # # If the Guid.xref is not existing in fvDir, then raise an exception # @@ -848,8 +859,9 @@ def evaluate(self, expression, isOffset): # Print out the usage # def Usage(): - print ("PatchFv Version 0.50") + print ("PatchFv Version 0.60") print ("Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\"") + print ("\tPatchFv FdFileDir FdFileName \"Offset, Value\"") def main(): # diff --git a/IntelFsp2Pkg/Tools/UserManuals/PatchFvUserManual.md b/IntelFsp2Pkg/Tools/UserManuals/PatchFvUserManual.md index 5f1031e729..f28eedf625 100644 --- a/IntelFsp2Pkg/Tools/UserManuals/PatchFvUserManual.md +++ b/IntelFsp2Pkg/Tools/UserManuals/PatchFvUserManual.md @@ -1,6 +1,7 @@ #Name **_PatchFv.py_** - The python script that patches the firmware volumes (**FV**) with in the flash device (**FD**) file post FSP build. +From version 0.60, script is capable of patching flash device (**FD**) directly. #Synopsis @@ -10,6 +11,12 @@ PatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch ["Offset, Value"]+ | ["Offset, Value, $Command"]+ | ["Offset, Value, $Command, @Comment"]+ ``` +``` +PatchFv FdFileDir FdFileName ["Offset, Value"]+ + | ["Offset, Value, @Comment"]+ + | ["Offset, Value, $Command"]+ + | ["Offset, Value, $Command, @Comment"]+ +``` #Description The **_PatchFv.py_** tool allows the developer to fix up FD images to follow the @@ -102,6 +109,19 @@ ModuleGuid:Offset < > Convert absolute address into an image offset (expr & FSP_SIZE) ``` +From version 0.60 tool allows to pass flash device file path as Argument 1 and +flash device name as Argument 2 and rules for passing offset & value are same +as explained in the previous sections. + +####Example usage: +Argument 1 +``` + YouPlatformFspBinPkg\ +``` +Argument 2 +``` + Fsp_Rebased_T +``` ###Special Commands: Special commands must use the **$** symbol as a prefix to the command itself. From 67893a2be1a97bbd250c6e0a2dc744346bc2e61d Mon Sep 17 00:00:00 2001 From: Yi Li Date: Fri, 14 Apr 2023 15:33:16 +0800 Subject: [PATCH 0878/1529] CryptoPkg: Enable DXE_CORE support in DxeCryptLib.inf REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4413 Make the DXE_CORE module able to call the crypto protocol, which can reduce FV size on platforms using the Crypto Binaries. Cc: Jian J Wang Cc: Jiewen Yao Cc: Xiaoyu Lu Cc: Guomin Jiang Signed-off-by: Yi Li Reviewed-by: Jiewen Yao --- CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf index b4945de336..972291574c 100644 --- a/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLibOnProtocolPpi/DxeCryptLib.inf @@ -16,7 +16,7 @@ FILE_GUID = B38CBDA6-8017-4111-8232-9E8328DE82F6 VERSION_STRING = 1.0 MODULE_TYPE = DXE_DRIVER - LIBRARY_CLASS = BaseCryptLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION + LIBRARY_CLASS = BaseCryptLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION DXE_CORE LIBRARY_CLASS = TlsLib | DXE_DRIVER UEFI_DRIVER UEFI_APPLICATION CONSTRUCTOR = DxeCryptLibConstructor From d9e8163b337be10d6fc8ae5b7c1b5516d101522a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20Ha=CC=88user?= Date: Thu, 20 Apr 2023 15:24:14 +0000 Subject: [PATCH 0879/1529] ArmPkg/AsmMacroIoLibV8: Introduce ASM_FUNC_ALIGN() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the current ASM_FUNC() macro, there is no good way to declare an alignment constraint for a function. As ASM_FUNC() switches sections, declaring the constraint before the macro invocation applies it to the current location in the previous section. Declaring the constraint after the macro invocation lets the function label point to the location prior to alignment. Depending on toolchain behaviour, this may cause the label to point to alignment padding preceding the actual function definition. To address these issues, introduce the ASM_FUNC_ALIGN() macro, which declares the alignment constraint right before the function label. Signed-off-by: Marvin Häuser Reviewed-by: Ard Biesheuvel --- ArmPkg/Include/AsmMacroIoLibV8.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ArmPkg/Include/AsmMacroIoLibV8.h b/ArmPkg/Include/AsmMacroIoLibV8.h index 135aaeca5d..81164ea9c9 100644 --- a/ArmPkg/Include/AsmMacroIoLibV8.h +++ b/ArmPkg/Include/AsmMacroIoLibV8.h @@ -41,8 +41,19 @@ Name: ; \ AARCH64_BTI(c) +#define _ASM_FUNC_ALIGN(Name, Section, Align) \ + .global Name ; \ + .section #Section, "ax" ; \ + .type Name, %function ; \ + .balign Align ; \ + Name: ; \ + AARCH64_BTI(c) + #define ASM_FUNC(Name) _ASM_FUNC(ASM_PFX(Name), .text. ## Name) +#define ASM_FUNC_ALIGN(Name, Align) \ + _ASM_FUNC_ALIGN(ASM_PFX(Name), .text. ## Name, Align) + #define MOV32(Reg, Val) \ movz Reg, (Val) >> 16, lsl #16 ; \ movk Reg, (Val) & 0xffff From 008ecb5d98ff8d3c9a0c5377d7d48cb2fbbfc2f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20Ha=CC=88user?= Date: Thu, 20 Apr 2023 15:24:15 +0000 Subject: [PATCH 0880/1529] ArmPkg/ArmMmuLib: Fix ArmReplaceLiveTranslationEntry() alignment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As the ASM_FUNC() macro performs a section switch, the preceding .balign directive applies the alignment constraint to the current location in the previous section. As the linker may not merge the sections in-order, ArmReplaceLiveTranslationEntry() may be left unaligned. Replace the explicit invocation of .balign with the ASM_FUNC_ALIGN() macro, which guarantees the alignment constraint is applied correctly. To make sure related issues are reliably caught in the future, align the end of the function before checking the total occupied size. This ensures crossing a 0x200 boundary will cause a compilation error. Signed-off-by: Marvin Häuser Reviewed-by: Leif Lindholm Reviewed-by: Ard Biesheuvel --- .../ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S index e936a5be4e..887439bc04 100644 --- a/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S +++ b/ArmPkg/Library/ArmMmuLib/AArch64/ArmMmuLibReplaceEntry.S @@ -69,17 +69,16 @@ .L2_\@: .endm - // Align this routine to a log2 upper bound of its size, so that it is - // guaranteed not to cross a page or block boundary. - .balign 0x200 - //VOID //ArmReplaceLiveTranslationEntry ( // IN UINT64 *Entry, // IN UINT64 Value, // IN UINT64 Address // ) -ASM_FUNC(ArmReplaceLiveTranslationEntry) +// +// Align this routine to a log2 upper bound of its size, so that it is +// guaranteed not to cross a page or block boundary. +ASM_FUNC_ALIGN(ArmReplaceLiveTranslationEntry, 0x200) // disable interrupts mrs x4, daif @@ -101,5 +100,8 @@ ASM_GLOBAL ASM_PFX(ArmReplaceLiveTranslationEntrySize) ASM_PFX(ArmReplaceLiveTranslationEntrySize): .long . - ArmReplaceLiveTranslationEntry - // Double check that we did not overrun the assumed maximum size + // Double check that we did not overrun the assumed maximum size or cross a + // 0x200 boundary (and thus implicitly not any larger power of two, including + // the page size). + .balign 0x200 .org ArmReplaceLiveTranslationEntry + 0x200 From a99a55d7404d8ba2f1a0cf91100c610f1415c1e1 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Sun, 2 Apr 2023 09:35:29 +0800 Subject: [PATCH 0881/1529] MdePkg/Include: Add DMTF PLDM Base definitions BZ #4396 This change adds definitions for DMTF PLDM base specification. Spec ref: https://www.dmtf.org/sites/default/files/standards/documents/DSP0240_1.1.0.pdf Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Abdul Lateef Attar Reviewed-by: Michael D Kinney --- MdePkg/Include/IndustryStandard/Pldm.h | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/Pldm.h diff --git a/MdePkg/Include/IndustryStandard/Pldm.h b/MdePkg/Include/IndustryStandard/Pldm.h new file mode 100644 index 0000000000..c821f081f8 --- /dev/null +++ b/MdePkg/Include/IndustryStandard/Pldm.h @@ -0,0 +1,82 @@ +/** @file + + The definitions of DMTF Platform Level Data Model (PLDM) + Base Specification. + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Revision Reference: + DMTF Platform Level Data Model (PLDM) Base Specification + Version 1.1.0 + https://www.dmtf.org/sites/default/files/standards/documents/DSP0240_1.1.0.pdf + +**/ + +#ifndef PLDM_H_ +#define PLDM_H_ + +#pragma pack(1) + +#define PLDM_MESSAGE_HEADER_VERSION 0 + +/// +/// General definitions from Platform Level Data Model (PLDM) Base +/// Specification (DMTF DSP0240) +/// +typedef struct { + UINT8 InstanceId : 5; ///< Request instance ID. + UINT8 Reserved : 1; ///< Reserved bit. + UINT8 DatagramBit : 1; ///< used to indicate whether the Instance ID field is + ///< being used for tracking and matching requests and + ///< responses, or just being used for asynchronous + ///< notifications. + UINT8 RequestBit : 1; ///< Request bit. + UINT8 PldmType : 6; ///< PLDM message type. + UINT8 HeaderVersion : 2; ///< Header version. + UINT8 PldmTypeCommandCode; ///< The command code of PLDM message type. +} PLDM_MESSAGE_HEADER; + +typedef PLDM_MESSAGE_HEADER PLDM_REQUEST_HEADER; + +#define PLDM_MESSAGE_HEADER_IS_REQUEST 1 +#define PLDM_MESSAGE_HEADER_IS_DATAGRAM 1 +#define PLDM_MESSAGE_HEADER_INSTANCE_ID_MASK 0x1f + +typedef struct { + PLDM_MESSAGE_HEADER PldmHeader; + UINT8 PldmCompletionCode; ///< PLDM completion of response message. +} PLDM_RESPONSE_HEADER; + +#pragma pack() + +#define PLDM_HEADER_VERSION 0x00 + +#define PLDM_COMPLETION_CODE_SUCCESS 0x00 +#define PLDM_COMPLETION_CODE_ERROR 0x01 +#define PLDM_COMPLETION_CODE_ERROR_INVALID_DATA 0x02 +#define PLDM_COMPLETION_CODE_ERROR_INVALID_LENGTH 0x03 +#define PLDM_COMPLETION_CODE_ERROR_NOT_READY 0x04 +#define PLDM_COMPLETION_CODE_ERROR_UNSUPPORTED_PLDM_CMD 0x05 +#define PLDM_COMPLETION_CODE_ERROR_INVALID_PLDM_TYPE 0x20 +#define PLDM_COMPLETION_CODE_SPECIFIC_START 0x80 +#define PLDM_COMPLETION_CODE_SPECIFIC_END 0xff + +/// +/// Type Code definitions from Platform Level Data Model (PLDM) IDs +/// and Codes Specification (DMTF DSP0245) +/// https://www.dmtf.org/sites/default/files/standards/documents/DSP0245_1.3.0.pdf +/// +#define PLDM_TYPE_MESSAGE_CONTROL_AND_DISCOVERY 0x00 +#define PLDM_TYPE_SMBIOS 0x01 +#define PLDM_TYPE_PLATFORM_MONITORING_AND_CONTROL 0x02 +#define PLDM_TYPE_BIOS_CONTROL_AND_CONFIGURATION 0x03 + +#define PLDM_TRANSFER_FLAG_START 0x01 +#define PLDM_TRANSFER_FLAG_MIDDLE 0x02 +#define PLDM_TRANSFER_FLAG_END 0x04 +#define PLDM_TRANSFER_FLAG_START_AND_END 0x05 + +#define PLDM_TRANSFER_OPERATION_FLAG_GET_NEXT_PART 0x00 +#define PLDM_TRANSFER_OPERATION_FLAG_GET_FIRST_PART 0x01 +#endif // PLDM_H_ From 26f23eb8373c764b84a68a2cfad237e20f6791b9 Mon Sep 17 00:00:00 2001 From: Linus Wu Date: Thu, 20 Apr 2023 14:44:34 +0800 Subject: [PATCH 0882/1529] UefiPayloadPkg: Move Network modules from Dxe FV to Network FV in elf REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4417 Since UefiPayload had supported multiple FV, move Network.fdf.inc to new firmware volume and add this network FV into elf file. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Signed-off-by: Linus Wu Reviewed-by: Gua Guo --- UefiPayloadPkg/UefiPayloadPkg.fdf | 32 +++++++++++++++++++++++-- UefiPayloadPkg/UniversalPayloadBuild.py | 12 ++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadPkg.fdf b/UefiPayloadPkg/UefiPayloadPkg.fdf index ee7d718b3f..f8c2aa8c4a 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.fdf +++ b/UefiPayloadPkg/UefiPayloadPkg.fdf @@ -60,6 +60,35 @@ FILE FV_IMAGE = 4E35FD93-9C72-4c15-8C4B-E77F1DB2D793 { SECTION FV_IMAGE = DXEFV } +!if $(NETWORK_DRIVER_ENABLE) == TRUE +################################################################################ +[FV.NETWORKFV] +FvNameGuid = 3CF5CB69-C439-4B84-AF11-8167B22D7221 +BlockSize = $(FD_BLOCK_SIZE) +FvForceRebase = FALSE +FvAlignment = 16 +ERASE_POLARITY = 1 +MEMORY_MAPPED = TRUE +STICKY_WRITE = TRUE +LOCK_CAP = TRUE +LOCK_STATUS = TRUE +WRITE_DISABLED_CAP = TRUE +WRITE_ENABLED_CAP = TRUE +WRITE_STATUS = TRUE +WRITE_LOCK_CAP = TRUE +WRITE_LOCK_STATUS = TRUE +READ_DISABLED_CAP = TRUE +READ_ENABLED_CAP = TRUE +READ_STATUS = TRUE +READ_LOCK_CAP = TRUE +READ_LOCK_STATUS = TRUE + +# +# UEFI network modules +# +!include NetworkPkg/Network.fdf.inc +!endif + ################################################################################ [FV.BDSFV] FvNameGuid = CA5590AF-9558-4822-B5EA-BE2E876CD3EC @@ -276,14 +305,13 @@ INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResour !if $(UNIVERSAL_PAYLOAD) == FALSE INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf -!endif - # # UEFI network modules # !if $(NETWORK_DRIVER_ENABLE) == TRUE !include NetworkPkg/Network.fdf.inc !endif +!endif # # Shell diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index db7ce0500b..83e0de95d8 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -108,6 +108,7 @@ def BuildUniversalPayload(Args, MacroList): DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc") DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) + NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt") UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin") @@ -185,6 +186,17 @@ def BuildUniversalPayload(Args, MacroList): ObjCopyFlag, EntryOutputDir ) + # + # Append network fv to sections if exists + # + if os.path.isfile(NetworkFvOutputDir): + index = remove_section.find(EntryOutputDir) + remove_section = remove_section[:index] + '--remove-section .upld.network_fv ' + remove_section[index:] + index = add_section.find(EntryOutputDir) + add_section = add_section[:index] + '--add-section .upld.network_fv=' + NetworkFvOutputDir + ' ' + add_section[index:] + index = set_section.find(EntryOutputDir) + set_section = set_section[:index] + '--set-section-alignment .upld.network_fv=16 ' + set_section[index:] + RunCommand(remove_section) RunCommand(add_section) RunCommand(set_section) From bf3c3e9db179c5eb06f9d0aeff3dec64a86a2e74 Mon Sep 17 00:00:00 2001 From: Marcin Juszkiewicz Date: Thu, 20 Apr 2023 21:45:32 +0200 Subject: [PATCH 0883/1529] ArmPkg: older assemblers may lack ID_AA64ISAR2_EL1 ArmCpuInfo needs to be able to read ID_AA64ISAR2_EL1 system register. Older toolchains do not know it. Same solution as one for QEMU: https://www.mail-archive.com/qemu-devel@nongnu.org/msg929586.html Signed-off-by: Marcin Juszkiewicz Reviewed-by: Leif Lindholm --- ArmPkg/Include/Chipset/AArch64.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ArmPkg/Include/Chipset/AArch64.h b/ArmPkg/Include/Chipset/AArch64.h index bfd2859f51..690433f68e 100644 --- a/ArmPkg/Include/Chipset/AArch64.h +++ b/ArmPkg/Include/Chipset/AArch64.h @@ -112,6 +112,10 @@ #define ARM_VECTOR_LOW_A32_FIQ 0x700 #define ARM_VECTOR_LOW_A32_SERR 0x780 +// The ID_AA64ISAR2_EL1 register is not recognized by older +// assemblers, we need to define it here. +#define ID_AA64ISAR2_EL1 S3_0_C0_C6_2 + // The ID_AA64MMFR2_EL1 register was added in ARMv8.2. Since we // build for ARMv8.0, we need to define the register here. #define ID_AA64MMFR2_EL1 S3_0_C0_C7_2 From 6e78d1549d663442b38cb85c9a612c117b8f8c17 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Sun, 2 Apr 2023 09:40:14 +0800 Subject: [PATCH 0884/1529] MdePkg/Include: Add DMTF PLDM SMBIOS definitions BZ #4396 This change adds definitions for DMTF PLDM SMBIOS Transfer specification. Spec ref: https://www.dmtf.org/sites/default/files/standards/documents/DSP0246_1.0.1.pdf Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Abdul Lateef Attar Reviewed-by: Liming Gao Reviewed-by: Michael D Kinney --- .../IndustryStandard/PldmSmbiosTransfer.h | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/PldmSmbiosTransfer.h diff --git a/MdePkg/Include/IndustryStandard/PldmSmbiosTransfer.h b/MdePkg/Include/IndustryStandard/PldmSmbiosTransfer.h new file mode 100644 index 0000000000..9b7a5e838e --- /dev/null +++ b/MdePkg/Include/IndustryStandard/PldmSmbiosTransfer.h @@ -0,0 +1,183 @@ +/** @file + + The definitions of DMTF Platform Level Data Model (PLDM) + SMBIOS Transfer Specification. + + Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Revision Reference: + DMTF Platform Level Data Model (PLDM) SMBIOS Transfer Specification + Version 1.0.1 + https://www.dmtf.org/sites/default/files/standards/documents/DSP0246_1.0.1.pdf + +**/ + +#ifndef PLDM_SMBIOS_TRANSFER_H_ +#define PLDM_SMBIOS_TRANSFER_H_ + +#include + +#pragma pack(1) + +/// +/// Smbios-related definitions from PLDM for SMBIOS Transfer +/// Specification (DMTF DSP0246) +/// +#define PLDM_GET_SMBIOS_STRUCTURE_TABLE_METADATA_COMMAND_CODE 0x01 +#define PLDM_SET_SMBIOS_STRUCTURE_TABLE_METADATA_COMMAND_CODE 0x02 +#define PLDM_GET_SMBIOS_STRUCTURE_TABLE_COMMAND_CODE 0x03 +#define PLDM_SET_SMBIOS_STRUCTURE_TABLE_COMMAND_CODE 0x04 +#define PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_COMMAND_CODE 0x05 +#define PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_COMMAND_CODE 0x06 + +/// +/// PLDM SMBIOS transfer command specific completion code. +/// +#define PLDM_COMPLETION_CODE_INVALID_DATA_TRANSFER_HANDLE 0x80 +#define PLDM_COMPLETION_CODE_INVALID_TRANSFER_OPERATION_FLAG 0x81 +#define PLDM_COMPLETION_CODE_INVALID_TRANSFER_FLAG 0x82 +#define PLDM_COMPLETION_CODE_NO_SMBIOS_STRUCTURE_TABLE_METADATA 0x83 +#define PLDM_COMPLETION_CODE_INVALID_DATA_INTEGRITY_CHECK 0x84 +#define PLDM_COMPLETION_CODE_SMBIOS_STRUCTURE_TABLE_UNAVAILABLE 0x85 + +/// +/// Get SMBIOS Structure Table Metadata Response. +/// +typedef struct { + UINT8 SmbiosMajorVersion; + UINT8 SmbiosMinorVersion; + UINT16 MaximumStructureSize; + UINT16 SmbiosStructureTableLength; + UINT16 NumberOfSmbiosStructures; + UINT32 SmbiosStructureTableIntegrityChecksum; +} PLDM_SMBIOS_STRUCTURE_TABLE_METADATA; + +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; + PLDM_SMBIOS_STRUCTURE_TABLE_METADATA SmbiosStructureTableMetadata; +} PLDM_GET_SMBIOS_STRUCTURE_TABLE_METADATA_RESPONSE_FORMAT; + +/// +/// Set SMBIOS Structure Table Metadata Request. +/// +typedef struct { + PLDM_REQUEST_HEADER RequestHeader; + PLDM_SMBIOS_STRUCTURE_TABLE_METADATA SmbiosStructureTableMetadata; +} PLDM_SET_SMBIOS_STRUCTURE_TABLE_METADATA_REQUEST_FORMAT; + +/// +/// Set SMBIOS Structure Table Metadata Response. +/// +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; +} PLDM_SET_SMBIOS_STRUCTURE_TABLE_METADATA_RESPONSE_FORMAT; + +/// +/// Get SMBIOS Structure Table Request. +/// +typedef struct { + UINT32 DataTransferHandle; + UINT8 TransferOperationFlag; +} PLDM_GET_SMBIOS_STRUCTURE_TABLE_REQUEST; + +typedef struct { + PLDM_REQUEST_HEADER RequestHeader; + PLDM_GET_SMBIOS_STRUCTURE_TABLE_REQUEST GetSmbiosStructureTableRequest; +} PLDM_GET_SMBIOS_STRUCTURE_TABLE_REQUEST_FORMAT; + +/// +/// Get SMBIOS Structure Table Response. +/// +typedef struct { + UINT32 NextDataTransferHandle; + UINT8 TransferFlag; + UINT8 Table[0]; +} PLDM_GET_SMBIOS_STRUCTURE_TABLE_RESPONSE; + +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; + PLDM_GET_SMBIOS_STRUCTURE_TABLE_RESPONSE GetSmbiosStructureTableResponse; +} PLDM_GET_SMBIOS_STRUCTURE_TABLE_RESPONSE_FORMAT; + +/// +/// Set SMBIOS Structure Table Request. +/// +typedef struct { + UINT32 DataTransferHandle; + UINT8 TransferFlag; + UINT8 Table[0]; +} PLDM_SET_SMBIOS_STRUCTURE_TABLE_REQUEST; + +typedef struct { + PLDM_REQUEST_HEADER RequestHeader; + PLDM_SET_SMBIOS_STRUCTURE_TABLE_REQUEST SetSmbiosStructureTableRequest; +} PLDM_SET_SMBIOS_STRUCTURE_TABLE_REQUEST_FORMAT; + +/// +/// Set SMBIOS Structure Table Response. +/// +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; + UINT32 NextDataTransferHandle; +} PLDM_SET_SMBIOS_STRUCTURE_TABLE_RESPONSE_FORMAT; + +/// +/// Get SMBIOS Structure by Type Request. +/// +typedef struct { + UINT32 DataTransferHandle; + UINT8 TransferOperationFlag; + UINT8 Type; + UINT16 StructureInstanceId; +} PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_REQUEST; + +typedef struct { + PLDM_REQUEST_HEADER RequestHeader; + PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_REQUEST GetSmbiosStructureByTypeRequest; +} PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_REQUEST_FORMAT; + +/// +/// Get SMBIOS Structure by Type Response. +/// +typedef struct { + UINT32 NextDataTransferHandle; + UINT8 TransferFlag; + UINT8 Table[0]; +} PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_RESPONSE; + +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; + PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_RESPONSE GetSmbiosStructureByTypeResponse; +} PLDM_GET_SMBIOS_STRUCTURE_BY_TYPE_RESPONSE_FORMAT; + +/// +/// Get SMBIOS Structure by Handle Request. +/// +typedef struct { + UINT32 DataTransferHandle; + UINT8 TransferOperationFlag; + UINT16 Handle; +} PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_REQUEST; + +typedef struct { + PLDM_REQUEST_HEADER RequestHeader; + PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_REQUEST GetSmbiosStructureByHandleRequest; +} PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_REQUEST_FORMAT; + +/// +/// Get SMBIOS Structure by Handle Response. +/// +typedef struct { + UINT32 NextDataTransferHandle; + UINT8 TransferFlag; + UINT8 Table[0]; +} PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_RESPONSE; + +typedef struct { + PLDM_RESPONSE_HEADER ResponseHeader; + PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_RESPONSE GetSmbiosStructureByTypeResponse; +} PLDM_GET_SMBIOS_STRUCTURE_BY_HANDLE_RESPONSE_FORMAT; +#pragma pack() + +#endif // PLDM_SMBIOS_TRANSFER_H_ From fe73e67812a298ac6310a9050261a0a1fc22ebcf Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 18 Apr 2023 11:00:22 -0400 Subject: [PATCH 0885/1529] BaseTools/Plugin: Clarify code coverage failure message HostBasedUnitTestRunner.py is a build plugin responsible for locating and executing host-based unit tests. Recently, commit 6bb00aa introduced support for the plugin to generate code coverage reports via lcov and OpenCppCoverage. The plugin has discovered unit tests by searching for executables with "Test" in the name for a while. However, the test coverage change makes assumptions about test presence when crafting the OpenCppCoverage command that ultimately fails with an ambiguous error message if no host-based unit tests are discovered (see "ERROR"). ``` SECTION - Run Host based Unit Tests SUBSECTION - Testing for architecture: X64 ERROR - UnitTest Coverage: Failed to generate cobertura format xml in single package. PROGRESS - --->Test Success: Host Unit Test Compiler Plugin NOOPT ``` This change preempts that message with a check in the plugin to determine if any host-based tests were discovered. If not, a message is printed with more guidance about how the developer should proceed to either (1) fix their tests so code coverage is generated as expected or (2) prevent the error message. New message: ``` SECTION - Run Host based Unit Tests SUBSECTION - Testing for architecture: X64 WARNING - UnitTest Coverage: No unit tests discovered. Test coverage will not be generated. Prevent this message by: 1. Adding host-based unit tests to this package 2. Ensuring tests have the word "Test" in their name 3. Disabling HostUnitTestCompilerPlugin in the package CI YAML file PROGRESS - --->Test Success: Host Unit Test Compiler Plugin NOOPT ``` Cc: Rebecca Cran Cc: Liming Gao Cc: Bob Feng Cc: Yuwei Chen Cc: Michael D Kinney Cc: Sean Brogan Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Rebecca Cran --- .../HostBasedUnitTestRunner.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index 0e013c5f1a..a384b55629 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -16,6 +16,7 @@ from edk2toolext.environment import shell_environment from edk2toollib.utility_functions import RunCmd from edk2toollib.utility_functions import GetHostInfo +from textwrap import dedent class HostBasedUnitTestRunner(IUefiBuildPlugin): @@ -84,6 +85,18 @@ def do_post_build(self, thebuilder): else: raise NotImplementedError("Unsupported Operating System") + if not testList: + logging.warning(dedent(""" + UnitTest Coverage: + No unit tests discovered. Test coverage will not be generated. + + Prevent this message by: + 1. Adding host-based unit tests to this package + 2. Ensuring tests have the word "Test" in their name + 3. Disabling HostUnitTestCompilerPlugin in the package CI YAML file + """).strip()) + return 0 + for test in testList: # Configure output name if test uses cmocka. shell_env.set_shell_var( From 8365f79b039646862c8963dffe9df74c447a3b04 Mon Sep 17 00:00:00 2001 From: Abner Chang Date: Sun, 16 Apr 2023 15:11:21 +0800 Subject: [PATCH 0886/1529] MdePkg: Add DEBUG_MANAGEABILITY print error level Bug #4414 Add DEBUG_MANAGEABILITY print error lever to output debug message of detailed manageability related module information, such as - RedfishPkg: - HTTP header/request/response - JSON plain text - Refish resource - Redfish Host interface information - Redfish credential information - Platform configuration to Redfish mapping - etc. - ManageabilityPKg - Protocol payload of MCTP/PLDM/IPMI - Payload of transport interface transfers - IPMI BLOB transfer - etc. - RedfishClinetPkg - Redfish feature driver dispatcher - Redfish BIOS attributes - Platform configuration (HII) to Redfish property information - Redfish C structure information - etc. Signed-off-by: Abner Chang Cc: Michael D Kinney Cc: Liming Gao Cc: Zhiguang Liu Cc: Nickle Wang Cc: Igor Kulchytskyy Cc: Isaac Oram Cc: Abdul Lateef Attar Cc: Tinh Nguyen --- MdePkg/Include/Library/DebugLib.h | 42 ++++++++++++++++--------------- MdePkg/MdePkg.dec | 1 + 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/MdePkg/Include/Library/DebugLib.h b/MdePkg/Include/Library/DebugLib.h index 9110be2f41..f0c9f64487 100644 --- a/MdePkg/Include/Library/DebugLib.h +++ b/MdePkg/Include/Library/DebugLib.h @@ -29,26 +29,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Declare bits for PcdDebugPrintErrorLevel and the ErrorLevel parameter of DebugPrint() // -#define DEBUG_INIT 0x00000001 // Initialization -#define DEBUG_WARN 0x00000002 // Warnings -#define DEBUG_LOAD 0x00000004 // Load events -#define DEBUG_FS 0x00000008 // EFI File system -#define DEBUG_POOL 0x00000010 // Alloc & Free (pool) -#define DEBUG_PAGE 0x00000020 // Alloc & Free (page) -#define DEBUG_INFO 0x00000040 // Informational debug messages -#define DEBUG_DISPATCH 0x00000080 // PEI/DXE/SMM Dispatchers -#define DEBUG_VARIABLE 0x00000100 // Variable -#define DEBUG_BM 0x00000400 // Boot Manager -#define DEBUG_BLKIO 0x00001000 // BlkIo Driver -#define DEBUG_NET 0x00004000 // Network Io Driver -#define DEBUG_UNDI 0x00010000 // UNDI Driver -#define DEBUG_LOADFILE 0x00020000 // LoadFile -#define DEBUG_EVENT 0x00080000 // Event messages -#define DEBUG_GCD 0x00100000 // Global Coherency Database changes -#define DEBUG_CACHE 0x00200000 // Memory range cachability changes -#define DEBUG_VERBOSE 0x00400000 // Detailed debug messages that may - // significantly impact boot performance -#define DEBUG_ERROR 0x80000000 // Error +#define DEBUG_INIT 0x00000001 // Initialization +#define DEBUG_WARN 0x00000002 // Warnings +#define DEBUG_LOAD 0x00000004 // Load events +#define DEBUG_FS 0x00000008 // EFI File system +#define DEBUG_POOL 0x00000010 // Alloc & Free (pool) +#define DEBUG_PAGE 0x00000020 // Alloc & Free (page) +#define DEBUG_INFO 0x00000040 // Informational debug messages +#define DEBUG_DISPATCH 0x00000080 // PEI/DXE/SMM Dispatchers +#define DEBUG_VARIABLE 0x00000100 // Variable +#define DEBUG_BM 0x00000400 // Boot Manager +#define DEBUG_BLKIO 0x00001000 // BlkIo Driver +#define DEBUG_NET 0x00004000 // Network Io Driver +#define DEBUG_UNDI 0x00010000 // UNDI Driver +#define DEBUG_LOADFILE 0x00020000 // LoadFile +#define DEBUG_EVENT 0x00080000 // Event messages +#define DEBUG_GCD 0x00100000 // Global Coherency Database changes +#define DEBUG_CACHE 0x00200000 // Memory range cachability changes +#define DEBUG_VERBOSE 0x00400000 // Detailed debug messages that may + // significantly impact boot performance +#define DEBUG_MANAGEABILITY 0x00800000 // Detailed debug and payload message of manageability + // related modules, such Redfish, IPMI, MCTP and etc. +#define DEBUG_ERROR 0x80000000 // Error // // Aliases of debug message mask bits diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index e70182bf7f..7488ccda7a 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -2282,6 +2282,7 @@ # BIT20 - Global Coherency Database changes message.
# BIT21 - Memory range cachability changes message.
# BIT22 - Detailed debug message.
+ # BIT23 - Manageability messages.
# BIT31 - Error message.
# @Prompt Debug Message Print Level. # @Expression 0x80000002 | (gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel & 0x7F84AA00) == 0 From fe6c19e12fcfeb421a497f661428983aee883ab0 Mon Sep 17 00:00:00 2001 From: Marcin Juszkiewicz Date: Fri, 21 Apr 2023 17:51:15 +0200 Subject: [PATCH 0887/1529] ArmLib: add functions to read system registers ArmCpuInfo uses those to read system registers and other parts of EDK2 may find them useful. Signed-off-by: Marcin Juszkiewicz Reviewed-by: Leif Lindholm --- ArmPkg/Library/ArmLib/AArch64/AArch64Lib.h | 50 +++++++++++++++- .../Library/ArmLib/AArch64/AArch64Support.S | 58 ++++++++++++++++--- 2 files changed, 99 insertions(+), 9 deletions(-) diff --git a/ArmPkg/Library/ArmLib/AArch64/AArch64Lib.h b/ArmPkg/Library/ArmLib/AArch64/AArch64Lib.h index 330481fc50..6380a019dd 100644 --- a/ArmPkg/Library/ArmLib/AArch64/AArch64Lib.h +++ b/ArmPkg/Library/ArmLib/AArch64/AArch64Lib.h @@ -40,7 +40,43 @@ ArmCleanInvalidateDataCacheEntryBySetWay ( UINTN EFIAPI -ArmReadIdAA64Pfr0 ( +ArmReadIdAA64Dfr0 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Dfr1 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Isar0 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Isar1 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Isar2 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Mmfr0 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Mmfr1 ( VOID ); @@ -54,4 +90,16 @@ ArmReadIdAA64Mmfr2 ( VOID ); +UINTN +EFIAPI +ArmReadIdAA64Pfr0 ( + VOID + ); + +UINTN +EFIAPI +ArmReadIdAA64Pfr1 ( + VOID + ); + #endif // AARCH64_LIB_H_ diff --git a/ArmPkg/Library/ArmLib/AArch64/AArch64Support.S b/ArmPkg/Library/ArmLib/AArch64/AArch64Support.S index d3cc1e8671..a7111e5188 100644 --- a/ArmPkg/Library/ArmLib/AArch64/AArch64Support.S +++ b/ArmPkg/Library/ArmLib/AArch64/AArch64Support.S @@ -425,10 +425,6 @@ ASM_FUNC(ArmCallWFI) wfi ret -ASM_FUNC(ArmReadIdAA64Mmfr2) - mrs x0, ID_AA64MMFR2_EL1 // read EL1 MMFR2 - ret - ASM_FUNC(ArmReadMpidr) mrs x0, mpidr_el1 // read EL1 MPIDR ret @@ -452,10 +448,6 @@ ASM_FUNC(ArmIsArchTimerImplemented) ret -ASM_FUNC(ArmReadIdAA64Pfr0) - mrs x0, id_aa64pfr0_el1 // Read ID_AA64PFR0 Register - ret - // VOID ArmWriteHcr(UINTN Hcr) ASM_FUNC(ArmWriteHcr) @@ -482,4 +474,54 @@ ASM_FUNC(ArmWriteCntHctl) msr cnthctl_el2, x0 ret + +ASM_FUNC(ArmReadIdAA64Dfr0) + mrs x0, ID_AA64DFR0_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Dfr1) + mrs x0, ID_AA64DFR1_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Isar0) + mrs x0, ID_AA64ISAR0_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Isar1) + mrs x0, ID_AA64ISAR1_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Isar2) + mrs x0, ID_AA64ISAR2_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Mmfr0) + mrs x0, ID_AA64MMFR0_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Mmfr1) + mrs x0, ID_AA64MMFR1_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Mmfr2) + mrs x0, ID_AA64MMFR2_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Pfr0) + mrs x0, ID_AA64PFR0_EL1 + ret + + +ASM_FUNC(ArmReadIdAA64Pfr1) + mrs x0, ID_AA64PFR1_EL1 + ret + ASM_FUNCTION_REMOVE_IF_UNREFERENCED From 27cb0ebe535f20da679dc3460294207653128b2c Mon Sep 17 00:00:00 2001 From: Marcin Juszkiewicz Date: Fri, 21 Apr 2023 17:51:16 +0200 Subject: [PATCH 0888/1529] ArmPkg: add ArmCpuInfo EFI application App goes through ID_AA64*_EL1 system registers and decode their values. Signed-off-by: Marcin Juszkiewicz Reviewed-by: Leif Lindholm --- ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.c | 2430 ++++++++++++++++++ ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf | 31 + ArmPkg/ArmPkg.dsc | 1 + 3 files changed, 2462 insertions(+) create mode 100644 ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.c create mode 100644 ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf diff --git a/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.c b/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.c new file mode 100644 index 0000000000..deea90fbdf --- /dev/null +++ b/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.c @@ -0,0 +1,2430 @@ +/** @file + Application to present AArch64 cpu information. + + Based on ARM DDI 0487I.a. Update this information when the + app is updated with features from subsequent releases. + +Copyright (c) 2023, Linaro Ltd. All rights reserved.
+ +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +// We cannot assume GCC extensions to be present so let use +// binary numbers via enum. +// Arm ARM uses binary numbers so this way it is more readable. +enum { + b0000, + b0001, + b0010, + b0011, + b0100, + b0101, + b0110, + b0111, + b1000, + b1001, + b1010, + b1011, + b1100, + b1101, + b1110, + b1111 +}; + +/** + Print formatted table line. + + Values can be empty if only new description line is needed. + + @param[in] Field name of system register + @param[in] Bits bits of system register + @param[in] Value value of those bits + @param[in] Description meaning of value +**/ +VOID +PrintText ( + CONST CHAR8 *Field, + CONST CHAR8 *Bits, + CONST CHAR8 *Value, + CONST CHAR8 *Description + ) +{ + AsciiPrint (" %-16a | %5a | %5a | %a\n", Field, Bits, Value, Description); +} + +/** + Print formatted table line with value printed in binary. + + @param[in] Field name of system register + @param[in] Bits bits of system register + @param[in] Value value of those bits + @param[in] Description meaning of value +**/ +VOID +PrintValues ( + CONST CHAR8 *Field, + CONST CHAR8 *Bits, + CONST UINT8 Value, + CONST CHAR8 *Description + ) +{ + STATIC CONST CHAR8 Nibbles[][5] = { + "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", + "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" + }; + + AsciiPrint (" %-16a | %5a | %5a | %a\n", Field, Bits, Nibbles[Value & 0xf], Description); +} + +/** + Print spacer for results table. +**/ +VOID +PrintSpacer ( + VOID + ) +{ + AsciiPrint ("------------------|-------|-------|----------------------------------------------\n"); +} + +/** + Handle ID_AA64DFR0_EL1 system register. + + @param[in] Aa64Dfr0 value of ID_AA64DFR0_EL1 system register +**/ +VOID +HandleAa64Dfr0 ( + CONST UINT64 Aa64Dfr0 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64DFR0"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = (Aa64Dfr0 >> 4) & 0xf; + switch (Value) { + case b0110: + Description = "Armv8 debug architecture"; + break; + case b0111: + Description = "Armv8 debug architecture with VHE"; + break; + case b1000: + Description = "FEAT_Debugv8p2 implemented."; + break; + case b1001: + Description = "FEAT_Debugv8p4 implemented."; + break; + case b1010: + Description = "FEAT_Debugv8p8 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Dfr0 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "Trace unit System registers not implemented."; + break; + case b0001: + Description = "Trace unit System registers implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Dfr0 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "Performance Monitors Extension not implemented."; + break; + case b0001: + Description = "FEAT_PMUv3 implemented."; + break; + case b0100: + Description = "FEAT_PMUv3p1 implemented."; + break; + case b0101: + Description = "FEAT_PMUv3p4 implemented."; + break; + case b0110: + Description = "FEAT_PMUv3p5 implemented."; + break; + case b0111: + Description = "FEAT_PMUv3p7 implemented."; + break; + case b1000: + Description = "FEAT_PMUv3p8 implemented."; + break; + case b1111: + Description = "IMPLEMENTATION DEFINED form of performance monitors supported."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Dfr0 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "reserved"; + break; + default: + Description = "Number of breakpoints, minus 1."; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 19:16 reserved + + Bits = "23:20"; + Value = (Aa64Dfr0 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "reserved"; + break; + default: + Description = "Number of watchpoints, minus 1."; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 27:24 reserved + + Bits = "31:28"; + Value = (Aa64Dfr0 >> 28) & 0xf; + switch (Value) { + default: + Description = "Number of breakpoints that are context-aware, minus 1."; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Dfr0 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SPE not implemented."; + break; + case b0001: + Description = "FEAT_SPE implemented."; + break; + case b0010: + Description = "FEAT_SPEv1p1 implemented."; + break; + case b0011: + Description = "FEAT_SPEv1p2 implemented."; + break; + case b0100: + Description = "FEAT_SPEv1p3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Dfr0 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_DoubleLock implemented."; + break; + case b1111: + Description = "FEAT_DoubleLock not implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Dfr0 >> 40) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TRF not implemented."; + break; + case b0001: + Description = "FEAT_TRF implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Dfr0 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TRBE not implemented."; + break; + case b0001: + Description = "FEAT_TRBE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "51:48"; + Value = (Aa64Dfr0 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_MTPMU not implemented."; + break; + case b0001: + Description = "FEAT_MTPMU and FEAT_PMUv3 implemented."; + break; + case b1111: + Description = "FEAT_MTPMU not implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Dfr0 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_BRBE not implemented."; + break; + case b0001: + Description = "FEAT_BRBE implemented."; + break; + case b0010: + Description = "FEAT_BRBEv1p1 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 59:56 reserved + + Bits = "63:60"; + Value = (Aa64Dfr0 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "Setting MDCR_EL2.HPMN to zero has CONSTRAINED UNPREDICTABLE behavior."; + break; + case b0001: + Description = "FEAT_HPMN0 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64ISAR0_EL1 system register. + + @param[in] Aa64Isar0 value of ID_AA64ISAR0_EL1 system register +**/ +VOID +HandleAa64Isar0 ( + CONST UINT64 Aa64Isar0 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64ISAR0"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + // 3:0 reserved + + Bits = "7:4 "; + Value = (Aa64Isar0 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_AES, FEAT_PMULL not implemented."; + break; + case b0001: + Description = "FEAT_AES implemented."; + break; + case b0010: + Description = "FEAT_AES and FEAT_PMULL implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Isar0 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SHA1 not implemented."; + break; + case b0001: + Description = "FEAT_SHA1 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Isar0 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SHA256, FEAT_SHA512 not implemented."; + break; + case b0001: + Description = "FEAT_SHA256 implemented."; + break; + case b0010: + Description = "FEAT_SHA512 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Isar0 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "CRC32 not implemented."; + break; + case b0001: + Description = "CRC32 instructions implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Isar0 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LSE not implemented."; + break; + case b0010: + Description = "FEAT_LSE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Isar0 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "TME instructions not implemented."; + break; + case b0001: + Description = "TME instructions implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Isar0 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RDM not implemented."; + break; + case b0001: + Description = "FEAT_RDM implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Isar0 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SHA3 not implemented."; + break; + case b0001: + Description = "FEAT_SHA3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Isar0 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SM3 not implemented."; + break; + case b0001: + Description = "FEAT_SM3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Isar0 >> 40) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SM4 not implemented."; + break; + case b0001: + Description = "FEAT_SM4 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Isar0 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_DotProd not implemented."; + break; + case b0001: + Description = "FEAT_DotProd implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "51:48"; + Value = (Aa64Isar0 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_FHM not implemented."; + break; + case b0001: + Description = "FEAT_FHM implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Isar0 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_FlagM/FEAT_FlagM2 not implemented."; + break; + case b0001: + Description = "FEAT_FlagM implemented."; + break; + case b0010: + Description = "FEAT_FlagM2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "59:56"; + Value = (Aa64Isar0 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TLBIOS/FEAT_TLBIRANGE not implemented."; + break; + case b0001: + Description = "FEAT_TLBIOS implemented."; + break; + case b0010: + Description = "FEAT_TLBIRANGE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "63:60"; + Value = (Aa64Isar0 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RNG not implemented."; + break; + case b0001: + Description = "FEAT_RNG implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64ISAR1_EL1 system register. + + @param[in] Aa64Isar1 value of ID_AA64ISAR1_EL1 system register +**/ +VOID +HandleAa64Isar1 ( + CONST UINT64 Aa64Isar1 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64ISAR1"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = (Aa64Isar1 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "DC CVAP not implemented."; + break; + case b0001: + Description = "FEAT_DPB implemented."; + break; + case b0010: + Description = "FEAT_DPB2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Isar1 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "Address Authentication (APA) not implemented."; + break; + case b0001: + Description = "FEAT_PAuth implemented."; + break; + case b0010: + Description = "FEAT_EPAC implemented."; + break; + case b0011: + Description = "FEAT_PAuth2 implemented."; + break; + case b0100: + Description = "FEAT_FPAC implemented."; + break; + case b0101: + Description = "FEAT_FPACCOMBINE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + if (Value > 0) { + PrintText ("", "", "", "FEAT_PACQARMA5 implemented."); + } + + Bits = "11:8 "; + Value = (Aa64Isar1 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "Address Authentication (API) not implemented."; + break; + case b0001: + Description = "FEAT_PAuth implemented."; + break; + case b0010: + Description = "FEAT_EPAC implemented."; + break; + case b0011: + Description = "FEAT_PAuth2 implemented."; + break; + case b0100: + Description = "FEAT_FPAC implemented."; + break; + case b0101: + Description = "FEAT_FPACCOMBINE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + if (Value > 0) { + PrintText ("", "", "", "FEAT_PACIMP implemented."); + } + + Bits = "15:12"; + Value = (Aa64Isar1 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_JSCVT not implemented."; + break; + case b0001: + Description = "FEAT_JSCVT implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Isar1 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_FCMA not implemented."; + break; + case b0001: + Description = "FEAT_FCMA implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Isar1 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LRCPC (2) not implemented."; + break; + case b0001: + Description = "FEAT_LRCPC implemented."; + break; + case b0010: + Description = "FEAT_LRCPC2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Isar1 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_PACQARMA5 not implemented."; + break; + case b0001: + Description = "FEAT_PACQARMA5 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Isar1 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_PACIMP not implemented."; + break; + case b0001: + Description = "FEAT_PACIMP implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Isar1 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_FRINTTS not implemented."; + break; + case b0001: + Description = "FEAT_FRINTTS implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Isar1 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SB not implemented."; + break; + case b0001: + Description = "FEAT_SB implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Isar1 >> 40) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SPECRES not implemented."; + break; + case b0001: + Description = "FEAT_SPECRES implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Isar1 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_BF16 not implemented."; + break; + case b0001: + Description = "FEAT_BF16 implemented."; + break; + case b0010: + Description = "FEAT_EBF16 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "51:48"; + Value = (Aa64Isar1 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_DGH not implemented."; + break; + case b0001: + Description = "FEAT_DGH implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Isar1 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_I8MM not implemented."; + break; + case b0001: + Description = "FEAT_I8MM implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "59:56"; + Value = (Aa64Isar1 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_XS not implemented."; + break; + case b0001: + Description = "FEAT_XS implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "63:60"; + Value = (Aa64Isar1 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LS64 not implemented."; + break; + case b0001: + Description = "FEAT_LS64 implemented."; + break; + case b0010: + Description = "FEAT_LS64_V implemented."; + break; + case b0011: + Description = "FEAT_LS64_ACCDATA implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64ISAR2_EL1 system register. + + @param[in] Aa64Isar2 value of ID_AA64ISAR2_EL1 system register +**/ +VOID +HandleAa64Isar2 ( + CONST UINT64 Aa64Isar2 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64ISAR2"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = (Aa64Isar2 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_WFxT not implemented."; + break; + case b0010: + Description = "FEAT_WFxT implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Isar2 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RPRES not implemented."; + break; + case b0001: + Description = "FEAT_RPRES implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Isar2 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_PACQARMA3 not implemented."; + break; + case b0001: + Description = "FEAT_PACQARMA3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Isar2 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "Address Authentication (APA3) not implemented."; + break; + case b0001: + Description = "FEAT_PAuth implemented."; + break; + case b0010: + Description = "FEAT_EPAC implemented."; + break; + case b0011: + Description = "FEAT_PAuth2 implemented."; + break; + case b0100: + Description = "FEAT_FPAC implemented."; + break; + case b0101: + Description = "FEAT_FPACCOMBINE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Isar2 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_MOPS not implemented."; + break; + case b0001: + Description = "FEAT_MOPS implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Isar2 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_HBC not implemented."; + break; + case b0001: + Description = "FEAT_HBC implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Isar2 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_CONSTPACFIELD not implemented."; + break; + case b0001: + Description = "FEAT_CONSTPACFIELD implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 63:28 reserved +} + +/** + Handle ID_AA64MMFR0_EL1 system register. + + @param[in] Aa64Mmfr0 value of ID_AA64MMFR0_EL1 system register +**/ +VOID +HandleAa64Mmfr0 ( + CONST UINT64 Aa64Mmfr0 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64MMFR0"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = Aa64Mmfr0 & 0xf; + switch (Value) { + case b0000: + Description = "32 Bits (4GB) of physical address range supported."; + break; + case b0001: + Description = "36 Bits (64GB) of physical address range supported."; + break; + case b0010: + Description = "40 Bits (1TB) of physical address range supported."; + break; + case b0011: + Description = "42 Bits (4TB) of physical address range supported."; + break; + case b0100: + Description = "44 Bits (16TB) of physical address range supported."; + break; + case b0101: + Description = "48 Bits (256TB) of physical address range supported."; + break; + case b0110: + Description = "52 Bits (4PB) of physical address range supported."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + if (Value == b0110) { + PrintText ("", "", "", "FEAT_LPA implemented."); + } + + Bits = "7:4 "; + Value = (Aa64Mmfr0 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "ASID: 8 Bits"; + break; + case b0010: + Description = "ASID: 16 Bits"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Mmfr0 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "No mixed-endian support."; + break; + case b0001: + Description = "Mixed-endian support."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // If mixed-endian is present, check whether supported at EL0 + if (((Aa64Mmfr0 >> 8) & 0xf) != b0000 ) { + if (((Aa64Mmfr0 >> 16) & 0xf) == b0000 ) { + PrintValues ("ID_AA64MMFR0", "19:16", b0000, "No mixed-endian support at EL0."); + } + + if (((Aa64Mmfr0 >> 16) & 0xf) == b0001 ) { + PrintValues ("ID_AA64MMFR0", "19:16", b0001, "Mixed-endian support at EL0."); + } + } + + Bits = "15:12"; + Value = (Aa64Mmfr0 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "No support for a distinction between Secure and Non-Secure Memory."; + break; + case b0001: + Description = "Supports a distinction between Secure and Non-Secure Memory."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Mmfr0 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = " 4KB granule supported."; + break; + case b1111: + Description = " 4KB granule not supported."; + break; + case b0001: + Description = " 4KB granule supported for 52-bit address."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Mmfr0 >> 40) & 0xf; + switch (Value) { + case b0001: + Description = " 4KB granule not supported at stage 2."; + break; + case b0010: + Description = " 4KB granule supported at stage 2."; + break; + case b0011: + Description = " 4KB granule supported at stage 2 for 52-bit address."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Mmfr0 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "16KB granule not supported."; + break; + case b0001: + Description = "16KB granule supported."; + break; + case b0010: + Description = "16KB granule supported for 52-bit address."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Mmfr0 >> 32) & 0xf; + switch (Value) { + case b0001: + Description = "16KB granule not supported at stage 2."; + break; + case b0010: + Description = "16KB granule supported at stage 2."; + break; + case b0011: + Description = "16KB granule supported at stage 2 for 52-bit address."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Mmfr0 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "64KB granule supported."; + break; + case b1111: + Description = "64KB granule not supported."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Mmfr0 >> 36) & 0xf; + switch (Value) { + case b0001: + Description = "64KB granule not supported at stage 2."; + break; + case b0010: + Description = "64KB granule supported at stage 2."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Mmfr0 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_ExS not implemented."; + break; + case b0001: + Description = "FEAT_ExS implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 55:48 reserved + + Bits = "59:56"; + Value = (Aa64Mmfr0 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_FGT not implemented."; + break; + case b0001: + Description = "FEAT_FGT implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "63:60"; + Value = (Aa64Mmfr0 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_ECV not implemented."; + break; + case b0001: + Description = "FEAT_ECV implemented."; + break; + case b0010: + Description = "FEAT_ECV implemented with extras."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64MMFR1_EL1 system register. + + @param[in] Aa64Mmfr1 value of ID_AA64MMFR1_EL1 system register + @param[in] Aa64Pfr0, value of ID_AA64PFR0_EL1 system register +**/ +VOID +HandleAa64Mmfr1 ( + CONST UINT64 Aa64Mmfr1, + CONST UINT64 Aa64Pfr0 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64MMFR1"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = Aa64Mmfr1 & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_HAFDBS not implemented."; + break; + case b0001: + Description = "FEAT_HAFDBS implemented without dirty status support."; + break; + case b0010: + Description = "FEAT_HAFDBS implemented with dirty status support."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Mmfr1 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_VMID16 not implemented."; + break; + case b0010: + Description = "FEAT_VMID16 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Mmfr1 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_VHE not implemented."; + break; + case b0001: + Description = "FEAT_VHE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Mmfr1 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_HPDS not implemented."; + break; + case b0001: + Description = "FEAT_HPDS implemented."; + break; + case b0010: + Description = "FEAT_HPDS2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Mmfr1 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LOR not implemented."; + break; + case b0001: + Description = "FEAT_LOR implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Mmfr1 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_PAN not implemented."; + break; + case b0001: + Description = "FEAT_PAN implemented."; + break; + case b0010: + Description = "FEAT_PAN2 implemented."; + break; + case b0011: + Description = "FEAT_PAN3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // when FEAT_RAS implemented + if ((((Aa64Pfr0 >> 28) & 0xf) == b0001) || + (((Aa64Pfr0 >> 28) & 0xf) == b0010)) + { + if (((Aa64Mmfr1 >> 24) & 0xf) == b0000 ) { + PrintValues ("ID_AA64MMFR1", "27:24", b0000, "The PE never generates an SError interrupt due to"); + PrintText ("", "", "", "an External abort on a speculative read."); + } + + if (((Aa64Mmfr1 >> 24) & 0xf) == b0001 ) { + PrintValues ("ID_AA64MMFR1", "27:24", b0001, "The PE might generate an SError interrupt due to"); + PrintText ("", "", "", "an External abort on a speculative read."); + } + } + + Bits = "31:28"; + Value = (Aa64Mmfr1 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_XNX not implemented."; + break; + case b0001: + Description = "FEAT_XNX implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Mmfr1 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TWED not implemented."; + break; + case b0001: + Description = "FEAT_TWED implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Mmfr1 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_ETS not implemented."; + break; + case b0001: + Description = "FEAT_ETS implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Mmfr1 >> 40) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_HCX not implemented."; + break; + case b0001: + Description = "FEAT_HCX implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Mmfr1 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_AFP not implemented."; + break; + case b0001: + Description = "FEAT_AFP implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "51:48"; + Value = (Aa64Mmfr1 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_nTLBPA not implemented."; + break; + case b0001: + Description = "FEAT_nTLBPA implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Mmfr1 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TIDCP1 not implemented"; + break; + case b0001: + Description = "FEAT_TIDCP1 implemented"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "59:56"; + Value = (Aa64Mmfr1 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_CMOW not implemented."; + break; + case b0001: + Description = "FEAT_CMOW implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 63:60 reserved +} + +/** + Handle ID_AA64MMFR2_EL1 system register. + + @param[in] Aa64Mmfr2 value of ID_AA64MMFR2_EL1 system register +**/ +VOID +HandleAa64Mmfr2 ( + CONST UINT64 Aa64Mmfr2 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64MMFR2"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = (Aa64Mmfr2) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TTCNP not implemented."; + break; + case b0001: + Description = "FEAT_TTCNP implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Mmfr2 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_UAO not implemented."; + break; + case b0001: + Description = "FEAT_UAO implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Mmfr2 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LSMAOC not implemented."; + break; + case b0001: + Description = "FEAT_LSMAOC implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Mmfr2 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_IESB not implemented."; + break; + case b0001: + Description = "FEAT_IESB implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Mmfr2 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LVA not implemented."; + break; + case b0001: + Description = "FEAT_LVA implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Mmfr2 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_CCIDX not implemented."; + break; + case b0001: + Description = "FEAT_CCIDX implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Mmfr2 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_NV not implemented."; + break; + case b0001: + Description = "FEAT_NV implemented."; + break; + case b0010: + Description = "FEAT_NV2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Mmfr2 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TTST not implemented."; + break; + case b0001: + Description = "FEAT_TTST implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "35:32"; + Value = (Aa64Mmfr2 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_LSE2 not implemented."; + break; + case b0001: + Description = "FEAT_LSE2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Mmfr2 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_IDST not implemented."; + break; + case b0001: + Description = "FEAT_IDST implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Mmfr2 >> 40) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_S2FWB not implemented."; + break; + case b0001: + Description = "FEAT_S2FWB implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 47:44 reserved + + Bits = "51:48"; + Value = (Aa64Mmfr2 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_TTL not implemented."; + break; + case b0001: + Description = "FEAT_TTL implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Mmfr2 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_BBM: Level 0 support for changing block size is supported."; + break; + case b0001: + Description = "FEAT_BBM: Level 1 support for changing block size is supported."; + break; + case b0010: + Description = "FEAT_BBM: Level 2 support for changing block size is supported."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "59:56"; + Value = (Aa64Mmfr2 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_EVT not implemented."; + break; + case b0001: + Description = "FEAT_EVT: HCR_EL2.{TOCU, TICAB, TID4} traps are supported."; + break; + case b0010: + Description = "FEAT_EVT: HCR_EL2.{TTLBOS, TTLSBIS, TOCU, TICAB, TID4} traps are supported."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "63:60"; + Value = (Aa64Mmfr2 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_E0PD not implemented."; + break; + case b0001: + Description = "FEAT_E0PD implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64PFR0_EL1 system register. + + @param[in] Aa64Pfr0, value of ID_AA64PFR0_EL1 system register + @param[in] Aa64Pfr1, value of ID_AA64PFR1_EL1 system register +**/ +VOID +HandleAa64Pfr0 ( + CONST UINT64 Aa64Pfr0, + CONST UINT64 Aa64Pfr1 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64PFR0"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = (Aa64Pfr0) & 0xf; + switch (Value) { + case b0001: + Description = "EL0 in AArch64 only"; + break; + case b0010: + Description = "EL0 in AArch64 and AArch32"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Pfr0 >> 4) & 0xf; + switch (Value) { + case b0001: + Description = "EL1 in AArch64 only"; + break; + case b0010: + Description = "EL1 in AArch64 and AArch32"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Pfr0 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "EL2 not implemented."; + break; + case b0001: + Description = "EL2 in AArch64 only"; + break; + case b0010: + Description = "EL2 in AArch64 and AArch32"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "15:12"; + Value = (Aa64Pfr0 >> 12) & 0xf; + switch (Value) { + case b0000: + Description = "EL3 not implemented."; + break; + case b0001: + Description = "EL3 in AArch64 only"; + break; + case b0010: + Description = "EL3 in AArch64 and AArch32"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "19:16"; + Value = (Aa64Pfr0 >> 16) & 0xf; + switch (Value) { + case b0000: + Description = "Floating-point implemented."; + break; + case b0001: + Description = "Floating-point with half-precision support (FEAT_FP16)."; + break; + case b1111: + Description = "Floating-point not implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "23:20"; + Value = (Aa64Pfr0 >> 20) & 0xf; + switch (Value) { + case b0000: + Description = "Advanced SIMD implemented."; + break; + case b0001: + Description = "Advanced SIMD with half precision support (FEAT_FP16)."; + break; + case b1111: + Description = "Advanced SIMD not implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "27:24"; + Value = (Aa64Pfr0 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "System registers of GIC CPU not implemented."; + break; + case b0001: + Description = "System registers to versions 3.0/4.0 of GIC CPU implemented."; + break; + case b0011: + Description = "System registers to versions 4.1 of GIC CPU implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Pfr0 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RAS not implemented."; + break; + case b0001: + Description = "FEAT_RAS implemented."; + break; + case b0010: + Description = "FEAT_RASv1p1 implemented."; + // b0010 FEAT_RASv1p1 implemented and, if EL3 is implemented, FEAT_DoubleFault implemented. + if ((((Aa64Pfr0 >> 12) & 0xf) == b0001) || + (((Aa64Pfr0 >> 12) & 0xf) == b0010)) + { + Description = "FEAT_RASv1p1 implemented. FEAT_DoubleFault implemented."; + } + + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + if (Value == b0001) { + if (((Aa64Pfr1 >> 12) & 0xf) == b0001 ) { + PrintValues ("ID_AA64PRF1", "15:12", b0001, "FEAT_RASv1p1 implemented."); + } + } + + Bits = "35:32"; + Value = (Aa64Pfr0 >> 32) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SVE not implemented."; + break; + case b0001: + Description = "FEAT_SVE implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "39:36"; + Value = (Aa64Pfr0 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "Secure EL2 not implemented."; + break; + case b0001: + Description = "Secure EL2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "43:40"; + Value = (Aa64Pfr0 >> 40) & 0xf; + switch (Value) { + case b0000: + if (((Aa64Pfr1 >> 16) & 0xf) == b0000 ) { + Description = "FEAT_MPAM not implemented."; + } + + if (((Aa64Pfr1 >> 16) & 0xf) == b0001 ) { + Description = "FEAT_MPAM v0.1 implemented."; + } + + break; + case b0001: + if (((Aa64Pfr1 >> 16) & 0xf) == b0000 ) { + Description = "FEAT_MPAM v1.0 implemented."; + } + + if (((Aa64Pfr1 >> 16) & 0xf) == b0001 ) { + Description = "FEAT_MPAM v1.1 implemented."; + } + + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "47:44"; + Value = (Aa64Pfr0 >> 44) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_AMU not implemented."; + break; + case b0001: + Description = "FEAT_AMUv1 implemented."; + break; + case b0010: + Description = "FEAT_AMUv1p1 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "51:48"; + Value = (Aa64Pfr0 >> 48) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_DIT not implemented."; + break; + case b0001: + Description = "FEAT_DIT implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "55:52"; + Value = (Aa64Pfr0 >> 52) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RME not implemented"; + break; + case b0001: + Description = "FEAT_RME implemented"; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "59:56"; + Value = (Aa64Pfr0 >> 56) & 0xf; + switch (Value) { + case b0000: + Description = "Not disclosed whether FEAT_CSV2 is implemented."; + break; + case b0001: + Description = "FEAT_CSV2 implemented."; + break; + case b0010: + Description = "FEAT_CSV2_2 implemented."; + break; + case b0011: + Description = "FEAT_CSV2_3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + if (Value == b0001) { + if (((Aa64Pfr1 >> 32) & 0xf) == b0001 ) { + PrintValues ("ID_AA64PRF1", "35:32", b0001, "FEAT_CSV2_1p1 implemented."); + } + + if (((Aa64Pfr1 >> 32) & 0xf) == b0010 ) { + PrintValues ("ID_AA64PRF1", "35:32", b0010, "FEAT_CSV2_1p2 implemented."); + } + } + + Bits = "63:60"; + Value = (Aa64Pfr0 >> 60) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_CSV3 not implemented."; + break; + case b0001: + Description = "FEAT_CSV3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); +} + +/** + Handle ID_AA64PFR1_EL1 system register. + + @param[in] Aa64Pfr1 value of ID_AA64PFR1_EL1 system register +**/ +VOID +HandleAa64Pfr1 ( + CONST UINT64 Aa64Pfr1 + ) +{ + UINT64 Value; + STATIC CONST CHAR8 RegName[] = "ID_AA64PFR1"; + CONST CHAR8 *Description; + CONST CHAR8 *Bits; + + Bits = "3:0 "; + Value = Aa64Pfr1 & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_BTI not implemented."; + break; + case b0001: + Description = "FEAT_BTI implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "7:4 "; + Value = (Aa64Pfr1 >> 4) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SSBS not implemented."; + break; + case b0001: + Description = "FEAT_SSBS implemented."; + break; + case b0010: + Description = "FEAT_SSBS2 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "11:8 "; + Value = (Aa64Pfr1 >> 8) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_MTE not implemented."; + break; + case b0001: + Description = "FEAT_MTE implemented."; + break; + case b0010: + Description = "FEAT_MTE2 implemented."; + break; + case b0011: + Description = "FEAT_MTE3 implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 15:12 is RAS_frac + // 19:16 is MPAM_frac + // 23:20 is reserved + + Bits = "27:24"; + Value = (Aa64Pfr1 >> 24) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_SME not implemented."; + break; + case b0001: + Description = "FEAT_SME implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + Bits = "31:28"; + Value = (Aa64Pfr1 >> 28) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_RNG_TRAP not implemented."; + break; + case b0001: + Description = "FEAT_RNG_TRAP implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 35:32 is CSV2_frac + + Bits = "39:36"; + Value = (Aa64Pfr1 >> 36) & 0xf; + switch (Value) { + case b0000: + Description = "FEAT_NMI not implemented."; + break; + case b0001: + Description = "FEAT_NMI implemented."; + break; + default: + Description = "unknown"; + break; + } + + PrintValues (RegName, Bits, Value, Description); + + // 63:40 are reserved +} + +/** + The user Entry Point for Application. The user code starts with this function + as the real entry point for the application. + + @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 +UefiMain ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + UINT64 Aa64Dfr0; + UINT64 Aa64Isar0; + UINT64 Aa64Isar1; + UINT64 Aa64Isar2; + UINT64 Aa64Mmfr0; + UINT64 Aa64Mmfr1; + UINT64 Aa64Mmfr2; + UINT64 Aa64Pfr0; + UINT64 Aa64Pfr1; + + Aa64Dfr0 = ArmReadIdAA64Dfr0 (); + Aa64Isar0 = ArmReadIdAA64Isar0 (); + Aa64Isar1 = ArmReadIdAA64Isar1 (); + Aa64Isar2 = ArmReadIdAA64Isar2 (); + Aa64Mmfr0 = ArmReadIdAA64Mmfr0 (); + Aa64Mmfr1 = ArmReadIdAA64Mmfr1 (); + Aa64Mmfr2 = ArmReadIdAA64Mmfr2 (); + Aa64Pfr0 = ArmReadIdAA64Pfr0 (); + Aa64Pfr1 = ArmReadIdAA64Pfr1 (); + + AsciiPrint ("ID_AA64MMFR0_EL1 = 0x%016lx\n", Aa64Mmfr0); + AsciiPrint ("ID_AA64MMFR1_EL1 = 0x%016lx\n", Aa64Mmfr1); + AsciiPrint ("ID_AA64MMFR2_EL1 = 0x%016lx\n", Aa64Mmfr2); + AsciiPrint ("ID_AA64PFR0_EL1 = 0x%016lx\n", Aa64Pfr0); + AsciiPrint ("ID_AA64PFR1_EL1 = 0x%016lx\n", Aa64Pfr1); + AsciiPrint ("ID_AA64ISAR0_EL1 = 0x%016lx\n", Aa64Isar0); + AsciiPrint ("ID_AA64ISAR1_EL1 = 0x%016lx\n", Aa64Isar1); + AsciiPrint ("ID_AA64ISAR2_EL1 = 0x%016lx\n", Aa64Isar2); + AsciiPrint ("ID_AA64DFR0_EL1 = 0x%016lx\n", Aa64Dfr0); + AsciiPrint ("\n"); + + PrintText ("Register", "Bits", "Value", "Feature"); + PrintSpacer (); + + HandleAa64Mmfr0 (Aa64Mmfr0); + PrintSpacer (); + HandleAa64Mmfr1 (Aa64Mmfr1, Aa64Pfr0); + PrintSpacer (); + HandleAa64Mmfr2 (Aa64Mmfr2); + + PrintSpacer (); + HandleAa64Pfr0 (Aa64Pfr0, Aa64Pfr1); + PrintSpacer (); + HandleAa64Pfr1 (Aa64Pfr1); + + PrintSpacer (); + HandleAa64Isar0 (Aa64Isar0); + PrintSpacer (); + HandleAa64Isar1 (Aa64Isar1); + PrintSpacer (); + HandleAa64Isar2 (Aa64Isar2); + + PrintSpacer (); + HandleAa64Dfr0 (Aa64Dfr0); + + return EFI_SUCCESS; +} diff --git a/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf b/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf new file mode 100644 index 0000000000..da29548a7f --- /dev/null +++ b/ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf @@ -0,0 +1,31 @@ +## @file +# Application to present AArch64 cpu information. +# +# Based on HelloWorld: +# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2023, Linaro Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010019 + BASE_NAME = ArmCpuInfo + FILE_GUID = b3134491-6502-4faf-a9da-007184e32163 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = UefiMain + +[Sources] + ArmCpuInfo.c + +[Packages] + ArmPkg/ArmPkg.dec + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + ArmLib + UefiApplicationEntryPoint + UefiLib diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc index 3fb95d1951..6b938ce8b6 100644 --- a/ArmPkg/ArmPkg.dsc +++ b/ArmPkg/ArmPkg.dsc @@ -166,6 +166,7 @@ ArmPkg/Drivers/ArmPsciMpServicesDxe/ArmPsciMpServicesDxe.inf ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf ArmPkg/Library/ArmMmuLib/ArmMmuPeiLib.inf + ArmPkg/Application/ArmCpuInfo/ArmCpuInfo.inf [Components.AARCH64, Components.ARM] ArmPkg/Library/StandaloneMmMmuLib/ArmMmuStandaloneMmLib.inf From 08215b5c36cac2381cce29532f36d1646f8eed7b Mon Sep 17 00:00:00 2001 From: Rebecca Cran Date: Mon, 24 Apr 2023 07:39:59 -0600 Subject: [PATCH 0889/1529] BaseTools: Add quotes around OBJCOPY cmd in build_rule.template Add quotes around the OBJCOPY command in build_rule.template to fix the case where LLVM is installed on Windows in a path with spaces such as C:\Program Files\LLVM. Signed-off-by: Rebecca Cran Reviewed-by: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Conf/build_rule.template | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index d42e7937cc..eb64c62060 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -352,12 +352,12 @@ -$(CP) $(DEBUG_DIR)(+)*.pdb $(OUTPUT_DIR) $(CP) ${src} $(DEBUG_DIR)(+)$(MODULE_NAME).debug - $(OBJCOPY) $(OBJCOPY_STRIPFLAG) ${src} + "$(OBJCOPY)" $(OBJCOPY_STRIPFLAG) ${src} # #The below 2 lines are only needed for UNIXGCC tool chain, which generates PE image directly # - -$(OBJCOPY) $(OBJCOPY_ADDDEBUGFLAG) ${src} + -"$(OBJCOPY)" $(OBJCOPY_ADDDEBUGFLAG) ${src} -$(CP) $(DEBUG_DIR)(+)$(MODULE_NAME).debug $(BIN_DIR)(+)$(MODULE_NAME_GUID).debug "$(GENFW)" -e $(MODULE_TYPE) -o ${dst} ${src} $(GENFW_FLAGS) From 141ce238c797492012348a32e1e142922c8ecb93 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Thu, 9 Mar 2023 16:32:49 +0100 Subject: [PATCH 0890/1529] DynamicTablesPkg/SsdtCpuTopology: Allow multi-packages topologies The topology of a platform is represented in ACPI using the PPTT table. It is possible to append information to CPUs/processor containers using their associated AML nodes in a SSDT table. A platform might have multiple 'physical packages' (or top-level nodes) in their PPTT topology representation. It can be assumed from [1] that a 'physical packages' is always a 'top-level node', and conversely. The SSDT topology generator doesn't support having multiple top-level nodes. The top-level node is also not generated in the SSDT topology representation. Add support to generate multiple top-level nodes in the SSDT topology generator and generate an AML node for this top-level node. This will allow to have matching PPTT and SSDT topology representations. Prior to this patch, this top-level AML node was not generated. Also factorize the flag checking in CheckProcNode() and add more checks. This patch takes inspiration from the discussion at: - v1: https://edk2.groups.io/g/devel/message/99410 - v2: https://edk2.groups.io/g/devel/message/99615 [1] ACPI 6.5, 5.2.30.1 Processor hierarchy node structure (Type 0): - "Multiple trees may be described, covering for example multiple packages. For the root of a tree, the parent pointer should be 0."" - "Each valid processor must belong to exactly one package. That is, the leaf must itself be a physical package or have an ancestor marked as a physical package." Suggested-by: Jeff Brasen Signed-off-by: Pierre Gondois Reviewed-by: Jeff Brasen Reviewed-by: Sami Mujawar --- .../SsdtCpuTopologyGenerator.c | 131 +++++++++++------- .../SsdtCpuTopologyGenerator.h | 4 + 2 files changed, 84 insertions(+), 51 deletions(-) diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c index c24da8ec71..6fb131b664 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.c @@ -805,6 +805,57 @@ CreateAmlProcessorContainer ( return Status; } +/** Check flags and topology of a ProcNode. + + @param [in] NodeFlags Flags of the ProcNode to check. + @param [in] IsLeaf The ProcNode is a leaf. + @param [in] NodeToken NodeToken of the ProcNode. + @param [in] ParentNodeToken Parent NodeToken of the ProcNode. + + @retval EFI_SUCCESS Success. + @retval EFI_INVALID_PARAMETER Invalid parameter. +**/ +STATIC +EFI_STATUS +EFIAPI +CheckProcNode ( + UINT32 NodeFlags, + BOOLEAN IsLeaf, + CM_OBJECT_TOKEN NodeToken, + CM_OBJECT_TOKEN ParentNodeToken + ) +{ + BOOLEAN InvalidFlags; + BOOLEAN HasPhysicalPackageBit; + BOOLEAN IsTopLevelNode; + + HasPhysicalPackageBit = (NodeFlags & EFI_ACPI_6_3_PPTT_PACKAGE_PHYSICAL) == + EFI_ACPI_6_3_PPTT_PACKAGE_PHYSICAL; + IsTopLevelNode = (ParentNodeToken == CM_NULL_TOKEN); + + // A top-level node is a Physical Package and conversely. + InvalidFlags = HasPhysicalPackageBit ^ IsTopLevelNode; + + // Check Leaf specific flags. + if (IsLeaf) { + InvalidFlags |= ((NodeFlags & PPTT_LEAF_MASK) != PPTT_LEAF_MASK); + } else { + InvalidFlags |= ((NodeFlags & PPTT_LEAF_MASK) != 0); + } + + if (InvalidFlags) { + DEBUG (( + DEBUG_ERROR, + "ERROR: SSDT-CPU-TOPOLOGY: Invalid flags for ProcNode: 0x%p.\n", + (VOID *)NodeToken + )); + ASSERT (0); + return EFI_INVALID_PARAMETER; + } + + return EFI_SUCCESS; +} + /** Create an AML representation of the Cpu topology. A processor container is by extension any non-leave device in the cpu topology. @@ -814,7 +865,6 @@ CreateAmlProcessorContainer ( Protocol Interface. @param [in] NodeToken Token of the CM_ARM_PROC_HIERARCHY_INFO currently handled. - Cannot be CM_NULL_TOKEN. @param [in] ParentNode Parent node to attach the created node to. @param [in,out] ProcContainerIndex Pointer to the current processor container @@ -838,6 +888,7 @@ CreateAmlCpuTopologyTree ( EFI_STATUS Status; UINT32 Index; UINT32 CpuIndex; + UINT32 ProcContainerName; AML_OBJECT_NODE_HANDLE ProcContainerNode; UINT32 Uid; UINT16 Name; @@ -846,11 +897,11 @@ CreateAmlCpuTopologyTree ( ASSERT (Generator->ProcNodeList != NULL); ASSERT (Generator->ProcNodeCount != 0); ASSERT (CfgMgrProtocol != NULL); - ASSERT (NodeToken != CM_NULL_TOKEN); ASSERT (ParentNode != NULL); ASSERT (ProcContainerIndex != NULL); - CpuIndex = 0; + CpuIndex = 0; + ProcContainerName = 0; for (Index = 0; Index < Generator->ProcNodeCount; Index++) { // Find the children of the CM_ARM_PROC_HIERARCHY_INFO @@ -859,16 +910,15 @@ CreateAmlCpuTopologyTree ( // Only Cpus (leaf nodes in this tree) have a GicCToken. // Create a Cpu node. if (Generator->ProcNodeList[Index].GicCToken != CM_NULL_TOKEN) { - if ((Generator->ProcNodeList[Index].Flags & PPTT_PROCESSOR_MASK) != - PPTT_CPU_PROCESSOR_MASK) - { - DEBUG (( - DEBUG_ERROR, - "ERROR: SSDT-CPU-TOPOLOGY: Invalid flags for cpu: 0x%x.\n", - Generator->ProcNodeList[Index].Flags - )); + Status = CheckProcNode ( + Generator->ProcNodeList[Index].Flags, + TRUE, + Generator->ProcNodeList[Index].Token, + NodeToken + ); + if (EFI_ERROR (Status)) { ASSERT (0); - return EFI_INVALID_PARAMETER; + return Status; } if (Generator->ProcNodeList[Index].OverrideNameUidEnabled) { @@ -893,24 +943,22 @@ CreateAmlCpuTopologyTree ( } else { // If this is not a Cpu, then this is a processor container. - // Acpi processor Id for clusters is not handled. - if ((Generator->ProcNodeList[Index].Flags & PPTT_PROCESSOR_MASK) != - PPTT_CLUSTER_PROCESSOR_MASK) - { - DEBUG (( - DEBUG_ERROR, - "ERROR: SSDT-CPU-TOPOLOGY: Invalid flags for cluster: 0x%x.\n", - Generator->ProcNodeList[Index].Flags - )); + Status = CheckProcNode ( + Generator->ProcNodeList[Index].Flags, + FALSE, + Generator->ProcNodeList[Index].Token, + NodeToken + ); + if (EFI_ERROR (Status)) { ASSERT (0); - return EFI_INVALID_PARAMETER; + return Status; } if (Generator->ProcNodeList[Index].OverrideNameUidEnabled) { Name = Generator->ProcNodeList[Index].OverrideName; Uid = Generator->ProcNodeList[Index].OverrideUid; } else { - Name = *ProcContainerIndex; + Name = ProcContainerName; Uid = *ProcContainerIndex; } @@ -933,6 +981,13 @@ CreateAmlCpuTopologyTree ( (*ProcContainerIndex)++; CpuIndex = 0; + // And reset the cluster name whenever there is a package. + if (NodeToken == CM_NULL_TOKEN) { + ProcContainerName = 0; + } else { + ProcContainerName++; + } + // Recursively continue creating an AML tree. Status = CreateAmlCpuTopologyTree ( Generator, @@ -974,8 +1029,6 @@ CreateTopologyFromProcHierarchy ( ) { EFI_STATUS Status; - UINT32 Index; - UINT32 TopLevelProcNodeIndex; UINT32 ProcContainerIndex; ASSERT (Generator != NULL); @@ -984,8 +1037,7 @@ CreateTopologyFromProcHierarchy ( ASSERT (CfgMgrProtocol != NULL); ASSERT (ScopeNode != NULL); - TopLevelProcNodeIndex = MAX_UINT32; - ProcContainerIndex = 0; + ProcContainerIndex = 0; Status = TokenTableInitialize (Generator, Generator->ProcNodeCount); if (EFI_ERROR (Status)) { @@ -993,33 +1045,10 @@ CreateTopologyFromProcHierarchy ( return Status; } - // It is assumed that there is one unique CM_ARM_PROC_HIERARCHY_INFO - // structure with no ParentToken and the EFI_ACPI_6_3_PPTT_PACKAGE_PHYSICAL - // flag set. All other CM_ARM_PROC_HIERARCHY_INFO are non-physical and - // have a ParentToken. - for (Index = 0; Index < Generator->ProcNodeCount; Index++) { - if ((Generator->ProcNodeList[Index].ParentToken == CM_NULL_TOKEN) && - (Generator->ProcNodeList[Index].Flags & - EFI_ACPI_6_3_PPTT_PACKAGE_PHYSICAL)) - { - if (TopLevelProcNodeIndex != MAX_UINT32) { - DEBUG (( - DEBUG_ERROR, - "ERROR: SSDT-CPU-TOPOLOGY: Top level CM_ARM_PROC_HIERARCHY_INFO " - "must be unique\n" - )); - ASSERT (0); - goto exit_handler; - } - - TopLevelProcNodeIndex = Index; - } - } // for - Status = CreateAmlCpuTopologyTree ( Generator, CfgMgrProtocol, - Generator->ProcNodeList[TopLevelProcNodeIndex].Token, + CM_NULL_TOKEN, ScopeNode, &ProcContainerIndex ); diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.h b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.h index f174d9c2e2..48e4455490 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.h +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCpuTopologyLibArm/SsdtCpuTopologyGenerator.h @@ -34,6 +34,10 @@ (EFI_ACPI_6_3_PPTT_PROCESSOR_ID_INVALID << 1) | \ (EFI_ACPI_6_3_PPTT_NODE_IS_NOT_LEAF << 3)) +// Leaf nodes specific mask. +#define PPTT_LEAF_MASK ((EFI_ACPI_6_3_PPTT_PROCESSOR_ID_VALID << 1) | \ + (EFI_ACPI_6_3_PPTT_NODE_IS_LEAF << 3)) + /** LPI states are stored in the ASL namespace at '\_SB_.Lxxx', with xxx being the node index of the LPI state. */ From d9531596946010b69d988c9a3d2a4f6147e3722b Mon Sep 17 00:00:00 2001 From: Igor Kulchytskyy Date: Thu, 20 Apr 2023 14:36:38 -0400 Subject: [PATCH 0891/1529] RedfishPkg: Remove the Discover Token global variables gRedfishDiscoveredToken may be allocated several times, if multiple NIC installed on the system. To avoid this issue Discover Token related global variables replaced with the local variables. Cc: Abner Chang Cc: Nickle Wang Cc: Igor Kulchytskyy Signed-off-by: Igor Kulchytskyy Reviewed-by: Abner Chang --- .../RedfishConfigHandlerDriver.c | 143 +++++++----------- .../RedfishDiscoverDxe/RedfishDiscoverDxe.c | 87 ++++++++--- .../RedfishDiscoverInternal.h | 28 +++- 3 files changed, 139 insertions(+), 119 deletions(-) diff --git a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c index 993ad338b6..161731b211 100644 --- a/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c +++ b/RedfishPkg/RedfishConfigHandler/RedfishConfigHandlerDriver.c @@ -22,12 +22,6 @@ EFI_HANDLE gEfiRedfishDiscoverControllerHandle = NULL; EFI_REDFISH_DISCOVER_PROTOCOL *gEfiRedfishDiscoverProtocol = NULL; BOOLEAN gRedfishDiscoverActivated = FALSE; BOOLEAN gRedfishServiceDiscovered = FALSE; -// -// Network interfaces discovered by EFI Redfish Discover Protocol. -// -UINTN gNumberOfNetworkInterfaces; -EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *gNetworkInterfaceInstances = NULL; -EFI_REDFISH_DISCOVERED_TOKEN *gRedfishDiscoveredToken = NULL; /// /// Driver Binding Protocol instance @@ -58,13 +52,6 @@ RedfishConfigStopRedfishDiscovery ( gBS->CloseEvent (gEfiRedfishDiscoverProtocolEvent); } - // - // Stop Redfish service discovery. - // - gEfiRedfishDiscoverProtocol->AbortAcquireRedfishService ( - gEfiRedfishDiscoverProtocol, - gNetworkInterfaceInstances - ); gEfiRedfishDiscoverControllerHandle = NULL; gEfiRedfishDiscoverProtocol = NULL; gRedfishDiscoverActivated = FALSE; @@ -318,36 +305,38 @@ RedfishServiceDiscoveredCallback ( EFI_REDFISH_DISCOVERED_TOKEN *RedfishDiscoveredToken; EFI_REDFISH_DISCOVERED_INSTANCE *RedfishInstance; - if (gRedfishServiceDiscovered) { - // - // Only support one Redfish service on platform. - // - return; - } - RedfishDiscoveredToken = (EFI_REDFISH_DISCOVERED_TOKEN *)Context; - RedfishInstance = RedfishDiscoveredToken->DiscoverList.RedfishInstances; + gBS->CloseEvent (RedfishDiscoveredToken->Event); + // - // Only pick up the first found Redfish service. + // Only support one Redfish service on platform. // - if (RedfishInstance->Status == EFI_SUCCESS) { - gRedfishConfigData.RedfishServiceInfo.RedfishServiceRestExHandle = RedfishInstance->Information.RedfishRestExHandle; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceVersion = RedfishInstance->Information.RedfishVersion; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceLocation = RedfishInstance->Information.Location; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceUuid = RedfishInstance->Information.Uuid; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceOs = RedfishInstance->Information.Os; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceOsVersion = RedfishInstance->Information.OsVersion; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceProduct = RedfishInstance->Information.Product; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceProductVer = RedfishInstance->Information.ProductVer; - gRedfishConfigData.RedfishServiceInfo.RedfishServiceUseHttps = RedfishInstance->Information.UseHttps; - gRedfishServiceDiscovered = TRUE; + if (!gRedfishServiceDiscovered) { + RedfishInstance = RedfishDiscoveredToken->DiscoverList.RedfishInstances; + // + // Only pick up the first found Redfish service. + // + if (RedfishInstance->Status == EFI_SUCCESS) { + gRedfishConfigData.RedfishServiceInfo.RedfishServiceRestExHandle = RedfishInstance->Information.RedfishRestExHandle; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceVersion = RedfishInstance->Information.RedfishVersion; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceLocation = RedfishInstance->Information.Location; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceUuid = RedfishInstance->Information.Uuid; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceOs = RedfishInstance->Information.Os; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceOsVersion = RedfishInstance->Information.OsVersion; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceProduct = RedfishInstance->Information.Product; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceProductVer = RedfishInstance->Information.ProductVer; + gRedfishConfigData.RedfishServiceInfo.RedfishServiceUseHttps = RedfishInstance->Information.UseHttps; + gRedfishServiceDiscovered = TRUE; + } + + // + // Invoke RedfishConfigHandlerInstalledCallback to execute + // the initialization of Redfish Configure Handler instance. + // + RedfishConfigHandlerInstalledCallback (gRedfishConfigData.Event, &gRedfishConfigData); } - // - // Invoke RedfishConfigHandlerInstalledCallback to execute - // the initialization of Redfish Configure Handler instance. - // - RedfishConfigHandlerInstalledCallback (gRedfishConfigData.Event, &gRedfishConfigData); + FreePool (RedfishDiscoveredToken); } /** @@ -371,6 +360,7 @@ RedfishDiscoverProtocolInstalled ( UINTN NetworkInterfaceIndex; EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *ThisNetworkInterface; EFI_REDFISH_DISCOVERED_TOKEN *ThisRedfishDiscoveredToken; + UINTN NumberOfNetworkInterfaces; DEBUG ((DEBUG_INFO, "%a: New network interface is installed on system by EFI Redfish discover driver.\n", __func__)); @@ -408,36 +398,29 @@ RedfishDiscoverProtocolInstalled ( } } - // - // Check the new found network interface. - // - if (gNetworkInterfaceInstances != NULL) { - FreePool (gNetworkInterfaceInstances); - } - Status = gEfiRedfishDiscoverProtocol->GetNetworkInterfaceList ( gEfiRedfishDiscoverProtocol, gRedfishConfigData.Image, - &gNumberOfNetworkInterfaces, - &gNetworkInterfaceInstances + &NumberOfNetworkInterfaces, + &ThisNetworkInterface ); - if (EFI_ERROR (Status) || (gNumberOfNetworkInterfaces == 0)) { + if (EFI_ERROR (Status) || (NumberOfNetworkInterfaces == 0)) { DEBUG ((DEBUG_ERROR, "%a: No network interfaces found on the handle.\n", __func__)); return; } - gRedfishDiscoveredToken = AllocateZeroPool (gNumberOfNetworkInterfaces * sizeof (EFI_REDFISH_DISCOVERED_TOKEN)); - if (gRedfishDiscoveredToken == NULL) { - DEBUG ((DEBUG_ERROR, "%a: Not enough memory for EFI_REDFISH_DISCOVERED_TOKEN.\n", __func__)); - return; - } - - ThisNetworkInterface = gNetworkInterfaceInstances; - ThisRedfishDiscoveredToken = gRedfishDiscoveredToken; // // Loop to discover Redfish service on each network interface. // - for (NetworkInterfaceIndex = 0; NetworkInterfaceIndex < gNumberOfNetworkInterfaces; NetworkInterfaceIndex++) { + for (NetworkInterfaceIndex = 0; NetworkInterfaceIndex < NumberOfNetworkInterfaces; NetworkInterfaceIndex++) { + ThisRedfishDiscoveredToken = (EFI_REDFISH_DISCOVERED_TOKEN *)AllocateZeroPool (sizeof (EFI_REDFISH_DISCOVERED_TOKEN)); + if (ThisRedfishDiscoveredToken == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Not enough memory for EFI_REDFISH_DISCOVERED_TOKEN.\n", __func__)); + return; + } + + ThisRedfishDiscoveredToken->Signature = REDFISH_DISCOVER_TOKEN_SIGNATURE; + // // Initial this Redfish Discovered Token // @@ -449,13 +432,11 @@ RedfishDiscoverProtocolInstalled ( &ThisRedfishDiscoveredToken->Event ); if (EFI_ERROR (Status)) { + FreePool (ThisRedfishDiscoveredToken); DEBUG ((DEBUG_ERROR, "%a: Failed to create event for Redfish discovered token.\n", __func__)); - goto ErrorReturn; + return; } - ThisRedfishDiscoveredToken->Signature = REDFISH_DISCOVER_TOKEN_SIGNATURE; - ThisRedfishDiscoveredToken->DiscoverList.NumberOfServiceFound = 0; - ThisRedfishDiscoveredToken->DiscoverList.RedfishInstances = NULL; // // Acquire for Redfish service which is reported by // Redfish Host Interface. @@ -467,21 +448,23 @@ RedfishDiscoverProtocolInstalled ( EFI_REDFISH_DISCOVER_HOST_INTERFACE, ThisRedfishDiscoveredToken ); - ThisNetworkInterface++; - ThisRedfishDiscoveredToken++; - } - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: Acquire Redfish service fail.\n", __func__)); - goto ErrorReturn; + // + // Free Redfish Discovered Token if Discover Instance was not created and + // Redfish Service Discovered Callback event was not triggered. + // + if ((ThisRedfishDiscoveredToken->DiscoverList.NumberOfServiceFound == 0) || + EFI_ERROR (ThisRedfishDiscoveredToken->DiscoverList.RedfishInstances->Status)) + { + gBS->CloseEvent (ThisRedfishDiscoveredToken->Event); + DEBUG ((DEBUG_ERROR, "%a: Free Redfish discovered token - %x.\n", __func__, ThisRedfishDiscoveredToken)); + FreePool (ThisRedfishDiscoveredToken); + } + + ThisNetworkInterface++; } return; - -ErrorReturn: - if (gRedfishDiscoveredToken != NULL) { - FreePool (gRedfishDiscoveredToken); - } } /** @@ -498,25 +481,9 @@ RedfishConfigHandlerDriverUnload ( IN EFI_HANDLE ImageHandle ) { - EFI_REDFISH_DISCOVERED_TOKEN *ThisRedfishDiscoveredToken; - UINTN NumberOfNetworkInterfacesIndex; - RedfishConfigDriverCommonUnload (ImageHandle); RedfishConfigStopRedfishDiscovery (); - if (gRedfishDiscoveredToken != NULL) { - ThisRedfishDiscoveredToken = gRedfishDiscoveredToken; - for (NumberOfNetworkInterfacesIndex = 0; NumberOfNetworkInterfacesIndex < gNumberOfNetworkInterfaces; NumberOfNetworkInterfacesIndex++) { - if (ThisRedfishDiscoveredToken->Event != NULL) { - gBS->CloseEvent (ThisRedfishDiscoveredToken->Event); - } - - FreePool (ThisRedfishDiscoveredToken); - ThisRedfishDiscoveredToken++; - } - - gRedfishDiscoveredToken = NULL; - } return EFI_SUCCESS; } diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c index 583c6f78e1..0900a2479e 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverDxe.c @@ -1095,8 +1095,11 @@ RedfishServiceGetNetworkInterface ( { EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *ThisNetworkInterfaceIntn; EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *ThisNetworkInterface; + EFI_REDFISH_DISCOVER_REST_EX_INSTANCE_INTERNAL *RestExInstance; - if ((NetworkIntfInstances == NULL) || (NumberOfNetworkIntfs == NULL) || (ImageHandle == NULL)) { + if ((This == NULL) || (NetworkIntfInstances == NULL) || (NumberOfNetworkIntfs == NULL) || + (ImageHandle == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -1107,12 +1110,26 @@ RedfishServiceGetNetworkInterface ( return EFI_NOT_FOUND; } + RestExInstance = EFI_REDFISH_DISOVER_DATA_FROM_DISCOVER_PROTOCOL (This); + + // + // Check the new found network interface. + // + if (RestExInstance->NetworkInterfaceInstances != NULL) { + FreePool (RestExInstance->NetworkInterfaceInstances); + RestExInstance->NetworkInterfaceInstances = NULL; + } + ThisNetworkInterface = (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *)AllocateZeroPool (sizeof (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE) * mNumNetworkInterface); if (ThisNetworkInterface == NULL) { return EFI_OUT_OF_RESOURCES; } - *NetworkIntfInstances = ThisNetworkInterface; + *NetworkIntfInstances = ThisNetworkInterface; + + RestExInstance->NetworkInterfaceInstances = ThisNetworkInterface; + RestExInstance->NumberOfNetworkInterfaces = 0; + ThisNetworkInterfaceIntn = (EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *)GetFirstNode (&mEfiRedfishDiscoverNetworkInterface); while (TRUE) { ThisNetworkInterface->IsIpv6 = FALSE; @@ -1130,7 +1147,7 @@ RedfishServiceGetNetworkInterface ( ThisNetworkInterface->SubnetPrefixLength = ThisNetworkInterfaceIntn->SubnetPrefixLength; ThisNetworkInterface->VlanId = ThisNetworkInterfaceIntn->VlanId; - (*NumberOfNetworkIntfs)++; + RestExInstance->NumberOfNetworkInterfaces++; if (IsNodeAtEnd (&mEfiRedfishDiscoverNetworkInterface, &ThisNetworkInterfaceIntn->Entry)) { break; } @@ -1139,6 +1156,8 @@ RedfishServiceGetNetworkInterface ( ThisNetworkInterface++; } + *NumberOfNetworkIntfs = RestExInstance->NumberOfNetworkInterfaces; + return EFI_SUCCESS; } @@ -1178,7 +1197,6 @@ RedfishServiceAcquireService ( { EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE *Instance; EFI_STATUS Status1; - EFI_STATUS Status2; BOOLEAN NewInstance; UINTN NumNetworkInterfaces; UINTN NetworkInterfacesIndex; @@ -1215,7 +1233,6 @@ RedfishServiceAcquireService ( for (NetworkInterfacesIndex = 0; NetworkInterfacesIndex < NumNetworkInterfaces; NetworkInterfacesIndex++) { Status1 = EFI_SUCCESS; - Status2 = EFI_SUCCESS; NewInstance = FALSE; Instance = GetInstanceByOwner (ImageHandle, TargetNetworkInterfaceInternal, Flags & ~EFI_REDFISH_DISCOVER_VALIDATION); // Check if we can re-use previous instance. if (Instance == NULL) { @@ -1223,6 +1240,7 @@ RedfishServiceAcquireService ( Instance = (EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE *)AllocateZeroPool (sizeof (EFI_REDFISH_DISCOVERED_INTERNAL_INSTANCE)); if (Instance == NULL) { DEBUG ((DEBUG_ERROR, "%a:Memory allocation fail.\n", __func__)); + return EFI_OUT_OF_RESOURCES; } InitializeListHead (&Instance->Entry); @@ -1258,9 +1276,12 @@ RedfishServiceAcquireService ( DEBUG ((DEBUG_ERROR, "%a:Redfish service discovery through SSDP is not supported\n", __func__)); return EFI_UNSUPPORTED; } else { - if (EFI_ERROR (Status1) && EFI_ERROR (Status2)) { - FreePool ((VOID *)Instance); - DEBUG ((DEBUG_ERROR, "%a:Something wrong on Redfish service discovery Status1=%x, Status2=%x.\n", __func__, Status1, Status2)); + if (EFI_ERROR (Status1)) { + if (NewInstance) { + FreePool ((VOID *)Instance); + } + + DEBUG ((DEBUG_ERROR, "%a:Something wrong on Redfish service discovery Status1=%r.\n", __func__, Status1)); } else { if (NewInstance) { InsertTailList (&mRedfishDiscoverList, &Instance->Entry); @@ -1387,13 +1408,6 @@ ReleaseNext:; } } -EFI_REDFISH_DISCOVER_PROTOCOL mRedfishDiscover = { - RedfishServiceGetNetworkInterface, - RedfishServiceAcquireService, - RedfishServiceAbortAcquire, - RedfishServiceReleaseService -}; - /** This function create an EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL for the given network interface. @@ -1713,12 +1727,20 @@ BuildupNetworkInterface ( NewNetworkInterfaceInstalled = FALSE; NetworkInterface->EfiRedfishDiscoverProtocolHandle = NULL; - Status = gBS->InstallProtocolInterface ( - &NetworkInterface->EfiRedfishDiscoverProtocolHandle, - &gEfiRedfishDiscoverProtocolGuid, - EFI_NATIVE_INTERFACE, - (VOID *)&mRedfishDiscover - ); + + RestExInstance->Signature = EFI_REDFISH_DISCOVER_DATA_SIGNATURE; + + RestExInstance->RedfishDiscoverProtocol.GetNetworkInterfaceList = RedfishServiceGetNetworkInterface; + RestExInstance->RedfishDiscoverProtocol.AcquireRedfishService = RedfishServiceAcquireService; + RestExInstance->RedfishDiscoverProtocol.AbortAcquireRedfishService = RedfishServiceAbortAcquire; + RestExInstance->RedfishDiscoverProtocol.ReleaseRedfishService = RedfishServiceReleaseService; + + Status = gBS->InstallProtocolInterface ( + &NetworkInterface->EfiRedfishDiscoverProtocolHandle, + &gEfiRedfishDiscoverProtocolGuid, + EFI_NATIVE_INTERFACE, + (VOID *)&RestExInstance->RedfishDiscoverProtocol + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Fail to install EFI_REDFISH_DISCOVER_PROTOCOL\n", __func__)); } @@ -1815,6 +1837,7 @@ StopServiceOnNetworkInterface ( EFI_HANDLE DiscoverProtocolHandle; EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL *ThisNetworkInterface; EFI_REDFISH_DISCOVER_REST_EX_INSTANCE_INTERNAL *RestExInstance; + EFI_REDFISH_DISCOVER_PROTOCOL *RedfishDiscoverProtocol; for (Index = 0; Index < (sizeof (gRequiredProtocol) / sizeof (REDFISH_DISCOVER_REQUIRED_PROTOCOL)); Index++) { Status = gBS->HandleProtocol ( @@ -1854,12 +1877,28 @@ StopServiceOnNetworkInterface ( // client which uses .EFI Redfish discover protocol. // if (DiscoverProtocolHandle != NULL) { - gBS->DisconnectController (DiscoverProtocolHandle, NULL, NULL); - Status = gBS->UninstallProtocolInterface ( + Status = gBS->HandleProtocol ( DiscoverProtocolHandle, &gEfiRedfishDiscoverProtocolGuid, - (VOID *)&mRedfishDiscover + (VOID **)&RedfishDiscoverProtocol ); + if (!EFI_ERROR (Status)) { + RestExInstance = EFI_REDFISH_DISOVER_DATA_FROM_DISCOVER_PROTOCOL (RedfishDiscoverProtocol); + // + // Stop Redfish service discovery. + // + RedfishDiscoverProtocol->AbortAcquireRedfishService ( + RedfishDiscoverProtocol, + RestExInstance->NetworkInterfaceInstances + ); + + gBS->DisconnectController (DiscoverProtocolHandle, NULL, NULL); + Status = gBS->UninstallProtocolInterface ( + DiscoverProtocolHandle, + &gEfiRedfishDiscoverProtocolGuid, + (VOID *)&RestExInstance->RedfishDiscoverProtocol + ); + } } return Status; diff --git a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h index 2704cd955d..d24c4081d9 100644 --- a/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h +++ b/RedfishPkg/RedfishDiscoverDxe/RedfishDiscoverInternal.h @@ -117,17 +117,31 @@ typedef struct { ///< on this network interface. } EFI_REDFISH_DISCOVER_NETWORK_INTERFACE_INTERNAL; +// +// Redfish Discover Instance signature +// + +#define EFI_REDFISH_DISCOVER_DATA_SIGNATURE SIGNATURE_32 ('E', 'R', 'D', 'D') + +#define EFI_REDFISH_DISOVER_DATA_FROM_DISCOVER_PROTOCOL(a) \ + CR (a, EFI_REDFISH_DISCOVER_REST_EX_INSTANCE_INTERNAL, RedfishDiscoverProtocol, EFI_REDFISH_DISCOVER_DATA_SIGNATURE) + // // Internal structure used to maintain REST EX properties. // typedef struct { - LIST_ENTRY Entry; ///< Link list entry. - EFI_HANDLE OpenDriverAgentHandle; ///< The agent to open network protocol. - EFI_HANDLE OpenDriverControllerHandle; ///< The controller handle to open network protocol. - EFI_HANDLE RestExChildHandle; ///< The child handle created through REST EX Service Protocol. - EFI_HANDLE RestExControllerHandle; ///< The controller handle which provide REST EX protocol. - EFI_REST_EX_PROTOCOL *RestExProtocolInterface; ///< Pointer to EFI_REST_EX_PROTOCOL. - UINT32 RestExId; ///< The identifier installed on REST EX controller handle. + LIST_ENTRY Entry; ///< Link list entry. + UINT32 Signature; ///< Instance signature. + EFI_HANDLE OpenDriverAgentHandle; ///< The agent to open network protocol. + EFI_HANDLE OpenDriverControllerHandle; ///< The controller handle to open network protocol. + EFI_HANDLE RestExChildHandle; ///< The child handle created through REST EX Service Protocol. + EFI_HANDLE RestExControllerHandle; ///< The controller handle which provide REST EX protocol. + EFI_REST_EX_PROTOCOL *RestExProtocolInterface; ///< Pointer to EFI_REST_EX_PROTOCOL. + UINT32 RestExId; ///< The identifier installed on REST EX controller handle. + UINTN NumberOfNetworkInterfaces; ///< Number of network interfaces can do Redfish service discovery. + EFI_REDFISH_DISCOVER_NETWORK_INTERFACE *NetworkInterfaceInstances; ///< Network interface instances. It's an array of instances. The number of entries + ///< in array is indicated by NumberOfNetworkInterfaces. + EFI_REDFISH_DISCOVER_PROTOCOL RedfishDiscoverProtocol; ///< EFI_REDFISH_DISCOVER_PROTOCOL protocol. } EFI_REDFISH_DISCOVER_REST_EX_INSTANCE_INTERNAL; /** From 0a895a357e98381994d7ace43ee717ab756f72f9 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 25 Apr 2023 12:47:05 +0800 Subject: [PATCH 0892/1529] UefiCpuPkg: Update code to support enable ProcTrace only on BSP Update code to support enable ProcTrace only on BSP. Add a new dynamic PCD to indicate if enable ProcTrace only on BSP. In ProcTrace.c code, if this new PCD is true, only allocate buffer and set CtrlReg.Bits.TraceEn to 1 for BSP. Bugzila: https://bugzilla.tianocore.org/show_bug.cgi?id=4423 Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Xiao X Chen --- .../CpuCommonFeaturesLib.inf | 3 +- .../Library/CpuCommonFeaturesLib/ProcTrace.c | 174 +++++++++++------- UefiCpuPkg/UefiCpuPkg.dec | 7 + 3 files changed, 119 insertions(+), 65 deletions(-) diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf index 7fbcd8da0e..d803012ce2 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf @@ -4,7 +4,7 @@ # This library registers CPU features defined in Intel(R) 64 and IA-32 # Architectures Software Developer's Manual. # -# Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2017 - 2023, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -62,3 +62,4 @@ gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset ## SOMETIMES_CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceOutputScheme ## SOMETIMES_CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceMemSize ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceBspOnly ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c b/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c index 04e6a60728..92d6f54b42 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c @@ -1,7 +1,7 @@ /** @file Intel Processor Trace feature. - Copyright (c) 2017 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2017 - 2023, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -46,6 +46,8 @@ typedef struct { UINTN *TopaMemArray; + BOOLEAN EnableOnBspOnly; + PROC_TRACE_PROCESSOR_DATA *ProcessorData; } PROC_TRACE_DATA; @@ -77,6 +79,7 @@ ProcTraceGetConfigData ( ConfigData->NumberOfProcessors = (UINT32)NumberOfProcessors; ConfigData->ProcTraceMemSize = PcdGet32 (PcdCpuProcTraceMemSize); ConfigData->ProcTraceOutputScheme = PcdGet8 (PcdCpuProcTraceOutputScheme); + ConfigData->EnableOnBspOnly = PcdGetBool (PcdCpuProcTraceBspOnly); return ConfigData; } @@ -188,6 +191,7 @@ ProcTraceInitialize ( MSR_IA32_RTIT_OUTPUT_BASE_REGISTER OutputBaseReg; MSR_IA32_RTIT_OUTPUT_MASK_PTRS_REGISTER OutputMaskPtrsReg; RTIT_TOPA_TABLE_ENTRY *TopaEntryPtr; + BOOLEAN IsBsp; // // The scope of the MSR_IA32_RTIT_* is core for below processor type, only program @@ -236,6 +240,12 @@ ProcTraceInitialize ( return RETURN_SUCCESS; } + IsBsp = (CpuInfo->ProcessorInfo.StatusFlag & PROCESSOR_AS_BSP_BIT) ? TRUE : FALSE; + + if (ProcTraceData->EnableOnBspOnly && !IsBsp) { + return RETURN_SUCCESS; + } + MemRegionBaseAddr = 0; FirstIn = FALSE; @@ -260,43 +270,62 @@ ProcTraceInitialize ( // address base in MSR, IA32_RTIT_OUTPUT_BASE (560h) bits 47:12. Note that all regions must be // aligned based on their size, not just 4K. Thus a 2M region must have bits 20:12 cleared. // - ThreadMemRegionTable = (UINTN *)AllocatePool (ProcTraceData->NumberOfProcessors * sizeof (UINTN *)); - if (ThreadMemRegionTable == NULL) { - DEBUG ((DEBUG_ERROR, "Allocate ProcTrace ThreadMemRegionTable Failed\n")); - return RETURN_OUT_OF_RESOURCES; - } - ProcTraceData->ThreadMemRegionTable = ThreadMemRegionTable; - - for (Index = 0; Index < ProcTraceData->NumberOfProcessors; Index++, ProcTraceData->AllocatedThreads++) { - Pages = EFI_SIZE_TO_PAGES (MemRegionSize); - Alignment = MemRegionSize; - AlignedAddress = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); - if (AlignedAddress == 0) { - DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, allocated only for %d threads\n", ProcTraceData->AllocatedThreads)); - if (Index == 0) { - // - // Could not allocate for BSP even - // - FreePool ((VOID *)ThreadMemRegionTable); - ThreadMemRegionTable = NULL; - return RETURN_OUT_OF_RESOURCES; + Pages = EFI_SIZE_TO_PAGES (MemRegionSize); + Alignment = MemRegionSize; + if (ProcTraceData->EnableOnBspOnly) { + // + // When only enable ProcTrace on BSP, this is the first and only time ProcTraceInitialize() runs. + // + MemRegionBaseAddr = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); + if (MemRegionBaseAddr == 0) { + // + // Could not allocate for BSP even + // + DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, failed to allocate buffer for BSP\n")); + return RETURN_OUT_OF_RESOURCES; + } + + DEBUG ((DEBUG_INFO, "ProcTrace: Allocated PT MemRegionBaseAddr(aligned) for BSP only: 0x%llX.\n", (UINT64)MemRegionBaseAddr)); + } else { + ThreadMemRegionTable = (UINTN *)AllocatePool (ProcTraceData->NumberOfProcessors * sizeof (UINTN *)); + if (ThreadMemRegionTable == NULL) { + DEBUG ((DEBUG_ERROR, "Allocate ProcTrace ThreadMemRegionTable Failed\n")); + return RETURN_OUT_OF_RESOURCES; + } + + ProcTraceData->ThreadMemRegionTable = ThreadMemRegionTable; + + for (Index = 0; Index < ProcTraceData->NumberOfProcessors; Index++, ProcTraceData->AllocatedThreads++) { + AlignedAddress = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); + if (AlignedAddress == 0) { + DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, allocated only for %d threads\n", ProcTraceData->AllocatedThreads)); + if (Index == 0) { + // + // Could not allocate for BSP even + // + FreePool ((VOID *)ThreadMemRegionTable); + ThreadMemRegionTable = NULL; + return RETURN_OUT_OF_RESOURCES; + } + + break; } - break; + ThreadMemRegionTable[Index] = AlignedAddress; + DEBUG ((DEBUG_INFO, "ProcTrace: PT MemRegionBaseAddr(aligned) for thread %d: 0x%llX \n", Index, (UINT64)ThreadMemRegionTable[Index])); } - ThreadMemRegionTable[Index] = AlignedAddress; - DEBUG ((DEBUG_INFO, "ProcTrace: PT MemRegionBaseAddr(aligned) for thread %d: 0x%llX \n", Index, (UINT64)ThreadMemRegionTable[Index])); + DEBUG ((DEBUG_INFO, "ProcTrace: Allocated PT mem for %d thread \n", ProcTraceData->AllocatedThreads)); } - - DEBUG ((DEBUG_INFO, "ProcTrace: Allocated PT mem for %d thread \n", ProcTraceData->AllocatedThreads)); } - if (ProcessorNumber < ProcTraceData->AllocatedThreads) { - MemRegionBaseAddr = ProcTraceData->ThreadMemRegionTable[ProcessorNumber]; - } else { - return RETURN_SUCCESS; + if (!ProcTraceData->EnableOnBspOnly) { + if (ProcessorNumber < ProcTraceData->AllocatedThreads) { + MemRegionBaseAddr = ProcTraceData->ThreadMemRegionTable[ProcessorNumber]; + } else { + return RETURN_SUCCESS; + } } /// @@ -367,50 +396,67 @@ ProcTraceInitialize ( // if (FirstIn) { DEBUG ((DEBUG_INFO, "ProcTrace: Enabling ToPA scheme \n")); - // - // Let BSP allocate ToPA table mem for all threads - // - TopaMemArray = (UINTN *)AllocatePool (ProcTraceData->AllocatedThreads * sizeof (UINTN *)); - if (TopaMemArray == NULL) { - DEBUG ((DEBUG_ERROR, "ProcTrace: Allocate mem for ToPA Failed\n")); - return RETURN_OUT_OF_RESOURCES; - } - ProcTraceData->TopaMemArray = TopaMemArray; + Pages = EFI_SIZE_TO_PAGES (sizeof (PROC_TRACE_TOPA_TABLE)); + Alignment = 0x1000; - for (Index = 0; Index < ProcTraceData->AllocatedThreads; Index++) { - Pages = EFI_SIZE_TO_PAGES (sizeof (PROC_TRACE_TOPA_TABLE)); - Alignment = 0x1000; - AlignedAddress = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); - if (AlignedAddress == 0) { - if (Index < ProcTraceData->AllocatedThreads) { - ProcTraceData->AllocatedThreads = Index; - } + if (ProcTraceData->EnableOnBspOnly) { + // + // When only enable ProcTrace on BSP, this is the first and only time ProcTraceInitialize() runs. + // + TopaTableBaseAddr = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); + if (TopaTableBaseAddr == 0) { + DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, failed to allocate ToPA mem for BSP")); + return RETURN_OUT_OF_RESOURCES; + } - DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, allocated ToPA mem only for %d threads\n", ProcTraceData->AllocatedThreads)); - if (Index == 0) { - // - // Could not allocate for BSP even - // - FreePool ((VOID *)TopaMemArray); - TopaMemArray = NULL; - return RETURN_OUT_OF_RESOURCES; + DEBUG ((DEBUG_INFO, "ProcTrace: Topa table address(aligned) for BSP only: 0x%llX \n", (UINT64)TopaTableBaseAddr)); + } else { + // + // Let BSP allocate ToPA table mem for all threads + // + TopaMemArray = (UINTN *)AllocatePool (ProcTraceData->AllocatedThreads * sizeof (UINTN *)); + if (TopaMemArray == NULL) { + DEBUG ((DEBUG_ERROR, "ProcTrace: Allocate mem for ToPA Failed\n")); + return RETURN_OUT_OF_RESOURCES; + } + + ProcTraceData->TopaMemArray = TopaMemArray; + + for (Index = 0; Index < ProcTraceData->AllocatedThreads; Index++) { + AlignedAddress = (UINTN)AllocateAlignedReservedPages (Pages, Alignment); + if (AlignedAddress == 0) { + if (Index < ProcTraceData->AllocatedThreads) { + ProcTraceData->AllocatedThreads = Index; + } + + DEBUG ((DEBUG_ERROR, "ProcTrace: Out of mem, allocated ToPA mem only for %d threads\n", ProcTraceData->AllocatedThreads)); + if (Index == 0) { + // + // Could not allocate for BSP even + // + FreePool ((VOID *)TopaMemArray); + TopaMemArray = NULL; + return RETURN_OUT_OF_RESOURCES; + } + + break; } - break; + TopaMemArray[Index] = AlignedAddress; + DEBUG ((DEBUG_INFO, "ProcTrace: Topa table address(aligned) for thread %d is 0x%llX \n", Index, (UINT64)TopaMemArray[Index])); } - TopaMemArray[Index] = AlignedAddress; - DEBUG ((DEBUG_INFO, "ProcTrace: Topa table address(aligned) for thread %d is 0x%llX \n", Index, (UINT64)TopaMemArray[Index])); + DEBUG ((DEBUG_INFO, "ProcTrace: Allocated ToPA mem for %d thread \n", ProcTraceData->AllocatedThreads)); } - - DEBUG ((DEBUG_INFO, "ProcTrace: Allocated ToPA mem for %d thread \n", ProcTraceData->AllocatedThreads)); } - if (ProcessorNumber < ProcTraceData->AllocatedThreads) { - TopaTableBaseAddr = ProcTraceData->TopaMemArray[ProcessorNumber]; - } else { - return RETURN_SUCCESS; + if (!ProcTraceData->EnableOnBspOnly) { + if (ProcessorNumber < ProcTraceData->AllocatedThreads) { + TopaTableBaseAddr = ProcTraceData->TopaMemArray[ProcessorNumber]; + } else { + return RETURN_SUCCESS; + } } TopaTable = (PROC_TRACE_TOPA_TABLE *)TopaTableBaseAddr; diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index a5528277ff..6845e80706 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -338,6 +338,13 @@ # @Prompt Current boot is a power-on reset. gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset|FALSE|BOOLEAN|0x0000001B + ## This PCD indicates whether CPU processor trace is enabled on BSP only when CPU processor trace is enabled.

+ # This PCD is ignored if CPU processor trace is disabled.

+ # TRUE - CPU processor trace is enabled on BSP only.
+ # FASLE - CPU processor trace is enabled on all CPU.
+ # @Prompt Enable CPU processor trace only on BSP. + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceBspOnly|FALSE|BOOLEAN|0x60000019 + [PcdsFixedAtBuild.X64, PcdsPatchableInModule.X64, PcdsDynamic.X64, PcdsDynamicEx.X64] ## Indicate access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock. # MMIO access is always allowed regardless of the value of this PCD. From f8f40208290537b1fde0af2a57100245df6fa147 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 25 Apr 2023 16:33:30 +0800 Subject: [PATCH 0893/1529] UefiCpuPkg: Update PT code to support enable collect performance Update ProcTrace feature code to support enable collect performance data by generating CYC and TSC packets. Add a new dynamic PCD to indicate if enable performance collecting. In ProcTrace.c code, if this new PCD is true, after check cpuid, CYC and TSC packets will be generated by setting the corresponding MSR bits feilds if supported. Bugzila: https://bugzilla.tianocore.org/show_bug.cgi?id=4423 Signed-off-by: Dun Tan Cc: Eric Dong Reviewed-by: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Xiao X Chen --- .../CpuCommonFeaturesLib.inf | 11 +++--- .../Library/CpuCommonFeaturesLib/ProcTrace.c | 38 +++++++++++++++---- UefiCpuPkg/UefiCpuPkg.dec | 8 ++++ 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf index d803012ce2..1b823155b1 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf @@ -58,8 +58,9 @@ LocalApicLib [Pcd] - gUefiCpuPkgTokenSpaceGuid.PcdCpuClockModulationDutyCycle ## SOMETIMES_CONSUMES - gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset ## SOMETIMES_CONSUMES - gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceOutputScheme ## SOMETIMES_CONSUMES - gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceMemSize ## SOMETIMES_CONSUMES - gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceBspOnly ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuClockModulationDutyCycle ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceOutputScheme ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceMemSize ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceBspOnly ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTracePerformanceCollecting ## SOMETIMES_CONSUMES diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c b/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c index 92d6f54b42..a4510eb802 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/ProcTrace.c @@ -33,6 +33,7 @@ typedef struct { MSR_IA32_RTIT_CTL_REGISTER RtitCtrl; MSR_IA32_RTIT_OUTPUT_BASE_REGISTER RtitOutputBase; MSR_IA32_RTIT_OUTPUT_MASK_PTRS_REGISTER RtitOutputMaskPtrs; + BOOLEAN CycPacketSupported; } PROC_TRACE_PROCESSOR_DATA; typedef struct { @@ -47,6 +48,7 @@ typedef struct { UINTN *TopaMemArray; BOOLEAN EnableOnBspOnly; + BOOLEAN EnablePerformanceCollecting; PROC_TRACE_PROCESSOR_DATA *ProcessorData; } PROC_TRACE_DATA; @@ -76,10 +78,11 @@ ProcTraceGetConfigData ( ASSERT (ConfigData != NULL); ConfigData->ProcessorData = (PROC_TRACE_PROCESSOR_DATA *)((UINT8 *)ConfigData + sizeof (PROC_TRACE_DATA)); - ConfigData->NumberOfProcessors = (UINT32)NumberOfProcessors; - ConfigData->ProcTraceMemSize = PcdGet32 (PcdCpuProcTraceMemSize); - ConfigData->ProcTraceOutputScheme = PcdGet8 (PcdCpuProcTraceOutputScheme); - ConfigData->EnableOnBspOnly = PcdGetBool (PcdCpuProcTraceBspOnly); + ConfigData->NumberOfProcessors = (UINT32)NumberOfProcessors; + ConfigData->ProcTraceMemSize = PcdGet32 (PcdCpuProcTraceMemSize); + ConfigData->ProcTraceOutputScheme = PcdGet8 (PcdCpuProcTraceOutputScheme); + ConfigData->EnableOnBspOnly = PcdGetBool (PcdCpuProcTraceBspOnly); + ConfigData->EnablePerformanceCollecting = PcdGetBool (PcdCpuProcTracePerformanceCollecting); return ConfigData; } @@ -111,7 +114,8 @@ ProcTraceSupport ( { PROC_TRACE_DATA *ProcTraceData; CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_EBX Ebx; - CPUID_INTEL_PROCESSOR_TRACE_MAIN_LEAF_ECX Ecx; + CPUID_INTEL_PROCESSOR_TRACE_MAIN_LEAF_ECX ProcTraceEcx; + CPUID_INTEL_PROCESSOR_TRACE_MAIN_LEAF_EBX ProcTraceEbx; // // Check if ProcTraceMemorySize option is enabled (0xFF means disable by user) @@ -132,15 +136,17 @@ ProcTraceSupport ( return FALSE; } - AsmCpuidEx (CPUID_INTEL_PROCESSOR_TRACE, CPUID_INTEL_PROCESSOR_TRACE_MAIN_LEAF, NULL, NULL, &Ecx.Uint32, NULL); - ProcTraceData->ProcessorData[ProcessorNumber].TopaSupported = (BOOLEAN)(Ecx.Bits.RTIT == 1); - ProcTraceData->ProcessorData[ProcessorNumber].SingleRangeSupported = (BOOLEAN)(Ecx.Bits.SingleRangeOutput == 1); + AsmCpuidEx (CPUID_INTEL_PROCESSOR_TRACE, CPUID_INTEL_PROCESSOR_TRACE_MAIN_LEAF, NULL, &ProcTraceEbx.Uint32, &ProcTraceEcx.Uint32, NULL); + ProcTraceData->ProcessorData[ProcessorNumber].TopaSupported = (BOOLEAN)(ProcTraceEcx.Bits.RTIT == 1); + ProcTraceData->ProcessorData[ProcessorNumber].SingleRangeSupported = (BOOLEAN)(ProcTraceEcx.Bits.SingleRangeOutput == 1); if ((ProcTraceData->ProcessorData[ProcessorNumber].TopaSupported && (ProcTraceData->ProcTraceOutputScheme == RtitOutputSchemeToPA)) || (ProcTraceData->ProcessorData[ProcessorNumber].SingleRangeSupported && (ProcTraceData->ProcTraceOutputScheme == RtitOutputSchemeSingleRange))) { ProcTraceData->ProcessorData[ProcessorNumber].RtitCtrl.Uint64 = AsmReadMsr64 (MSR_IA32_RTIT_CTL); ProcTraceData->ProcessorData[ProcessorNumber].RtitOutputBase.Uint64 = AsmReadMsr64 (MSR_IA32_RTIT_OUTPUT_BASE); ProcTraceData->ProcessorData[ProcessorNumber].RtitOutputMaskPtrs.Uint64 = AsmReadMsr64 (MSR_IA32_RTIT_OUTPUT_MASK_PTRS); + ProcTraceData->ProcessorData[ProcessorNumber].CycPacketSupported = (BOOLEAN)(ProcTraceEbx.Bits.ConfigurablePsb == 1); + return TRUE; } @@ -517,6 +523,22 @@ ProcTraceInitialize ( CtrlReg.Bits.User = 1; CtrlReg.Bits.BranchEn = 1; CtrlReg.Bits.TraceEn = 1; + + // + // Generate CYC/TSC timing packets to collect performance data. + // + if (ProcTraceData->EnablePerformanceCollecting) { + if (ProcTraceData->ProcessorData[ProcessorNumber].CycPacketSupported) { + CtrlReg.Bits.CYCEn = 1; + CtrlReg.Bits.CYCThresh = 5; + } + + // + // Write to TSCEn is always supported + // + CtrlReg.Bits.TSCEn = 1; + } + CPU_REGISTER_TABLE_WRITE64 ( ProcessorNumber, Msr, diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 6845e80706..d31c3b127c 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -345,6 +345,14 @@ # @Prompt Enable CPU processor trace only on BSP. gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceBspOnly|FALSE|BOOLEAN|0x60000019 + ## This PCD indicates if enable performance collecting when CPU processor trace is enabled.

+ # CYC/TSC timing packets will be generated to collect performance data if this PCD is TRUE. + # This PCD is ignored if CPU processor trace is disabled.

+ # TRUE - Performance collecting will be enabled in processor trace.
+ # FASLE - Performance collecting will be disabled in processor trace.
+ # @Prompt Enable performance collecting when processor trace is enabled. + gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTracePerformanceCollecting|FALSE|BOOLEAN|0x60000020 + [PcdsFixedAtBuild.X64, PcdsPatchableInModule.X64, PcdsDynamic.X64, PcdsDynamicEx.X64] ## Indicate access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock. # MMIO access is always allowed regardless of the value of this PCD. From 0d87bcbce7ca38ef4becb1e49dd9aae48b40f6ca Mon Sep 17 00:00:00 2001 From: Michael Roth Date: Wed, 26 Apr 2023 04:32:55 +0800 Subject: [PATCH 0894/1529] OvmfPkg/AmdSevDxe: Allocate SEV-SNP CC blob as EfiACPIReclaimMemory The SEV-SNP Confidential Computing blob contains metadata that should remain accessible for the life of the guest. Allocate it as EfiACPIReclaimMemory to ensure the memory isn't overwritten by the guest operating system later. Reported-by: Dov Murik Suggested-by: Dov Murik Reviewed-by: Dov Murik Reviewed-by: Tom Lendacky Acked-by: Gerd Hoffmann Signed-off-by: Michael Roth --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 62 +++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 14 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index 05b728d32a..df807066fa 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -28,15 +28,36 @@ // Present, initialized, tested bits defined in MdeModulePkg/Core/Dxe/DxeMain.h #define EFI_MEMORY_INTERNAL_MASK 0x0700000000000000ULL -STATIC CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION mSnpBootDxeTable = { - SIGNATURE_32 ('A', 'M', 'D', 'E'), - 1, - 0, - (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfSnpSecretsBase), - FixedPcdGet32 (PcdOvmfSnpSecretsSize), - (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfCpuidBase), - FixedPcdGet32 (PcdOvmfCpuidSize), -}; +STATIC +EFI_STATUS +AllocateConfidentialComputingBlob ( + OUT CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION **CcBlobPtr + ) +{ + EFI_STATUS Status; + CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION *CcBlob; + + Status = gBS->AllocatePool ( + EfiACPIReclaimMemory, + sizeof (CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION), + (VOID **)&CcBlob + ); + if (EFI_ERROR (Status)) { + return Status; + } + + CcBlob->Header = SIGNATURE_32 ('A', 'M', 'D', 'E'); + CcBlob->Version = 1; + CcBlob->Reserved1 = 0; + CcBlob->SecretsPhysicalAddress = (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfSnpSecretsBase); + CcBlob->SecretsSize = FixedPcdGet32 (PcdOvmfSnpSecretsSize); + CcBlob->CpuidPhysicalAddress = (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfCpuidBase); + CcBlob->CpuidLSize = FixedPcdGet32 (PcdOvmfCpuidSize); + + *CcBlobPtr = CcBlob; + + return EFI_SUCCESS; +} STATIC EFI_HANDLE mAmdSevDxeHandle = NULL; @@ -175,10 +196,11 @@ AmdSevDxeEntryPoint ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap; - UINTN NumEntries; - UINTN Index; + EFI_STATUS Status; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDescMap; + UINTN NumEntries; + UINTN Index; + CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION *SnpBootDxeTable; // // Do nothing when SEV is not enabled @@ -284,6 +306,18 @@ AmdSevDxeEntryPoint ( } } + Status = AllocateConfidentialComputingBlob (&SnpBootDxeTable); + if (EFI_ERROR (Status)) { + DEBUG (( + DEBUG_ERROR, + "%a: AllocateConfidentialComputingBlob(): %r\n", + __func__, + Status + )); + ASSERT (FALSE); + CpuDeadLoop (); + } + if (MemEncryptSevSnpIsEnabled ()) { // // Memory acceptance began being required in SEV-SNP, so install the @@ -321,7 +355,7 @@ AmdSevDxeEntryPoint ( // return gBS->InstallConfigurationTable ( &gConfidentialComputingSevSnpBlobGuid, - &mSnpBootDxeTable + SnpBootDxeTable ); } From 0989ecae52fb42cecc6edc58625d1f54165cd7f2 Mon Sep 17 00:00:00 2001 From: "Roth, Michael via groups.io" Date: Wed, 26 Apr 2023 04:32:56 +0800 Subject: [PATCH 0895/1529] OvmfPkg/AmdSevDxe: Update ConfidentialComputing blob struct definition The Confidential Computing blob defined here is intended to match the definition defined by linux guest kernel. Previously, both definitions relied on natural alignment, but that relies on both OVMF and kernel being compiled as 64-bit. While there aren't currently any plans to enable SNP support for 32-bit compilations, the kernel definition has since been updated to use explicit padding/reserved fields to avoid this dependency. Update OVMF to match that definition. While at it, also fix up the Reserved fields to match the numbering used in the kernel. No functional changes (for currently-supported environments, at least). Reviewed-by: Tom Lendacky Acked-by: Jiewen Yao Acked-by: Gerd Hoffmann Signed-off-by: Michael Roth --- OvmfPkg/AmdSevDxe/AmdSevDxe.c | 4 +++- OvmfPkg/Include/Guid/ConfidentialComputingSevSnpBlob.h | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/AmdSevDxe/AmdSevDxe.c b/OvmfPkg/AmdSevDxe/AmdSevDxe.c index df807066fa..db3675ae86 100644 --- a/OvmfPkg/AmdSevDxe/AmdSevDxe.c +++ b/OvmfPkg/AmdSevDxe/AmdSevDxe.c @@ -48,11 +48,13 @@ AllocateConfidentialComputingBlob ( CcBlob->Header = SIGNATURE_32 ('A', 'M', 'D', 'E'); CcBlob->Version = 1; - CcBlob->Reserved1 = 0; + CcBlob->Reserved = 0; CcBlob->SecretsPhysicalAddress = (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfSnpSecretsBase); CcBlob->SecretsSize = FixedPcdGet32 (PcdOvmfSnpSecretsSize); + CcBlob->Reserved1 = 0; CcBlob->CpuidPhysicalAddress = (UINT64)(UINTN)FixedPcdGet32 (PcdOvmfCpuidBase); CcBlob->CpuidLSize = FixedPcdGet32 (PcdOvmfCpuidSize); + CcBlob->Reserved2 = 0; *CcBlobPtr = CcBlob; diff --git a/OvmfPkg/Include/Guid/ConfidentialComputingSevSnpBlob.h b/OvmfPkg/Include/Guid/ConfidentialComputingSevSnpBlob.h index b328310fd0..83620e31b8 100644 --- a/OvmfPkg/Include/Guid/ConfidentialComputingSevSnpBlob.h +++ b/OvmfPkg/Include/Guid/ConfidentialComputingSevSnpBlob.h @@ -18,14 +18,16 @@ { 0x85, 0x54, 0x93, 0xd7, 0x77, 0x91, 0x2d, 0x42 }, \ } -typedef struct { +typedef PACKED struct { UINT32 Header; UINT16 Version; - UINT16 Reserved1; + UINT16 Reserved; UINT64 SecretsPhysicalAddress; UINT32 SecretsSize; + UINT32 Reserved1; UINT64 CpuidPhysicalAddress; UINT32 CpuidLSize; + UINT32 Reserved2; } CONFIDENTIAL_COMPUTING_SNP_BLOB_LOCATION; extern EFI_GUID gConfidentialComputingSevSnpBlobGuid; From a6aadd3503ca3c9145c6c0d99f096ff942847378 Mon Sep 17 00:00:00 2001 From: "Roth, Michael via groups.io" Date: Wed, 26 Apr 2023 04:32:57 +0800 Subject: [PATCH 0896/1529] OvmfPkg/CcExitLib: Fix SEV-SNP XSave area size calculation CPUID leaf 0xD sub-leafs 0x0 and 0x1 contain cumulative sizes for the enabled XSave areas. Those sizes are calculated by tallying up all the other sub-leafs that contain per-area size information for XSave areas that are currently enabled in XCr0/XSS. The current check has the logic inverted. Fix that. This doesn't seem to cause problems currently, but could in the future if OVMF made more extensive use of XSave areas. It was noticed while implementing SNP-related tests for KVM Unit Tests, which re-uses the OVMF #VC handler in some cases. Reported-by: Pavan Kumar Paluri Cc: Pavan Kumar Paluri Reviewed-by: Tom Lendacky Acked-by: Jiewen Yao Acked-by: Gerd Hoffmann Signed-off-by: Michael Roth --- OvmfPkg/Library/CcExitLib/CcExitVcHandler.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index 7fe11c5324..94f0c4872c 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -1145,9 +1145,7 @@ GetCpuidXSaveSize ( for (Idx = 0; Idx < CpuidInfo->Count; Idx++) { SEV_SNP_CPUID_FUNCTION *CpuidFn = &CpuidInfo->function[Idx]; - if (!((CpuidFn->EaxIn == 0xD) && - ((CpuidFn->EcxIn == 0) || (CpuidFn->EcxIn == 1)))) - { + if (!((CpuidFn->EaxIn == 0xD) && (CpuidFn->EcxIn > 1))) { continue; } From 62f4d66bcd3d8cca92f50aaeeb71540c711cc757 Mon Sep 17 00:00:00 2001 From: "Roth, Michael via groups.io" Date: Wed, 26 Apr 2023 04:32:58 +0800 Subject: [PATCH 0897/1529] OvmfPkg/CcExitLib: Use documented XSave area base size for SEV-SNP Currently OVMF tries to rely on the base size advertised via the CPUID table entries corresponding to leaf 0xD, sub-leafs 0x0/0x1. This will generally work for KVM guests, but might not for other SEV-SNP hypervisor implementations. Make the handling more robust by simply using the base area size documented by the APM. Reviewed-by: Tom Lendacky Acked-by: Jiewen Yao Acked-by: Gerd Hoffmann Signed-off-by: Michael Roth --- OvmfPkg/Library/CcExitLib/CcExitVcHandler.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index 94f0c4872c..0fc30f7bc4 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -1114,8 +1114,6 @@ SnpEnabled ( @param[in] XFeaturesEnabled Bit-mask of enabled XSAVE features/areas as indicated by XCR0/MSR_IA32_XSS bits - @param[in] XSaveBaseSize Base/legacy XSAVE area size (e.g. when - XCR0 is 1) @param[in, out] XSaveSize Pointer to storage for calculated XSAVE area size @param[in] Compacted Whether or not the calculation is for the @@ -1130,7 +1128,6 @@ STATIC BOOLEAN GetCpuidXSaveSize ( IN UINT64 XFeaturesEnabled, - IN UINT32 XSaveBaseSize, IN OUT UINT32 *XSaveSize, IN BOOLEAN Compacted ) @@ -1139,7 +1136,10 @@ GetCpuidXSaveSize ( UINT64 XFeaturesFound = 0; UINT32 Idx; - *XSaveSize = XSaveBaseSize; + // + // The base/legacy XSave size is documented to be 0x240 in the APM. + // + *XSaveSize = 0x240; CpuidInfo = (SEV_SNP_CPUID_INFO *)(UINT64)PcdGet32 (PcdOvmfCpuidBase); for (Idx = 0; Idx < CpuidInfo->Count; Idx++) { @@ -1355,7 +1355,6 @@ GetCpuidFw ( if (!GetCpuidXSaveSize ( XCr0 | XssMsr.Uint64, - *Ebx, &XSaveSize, Compacted )) From 780ce86b20c2b31d65d281b79c1fbcfa9925cf7e Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Sun, 23 Apr 2023 09:14:22 +0800 Subject: [PATCH 0898/1529] BaseTools/Plugin: Report error if code coverage failure If code coverage exist failure, CI/CD need to catch it Cc: Michael D Kinney Cc: Sean Brogan Cc: Michael Kubacki Signed-off-by: Gua Guo Reviewed-by: Michael D Kinney Reviewed-by: Michael Kubacki --- .../HostBasedUnitTestRunner/HostBasedUnitTestRunner.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index a384b55629..d993de9412 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -130,9 +130,13 @@ def do_post_build(self, thebuilder): if thebuilder.env.GetValue("CODE_COVERAGE") != "FALSE": if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "GCC5": - self.gen_code_coverage_gcc(thebuilder) + ret = self.gen_code_coverage_gcc(thebuilder) + if ret != 0: + failure_count += 1 elif thebuilder.env.GetValue("TOOL_CHAIN_TAG").startswith ("VS"): - self.gen_code_coverage_msvc(thebuilder) + ret = self.gen_code_coverage_msvc(thebuilder) + if ret != 0: + failure_count += 1 else: logging.info("Skipping code coverage. Currently, support GCC and MSVC compiler.") From 7107cbe203b1faca0145ec876fe3930683f5ecce Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Sun, 23 Apr 2023 09:17:51 +0800 Subject: [PATCH 0899/1529] .azurepipelines: Choose container that have installed lcov Azure should install code coverage tool (lcov), it didn't exist on Fedora and Ubuntu by default. Update docker setting, pick below solution between 47addc9 and 3b3eb8f 3b3eb8f Fixes and improvements to dev containers (#69) 54e5bd1 Enable GTK on Fedora QEMU (#63) f1c7a20 Fedora: install code coverage tools for GCC (#62) 2ce82af Ubuntu-22: Add initial Ubuntu-22 image (#61) 14d2aba Add Fedora 37 image with gcc12 (#60) 5b8a008 Add dotnet runtime to fedora build (#57) f5c874a Fix platform build file name for EDK2 change (#58) 48540ad Ubuntu-20: Fix dev image entrypoint (#55) 98e849d Fedora-35: Add Powershell to build image (#52) Cc: Michael D Kinney Cc: Sean Brogan Cc: Michael Kubacki Cc: Oliver Steffen Cc: Chris Fernald Signed-off-by: Gua Guo Reviewed-by: Michael D Kinney Reviewed-by: Michael Kubacki Reviewed-by: Chris Fernald --- .azurepipelines/templates/defaults.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/defaults.yml b/.azurepipelines/templates/defaults.yml index 74d6b41783..8412a43cad 100644 --- a/.azurepipelines/templates/defaults.yml +++ b/.azurepipelines/templates/defaults.yml @@ -9,4 +9,4 @@ variables: default_python_version: ">=3.10.6" - default_linux_image: "ghcr.io/tianocore/containers/fedora-35-test:47addc9" + default_linux_image: "ghcr.io/tianocore/containers/fedora-35-test:3b3eb8f" From b4c2880ca4f5465e45cf1f1a9f322978d266ac14 Mon Sep 17 00:00:00 2001 From: Gua Guo Date: Thu, 27 Apr 2023 13:07:02 +0800 Subject: [PATCH 0900/1529] .azurepipelines: Switch linux image default to Fedora-37 Switch default linux build image from Fedora-35 to Fedora-37 Cc: Michael D Kinney Cc: Sean Brogan Cc: Michael Kubacki Cc: Oliver Steffen Cc: Chris Fernald Signed-off-by: Gua Guo Reviewed-by: Michael Kubacki --- .azurepipelines/templates/defaults.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/defaults.yml b/.azurepipelines/templates/defaults.yml index 8412a43cad..6730a0e8e4 100644 --- a/.azurepipelines/templates/defaults.yml +++ b/.azurepipelines/templates/defaults.yml @@ -9,4 +9,4 @@ variables: default_python_version: ">=3.10.6" - default_linux_image: "ghcr.io/tianocore/containers/fedora-35-test:3b3eb8f" + default_linux_image: "ghcr.io/tianocore/containers/fedora-37-test:3b3eb8f" From 6f34b14e5e3cded0af2d2b23ae20828da04e7800 Mon Sep 17 00:00:00 2001 From: BruceX Wang Date: Wed, 26 Apr 2023 14:32:01 +0800 Subject: [PATCH 0901/1529] UefiPayloadPkg: Clang dependency removal REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4426 Use Python to replace llvm-objcopy in UniversalPayloadBuild.py. 1. AddSection32() and AddSection64(): Make a section named
with the contents of . 2. RemoveSection32() and RemoveSection64(): Remove
. 3. ReplaceFv (): remove the section before add the section if the file exists. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Signed-off-by: BruceX Wang Reviewed-by: Gua Guo --- UefiPayloadPkg/Tools/ElfFv.py | 809 ++++++++++++++++++++++++ UefiPayloadPkg/Tools/__init__.py | 6 + UefiPayloadPkg/UefiPayloadPkg.ci.yaml | 1 + UefiPayloadPkg/UniversalPayloadBuild.py | 232 ++++--- 4 files changed, 923 insertions(+), 125 deletions(-) create mode 100644 UefiPayloadPkg/Tools/ElfFv.py create mode 100644 UefiPayloadPkg/Tools/__init__.py diff --git a/UefiPayloadPkg/Tools/ElfFv.py b/UefiPayloadPkg/Tools/ElfFv.py new file mode 100644 index 0000000000..a3d5bf08b9 --- /dev/null +++ b/UefiPayloadPkg/Tools/ElfFv.py @@ -0,0 +1,809 @@ +## @file +# OBJCOPY parser, it's used to replace FV +# +# Copyright (c) 2023, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import argparse +from ctypes import * +import struct + +class ElfSectionHeader64: + def __init__(self, sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize): + self.sh_name = sh_name + self.sh_type = sh_type + self.sh_flags = sh_flags + self.sh_addr = sh_addr + self.sh_offset = sh_offset + self.sh_size = sh_size + self.sh_link = sh_link + self.sh_info = sh_info + self.sh_addralign = sh_addralign + self.sh_entsize = sh_entsize + + def pack(self): + return struct.pack(' RemoveNameOffset): + unpacked_header.sh_name -= RemoveNameOffset + # Modify size of name string section entry in section entry. + if (Index == StringIndexNumber): + unpacked_header.sh_size -= len (SectionName) + # added section + else : + if (Index == StringIndexNumber): + unpacked_header.sh_size += len (SectionName) + NewSHentry = ElfSectionHeader64 ( + unpacked_header.sh_name, + unpacked_header.sh_type, + unpacked_header.sh_flags, + unpacked_header.sh_addr, + unpacked_header.sh_offset, + unpacked_header.sh_size, + unpacked_header.sh_link, + unpacked_header.sh_info, + unpacked_header.sh_addralign, + unpacked_header.sh_entsize).pack() + return NewSHentry + +def AddSectionHeader32(SHentry, NewUPLEntrylen, SectionHeaderEntrySize, Index, RemoveNameOffset, SectionName, StringIndexNumber): + SHentry = bytearray(SHentry) + unpacked_header = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + if (Index != 0): + NewSHentry = SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)] + unpacked_header.sh_offset = NewUPLEntrylen + # Modify offset of name in section entry + # if RemoveNameOffset != 0 that is remove function. + if (RemoveNameOffset != 0): + if (unpacked_header.sh_name > RemoveNameOffset): + unpacked_header.sh_name -= RemoveNameOffset + # Modify size of name string section entry in section entry. + if (Index == StringIndexNumber): + unpacked_header.sh_size -= len (SectionName) + # added section + else : + if (Index == StringIndexNumber): + unpacked_header.sh_size += len (SectionName) + NewSHentry = ElfSectionHeader32 ( + unpacked_header.sh_name, + unpacked_header.sh_type, + unpacked_header.sh_flags, + unpacked_header.sh_addr, + unpacked_header.sh_offset, + unpacked_header.sh_size, + unpacked_header.sh_link, + unpacked_header.sh_info, + unpacked_header.sh_addralign, + unpacked_header.sh_entsize).pack() + return NewSHentry + +def ModifyPHSegmentOffset64(NewUPLEntry, ElfHeaderOffset, PHSegmentName): + # Modify offset and address of program header tables. + elf_header = ElfHeader64(NewUPLEntry[:64]) + SHentry = NewUPLEntry[ElfHeaderOffset:] + # Elf program header tables start from 0x40 in 64-bits objects + PHentry = NewUPLEntry[64: 64 + (elf_header.e_phnum * elf_header.e_phentsize)] + PHdrs = [] + SHdrs = [] + for i in range(elf_header.e_shnum): + SHData = SHentry[(i * elf_header.e_shentsize): (i * elf_header.e_shentsize) + elf_header.e_shentsize] + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHData) + SHdrs.append(unpacked_SectionHeader) + for i in range(elf_header.e_phnum): + PHData = PHentry[(i * elf_header.e_phentsize): (i * elf_header.e_phentsize) + elf_header.e_phentsize] + unpacked_ProgramHeader = Elf64_Phdr(PHData) + PHdrs.append(unpacked_ProgramHeader) + if (PHSegmentName == '.text'): + PHdrs[0].p_offset = SHdrs[1].sh_offset + PHdrs[0].p_paddr = SHdrs[1].sh_addr + PHdrs[4].p_offset = SHdrs[1].sh_offset + PHdrs[4].p_paddr = SHdrs[1].sh_addr + elif (PHSegmentName == '.dynamic'): + PHdrs[1].p_offset = SHdrs[2].sh_offset + PHdrs[1].p_paddr = SHdrs[2].sh_addr + PHdrs[3].p_offset = SHdrs[2].sh_offset + PHdrs[3].p_paddr = SHdrs[2].sh_addr + elif (PHSegmentName == '.data'): + PHdrs[2].p_offset = SHdrs[3].sh_offset + PHdrs[2].p_paddr = SHdrs[3].sh_addr + packed_PHData = b'' + for phdr in PHdrs: + packed_PHData += phdr.pack() + NewUPLEntry = bytearray(NewUPLEntry) + NewUPLEntry[64: 64 + (elf_header.e_phnum * elf_header.e_phentsize)] = packed_PHData + return NewUPLEntry + +def ModifyPHSegmentOffset32(NewUPLEntry, ElfHeaderOffset, PHSegmentName): + # Modify offset and address of program header tables. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(NewUPLEntry[:52]) + SHentry = NewUPLEntry[ElfHeaderOffset:] + # Elf program header tables start from 0x34 in 32-bits objects + PHentry = NewUPLEntry[52: 52 + (elf_header.e_phnum * elf_header.e_phentsize)] + PHdrs = [] + SHdrs = [] + for i in range(elf_header.e_shnum): + SHData = SHentry[(i * elf_header.e_shentsize): (i * elf_header.e_shentsize) + elf_header.e_shentsize] + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHData) + SHdrs.append(unpacked_SectionHeader) + for i in range(elf_header.e_phnum): + PHData = PHentry[(i * elf_header.e_phentsize): (i * elf_header.e_phentsize) + elf_header.e_phentsize] + unpacked_ProgramHeader = Elf32_Phdr(PHData) + PHdrs.append(unpacked_ProgramHeader) + if (PHSegmentName == '.text'): + PHdrs[0].p_offset = SHdrs[1].sh_offset + PHdrs[0].p_paddr = SHdrs[1].sh_addr + PHdrs[0].p_vaddr = SHdrs[1].sh_addr + PHdrs[2].p_offset = SHdrs[1].sh_offset + PHdrs[2].p_paddr = SHdrs[1].sh_addr + PHdrs[0].p_vaddr = SHdrs[1].sh_addr + elif (PHSegmentName == '.data'): + PHdrs[1].p_offset = SHdrs[2].sh_offset + PHdrs[1].p_paddr = SHdrs[2].sh_addr + PHdrs[1].p_vaddr = SHdrs[2].sh_addr + packed_PHData = b'' + for phdr in PHdrs: + packed_PHData += phdr.pack() + NewUPLEntry = bytearray(NewUPLEntry) + NewUPLEntry[52: 52 + (elf_header.e_phnum * elf_header.e_phentsize)] = packed_PHData + return NewUPLEntry + +def RemoveSection64(UniversalPayloadEntry, RemoveSectionName): + # If elf is 64-bit objects. + # Get offsets as follows: + # 1. Section name which will remove in section name string. + # 2. Section which will remove. + # 3. Section header which will remove. + with open(UniversalPayloadEntry,'rb') as f: + UPLEntry = f.read() + RemoveSectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntry, RemoveSectionName) + if (RemoveSectionNameOffset == -1): + raise argparse.ArgumentTypeError ('Section: {} not found.'.format (RemoveSectionNameOffset)) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # find deleted fv section offset. + # Elf header is stored at 0x0-0x40 in 64-bits objects + elf_header = ElfHeader64(UPLEntry[:64]) + Counter = 0 + RemoveIndex = 0 + RemoveNameOffset = 0 + for Index in range(0, elf_header.e_shnum): + # Read Index of section header. + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * elf_header.e_shentsize):((Index * elf_header.e_shentsize) + elf_header.e_shentsize)]) + # Find offset of section name which is removed. + if (unpacked_SectionHeader.sh_name == RemoveSectionNameOffset): + RemoveIndex = Counter + Counter += 1 + else: + Counter += 1 + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header size is 0x40 with 64-bit object. + ElfHeaderSize = 64 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, RemoveSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of deleted section is removed in name string section. + # 2. deleted section is removed in dll file. + # 3. re-align sections before and after deleted section. + NewUPLEntrylen = [] + for Index in range(0, (SectionHeaderEntryNumber)): + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntrylen.append(len(NewUPLEntry)) + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section in front of removed section + elif (Index + 1 == RemoveIndex): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read section address alignment + # If section that will be removed in .dll is not first and last one . + # Address alignment, section will align with alignment of section after deleted section. + # Check next and the section after next are not end of section. + if ((Index + 2) < (SectionHeaderEntryNumber - 1)): + unpacked_Next2SectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 2) * SectionHeaderEntrySize):(((Index + 2) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_Next2SectionHeader.sh_addralign) + else: + # It is align 8 bytes if next section or the section after next is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is Deleted section + elif (Index == RemoveIndex): + # Don't add removed section to elf. + # Find offset of section name. + RemoveNameOffset = unpacked_SectionHeader.sh_name + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Remove name of removed section in name string section. + # Section header isn't exist if RemoveSectionNameOffset equal to -1. + StringIndex = bytearray(StringIndex) + RemoveSectionName = bytearray(RemoveSectionName, encoding='utf-8') + RemoveSectionName = RemoveSectionName + bytes('\0', encoding='utf-8') + StringIndex = StringIndex.replace(RemoveSectionName,b'') + NewUPLEntry += StringIndex + # other sections. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + else: + # If section is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + SectionHeaderOffset = len(NewUPLEntry) + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + if (Number != RemoveIndex): + NewSHentry = AddSectionHeader64(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, RemoveSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + # Modify number of sections and offset of section header in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum -= 1 + NewUPLEntry = elf_header.pack() + NewUPLEntry[64:] + # write to Elf. + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + +def RemoveSection32(UniversalPayloadEntry, RemoveSectionName): + # If elf is 32-bit objects. + # Get offsets as follows: + # 1. Section name which will remove in section name string. + # 2. Section which will remove. + # 3. Section header which will remove. + with open(UniversalPayloadEntry,'rb') as f: + UPLEntry = f.read() + RemoveSectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, EI_CLASS = FindSection(UPLEntry, RemoveSectionName) + if (RemoveSectionNameOffset == -1): + raise argparse.ArgumentTypeError ('Section: {} not found.'.format (RemoveSectionNameOffset)) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # find deleted fv section offset. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(UPLEntry[:52]) + Counter = 0 + RemoveIndex = 0 + RemoveNameOffset = 0 + for Index in range(0, elf_header.e_shnum): + # Read Index of section header. + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * elf_header.e_shentsize):((Index * elf_header.e_shentsize) + elf_header.e_shentsize)]) + # Find offset of section name which is removed. + if (unpacked_SectionHeader.sh_name == RemoveSectionNameOffset): + RemoveIndex = Counter + Counter += 1 + else: + Counter += 1 + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header size is 0x34 with 32-bit object. + ElfHeaderSize = 52 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, RemoveSection32() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of deleted section is removed in name string section. + # 2. deleted section is removed in dll file. + # 3. re-align sections before and after deleted section. + NewUPLEntrylen = [] + for Index in range(0, (SectionHeaderEntryNumber)): + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntrylen.append(len(NewUPLEntry)) + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section in front of removed section + elif (Index + 1 == RemoveIndex): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read section address alignment + # If section that will be removed in .dll is not first and last one . + # Address alignment, section will align with alignment of section after deleted section. + # Check next and the section after next are not end of section. + if ((Index + 2) < (SectionHeaderEntryNumber - 1)): + unpacked_Next2SectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 2) * SectionHeaderEntrySize):(((Index + 2) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_Next2SectionHeader.sh_addralign) + else: + # It is align 8 bytes if next section or the section after next is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is Deleted section + elif (Index == RemoveIndex): + # Don't add removed section to elf. + # Find offset of section name. + RemoveNameOffset = unpacked_SectionHeader.sh_name + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Remove name of removed section in name string section. + # Section header isn't exist if RemoveSectionNameOffset equal to -1. + StringIndex = bytearray(StringIndex) + RemoveSectionName = bytearray(RemoveSectionName, encoding='utf-8') + RemoveSectionName = RemoveSectionName + bytes('\0', encoding='utf-8') + StringIndex = StringIndex.replace(RemoveSectionName,b'') + NewUPLEntry += StringIndex + # other sections. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + else: + # If section is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + SectionHeaderOffset = len(NewUPLEntry) + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + if (Number != RemoveIndex): + NewSHentry = AddSectionHeader32(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, RemoveSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + # Modify number of sections and offset of section header in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum -= 1 + NewUPLEntry = elf_header.pack() + NewUPLEntry[52:] + # write to Elf. + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + +def AddSection64(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment): + with open(UniversalPayloadEntry,'rb+') as f: + UPLEntry = f.read() + fFileBinary = open(FileBinary, 'rb') + Binary_File = fFileBinary.read() + ElfHeaderOffset, SectionHeaderEntryNumber, StringIndexNumber, _, _, SectionHeaderEntrySize, _, _ = ElfHeaderParser(UPLEntry) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header is stored at 0x0-0x40 in 64-bits objects + elf_header = ElfHeader64(UPLEntry[:64]) + # Elf header size is 0x40 with 64-bit object. + ElfHeaderSize = 64 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, AddSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of added section is added in name string section. + # 2. added section is added in dll file. + # 3. re-align sections before and after added section. + NewUPLEntrylen = [] + StringIndexValue = 0 + for Index in range(0, SectionHeaderEntryNumber): + NewUPLEntrylen.append(len(NewUPLEntry)) + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + # Sections is recombined. + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section is last one. + elif (Index == (SectionHeaderEntryNumber - 1)): + # Add new section at the end. + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + NewUPLEntry = SectionAlignment(NewUPLEntry, Alignment) + LastUPLEntrylen = len(NewUPLEntry) + NewUPLEntry += Binary_File + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read name of added Section after StringIndex is transform into string. + StringIndex = bytearray(StringIndex) + StringIndexValue = len(StringIndex) + AddSectionName = bytearray(AddSectionName, encoding='utf-8') + bytes('\0', encoding='utf-8') + StringIndex += AddSectionName + NewUPLEntry += StringIndex + # section after name string section but not last one. + elif ((Index > StringIndexNumber) and (Index < (SectionHeaderEntryNumber - 1))): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section before name string section. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + SectionHeaderOffset = len(NewUPLEntry) + RemoveNameOffset = 0 + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + NewSHentry = AddSectionHeader64(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, AddSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + NewUPLEntry += bytearray(AddNewSectionEntry64(LastUPLEntrylen, StringIndexValue, len(Binary_File), Alignment)) + # Modify number of sections and offset of section header in Elf header. + # Modify offset in in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum += 1 + elf_header = elf_header.pack() + UPLEntryBin = elf_header + NewUPLEntry[64:] + # Modify offsets and address of program header table in elf. + PHSegmentName = '.text' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. + PHSegmentName = '.dynamic' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. + PHSegmentName = '.data' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + fFileBinary.close() + return UPLEntryBin + +def AddSection32(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment): + with open(UniversalPayloadEntry,'rb+') as f: + # Read Elf and binary which will be write to elf. + UPLEntry = f.read() + fFileBinary = open(FileBinary, 'rb') + Binary_File = fFileBinary.read() + ElfHeaderOffset, SectionHeaderEntryNumber, StringIndexNumber, _, _, SectionHeaderEntrySize, _, _ = ElfHeaderParser(UPLEntry) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(UPLEntry[:52]) + # Elf header size is 0x34 with 32-bit object. + ElfHeaderSize = 52 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, AddSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of added section is added in name string section. + # 2. added section is added in dll file. + # 3. re-align sections before and after added section. + NewUPLEntrylen = [] + StringIndexValue = 0 + for Index in range(0, SectionHeaderEntryNumber): + NewUPLEntrylen.append(len(NewUPLEntry)) + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + # Sections is recombined. + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section is last one. + elif (Index == (SectionHeaderEntryNumber - 1)): + # Add new section at the end. + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + NewUPLEntry = SectionAlignment(NewUPLEntry, Alignment) + LastUPLEntrylen = len(NewUPLEntry) + NewUPLEntry += Binary_File + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read name of added Section after StringIndex is transform into string. + StringIndex = bytearray(StringIndex) + StringIndexValue = len(StringIndex) + AddSectionName = bytearray(AddSectionName, encoding='utf-8') + bytes('\0', encoding='utf-8') + StringIndex += AddSectionName + NewUPLEntry += StringIndex + # section after name string section but not last one. + elif ((Index > StringIndexNumber) and (Index < (SectionHeaderEntryNumber - 1))): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section before name string section. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + SectionHeaderOffset = len(NewUPLEntry) + RemoveNameOffset = 0 + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + NewSHentry = AddSectionHeader32(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, AddSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + NewUPLEntry += bytearray(AddNewSectionEntry32(LastUPLEntrylen, StringIndexValue, len(Binary_File), Alignment)) + # Modify number of sections and offset of section header in Elf header. + # Modify offset in in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum += 1 + PHTableSize = elf_header.e_phentsize + elf_header = elf_header.pack() + UPLEntryBin = elf_header + NewUPLEntry[52:] + # Modify offsets and address of program header table in elf. + PHSegmentName = '.text' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset32(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. Its are stored at 0x08-0x0F and 0x10-0x17 + PHSegmentName = '.data' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset32(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + fFileBinary.close() + return UPLEntryBin + +def ReplaceFv (UniversalPayloadEntry, FileBinary, AddSectionName, Alignment = 16): + with open(UniversalPayloadEntry,'rb+') as f: + UPLEntry = f.read() + SectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, EI_CLASS = FindSection(UPLEntry, AddSectionName) + # If elf is 64-bit objects. + if (EI_CLASS == 2): + # Remove section if it exists. + if (SectionNameOffset != -1): + RemoveSection64(UniversalPayloadEntry, AddSectionName) + # Add section. + NewUPLEntry = AddSection64(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment) + # If elf is 32-bit objects. + else: + # Remove section if it exists. + if (SectionNameOffset != -1): + RemoveSection32(UniversalPayloadEntry, AddSectionName) + # Add section. + NewUPLEntry = AddSection32(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment) + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + return 0 diff --git a/UefiPayloadPkg/Tools/__init__.py b/UefiPayloadPkg/Tools/__init__.py new file mode 100644 index 0000000000..c754125fd3 --- /dev/null +++ b/UefiPayloadPkg/Tools/__init__.py @@ -0,0 +1,6 @@ +## @file +# This file is used to replace FV. +# +# Copyright (c) 2023, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## diff --git a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml index 909379eaac..278f271c36 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml +++ b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml @@ -18,6 +18,7 @@ ], ## Both file path and directory path are accepted. "IgnoreFiles": [ + "Tools/", "Include/Coreboot.h", "Library/CbParseLib/CbParseLib.c", "PayloadLoaderPeim/ElfLib/ElfCommon.h", diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 83e0de95d8..416946a431 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -11,7 +11,7 @@ import shutil import sys from ctypes import * - +from Tools.ElfFv import ReplaceFv sys.dont_write_bytecode = True class UPLD_INFO_HEADER(LittleEndianStructure): @@ -36,106 +36,56 @@ def __init__(self): self.ImageId = b'UEFI' self.ProducerId = b'INTEL' -def GenSpecRevision (Argument): - try: - (MajorStr, MinorStr) = Argument.split('.') - except: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) - # - # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version. - # - if len(MinorStr) > 0 and len(MinorStr) < 3: - try: - Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4) - except: - raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument)) - else: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) +def BuildUniversalPayload(Args): + def RunCommand(cmd): + print(cmd) + p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE']) + while True: + line = p.stdout.readline() + if not line: + break + print(line.strip().decode(errors='ignore')) + + p.communicate() + if p.returncode != 0: + print("- Failed - error happened when run command: %s"%cmd) + raise Exception("ERROR: when run command: %s"%cmd) - if len(MajorStr) > 0 and len(MajorStr) < 3: - try: - Major = int(MajorStr, 16) - except: - raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument)) - else: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) - - return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0) - -def Validate32BitInteger (Argument): - try: - Value = int (Argument, 0) - except: - raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument)) - if Value < 0: - raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument)) - if Value > 0xffffffff: - raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument)) - return Value - -def RunCommand(cmd): - print(cmd) - p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE']) - while True: - line = p.stdout.readline() - if not line: - break - print(line.strip().decode(errors='ignore')) - - p.communicate() - if p.returncode != 0: - print("- Failed - error happened when run command: %s"%cmd) - raise Exception("ERROR: when run command: %s"%cmd) - -def BuildUniversalPayload(Args, MacroList): BuildTarget = Args.Target ToolChain = Args.ToolChain Quiet = "--quiet" if Args.Quiet else "" ElfToolChain = 'CLANGDWARF' BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64")) + BuildModule = "" + BuildArch = "" if Args.Arch == 'X64': BuildArch = "X64" - ObjCopyFlag = "elf64-x86-64" EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("X64/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll")) else: BuildArch = "IA32 -a X64" - ObjCopyFlag = "elf32-i386" EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("IA32/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll")) if Args.PreBuildUplBinary is not None: EntryOutputDir = os.path.abspath(Args.PreBuildUplBinary) - EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc") - DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) - BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) - NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) - PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt") UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin") - if "CLANG_BIN" in os.environ: - LlvmObjcopyPath = os.path.join(os.environ["CLANG_BIN"], "llvm-objcopy") - else: - LlvmObjcopyPath = "llvm-objcopy" - try: - RunCommand('"%s" --version'%LlvmObjcopyPath) - except: - print("- Failed - Please check if LLVM is installed or if CLANG_BIN is set correctly") - sys.exit(1) - Pcds = "" if (Args.pcd != None): for PcdItem in Args.pcd: Pcds += " --pcd {}".format (PcdItem) Defines = "" - for key in MacroList: - Defines +=" -D {0}={1}".format(key, MacroList[key]) + if (Args.Macro != None): + for MacroItem in Args.Macro: + Defines += " -D {}".format (MacroItem) # # Building DXE core and DXE drivers as DXEFV. # if Args.BuildEntryOnly == False: + PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") BuildPayload = "build -p {} -b {} -a X64 -t {} -y {} {}".format (DscPath, BuildTarget, ToolChain, PayloadReportPath, Quiet) BuildPayload += Pcds BuildPayload += Defines @@ -144,6 +94,7 @@ def BuildUniversalPayload(Args, MacroList): # Building Universal Payload entry. # if Args.PreBuildUplBinary is None: + EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, ElfToolChain, ModuleReportPath, Quiet) BuildModule += Pcds BuildModule += Defines @@ -151,59 +102,80 @@ def BuildUniversalPayload(Args, MacroList): # # Buid Universal Payload Information Section ".upld_info" # - upld_info_hdr = UPLD_INFO_HEADER() + upld_info_hdr = UPLD_INFO_HEADER() upld_info_hdr.SpecRevision = Args.SpecRevision - upld_info_hdr.Revision = Args.Revision - upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16] - upld_info_hdr.ImageId = Args.ImageId.encode()[:16] - upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0 + upld_info_hdr.Revision = Args.Revision + upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16] + upld_info_hdr.ImageId = Args.ImageId.encode()[:16] + upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0 fp = open(UpldInfoFile, 'wb') fp.write(bytearray(upld_info_hdr)) fp.close() + MultiFvList = [] if Args.BuildEntryOnly == False: - # - # Copy the DXEFV as a section in elf format Universal Payload entry. - # - remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv --remove-section .upld.bds_fv {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} --add-section .upld.bds_fv={} {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - UpldInfoFile, - DxeFvOutputDir, - BdsFvOutputDir, - EntryOutputDir - ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - # - # Append network fv to sections if exists - # - if os.path.isfile(NetworkFvOutputDir): - index = remove_section.find(EntryOutputDir) - remove_section = remove_section[:index] + '--remove-section .upld.network_fv ' + remove_section[index:] - index = add_section.find(EntryOutputDir) - add_section = add_section[:index] + '--add-section .upld.network_fv=' + NetworkFvOutputDir + ' ' + add_section[index:] - index = set_section.find(EntryOutputDir) - set_section = set_section[:index] + '--set-section-alignment .upld.network_fv=16 ' + set_section[index:] - - RunCommand(remove_section) - RunCommand(add_section) - RunCommand(set_section) + MultiFvList = [ + ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ], + ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ], + ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) ], + ] + AddSectionName = '.upld_info' + ReplaceFv (EntryOutputDir, UpldInfoFile, AddSectionName, Alignment = 4) shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf')) + return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.elf') + def main(): + def ValidateSpecRevision (Argument): + try: + (MajorStr, MinorStr) = Argument.split('.') + except: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + # + # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version. + # + if len(MinorStr) > 0 and len(MinorStr) < 3: + try: + Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4) + except: + raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + if len(MajorStr) > 0 and len(MajorStr) < 3: + try: + Major = int(MajorStr, 16) + except: + raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0) + + def Validate32BitInteger (Argument): + try: + Value = int (Argument, 0) + except: + raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument)) + if Value < 0: + raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument)) + if Value > 0xffffffff: + raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument)) + return Value + + def ValidateAddFv (Argument): + Value = Argument.split ("=") + if len (Value) != 2: + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if Value[0][-3:] != "_fv": + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if Value[1][-3:].lower () != ".fv": + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if os.path.exists (Value[1]) == False: + raise argparse.ArgumentTypeError ('File {} is not found.'.format (Value[1])) + return Value + parser = argparse.ArgumentParser(description='For building Universal Payload') parser.add_argument('-t', '--ToolChain') parser.add_argument('-b', '--Target', default='DEBUG') @@ -212,22 +184,32 @@ def main(): parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI') parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.') parser.add_argument("-p", "--pcd", action="append") - parser.add_argument("-s", "--SpecRevision", type=GenSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') + parser.add_argument("-s", "--SpecRevision", type=ValidateSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build') parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).') parser.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file') parser.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file') - MacroList = {} + parser.add_argument("-sk", "--SkipBuild", action='store_true', help='Skip UniversalPayload build') + parser.add_argument("-af", "--AddFv", type=ValidateAddFv, action='append', help='Add or replace specific FV into payload, Ex: uefi_fv=XXX.fv') args = parser.parse_args() - if args.Macro is not None: - for Argument in args.Macro: - if Argument.count('=') != 1: - print("Unknown variable passed in: %s"%Argument) - raise Exception("ERROR: Unknown variable passed in: %s"%Argument) - tokens = Argument.strip().split('=') - MacroList[tokens[0].upper()] = tokens[1] - BuildUniversalPayload(args, MacroList) - print ("Successfully build Universal Payload") + + MultiFvList = [] + UniversalPayloadBinary = args.PreBuildUplBinary + if (args.SkipBuild == False): + MultiFvList, UniversalPayloadBinary = BuildUniversalPayload(args) + + if (args.AddFv != None): + for (SectionName, SectionFvFile) in args.AddFv: + MultiFvList.append ([SectionName, SectionFvFile]) + + if (UniversalPayloadBinary != None): + for (SectionName, SectionFvFile) in MultiFvList: + if os.path.exists (SectionFvFile) == False: + continue + print ("Patch {}={} into {}".format (SectionName, SectionFvFile, UniversalPayloadBinary)) + ReplaceFv (UniversalPayloadBinary, SectionFvFile, '.upld.{}'.format (SectionName)) + + print ("\nSuccessfully build Universal Payload") if __name__ == '__main__': main() From f5d8b86b5c63adb8aef4025ab185d61eccd63b87 Mon Sep 17 00:00:00 2001 From: Nhi Pham Date: Wed, 12 Apr 2023 17:21:49 +0800 Subject: [PATCH 0902/1529] SecurityPkg/DxeImageVerificationLib: Add AUTH_SIG_NOT_FOUND Action Add the AUTH_SIG_NOT_FOUND Action to the Image Execution Info Table when the Image is signed but signature is not allowed by DB and the hash of image is not found in DB/DBX. This is documented in the UEFI spec 2.10, table 32.5. This issue is found by the SIE SCT with the error message as follows: SecureBoot - TestImage1.bin in Image Execution Info Table with SIG_NOT_FOUND. --FAILURE B3A670AA-0FBA-48CA-9D01-0EE9700965A9 SctPkg/TestCase/UEFI/EFI/RuntimeServices/SecureBoot/BlackBoxTest/ ImageLoadingBBTest.c:1079:Status Success Signed-off-by: Nhi Pham Reviewed-by: Min Xu Reviewed-by: Jiewen Yao --- .../Library/DxeImageVerificationLib/DxeImageVerificationLib.c | 1 + 1 file changed, 1 insertion(+) diff --git a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c index b3d40c21e9..5d8dbd5468 100644 --- a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c +++ b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c @@ -1993,6 +1993,7 @@ DxeImageVerificationHandler ( if (!EFI_ERROR (DbStatus) && IsFound) { IsVerified = TRUE; } else { + Action = EFI_IMAGE_EXECUTION_AUTH_SIG_NOT_FOUND; DEBUG ((DEBUG_INFO, "DxeImageVerificationLib: Image is signed but signature is not allowed by DB and %s hash of image is not found in DB/DBX.\n", mHashTypeStr)); } } From 0aec9c38c71b4cb3b727607e7919cf8ef4962c38 Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Fri, 21 Apr 2023 14:48:30 +0800 Subject: [PATCH 0903/1529] MdeModulePkg/RegularExpressionDxe: Fix Arm build error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Arm CI build error: - ArmPkg/Library/CompilerIntrinsicsLib/memset.c:39:1: warning: type of ‘memset’ does not match original declaration [-Wlto-type-mismatch] MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c:123:1: note: type ‘char’ should match type ‘int’ - multiple definition of `memcpy'; OnigurumaUefiPort.obj (symbol from plugin):(.text+0x0): first defined here Fix: - Update memset() implementation to match memset() definition in ArmPkg/Library/CompilerIntrinsicsLib. - memcpy() is supported by ArmPkg/Library/CompilerIntrinsicsLib. Exclude it in OnigurumaUefiPort.c. Signed-off-by: Nickle Wang Cc: Jian J Wang Cc: Liming Gao Cc: Michael D Kinney Cc: Nick Ramirez Reviewed-by: Liming Gao --- .../Universal/RegularExpressionDxe/OnigurumaUefiPort.c | 8 ++++++-- .../Universal/RegularExpressionDxe/OnigurumaUefiPort.h | 7 +++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c index 6661c67f97..0d8984dde0 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c +++ b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c @@ -4,6 +4,7 @@ (C) Copyright 2014-2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2020, Intel Corporation. All rights reserved.
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -109,6 +110,7 @@ realloc ( return NULL; } +#if !defined (MDE_CPU_ARM) void * memcpy ( void *dest, @@ -119,14 +121,16 @@ memcpy ( return CopyMem (dest, src, (UINTN)count); } +#endif + void * memset ( void *dest, - char ch, + int ch, unsigned int count ) { - return SetMem (dest, count, ch); + return SetMem (dest, (UINTN)count, (UINT8)ch); } void diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h index 248109b0c9..8931f8ec50 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h +++ b/MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.h @@ -4,7 +4,7 @@ (C) Copyright 2014-2021 Hewlett Packard Enterprise Development LP
Copyright (c) 2020, Intel Corporation. All rights reserved.
- Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -107,6 +107,7 @@ realloc ( size_t size ); +#if !defined (MDE_CPU_ARM) void * memcpy ( void *dest, @@ -114,10 +115,12 @@ memcpy ( unsigned int count ); +#endif + void * memset ( void *dest, - char ch, + int ch, unsigned int count ); From 8c548eca28435193769ef5a3f3d586d14c45880a Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Mon, 10 Apr 2023 21:09:14 +0800 Subject: [PATCH 0904/1529] RedfishPkg: introduce EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL EDKII Redfish Platform Config Protocol defines the protocol interfaces that abstracts the platform configuration format and storage from EDK2 Redfish Feature driver. This protocol provides the interfaces to get and set platform configuration with the format and configuration storage agnostic to the Redfish feature driver. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang Reviewed-by: Igor Kulchytskyy --- .../Protocol/EdkIIRedfishPlatformConfig.h | 257 ++++++++++++++++++ RedfishPkg/RedfishPkg.dec | 3 + 2 files changed, 260 insertions(+) create mode 100644 RedfishPkg/Include/Protocol/EdkIIRedfishPlatformConfig.h diff --git a/RedfishPkg/Include/Protocol/EdkIIRedfishPlatformConfig.h b/RedfishPkg/Include/Protocol/EdkIIRedfishPlatformConfig.h new file mode 100644 index 0000000000..d20b2c980e --- /dev/null +++ b/RedfishPkg/Include/Protocol/EdkIIRedfishPlatformConfig.h @@ -0,0 +1,257 @@ +/** @file + This file defines the EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL interface. + + (C) Copyright 2021-2022 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef EDKII_REDFISH_PLATFORM_CONFIG_H_ +#define EDKII_REDFISH_PLATFORM_CONFIG_H_ + +typedef struct _EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL; + +/// +/// Definition of EDKII_REDFISH_TYPE_VALUE +/// +typedef union { + INT64 Integer; + BOOLEAN Boolean; + CHAR8 *Buffer; + CHAR8 **StringArray; + INT64 *IntegerArray; + BOOLEAN *BooleanArray; +} EDKII_REDFISH_TYPE_VALUE; + +/// +/// Definition of EDKII_REDFISH_VALUE_TYPES +/// +typedef enum { + RedfishValueTypeUnknown = 0, + RedfishValueTypeInteger, + RedfishValueTypeBoolean, + RedfishValueTypeString, + RedfishValueTypeStringArray, + RedfishValueTypeIntegerArray, + RedfishValueTypeBooleanArray, + RedfishValueTypeMax +} EDKII_REDFISH_VALUE_TYPES; + +/// +/// Definition of EDKII_REDFISH_ATTRIBUTE_TYPES +/// +typedef enum { + RedfishAttributeTypeUnknown = 0, + RedfishAttributeTypeEnumeration, + RedfishAttributeTypeString, + RedfishAttributeTypeInteger, + RedfishAttributeTypeBoolean, + RedfishAttributeTypePassword +} EDKII_REDFISH_ATTRIBUTE_TYPES; + +/// +/// Definition of EDKII_REDFISH_VALUE +/// +typedef struct { + EDKII_REDFISH_VALUE_TYPES Type; + EDKII_REDFISH_TYPE_VALUE Value; + UINTN ArrayCount; +} EDKII_REDFISH_VALUE; + +/// +/// Definition of EDKII_REDFISH_ATTRIBUTE_VALUE +/// +typedef struct { + CHAR8 *ValueName; + CHAR8 *ValueDisplayName; +} EDKII_REDFISH_ATTRIBUTE_VALUE; + +/// +/// Definition of EDKII_REDFISH_POSSIBLE_VALUES +/// +typedef struct { + UINTN ValueCount; + EDKII_REDFISH_ATTRIBUTE_VALUE *ValueArray; +} EDKII_REDFISH_POSSIBLE_VALUES; + +/// +/// Definition of EDKII_REDFISH_ATTRIBUTE +/// +typedef struct { + CHAR8 *AttributeName; + CHAR8 *DisplayName; + CHAR8 *HelpText; + CHAR8 *MenuPath; + EDKII_REDFISH_ATTRIBUTE_TYPES Type; + BOOLEAN ResetRequired; + BOOLEAN ReadOnly; + BOOLEAN GrayedOut; + BOOLEAN Suppress; + UINT64 NumMaximum; + UINT64 NumMinimum; + UINT64 NumStep; + UINT8 StrMaxSize; + UINT8 StrMinSize; + EDKII_REDFISH_POSSIBLE_VALUES Values; +} EDKII_REDFISH_ATTRIBUTE; + +/** + Get Redfish value with the given Schema and Configure Language. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[in] Schema The Redfish schema to query. + @param[in] Version The Redfish version to query. + @param[in] ConfigureLang The target value which match this configure Language. + @param[out] Value The returned value. + + @retval EFI_SUCCESS Value is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_GET_VALUE)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + IN CHAR8 *Schema, + IN CHAR8 *Version, + IN EFI_STRING ConfigureLang, + OUT EDKII_REDFISH_VALUE *Value + ); + +// +// Default class standard +// +#define EDKII_REDFISH_DEFAULT_CLASS_STANDARD EFI_HII_DEFAULT_CLASS_STANDARD + +/** + Get Redfish default value with the given Schema and Configure Language. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[in] Schema The Redfish schema to query. + @param[in] Version The Redfish version to query. + @param[in] ConfigureLang The target value which match this configure Language. + @param[in] DefaultClass The UEFI defined default class. + Please refer to UEFI spec. 33.2.5.8 "defaults" for details. + @param[out] Value The returned value. + + @retval EFI_SUCCESS Value is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_GET_DEFAULT_VALUE)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + IN CHAR8 *Schema, + IN CHAR8 *Version, + IN EFI_STRING ConfigureLang, + IN UINT16 DefaultClass, + OUT EDKII_REDFISH_VALUE *Value + ); + +/** + Set Redfish value with the given Schema and Configure Language. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[in] Schema The Redfish schema to query. + @param[in] Version The Redfish version to query. + @param[in] ConfigureLang The target value which match this configure Language. + @param[in] Value The value to set. + + @retval EFI_SUCCESS Value is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_SET_VALUE)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + IN CHAR8 *Schema, + IN CHAR8 *Version, + IN EFI_STRING ConfigureLang, + IN EDKII_REDFISH_VALUE Value + ); + +/** + Get Redfish attribute value with the given Schema and Configure Language. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[in] Schema The Redfish schema to query. + @param[in] Version The Redfish version to query. + @param[in] ConfigureLang The target value which match this configure Language. + @param[out] AttributeValue The attribute value. + + @retval EFI_SUCCESS Value is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_GET_ATTRIBUTE)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + IN CHAR8 *Schema, + IN CHAR8 *Version, + IN EFI_STRING ConfigureLang, + OUT EDKII_REDFISH_ATTRIBUTE *AttributeValue + ); + +/** + Get the list of Configure Language from platform configuration by the given Schema and RegexPattern. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[in] Schema The Redfish schema to query. + @param[in] Version The Redfish version to query. + @param[in] RegexPattern The target Configure Language pattern. This is used for regular expression matching. + @param[out] ConfigureLangList The list of Configure Language. + @param[out] Count The number of Configure Language in ConfigureLangList. + + @retval EFI_SUCCESS ConfigureLangList is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_GET_CONFIG_LANG)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + IN CHAR8 *Schema, + IN CHAR8 *Version, + IN EFI_STRING RegexPattern, + OUT EFI_STRING **ConfigureLangList, + OUT UINTN *Count + ); + +/** + Get the list of supported Redfish schema from platform configuration. + + @param[in] This Pointer to EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL instance. + @param[out] SupportedSchema The supported schema list which is separated by ';'. + For example: "x-uefi-redfish-Memory.v1_7_1;x-uefi-redfish-Boot.v1_0_1" + The SupportedSchema is allocated by the callee. It's caller's + responsibility to free this buffer using FreePool(). + + @retval EFI_SUCCESS Schema is returned successfully. + @retval Others Some error happened. + +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_REDFISH_PLATFORM_CONFIG_GET_SUPPORTED_SCHEMA)( + IN EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL *This, + OUT CHAR8 **SupportedSchema + ); + +struct _EDKII_REDFISH_PLATFORM_CONFIG_PROTOCOL { + UINT64 Revision; + EDKII_REDFISH_PLATFORM_CONFIG_GET_VALUE GetValue; + EDKII_REDFISH_PLATFORM_CONFIG_SET_VALUE SetValue; + EDKII_REDFISH_PLATFORM_CONFIG_GET_DEFAULT_VALUE GetDefaultValue; + EDKII_REDFISH_PLATFORM_CONFIG_GET_ATTRIBUTE GetAttribute; + EDKII_REDFISH_PLATFORM_CONFIG_GET_CONFIG_LANG GetConfigureLang; + EDKII_REDFISH_PLATFORM_CONFIG_GET_SUPPORTED_SCHEMA GetSupportedSchema; +}; + +extern EFI_GUID gEdkIIRedfishPlatformConfigProtocolGuid; + +#endif diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec index f171053aec..904630ae4b 100644 --- a/RedfishPkg/RedfishPkg.dec +++ b/RedfishPkg/RedfishPkg.dec @@ -78,6 +78,9 @@ ## Include/Protocol/Edk2RedfishConfigHandler.h gEdkIIRedfishConfigHandlerProtocolGuid = { 0xbc0fe6bb, 0x2cc9, 0x463e, { 0x90, 0x82, 0xfa, 0x11, 0x76, 0xfc, 0x67, 0xde } } + ## Include/Protocol/EdkIIRedfishPlatformConfig.h + gEdkIIRedfishPlatformConfigProtocolGuid = { 0X4D94A7C7, 0X4CE4, 0X4A84, { 0X88, 0XC1, 0X33, 0X0C, 0XD4, 0XA3, 0X47, 0X67 } } + [Guids] gEfiRedfishPkgTokenSpaceGuid = { 0x4fdbccb7, 0xe829, 0x4b4c, { 0x88, 0x87, 0xb2, 0x3f, 0xd7, 0x25, 0x4b, 0x85 }} From c8b3363639535419bf145bccbc070f03a560975c Mon Sep 17 00:00:00 2001 From: Nickle Wang Date: Mon, 10 Apr 2023 21:12:03 +0800 Subject: [PATCH 0905/1529] RedfishPkg: introduce HII utility helper library HiiUtilityLib is a helper library that provides the functions to manipulate HII options. Signed-off-by: Nickle Wang Cc: Abner Chang Cc: Igor Kulchytskyy Cc: Nick Ramirez Reviewed-by: Abner Chang Reviewed-by: Igor Kulchytskyy --- RedfishPkg/Include/Library/HiiUtilityLib.h | 1204 ++++ .../Library/HiiUtilityLib/HiiExpression.c | 1439 ++++ .../Library/HiiUtilityLib/HiiExpression.h | 191 + .../Library/HiiUtilityLib/HiiIfrParse.c | 2715 ++++++++ .../Library/HiiUtilityLib/HiiInternal.h | 376 ++ .../HiiUtilityLib/HiiUtilityInternal.c | 5770 +++++++++++++++++ .../Library/HiiUtilityLib/HiiUtilityLib.c | 810 +++ .../Library/HiiUtilityLib/HiiUtilityLib.inf | 62 + RedfishPkg/RedfishPkg.dec | 4 + 9 files changed, 12571 insertions(+) create mode 100644 RedfishPkg/Include/Library/HiiUtilityLib.h create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiExpression.c create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiExpression.h create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiIfrParse.c create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiInternal.h create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiUtilityInternal.c create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiUtilityLib.c create mode 100644 RedfishPkg/Library/HiiUtilityLib/HiiUtilityLib.inf diff --git a/RedfishPkg/Include/Library/HiiUtilityLib.h b/RedfishPkg/Include/Library/HiiUtilityLib.h new file mode 100644 index 0000000000..0999ef77fe --- /dev/null +++ b/RedfishPkg/Include/Library/HiiUtilityLib.h @@ -0,0 +1,1204 @@ +/** @file + Definitions of RedfishPlatformConfigLib. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef HII_UTILITY_LIB_ +#define HII_UTILITY_LIB_ + +#include +#include + +// +// IFR relative definition +// +#define EFI_HII_EXPRESSION_INCONSISTENT_IF 0 +#define EFI_HII_EXPRESSION_NO_SUBMIT_IF 1 +#define EFI_HII_EXPRESSION_GRAY_OUT_IF 2 +#define EFI_HII_EXPRESSION_SUPPRESS_IF 3 +#define EFI_HII_EXPRESSION_DISABLE_IF 4 +#define EFI_HII_EXPRESSION_VALUE 5 +#define EFI_HII_EXPRESSION_RULE 6 +#define EFI_HII_EXPRESSION_READ 7 +#define EFI_HII_EXPRESSION_WRITE 8 +#define EFI_HII_EXPRESSION_WARNING_IF 9 + +#define EFI_HII_VARSTORE_BUFFER 0 +#define EFI_HII_VARSTORE_NAME_VALUE 1 +#define EFI_HII_VARSTORE_EFI_VARIABLE 2 // EFI Varstore type follow UEFI spec before 2.3.1. +#define EFI_HII_VARSTORE_EFI_VARIABLE_BUFFER 3 // EFI varstore type follow UEFI spec 2.3.1 and later. + +/// +/// HII_NAME_VALUE_NODE for name/value storage +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + CHAR16 *Name; + CHAR16 *Value; +} HII_NAME_VALUE_NODE; + +#define HII_NAME_VALUE_NODE_SIGNATURE SIGNATURE_32 ('N', 'V', 'S', 'T') +#define HII_NAME_VALUE_NODE_FROM_LINK(a) CR (a, HII_NAME_VALUE_NODE, Link, HII_NAME_VALUE_NODE_SIGNATURE) + +/// +/// Storage info +/// +typedef union { + EFI_STRING_ID VarName; + UINT16 VarOffset; +} HII_VAR_STORE_INFO; + +/// +/// FormSet storage +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + UINT8 Type; ///< Storage type + EFI_HII_HANDLE HiiHandle; ///< HiiHandle for this varstore. + + /// + /// For all type of storages. + /// + UINT16 VarStoreId; ///< VarStore ID. + EFI_GUID Guid; ///< VarStore Guid. + + /// + /// For EFI_IFR_VARSTORE, EFI_IFR_VARSTORE_EFI + /// + CHAR16 *Name; ///< VarStore name + UINT16 Size; ///< VarStore size. + UINT8 *Buffer; ///< Buffer storage. + UINT8 *EditBuffer; ///< Edit copy for Buffer Storage + + /// + /// For EFI_IFR_VARSTORE_EFI: EFI Variable. + /// + UINT32 Attributes; + + /// + /// For EFI_IFR_VARSTORE_NAME_VALUE. + /// + LIST_ENTRY NameValueList; ///< List of NAME_VALUE_NODE + + CHAR16 *ConfigHdr; ///< + CHAR16 *ConfigRequest; ///< = + + UINTN ElementCount; ///< Number of in the + UINTN SpareStrLen; ///< Spare length of ConfigRequest string buffer +} HII_FORMSET_STORAGE; + +#define HII_STORAGE_SIGNATURE SIGNATURE_32 ('B', 'S', 'T', 'G') +#define HII_STORAGE_FROM_LINK(a) CR (a, HII_FORMSET_STORAGE, Link, HII_STORAGE_SIGNATURE) + +/// +/// Definition of EXPRESS_RESULT +/// +typedef enum { + ExpressFalse = 0, + ExpressGrayOut, + ExpressSuppress, + ExpressDisable +} EXPRESS_RESULT; + +/// +/// Definition of EXPRESS_LEVEL +/// +typedef enum { + ExpressNone = 0, + ExpressForm, + ExpressStatement, + ExpressOption +} EXPRESS_LEVEL; + +/// +/// Definition of HII_EXPRESSION_OPCODE_EXTRA +/// +typedef union { + EFI_HII_VALUE Value; ///< EFI_IFR_UINT64, EFI_IFR_UINT32, EFI_IFR_UINT16, EFI_IFR_UINT8, EFI_IFR_STRING_REF1 + UINT8 Format; ///< For EFI_IFR_TO_STRING, EFI_IFR_FIND + UINT8 Flags; ///< For EFI_IFR_SPAN + UINT8 RuleId; ///< For EFI_IFR_RULE_REF + EFI_GUID Guid; ///< For EFI_IFR_SECURITY, EFI_IFR_MATCH2 + + struct { + EFI_QUESTION_ID QuestionId; + EFI_HII_VALUE Value; + } EqIdValData; + + struct { + EFI_QUESTION_ID QuestionId1; + EFI_QUESTION_ID QuestionId2; + } EqIdIdData; + + struct { + EFI_QUESTION_ID QuestionId; ///< For EFI_IFR_EQ_ID_VAL_LIST + UINT16 ListLength; + UINT16 *ValueList; + } EqIdListData; + + struct { + EFI_QUESTION_ID QuestionId; + } QuestionRef1Data; + + struct { + EFI_STRING_ID DevicePath; ///< For EFI_IFR_QUESTION_REF3_3 + EFI_GUID Guid; + } QuestionRef3Data; + + struct { + HII_FORMSET_STORAGE *VarStorage; + HII_VAR_STORE_INFO VarStoreInfo; + UINT8 ValueType; + UINT8 ValueWidth; + CHAR16 *ValueName; + } GetSetData; +} HII_EXPRESSION_OPCODE_EXTRA; + +typedef union _HII_DEPENDENCY_EXPRESSION HII_DEPENDENCY_EXPRESSION; + +/// +/// Definition of HII_EXPRESSION_CONSTANT +/// +/// Operand: +/// +/// EFI_IFR_TRUE +/// EFI_IFR_FALSE +/// EFI_IFR_ONE +/// EFI_IFR_ONES +/// EFI_IFR_ZERO +/// EFI_IFR_UNDEFINED +/// EFI_IFR_VERSION +/// EFI_IFR_UINT8 +/// EFI_IFR_UINT16 +/// EFI_IFR_UINT32 +/// EFI_IFR_UINT64 +/// +typedef struct { + UINT8 Operand; + EFI_HII_VALUE Value; +} HII_EXPRESSION_CONSTANT; + +/// +/// Definition of HII_DEPENDENCY_DUP +/// +typedef struct { + UINT8 Operand; +} HII_DEPENDENCY_DUP; + +/// +/// Definition of HII_DEPENDENCY_EQ_ID_VAL +/// +typedef struct { + UINT8 Operand; + EFI_QUESTION_ID QuestionId; + EFI_HII_VALUE Value; +} HII_DEPENDENCY_EQ_ID_VAL; + +/// +/// Definition of HII_DEPENDENCY_EQ_ID_VAL +/// +typedef struct { + UINT8 Operand; + EFI_QUESTION_ID QuestionId1; + EFI_QUESTION_ID QuestionId2; +} HII_DEPENDENCY_EQ_ID_ID; + +/// +/// Definition of HII_DEPENDENCY_EQ_ID_VAL_LIST +/// +typedef struct { + UINT8 Operand; + EFI_QUESTION_ID QuestionId; + UINT16 ListLength; + UINT16 *ValueList; +} HII_DEPENDENCY_EQ_ID_VAL_LIST; + +/// +/// Definition of HII_DEPENDENCY_QUESTION_REF1 +/// +typedef struct { + UINT8 Operand; + EFI_QUESTION_ID QuestionId; +} HII_DEPENDENCY_QUESTION_REF1; + +/// +/// Definition of HII_DEPENDENCY_RULE_REF +/// +typedef struct { + UINT8 Operand; + UINT8 RuleId; +} HII_DEPENDENCY_RULE_REF; + +/// +/// Definition of HII_DEPENDENCY_STRING_REF1 +/// +typedef struct { + UINT8 Operand; + EFI_HII_VALUE Value; +} HII_DEPENDENCY_STRING_REF1; + +/// +/// Definition of HII_DEPENDENCY_THIS +/// +typedef struct { + UINT8 Operand; + EFI_QUESTION_ID QuestionId; +} HII_DEPENDENCY_THIS; + +/// +/// Definition of HII_DEPENDENCY_SECURITY +/// +typedef struct { + UINT8 Operand; + EFI_GUID Permissions; +} HII_DEPENDENCY_SECURITY; + +/// +/// Definition of HII_DEPENDENCY_GET +/// +typedef struct { + UINT8 Operand; + HII_FORMSET_STORAGE *VarStorage; + HII_VAR_STORE_INFO VarStoreInfo; + UINT8 ValueType; + UINT8 ValueWidth; + CHAR16 *ValueName; +} HII_DEPENDENCY_GET; + +/// +/// Definition of HII_DEPENDENCY_LENGTH +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_LENGTH; + +/// +/// Definition of HII_DEPENDENCY_BITWISE_NOT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_BITWISE_NOT; + +/// +/// Definition of HII_DEPENDENCY_STRING_REF2 +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_STRING_REF2; + +/// +/// Definition of HII_DEPENDENCY_QUESTION_REF2 +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_QUESTION_REF2; + +/// +/// Definition of HII_DEPENDENCY_QUESTION_REF3 +/// +typedef struct { + UINT8 Operand; + EFI_STRING_ID DevicePath; + EFI_GUID Guid; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_QUESTION_REF3; + +/// +/// Definition of HII_DEPENDENCY_TO_BOOLEAN +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_TO_BOOLEAN; + +/// +/// Definition of HII_DEPENDENCY_TO_STRING +/// +typedef struct { + UINT8 Operand; + UINT8 Format; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_TO_STRING; + +/// +/// Definition of HII_DEPENDENCY_TO_UINT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_TO_UINT; + +/// +/// Definition of HII_DEPENDENCY_TO_UPPER +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_TO_UPPER; + +/// +/// Definition of HII_DEPENDENCY_TO_LOWER +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_TO_LOWER; + +/// +/// Definition of HII_DEPENDENCY_SET +/// +typedef struct { + UINT8 Operand; + HII_FORMSET_STORAGE *VarStorage; + HII_VAR_STORE_INFO VarStoreInfo; + UINT8 ValueType; + UINT8 ValueWidth; + CHAR16 *ValueName; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_SET; + +/// +/// Definition of HII_DEPENDENCY_NOT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression; +} HII_DEPENDENCY_NOT; + +/// +/// Definition of HII_DEPENDENCY_CATENATE +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *LeftStringExp; + HII_DEPENDENCY_EXPRESSION *RightStringExp; +} HII_DEPENDENCY_CATENATE; + +/// +/// Definition of HII_DEPENDENCY_MATCH +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *StringExp; + HII_DEPENDENCY_EXPRESSION *PatternExp; +} HII_DEPENDENCY_MATCH; + +/// +/// Definition of HII_DEPENDENCY_MATCH2 +/// +typedef struct { + UINT8 Operand; + EFI_GUID SyntaxType; + HII_DEPENDENCY_EXPRESSION *StringExp; + HII_DEPENDENCY_EXPRESSION *PatternExp; +} HII_DEPENDENCY_MATCH2; + +/// +/// Definition of HII_DEPENDENCY_MULT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_MULT; + +/// +/// Definition of HII_DEPENDENCY_DIV +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; ///< right value + HII_DEPENDENCY_EXPRESSION *LeftHandExp; ///< left value +} HII_DEPENDENCY_DIV; + +/// +/// Definition of HII_DEPENDENCY_MOD +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; ///< right value + HII_DEPENDENCY_EXPRESSION *LeftHandExp; ///< left value +} HII_DEPENDENCY_MOD; + +/// +/// Definition of HII_DEPENDENCY_ADD +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; ///< right value + HII_DEPENDENCY_EXPRESSION *LeftHandExp; ///< left value +} HII_DEPENDENCY_ADD; + +/// +/// Definition of HII_DEPENDENCY_SUBTRACT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; ///< right value + HII_DEPENDENCY_EXPRESSION *LeftHandExp; ///< left value +} HII_DEPENDENCY_SUBTRACT; + +/// +/// Definition of HII_DEPENDENCY_SHIFT_LEFT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_SHIFT_LEFT; + +/// +/// Definition of HII_DEPENDENCY_SHIFT_RIGHT +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_SHIFT_RIGHT; + +/// +/// Definition of HII_DEPENDENCY_GREATER_THAN +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_GREATER_THAN; + +/// +/// Definition of HII_DEPENDENCY_GREATER_EQUAL +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_GREATER_EQUAL; + +/// +/// Definition of HII_DEPENDENCY_LESS_THAN +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_LESS_THAN; + +/// +/// Definition of HII_DEPENDENCY_LESS_EQUAL +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *RightHandExp; + HII_DEPENDENCY_EXPRESSION *LeftHandExp; +} HII_DEPENDENCY_LESS_EQUAL; + +/// +/// Definition of HII_DEPENDENCY_EQUAL +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_EQUAL; + +/// +/// Definition of HII_DEPENDENCY_NOT_EQUAL +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_NOT_EQUAL; + +/// +/// Definition of HII_DEPENDENCY_BITWISE_AND +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_BITWISE_AND; + +/// +/// Definition of HII_DEPENDENCY_BITWISE_OR +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_BITWISE_OR; + +/// +/// Definition of HII_DEPENDENCY_AND +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_AND; + +/// +/// Definition of HII_DEPENDENCY_OR +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExpression1; + HII_DEPENDENCY_EXPRESSION *SubExpression2; +} HII_DEPENDENCY_OR; + +/// +/// Definition of HII_DEPENDENCY_CONDITIONAL +/// +/// Ternary expression +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *CondTrueValExp; ///< right value + HII_DEPENDENCY_EXPRESSION *CondFalseValExp; ///< middle value + HII_DEPENDENCY_EXPRESSION *ConditionExp; ///< left value +} HII_DEPENDENCY_CONDITIONAL; + +/// +/// Definition of HII_DEPENDENCY_FIND +/// +typedef struct { + UINT8 Operand; + UINT8 Format; + HII_DEPENDENCY_EXPRESSION *IndexExp; ///< right value + HII_DEPENDENCY_EXPRESSION *StringToCompWithExp; ///< middle value + HII_DEPENDENCY_EXPRESSION *StringToSearchExp; ///< left value +} HII_DEPENDENCY_FIND; + +/// +/// Definition of HII_DEPENDENCY_MID +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *LengthExp; ///< right value + HII_DEPENDENCY_EXPRESSION *IndexExp; ///< middle value + HII_DEPENDENCY_EXPRESSION *StringOrBufferExp; ///< left value +} HII_DEPENDENCY_MID; + +/// +/// Definition of HII_DEPENDENCY_TOKEN +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *IndexExp; ///< right value + HII_DEPENDENCY_EXPRESSION *DelimiterExp; ///< middle value + HII_DEPENDENCY_EXPRESSION *StringToSearchExp; ///< left value +} HII_DEPENDENCY_TOKEN; + +/// +/// Definition of HII_DEPENDENCY_SPAN +/// +typedef struct { + UINT8 Operand; + UINT8 Flags; + HII_DEPENDENCY_EXPRESSION *IndexExp; ///< right value + HII_DEPENDENCY_EXPRESSION *CharsetExp; ///< middle value + HII_DEPENDENCY_EXPRESSION *StringToSearchExp; ///< left value +} HII_DEPENDENCY_SPAN; + +/// +/// Map expression +/// +typedef struct { + HII_DEPENDENCY_EXPRESSION *MatchExp; + HII_DEPENDENCY_EXPRESSION *ReturnExp; +} HII_DEPENDENCY_EXPRESSION_PAIR; + +/// +/// Definition of HII_DEPENDENCY_MAP +/// +typedef struct { + UINT8 Operand; + HII_DEPENDENCY_EXPRESSION *SubExp; + HII_DEPENDENCY_EXPRESSION_PAIR *ExpPair; + UINT8 ExpPairNo; +} HII_DEPENDENCY_MAP; + +/// +/// Definition of HII_DEPENDENCY_EXPRESSION +/// +union _HII_DEPENDENCY_EXPRESSION { + /// + /// Constant + /// + HII_EXPRESSION_CONSTANT ConstantExp; + /// + /// build-in expression + /// + HII_DEPENDENCY_DUP DupExp; + HII_DEPENDENCY_EQ_ID_VAL EqIdValExp; + HII_DEPENDENCY_EQ_ID_ID EqIdIdExp; + HII_DEPENDENCY_EQ_ID_VAL_LIST EqIdListExp; + HII_DEPENDENCY_QUESTION_REF1 QuestionRef1Exp; + HII_DEPENDENCY_RULE_REF RuleRefExp; + HII_DEPENDENCY_STRING_REF1 StringRef1Exp; + HII_DEPENDENCY_THIS ThisExp; + HII_DEPENDENCY_SECURITY SecurityExp; + HII_DEPENDENCY_GET GetExp; + + /// + /// unary expression + /// + HII_DEPENDENCY_LENGTH LengthExp; + HII_DEPENDENCY_BITWISE_NOT BitWiseNotExp; + HII_DEPENDENCY_STRING_REF2 StringRef2Exp; + HII_DEPENDENCY_QUESTION_REF2 QuestionRef2Exp; + HII_DEPENDENCY_QUESTION_REF3 QuestionRef3Exp; + HII_DEPENDENCY_TO_BOOLEAN ToBooleanExp; + HII_DEPENDENCY_TO_STRING ToStringExp; + HII_DEPENDENCY_TO_UINT ToUintExp; + HII_DEPENDENCY_TO_UPPER ToUpperExp; + HII_DEPENDENCY_TO_LOWER ToLowerExp; + HII_DEPENDENCY_SET SetExp; + HII_DEPENDENCY_NOT NotExp; + + /// + /// Binary expression + /// + HII_DEPENDENCY_CATENATE CatenateExp; + HII_DEPENDENCY_MATCH MatchExp; + HII_DEPENDENCY_MATCH2 Match2Exp; + HII_DEPENDENCY_MULT MultExp; + HII_DEPENDENCY_DIV DivExp; + HII_DEPENDENCY_MOD ModExp; + HII_DEPENDENCY_ADD AddExp; + HII_DEPENDENCY_SUBTRACT SubtractExp; + HII_DEPENDENCY_SHIFT_LEFT ShiftLeftExp; + HII_DEPENDENCY_SHIFT_RIGHT ShiftRightExp; + HII_DEPENDENCY_GREATER_THAN GreaterThanExp; + HII_DEPENDENCY_GREATER_EQUAL GreaterEqualExp; + HII_DEPENDENCY_LESS_THAN LessThanExp; + HII_DEPENDENCY_LESS_EQUAL LessEqualExp; + HII_DEPENDENCY_EQUAL EqualExp; + HII_DEPENDENCY_NOT_EQUAL NotEqualExp; + HII_DEPENDENCY_BITWISE_AND BitwiseAndExp; + HII_DEPENDENCY_BITWISE_OR BitwiseOrExp; + HII_DEPENDENCY_AND AndExp; + HII_DEPENDENCY_OR OrExp; + + /// + /// ternary expression + /// + HII_DEPENDENCY_CONDITIONAL ConditionalExp; + HII_DEPENDENCY_FIND FindExp; + HII_DEPENDENCY_MID MidExp; + HII_DEPENDENCY_TOKEN TokenExp; + HII_DEPENDENCY_SPAN SpanExp; + HII_DEPENDENCY_MAP MapExp; +}; + +/// +/// Definition of HII_EXPRESSION_OPCODE +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + UINT8 Operand; + HII_EXPRESSION_OPCODE_EXTRA ExtraData; + LIST_ENTRY MapExpressionList; ///< nested expressions inside of Map opcode. +} HII_EXPRESSION_OPCODE; + +#define HII_EXPRESSION_OPCODE_SIGNATURE SIGNATURE_32 ('E', 'X', 'O', 'P') +#define HII_EXPRESSION_OPCODE_FROM_LINK(a) CR (a, HII_EXPRESSION_OPCODE, Link, HII_EXPRESSION_OPCODE_SIGNATURE) + +/// +/// Definition of HII_WARNING_IF_DATA +/// +typedef struct { + EFI_STRING_ID WarningIfError; + UINT8 TimeOut; +} HII_WARNING_IF_DATA; + +/// +/// Definition of HII_EXTRA_DATA +/// +typedef union { + UINT8 RuleId; ///< For EFI_IFR_RULE only + EFI_STRING_ID Error; ///< For EFI_IFR_NO_SUBMIT_IF, EFI_IFR_INCONSISTENT_IF only + HII_WARNING_IF_DATA WarningIfData; +} HII_EXTRA_DATA; + +/// +/// Definition of HII_EXPRESSION +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + UINT8 Type; ///< Type for this expression + EFI_IFR_OP_HEADER *OpCode; ///< Save the opcode buffer. + LIST_ENTRY OpCodeListHead; ///< OpCodes consist of this expression (HII_EXPRESSION_OPCODE) + HII_DEPENDENCY_EXPRESSION *RootDependencyExp; ///< Expression OpCodes tree layout to describe dependency of this expression. + HII_EXTRA_DATA ExtraData; + EFI_HII_VALUE Result; ///< Expression evaluation result +} HII_EXPRESSION; + +#define HII_EXPRESSION_SIGNATURE SIGNATURE_32 ('F', 'E', 'X', 'P') +#define HII_EXPRESSION_FROM_LINK(a) CR (a, HII_EXPRESSION, Link, HII_EXPRESSION_SIGNATURE) + +/// +/// Definition of HII_EXPRESSION_LIST +/// +typedef struct { + UINTN Signature; + UINTN Count; + HII_EXPRESSION *Expression[1]; ///< Array[Count] of expressions +} HII_EXPRESSION_LIST; + +#define HII_EXPRESSION_LIST_SIGNATURE SIGNATURE_32 ('F', 'E', 'X', 'R') + +/// +/// Definition of HII_STATEMENT_VALUE +/// +typedef struct { + /// + /// HII Data Type + /// + UINT8 Type; + EFI_IFR_TYPE_VALUE Value; + /// + /// Buffer Data and Length if Type is EFI_IFR_TYPE_BUFFER or EFI_IFR_TYPE_STRING + /// + UINT8 *Buffer; + UINT16 BufferLen; + UINT8 BufferValueType; ///< Data type for buffer internal data, currently only for orderedlist +} HII_STATEMENT_VALUE; + +/// +/// Default value +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + UINT16 DefaultId; + HII_STATEMENT_VALUE Value; ///< Default value + + HII_EXPRESSION *ValueExpression; ///< Not-NULL indicates default value is provided by EFI_IFR_VALUE +} HII_QUESTION_DEFAULT; + +#define HII_QUESTION_DEFAULT_SIGNATURE SIGNATURE_32 ('Q', 'D', 'F', 'T') +#define HII_QUESTION_DEFAULT_FROM_LINK(a) CR (a, HII_QUESTION_DEFAULT, Link, HII_QUESTION_DEFAULT_SIGNATURE) + +#define HII_QUESTION_OPTION_SIGNATURE SIGNATURE_32 ('Q', 'O', 'P', 'T') + +/// +/// Option value +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + EFI_IFR_ONE_OF_OPTION *OpCode; ///< OneOfOption Data + + EFI_STRING_ID Text; + UINT8 Flags; + HII_STATEMENT_VALUE Value; + EFI_IMAGE_ID ImageId; + + HII_EXPRESSION_LIST *SuppressExpression; ///< Non-NULL indicates nested inside of SuppressIf +} HII_QUESTION_OPTION; + +#define HII_QUESTION_OPTION_FROM_LINK(a) CR (a, HII_QUESTION_OPTION, Link, HII_QUESTION_OPTION_SIGNATURE) + +/// +/// class of default +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + UINT16 DefaultId; + EFI_STRING_ID DefaultName; +} HII_FORMSET_DEFAULTSTORE; + +#define HII_FORMSET_DEFAULTSTORE_SIGNATURE SIGNATURE_32 ('F', 'D', 'F', 'S') +#define HII_FORMSET_DEFAULTSTORE_FROM_LINK(a) CR (a, HII_FORMSET_DEFAULTSTORE, Link, HII_FORMSET_DEFAULTSTORE_SIGNATURE) + +/// +/// Definition of HII_STATEMENT_EXTRA +/// +typedef union { + UINT8 Flags; + EFI_STRING_ID TextTwo; + EFI_DEFAULT_ID DefaultId; + EFI_STRING_ID QuestionConfig; + EFI_GUID Guid; + + struct { + UINT8 Flags; + UINT64 Minimum; ///< for EFI_IFR_ONE_OF/EFI_IFR_NUMERIC, it's Min/Max value + UINT64 Maximum; ///< for EFI_IFR_STRING/EFI_IFR_PASSWORD, it's Min/Max length + UINT64 Step; + EFI_GUID Guid; + } NumData; + + struct { + UINT8 Flags; + UINT8 MaxContainers; ///< for EFI_IFR_ORDERED_LIST + } OrderListData; + + struct { + UINT8 Flags; + UINT8 MinSize; + UINT8 MaxSize; + } StrData; + + struct { + UINT16 MinSize; + UINT16 MaxSize; + } PwdData; +} HII_STATEMENT_EXTRA; + +/// +/// Statement (Question) +/// +typedef struct _HII_STATEMENT HII_STATEMENT; +struct _HII_STATEMENT { + UINTN Signature; + LIST_ENTRY Link; + + UINT8 Operand; ///< The operand (first byte) of this Statement or Question + EFI_IFR_OP_HEADER *OpCode; + + /// + /// Statement Header + /// + EFI_STRING_ID Prompt; + EFI_STRING_ID Help; + + /// + /// Question Header + /// + EFI_QUESTION_ID QuestionId; ///< Question id, the value of zero is reserved + EFI_VARSTORE_ID VarStoreId; ///< VarStore id, a value of zero indicates no variable storage + HII_VAR_STORE_INFO VarStoreInfo; ///< VarStoreInfoIf VarStoreId refers to Buffer Storage (EFI_IFR_VARSTORE or EFI_IFR_VARSTORE_EFI), then VarStoreInfo contains a 16-bit Buffer Storage offset (VarOffset). + ///< If VarStoreId refers to Name/Value Storage (EFI_IFR_VARSTORE_NAME_VALUE), then VarStoreInfo contains the String ID of the name (VarName) for this name/value pair. + UINT8 QuestionFlags; ///< The flag of this Question.(Readonly, reset required, callback attribute....) + + BOOLEAN QuestionReferToBitField; ///< Whether the question is stored in a bit field. + UINT16 StorageWidth; ///< The storage width of this Question. + UINT16 BitStorageWidth; ///< The Storage width of this Question in bit level. + UINT16 BitVarOffset; ///< The storage offset of this Question in bit level. + CHAR16 *VariableName; ///< Name/Value or EFI Variable name + CHAR16 *BlockName; ///< Buffer storage block name: "OFFSET=...WIDTH=..." + + HII_FORMSET_STORAGE *Storage; ///< Point to the storage that store this question. + HII_STATEMENT_EXTRA ExtraData; + + BOOLEAN Locked; ///< Whether this statement is locked. + + HII_STATEMENT_VALUE Value; + + /// + /// Get from IFR parsing + /// + + HII_STATEMENT *ParentStatement; ///< Parent Statement of current statement. + HII_EXPRESSION_LIST *ExpressionList; ///< nesting inside of GrayedOutIf/DisableIf/SuppressIf + HII_EXPRESSION *ValueExpression; ///< nested EFI_IFR_VALUE, provide Question value and indicate Question is ReadOnly + + EFI_IMAGE_ID ImageId; ///< nested EFI_IFR_IMAGE + UINT8 RefreshInterval; ///< nested EFI_IFR_REFRESH, refresh interval(in seconds) for Question value, 0 means no refresh + + LIST_ENTRY DefaultListHead; ///< nested EFI_IFR_DEFAULT list (HII_QUESTION_DEFAULT), provide default values + LIST_ENTRY OptionListHead; ///< nested EFI_IFR_ONE_OF_OPTION list (HII_QUESTION_OPTION) + LIST_ENTRY InconsistentListHead; ///< nested inconsistent expression list (HII_EXPRESSION) + LIST_ENTRY NoSubmitListHead; ///< nested nosubmit expression list (HII_EXPRESSION) + LIST_ENTRY WarningListHead; ///< nested warning expression list (HII_EXPRESSION) + + HII_EXPRESSION *ReadExpression; ///< nested EFI_IFR_READ, provide this question value by read expression. + HII_EXPRESSION *WriteExpression; ///< nested EFI_IFR_WRITE, evaluate write expression after this question value is set. +}; + +#define HII_STATEMENT_SIGNATURE SIGNATURE_32 ('H', 'S', 'T', 'A') +#define HII_STATEMENT_FROM_LINK(a) CR (a, HII_STATEMENT, Link, HII_STATEMENT_SIGNATURE) + +/// +/// Form +/// +#define STANDARD_MAP_FORM_TYPE 0x01 + +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + UINT16 FormId; ///< FormId of normal form or formmap form. + EFI_STRING_ID FormTitle; ///< FormTile of normal form, or FormMapMethod title of formmap form. + UINT16 FormType; ///< Specific form type for the different form. + + EFI_IMAGE_ID ImageId; ///< The image id. + + BOOLEAN ModalForm; ///< Whether this is a modal form. + BOOLEAN Locked; ///< Whether this form is locked. + EFI_GUID RefreshGuid; ///< Form refresh event guid. + + LIST_ENTRY StatementListHead; ///< List of Statements and Questions (HII_STATEMENT) + LIST_ENTRY ConfigRequestHead; ///< List of configrequest for all storage. + LIST_ENTRY RuleListHead; ///< nested EFI_IFR_RULE list, pre-defined expressions attached to the form. + HII_EXPRESSION_LIST *SuppressExpression; ///< nesting inside of SuppressIf +} HII_FORM; + +#define HII_FORM_SIGNATURE SIGNATURE_32 ('F', 'F', 'R', 'M') +#define HII_FORM_FROM_LINK(a) CR (a, HII_FORM, Link, HII_FORM_SIGNATURE) + +/// +/// FormSet +/// +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + EFI_HII_HANDLE HiiHandle; ///< Unique id for formset, HII Handle of this FormSet package. + EFI_HANDLE DriverHandle; ///< EFI_HANDLE which was registered with the package list in NewPackageList(). + EFI_HII_CONFIG_ACCESS_PROTOCOL *ConfigAccess; ///< ConfigAccess Protocol associated with this HiiPackageList + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + + UINTN IfrBinaryLength; ///< Ifr binary data length of this formset. + UINT8 *IfrBinaryData; ///< Point to the Ifr binary data. + + EFI_GUID Guid; ///< Formset Guid. + EFI_STRING_ID FormSetTitle; ///< String Id of Formset title. + EFI_STRING_ID Help; ///< String Id of Formset title. + + UINT8 NumberOfClassGuid; ///< Class Guid name + EFI_GUID ClassGuid[3]; ///< Up to three ClassGuid + + EFI_IMAGE_ID ImageId; ///< The image id. + + LIST_ENTRY StatementListOSF; ///< Statement list out side of the form. + LIST_ENTRY StorageListHead; ///< Storage list (HII_FORMSET_STORAGE) + LIST_ENTRY DefaultStoreListHead; ///< DefaultStore list (HII_FORMSET_DEFAULTSTORE) + LIST_ENTRY FormListHead; ///< Form list (HII_FORM_BROWSER_FORM) +} HII_FORMSET; + +#define HII_FORMSET_SIGNATURE SIGNATURE_32 ('H', 'I', 'F', 'S') +#define HII_FORMSET_FROM_LINK(a) CR (a, HII_FORMSET, Link, HII_FORMSET_SIGNATURE) + +/// +/// Get/set question value from/to. +/// +typedef enum { + GetSetValueWithBuffer = 0, ///< Get/Set question value from/to buffer in the storage. + GetSetValueWithHiiDriver, ///< Get/Set question value from/to hii driver. + GetSetValueWithBoth, ///< Compare the editbuffer with buffer for this question, not use the question value. + GetSetValueWithMax ///< Invalid value. +} GET_SET_QUESTION_VALUE_WITH; + +/** + Initialize the internal data structure of a FormSet. + + @param[in] Handle PackageList Handle + @param[in,out] FormSetGuid On input, GUID or class GUID of a formset. If not + specified (NULL or zero GUID), take the first + FormSet with class GUID EFI_HII_PLATFORM_SETUP_FORMSET_GUID + found in package list. + On output, GUID of the formset found(if not NULL). + @param[out] FormSet FormSet data structure. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_NOT_FOUND The specified FormSet could not be found. + +**/ +EFI_STATUS +CreateFormSetFromHiiHandle ( + IN EFI_HII_HANDLE Handle, + IN OUT EFI_GUID *FormSetGuid, + OUT HII_FORMSET *FormSet + ); + +/** + Initialize a Formset and get current setting for Questions. + + @param[in,out] FormSet FormSet data structure. + +**/ +VOID +InitializeFormSet ( + IN OUT HII_FORMSET *FormSet + ); + +/** + Free resources allocated for a FormSet. + + @param[in,out] FormSet Pointer of the FormSet + +**/ +VOID +DestroyFormSet ( + IN OUT HII_FORMSET *FormSet + ); + +/** + Save Question Value to the memory, but not to storage. + + @param[in] FormSet FormSet data structure. + @param[in] Form Form data structure. + @param[in,out] Question Pointer to the Question. + @param[in] QuestionValue New Question Value to be set. + + @retval EFI_SUCCESS The question value has been set successfully. + @retval EFI_INVALID_PARAMETER One or more parameters are invalid. + +**/ +EFI_STATUS +SetQuestionValue ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form, + IN OUT HII_STATEMENT *Question, + IN HII_STATEMENT_VALUE *QuestionValue + ); + +/** + Get Question's current Value from storage. + + @param[in] FormSet FormSet data structure. + @param[in] Form Form data structure. + @param[in,out] Question Question to be initialized. + + @return the current Question Value in storage if success. + @return NULL if Question is not found or any error occurs. + +**/ +HII_STATEMENT_VALUE * +RetrieveQuestion ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form, + IN OUT HII_STATEMENT *Question + ); + +/** + Get Question's current Value. + + @param[in] FormSet FormSet data structure. + @param[in] Form Form data structure. + @param[out] Question Question to be initialized. + @param[in] GetValueFrom Where to get value, may from editbuffer, buffer or hii driver. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_INVALID_PARAMETER Formset, Form or Question is NULL. + +**/ +EFI_STATUS +GetQuestionValue ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form, + IN OUT HII_STATEMENT *Question, + IN GET_SET_QUESTION_VALUE_WITH GetValueFrom + ); + +/** + Submit data for a form. + + @param[in] FormSet FormSet which contains the Form. + @param[in] Form Form to submit. + + @retval EFI_SUCCESS The function completed successfully. + @retval Others Other errors occur. + +**/ +EFI_STATUS +SubmitForm ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form + ); + +/** + Evaluate the result of a HII expression. + + If Expression is NULL, then ASSERT. + + @param[in] FormSet FormSet associated with this expression. + @param[in] Form Form associated with this expression. + @param[in,out] Expression Expression to be evaluated. + + @retval EFI_SUCCESS The expression evaluated successfully + @retval EFI_NOT_FOUND The Question which referenced by a QuestionId + could not be found. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the + stack. + @retval EFI_ACCESS_DENIED The pop operation underflowed the stack + @retval EFI_INVALID_PARAMETER Syntax error with the Expression + +**/ +EFI_STATUS +EvaluateHiiExpression ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form, + IN OUT HII_EXPRESSION *Expression + ); + +/** + Retrieve dependencies within an expression. These dependencies can express how + this expression will be evaluated. + + @param[in] Expression Expression to retrieve dependencies. + + @retval EFI_SUCCESS The dependencies were successfully retrieved. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory. + +**/ +EFI_STATUS +GetHiiExpressionDependency ( + IN HII_EXPRESSION *Expression + ); + +/** + Get default value of question. + + @param[in] FormSet The form set. + @param[in] Form The form. + @param[in] Question The question. + @param[in] DefaultId The Class of the default. + @param[out] DefaultValue The default value of given question. + + @retval EFI_SUCCESS Question is reset to default value. + +**/ +EFI_STATUS +GetQuestionDefault ( + IN HII_FORMSET *FormSet, + IN HII_FORM *Form, + IN HII_STATEMENT *Question, + IN UINT16 DefaultId, + OUT HII_STATEMENT_VALUE *DefaultValue + ); + +/** + Return the result of the expression list. Check the expression list and + return the highest priority express result. + Priority: DisableIf > SuppressIf > GrayOutIf > FALSE + + @param[in] ExpList The input expression list. + @param[in] Evaluate Whether need to evaluate the expression first. + @param[in] FormSet FormSet associated with this expression. + @param[in] Form Form associated with this expression. + + @retval EXPRESS_RESULT Return the higher priority express result. + DisableIf > SuppressIf > GrayOutIf > FALSE + +**/ +EXPRESS_RESULT +EvaluateExpressionList ( + IN HII_EXPRESSION_LIST *ExpList, + IN BOOLEAN Evaluate, + IN HII_FORMSET *FormSet OPTIONAL, + IN HII_FORM *Form OPTIONAL + ); + +#endif // HII_UTILITY_LIB_ diff --git a/RedfishPkg/Library/HiiUtilityLib/HiiExpression.c b/RedfishPkg/Library/HiiUtilityLib/HiiExpression.c new file mode 100644 index 0000000000..c36c241642 --- /dev/null +++ b/RedfishPkg/Library/HiiUtilityLib/HiiExpression.c @@ -0,0 +1,1439 @@ +/** @file + The implementation of HII expression. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ +#include "HiiInternal.h" + +// +// Global stack used to evaluate boolean expressions +// +EFI_HII_VALUE *mOpCodeScopeStack = NULL; +EFI_HII_VALUE *mOpCodeScopeStackEnd = NULL; +EFI_HII_VALUE *mOpCodeScopeStackPointer = NULL; + +// +// Stack used for Suppressif/grayoutif/disableif expression list. +// +HII_EXPRESSION **mFormExpressionStack = NULL; +HII_EXPRESSION **mFormExpressionEnd = NULL; +HII_EXPRESSION **mFormExpressionPointer = NULL; + +HII_EXPRESSION **mStatementExpressionStack = NULL; +HII_EXPRESSION **mStatementExpressionEnd = NULL; +HII_EXPRESSION **mStatementExpressionPointer = NULL; + +HII_EXPRESSION **mOptionExpressionStack = NULL; +HII_EXPRESSION **mOptionExpressionEnd = NULL; +HII_EXPRESSION **mOptionExpressionPointer = NULL; + +// +// Stack used for the sub expresion in map expression. +// +EFI_HII_VALUE *mCurrentExpressionStack = NULL; +EFI_HII_VALUE *mCurrentExpressionEnd = NULL; +EFI_HII_VALUE *mCurrentExpressionPointer = NULL; + +// +// Stack used for the map expression list. +// +EFI_HII_VALUE *mMapExpressionListStack = NULL; +EFI_HII_VALUE *mMapExpressionListEnd = NULL; +EFI_HII_VALUE *mMapExpressionListPointer = NULL; + +// +// Stack used for dependency expression. +// +HII_DEPENDENCY_EXPRESSION **mExpressionDependencyStack = NULL; +HII_DEPENDENCY_EXPRESSION **mExpressionDependencyEnd = NULL; +HII_DEPENDENCY_EXPRESSION **mExpressionDependencyPointer = NULL; + +/** + Grow size of the stack. + + This is an internal function. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + + @retval EFI_SUCCESS Grow stack success. + @retval EFI_OUT_OF_RESOURCES No enough memory for stack space. + +**/ +EFI_STATUS +GrowStack ( + IN OUT EFI_HII_VALUE **Stack, + IN OUT EFI_HII_VALUE **StackPtr, + IN OUT EFI_HII_VALUE **StackEnd + ) +{ + UINTN Size; + EFI_HII_VALUE *NewStack; + + Size = EXPRESSION_STACK_SIZE_INCREMENT; + if (*StackPtr != NULL) { + Size = Size + (*StackEnd - *Stack); + } + + NewStack = AllocatePool (Size * sizeof (EFI_HII_VALUE)); + if (NewStack == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + if (*StackPtr != NULL) { + // + // Copy from Old Stack to the New Stack + // + CopyMem ( + NewStack, + *Stack, + (*StackEnd - *Stack) * sizeof (EFI_HII_VALUE) + ); + + // + // Free The Old Stack + // + FreePool (*Stack); + } + + // + // Make the Stack pointer point to the old data in the new stack + // + *StackPtr = NewStack + (*StackPtr - *Stack); + *Stack = NewStack; + *StackEnd = NewStack + Size; + + return EFI_SUCCESS; +} + +/** + Push an element onto the Boolean Stack. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + @param Data Data to push. + + @retval EFI_SUCCESS Push stack success. + +**/ +EFI_STATUS +PushStack ( + IN OUT EFI_HII_VALUE **Stack, + IN OUT EFI_HII_VALUE **StackPtr, + IN OUT EFI_HII_VALUE **StackEnd, + IN EFI_HII_VALUE *Data + ) +{ + EFI_STATUS Status; + + // + // Check for a stack overflow condition + // + if (*StackPtr >= *StackEnd) { + // + // Grow the stack + // + Status = GrowStack (Stack, StackPtr, StackEnd); + if (EFI_ERROR (Status)) { + return Status; + } + } + + // + // Push the item onto the stack + // + CopyMem (*StackPtr, Data, sizeof (EFI_HII_VALUE)); + if (Data->Type == EFI_IFR_TYPE_BUFFER) { + (*StackPtr)->Buffer = AllocateCopyPool (Data->BufferLen, Data->Buffer); + if ((*StackPtr)->Buffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + } + + *StackPtr = *StackPtr + 1; + + return EFI_SUCCESS; +} + +/** + Pop an element from the stack. + + @param Stack On input: old stack + @param StackPtr On input: old stack pointer; On output: new stack pointer + @param Data Data to pop. + + @retval EFI_SUCCESS The value was popped onto the stack. + @retval EFI_ACCESS_DENIED The pop operation underflowed the stack + +**/ +EFI_STATUS +PopStack ( + IN EFI_HII_VALUE *Stack, + IN OUT EFI_HII_VALUE **StackPtr, + OUT EFI_HII_VALUE *Data + ) +{ + // + // Check for a stack underflow condition + // + if (*StackPtr == Stack) { + return EFI_ACCESS_DENIED; + } + + // + // Pop the item off the stack + // + *StackPtr = *StackPtr - 1; + CopyMem (Data, *StackPtr, sizeof (EFI_HII_VALUE)); + return EFI_SUCCESS; +} + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetCurrentExpressionStack ( + VOID + ) +{ + mCurrentExpressionPointer = mCurrentExpressionStack; + mFormExpressionPointer = mFormExpressionStack; + mStatementExpressionPointer = mStatementExpressionStack; + mOptionExpressionPointer = mOptionExpressionStack; +} + +/** + Push current expression onto the Stack + + @param Pointer Pointer to current expression. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushCurrentExpression ( + IN VOID *Pointer + ) +{ + EFI_HII_VALUE Data; + + Data.Type = EFI_IFR_TYPE_NUM_SIZE_64; + Data.Value.u64 = (UINT64)(UINTN)Pointer; + + return PushStack ( + &mCurrentExpressionStack, + &mCurrentExpressionPointer, + &mCurrentExpressionEnd, + &Data + ); +} + +/** + Pop current expression from the Stack + + @param Pointer Pointer to current expression to be pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopCurrentExpression ( + OUT VOID **Pointer + ) +{ + EFI_STATUS Status; + EFI_HII_VALUE Data; + + Status = PopStack ( + mCurrentExpressionStack, + &mCurrentExpressionPointer, + &Data + ); + + *Pointer = (VOID *)(UINTN)Data.Value.u64; + + return Status; +} + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetMapExpressionListStack ( + VOID + ) +{ + mMapExpressionListPointer = mMapExpressionListStack; +} + +/** + Grow size of the stack. + + This is an internal function. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + @param MemberSize The stack member size. + + @retval EFI_SUCCESS Grow stack success. + @retval EFI_OUT_OF_RESOURCES No enough memory for stack space. + +**/ +EFI_STATUS +GrowConditionalStack ( + IN OUT HII_EXPRESSION ***Stack, + IN OUT HII_EXPRESSION ***StackPtr, + IN OUT HII_EXPRESSION ***StackEnd, + IN UINTN MemberSize + ) +{ + UINTN Size; + HII_EXPRESSION **NewStack; + + Size = EXPRESSION_STACK_SIZE_INCREMENT; + if (*StackPtr != NULL) { + Size = Size + (*StackEnd - *Stack); + } + + NewStack = AllocatePool (Size * MemberSize); + if (NewStack == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + if (*StackPtr != NULL) { + // + // Copy from Old Stack to the New Stack + // + CopyMem ( + NewStack, + *Stack, + (*StackEnd - *Stack) * MemberSize + ); + + // + // Free The Old Stack + // + FreePool (*Stack); + } + + // + // Make the Stack pointer point to the old data in the new stack + // + *StackPtr = NewStack + (*StackPtr - *Stack); + *Stack = NewStack; + *StackEnd = NewStack + Size; + + return EFI_SUCCESS; +} + +/** + Push an element onto the Stack. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + @param Data Data to push. + + @retval EFI_SUCCESS Push stack success. + +**/ +EFI_STATUS +PushConditionalStack ( + IN OUT HII_EXPRESSION ***Stack, + IN OUT HII_EXPRESSION ***StackPtr, + IN OUT HII_EXPRESSION ***StackEnd, + IN HII_EXPRESSION **Data + ) +{ + EFI_STATUS Status; + + // + // Check for a stack overflow condition + // + if (*StackPtr >= *StackEnd) { + // + // Grow the stack + // + Status = GrowConditionalStack (Stack, StackPtr, StackEnd, sizeof (HII_EXPRESSION *)); + if (EFI_ERROR (Status)) { + return Status; + } + } + + // + // Push the item onto the stack + // + CopyMem (*StackPtr, Data, sizeof (HII_EXPRESSION *)); + *StackPtr = *StackPtr + 1; + + return EFI_SUCCESS; +} + +/** + Pop an element from the stack. + + @param Stack On input: old stack + @param StackPtr On input: old stack pointer; On output: new stack pointer + @param Data Data to pop. + + @retval EFI_SUCCESS The value was popped onto the stack. + @retval EFI_ACCESS_DENIED The pop operation underflowed the stack + +**/ +EFI_STATUS +PopConditionalStack ( + IN HII_EXPRESSION **Stack, + IN OUT HII_EXPRESSION ***StackPtr, + OUT HII_EXPRESSION **Data + ) +{ + // + // Check for a stack underflow condition + // + if (*StackPtr == Stack) { + return EFI_ACCESS_DENIED; + } + + // + // Pop the item off the stack + // + *StackPtr = *StackPtr - 1; + CopyMem (Data, *StackPtr, sizeof (HII_EXPRESSION *)); + return EFI_SUCCESS; +} + +/** + Get the expression list count. + + @param Level Which type this expression belong to. Form, + statement or option? + + @retval >=0 The expression count + @retval -1 Input parameter error. + +**/ +INTN +GetConditionalExpressionCount ( + IN EXPRESS_LEVEL Level + ) +{ + switch (Level) { + case ExpressForm: + return mFormExpressionPointer - mFormExpressionStack; + case ExpressStatement: + return mStatementExpressionPointer - mStatementExpressionStack; + case ExpressOption: + return mOptionExpressionPointer - mOptionExpressionStack; + default: + ASSERT (FALSE); + return -1; + } +} + +/** + Get the expression Buffer pointer. + + @param Level Which type this expression belong to. Form, + statement or option? + + @retval The start pointer of the expression buffer or NULL. + +**/ +HII_EXPRESSION ** +GetConditionalExpressionList ( + IN EXPRESS_LEVEL Level + ) +{ + switch (Level) { + case ExpressForm: + return mFormExpressionStack; + case ExpressStatement: + return mStatementExpressionStack; + case ExpressOption: + return mOptionExpressionStack; + default: + ASSERT (FALSE); + return NULL; + } +} + +/** + Push the expression options onto the Stack. + + @param Pointer Pointer to the current expression. + @param Level Which type this expression belong to. Form, + statement or option? + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushConditionalExpression ( + IN HII_EXPRESSION *Pointer, + IN EXPRESS_LEVEL Level + ) +{ + switch (Level) { + case ExpressForm: + return PushConditionalStack ( + &mFormExpressionStack, + &mFormExpressionPointer, + &mFormExpressionEnd, + &Pointer + ); + case ExpressStatement: + return PushConditionalStack ( + &mStatementExpressionStack, + &mStatementExpressionPointer, + &mStatementExpressionEnd, + &Pointer + ); + case ExpressOption: + return PushConditionalStack ( + &mOptionExpressionStack, + &mOptionExpressionPointer, + &mOptionExpressionEnd, + &Pointer + ); + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; + } +} + +/** + Pop the expression options from the Stack + + @param Level Which type this expression belong to. Form, + statement or option? + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopConditionalExpression ( + IN EXPRESS_LEVEL Level + ) +{ + HII_EXPRESSION *Pointer; + + switch (Level) { + case ExpressForm: + return PopConditionalStack ( + mFormExpressionStack, + &mFormExpressionPointer, + &Pointer + ); + + case ExpressStatement: + return PopConditionalStack ( + mStatementExpressionStack, + &mStatementExpressionPointer, + &Pointer + ); + + case ExpressOption: + return PopConditionalStack ( + mOptionExpressionStack, + &mOptionExpressionPointer, + &Pointer + ); + + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; + } +} + +/** + Push the list of map expression onto the Stack + + @param Pointer Pointer to the list of map expression to be pushed. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushMapExpressionList ( + IN VOID *Pointer + ) +{ + EFI_HII_VALUE Data; + + Data.Type = EFI_IFR_TYPE_NUM_SIZE_64; + Data.Value.u64 = (UINT64)(UINTN)Pointer; + + return PushStack ( + &mMapExpressionListStack, + &mMapExpressionListPointer, + &mMapExpressionListEnd, + &Data + ); +} + +/** + Pop the list of map expression from the Stack + + @param Pointer Pointer to the list of map expression to be pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopMapExpressionList ( + OUT VOID **Pointer + ) +{ + EFI_STATUS Status; + EFI_HII_VALUE Data; + + Status = PopStack ( + mMapExpressionListStack, + &mMapExpressionListPointer, + &Data + ); + + *Pointer = (VOID *)(UINTN)Data.Value.u64; + + return Status; +} + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetScopeStack ( + VOID + ) +{ + mOpCodeScopeStackPointer = mOpCodeScopeStack; +} + +/** + Push an Operand onto the Stack + + @param Operand Operand to push. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the + stack. + +**/ +EFI_STATUS +PushScope ( + IN UINT8 Operand + ) +{ + EFI_HII_VALUE Data; + + Data.Type = EFI_IFR_TYPE_NUM_SIZE_8; + Data.Value.u8 = Operand; + + return PushStack ( + &mOpCodeScopeStack, + &mOpCodeScopeStackPointer, + &mOpCodeScopeStackEnd, + &Data + ); +} + +/** + Pop an Operand from the Stack + + @param Operand Operand to pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the + stack. + +**/ +EFI_STATUS +PopScope ( + OUT UINT8 *Operand + ) +{ + EFI_STATUS Status; + EFI_HII_VALUE Data; + + Status = PopStack ( + mOpCodeScopeStack, + &mOpCodeScopeStackPointer, + &Data + ); + + *Operand = Data.Value.u8; + + return Status; +} + +/** + Grow size of the stack for Expression Dependencies. + + This is an internal function. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + + @retval EFI_SUCCESS Grow Dependency stack success. + @retval EFI_OUT_OF_RESOURCES No enough memory for stack space. + +**/ +EFI_STATUS +GrowDependencyStack ( + IN OUT HII_DEPENDENCY_EXPRESSION ***Stack, + IN OUT HII_DEPENDENCY_EXPRESSION ***StackPtr, + IN OUT HII_DEPENDENCY_EXPRESSION ***StackEnd + ) +{ + UINTN Size; + HII_DEPENDENCY_EXPRESSION **NewStack; + + Size = EXPRESSION_STACK_SIZE_INCREMENT; + if (*StackPtr != NULL) { + Size = Size + (*StackEnd - *Stack); + } + + NewStack = AllocatePool (Size * sizeof (HII_DEPENDENCY_EXPRESSION *)); + if (NewStack == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + if (*StackPtr != NULL) { + // + // Copy from Old Stack to the New Stack + // + CopyMem ( + NewStack, + *Stack, + (*StackEnd - *Stack) * sizeof (HII_DEPENDENCY_EXPRESSION *) + ); + + // + // Free The Old Stack + // + FreePool (*Stack); + } + + // + // Make the Stack pointer point to the old data in the new stack + // + *StackPtr = NewStack + (*StackPtr - *Stack); + *Stack = NewStack; + *StackEnd = NewStack + Size; + + return EFI_SUCCESS; +} + +/** + Push an element onto the Stack for Expression Dependencies. + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param StackEnd On input: old stack end; On output: new stack end + @param Data Data to push. + + @retval EFI_SUCCESS Push stack success. + +**/ +EFI_STATUS +PushDependencyStack ( + IN OUT HII_DEPENDENCY_EXPRESSION ***Stack, + IN OUT HII_DEPENDENCY_EXPRESSION ***StackPtr, + IN OUT HII_DEPENDENCY_EXPRESSION ***StackEnd, + IN HII_DEPENDENCY_EXPRESSION **Data + ) +{ + EFI_STATUS Status; + + // + // Check for a stack overflow condition + // + if (*StackPtr >= *StackEnd) { + // + // Grow the stack + // + Status = GrowDependencyStack (Stack, StackPtr, StackEnd); + if (EFI_ERROR (Status)) { + return Status; + } + } + + // + // Push the item onto the stack + // + CopyMem (*StackPtr, Data, sizeof (HII_DEPENDENCY_EXPRESSION *)); + *StackPtr = *StackPtr + 1; + + return EFI_SUCCESS; +} + +/** + Pop the Expression Dependency options from the Stack + + @param Stack On input: old stack; On output: new stack + @param StackPtr On input: old stack pointer; On output: new stack + pointer + @param Data Data to push. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopDependencyStack ( + IN HII_DEPENDENCY_EXPRESSION **Stack, + IN OUT HII_DEPENDENCY_EXPRESSION ***StackPtr, + OUT HII_DEPENDENCY_EXPRESSION **Data + ) +{ + // + // Check for a stack underflow condition + // + if (*StackPtr == Stack) { + return EFI_ACCESS_DENIED; + } + + // + // Pop the item off the stack + // + *StackPtr = *StackPtr - 1; + CopyMem (Data, *StackPtr, sizeof (HII_DEPENDENCY_EXPRESSION *)); + return EFI_SUCCESS; +} + +/** + Push the list of Expression Dependencies onto the Stack + + @param Pointer Pointer to the list of map expression to be pushed. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushDependencyExpDes ( + IN HII_DEPENDENCY_EXPRESSION **Pointer + ) +{ + return PushDependencyStack ( + &mExpressionDependencyStack, + &mExpressionDependencyPointer, + &mExpressionDependencyEnd, + Pointer + ); +} + +/** + Pop the list of Expression Dependencies from the Stack + + @param Pointer Pointer to the list of map expression to be pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopDependencyExpDes ( + OUT HII_DEPENDENCY_EXPRESSION **Pointer + ) +{ + return PopDependencyStack ( + mExpressionDependencyStack, + &mExpressionDependencyPointer, + Pointer + ); +} + +/** + Retrieve dependencies within an expression. These dependencies can express how + this expression will be evaluated. + + @param[in,out] Expression Expression to retrieve dependencies. + + @retval EFI_SUCCESS The dependencies were successfully retrieved. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory. + +**/ +EFI_STATUS +GetHiiExpressionDependency ( + IN OUT HII_EXPRESSION *Expression + ) +{ + EFI_STATUS Status; + LIST_ENTRY *Link; + HII_EXPRESSION_OPCODE *ExpressionOpCode; + HII_DEPENDENCY_EXPRESSION *DepExpressionOpCode; + LIST_ENTRY *SubExpressionLink; + HII_EXPRESSION *SubExpression; + UINT8 MapPairCount; + + Link = GetFirstNode (&Expression->OpCodeListHead); + while (!IsNull (&Expression->OpCodeListHead, Link)) { + ExpressionOpCode = HII_EXPRESSION_OPCODE_FROM_LINK (Link); + Link = GetNextNode (&Expression->OpCodeListHead, Link); + Status = EFI_SUCCESS; + + DepExpressionOpCode = (HII_DEPENDENCY_EXPRESSION *)AllocateZeroPool (sizeof (HII_DEPENDENCY_EXPRESSION)); + if (DepExpressionOpCode == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + switch (ExpressionOpCode->Operand) { + // + // Constant + // + case EFI_IFR_FALSE_OP: + case EFI_IFR_ONE_OP: + case EFI_IFR_ONES_OP: + case EFI_IFR_TRUE_OP: + case EFI_IFR_UINT8_OP: + case EFI_IFR_UINT16_OP: + case EFI_IFR_UINT32_OP: + case EFI_IFR_UINT64_OP: + case EFI_IFR_UNDEFINED_OP: + case EFI_IFR_VERSION_OP: + case EFI_IFR_ZERO_OP: + DepExpressionOpCode->ConstantExp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->ConstantExp.Value, &ExpressionOpCode->ExtraData.Value, sizeof (EFI_HII_VALUE)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + // + // Built-in functions + // + case EFI_IFR_DUP_OP: + DepExpressionOpCode->DupExp.Operand = ExpressionOpCode->Operand; + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_EQ_ID_VAL_OP: + DepExpressionOpCode->EqIdValExp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->EqIdValExp.QuestionId, &ExpressionOpCode->ExtraData.EqIdValData.QuestionId, sizeof (EFI_QUESTION_ID)); + CopyMem (&DepExpressionOpCode->EqIdValExp.Value, &ExpressionOpCode->ExtraData.EqIdValData.Value, sizeof (EFI_HII_VALUE)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_EQ_ID_ID_OP: + DepExpressionOpCode->EqIdIdExp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->EqIdIdExp.QuestionId1, &ExpressionOpCode->ExtraData.EqIdIdData.QuestionId1, sizeof (EFI_QUESTION_ID)); + CopyMem (&DepExpressionOpCode->EqIdIdExp.QuestionId2, &ExpressionOpCode->ExtraData.EqIdIdData.QuestionId2, sizeof (EFI_QUESTION_ID)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_EQ_ID_VAL_LIST_OP: + DepExpressionOpCode->EqIdListExp.Operand = ExpressionOpCode->Operand; + DepExpressionOpCode->EqIdListExp.ListLength = ExpressionOpCode->ExtraData.EqIdListData.ListLength; + CopyMem (&DepExpressionOpCode->EqIdListExp.QuestionId, &ExpressionOpCode->ExtraData.EqIdListData.QuestionId, sizeof (EFI_QUESTION_ID)); + PushDependencyExpDes (&DepExpressionOpCode); + DepExpressionOpCode->EqIdListExp.ValueList = AllocateCopyPool ( + DepExpressionOpCode->EqIdListExp.ListLength * sizeof (UINT16), + ExpressionOpCode->ExtraData.EqIdListData.ValueList + ); + if (DepExpressionOpCode->EqIdListExp.ValueList == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_GET_OP: + DepExpressionOpCode->GetExp.Operand = ExpressionOpCode->Operand; + DepExpressionOpCode->GetExp.VarStorage = ExpressionOpCode->ExtraData.GetSetData.VarStorage; + CopyMem (&DepExpressionOpCode->GetExp.VarStoreInfo.VarName, &ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo.VarName, sizeof (EFI_STRING_ID)); + CopyMem (&DepExpressionOpCode->GetExp.VarStoreInfo.VarOffset, &ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo.VarOffset, sizeof (UINT16)); + DepExpressionOpCode->GetExp.VarStoreInfo = ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo; + if (ExpressionOpCode->ExtraData.GetSetData.ValueName != NULL) { + DepExpressionOpCode->GetExp.ValueName = (CHAR16 *)AllocateCopyPool (sizeof (ExpressionOpCode->ExtraData.GetSetData.ValueName), ExpressionOpCode->ExtraData.GetSetData.ValueName); + if (DepExpressionOpCode->GetExp.ValueName == NULL) { + return EFI_OUT_OF_RESOURCES; + } + } + + DepExpressionOpCode->GetExp.ValueType = ExpressionOpCode->ExtraData.GetSetData.ValueType; + DepExpressionOpCode->GetExp.ValueWidth = ExpressionOpCode->ExtraData.GetSetData.ValueWidth; + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_QUESTION_REF1_OP: + DepExpressionOpCode->QuestionRef1Exp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->QuestionRef1Exp.QuestionId, &ExpressionOpCode->ExtraData.QuestionRef1Data.QuestionId, sizeof (EFI_QUESTION_ID)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_RULE_REF_OP: + DepExpressionOpCode->RuleRefExp.Operand = ExpressionOpCode->Operand; + DepExpressionOpCode->RuleRefExp.RuleId = ExpressionOpCode->ExtraData.RuleId; + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_STRING_REF1_OP: + DepExpressionOpCode->StringRef1Exp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->StringRef1Exp.Value.Value.string, &ExpressionOpCode->ExtraData.Value.Value.string, sizeof (EFI_STRING_ID)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_THIS_OP: + DepExpressionOpCode->ThisExp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->ThisExp.QuestionId, &ExpressionOpCode->ExtraData.QuestionRef1Data.QuestionId, sizeof (EFI_QUESTION_ID)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SECURITY_OP: + DepExpressionOpCode->SecurityExp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->SecurityExp.Permissions, &ExpressionOpCode->ExtraData.Guid, sizeof (EFI_GUID)); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + // + // unary-op + // + case EFI_IFR_LENGTH_OP: + DepExpressionOpCode->LengthExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->LengthExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_NOT_OP: + DepExpressionOpCode->NotExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->NotExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_BITWISE_NOT_OP: + DepExpressionOpCode->BitWiseNotExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->BitWiseNotExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_QUESTION_REF2_OP: + DepExpressionOpCode->QuestionRef2Exp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->QuestionRef2Exp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_QUESTION_REF3_OP: + DepExpressionOpCode->QuestionRef3Exp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->QuestionRef3Exp.DevicePath, &ExpressionOpCode->ExtraData.QuestionRef3Data.DevicePath, sizeof (EFI_DEVICE_PATH)); + CopyMem (&DepExpressionOpCode->QuestionRef3Exp.Guid, &ExpressionOpCode->ExtraData.QuestionRef3Data.Guid, sizeof (EFI_GUID)); + PopDependencyExpDes (&DepExpressionOpCode->QuestionRef3Exp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SET_OP: + DepExpressionOpCode->SetExp.Operand = ExpressionOpCode->Operand; + DepExpressionOpCode->SetExp.VarStorage = ExpressionOpCode->ExtraData.GetSetData.VarStorage; + CopyMem (&DepExpressionOpCode->SetExp.VarStoreInfo.VarName, &ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo.VarName, sizeof (EFI_STRING_ID)); + CopyMem (&DepExpressionOpCode->SetExp.VarStoreInfo.VarOffset, &ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo.VarOffset, sizeof (UINT16)); + DepExpressionOpCode->SetExp.VarStoreInfo = ExpressionOpCode->ExtraData.GetSetData.VarStoreInfo; + if (ExpressionOpCode->ExtraData.GetSetData.ValueName != NULL) { + DepExpressionOpCode->SetExp.ValueName = (CHAR16 *)AllocateCopyPool (sizeof (ExpressionOpCode->ExtraData.GetSetData.ValueName), ExpressionOpCode->ExtraData.GetSetData.ValueName); + if (DepExpressionOpCode->SetExp.ValueName == NULL) { + return EFI_OUT_OF_RESOURCES; + } + } + + DepExpressionOpCode->SetExp.ValueType = ExpressionOpCode->ExtraData.GetSetData.ValueType; + DepExpressionOpCode->SetExp.ValueWidth = ExpressionOpCode->ExtraData.GetSetData.ValueWidth; + PopDependencyExpDes (&DepExpressionOpCode->SetExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_STRING_REF2_OP: + DepExpressionOpCode->StringRef2Exp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->StringRef2Exp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TO_BOOLEAN_OP: + DepExpressionOpCode->ToBooleanExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ToBooleanExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TO_STRING_OP: + DepExpressionOpCode->ToStringExp.Operand = ExpressionOpCode->Operand; + DepExpressionOpCode->ToStringExp.Format = ExpressionOpCode->ExtraData.Format; + PopDependencyExpDes (&DepExpressionOpCode->ToStringExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TO_UINT_OP: + DepExpressionOpCode->ToUintExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ToUintExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TO_LOWER_OP: + DepExpressionOpCode->ToLowerExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ToLowerExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TO_UPPER_OP: + DepExpressionOpCode->ToUpperExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ToUpperExp.SubExpression); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + // + // binary-op + // + case EFI_IFR_ADD_OP: + DepExpressionOpCode->AddExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->AddExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->AddExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_AND_OP: + DepExpressionOpCode->AndExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->AndExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->AndExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_BITWISE_AND_OP: + DepExpressionOpCode->BitwiseAndExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->BitwiseAndExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->BitwiseAndExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_BITWISE_OR_OP: + DepExpressionOpCode->BitwiseOrExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->BitwiseOrExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->BitwiseOrExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_CATENATE_OP: + DepExpressionOpCode->CatenateExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->CatenateExp.LeftStringExp); + PopDependencyExpDes (&DepExpressionOpCode->CatenateExp.RightStringExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_DIVIDE_OP: + DepExpressionOpCode->DivExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->DivExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->DivExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_EQUAL_OP: + DepExpressionOpCode->EqualExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->EqualExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->EqualExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_GREATER_EQUAL_OP: + DepExpressionOpCode->GreaterEqualExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->GreaterEqualExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->GreaterEqualExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_GREATER_THAN_OP: + DepExpressionOpCode->GreaterThanExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->GreaterThanExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->GreaterThanExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_LESS_EQUAL_OP: + DepExpressionOpCode->LessEqualExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->LessEqualExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->LessEqualExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_LESS_THAN_OP: + DepExpressionOpCode->LessThanExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->LessThanExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->LessThanExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_MATCH_OP: + DepExpressionOpCode->MatchExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->MatchExp.PatternExp); + PopDependencyExpDes (&DepExpressionOpCode->MatchExp.StringExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_MATCH2_OP: + DepExpressionOpCode->Match2Exp.Operand = ExpressionOpCode->Operand; + CopyMem (&DepExpressionOpCode->Match2Exp.SyntaxType, &ExpressionOpCode->ExtraData.Guid, sizeof (EFI_GUID)); + PopDependencyExpDes (&DepExpressionOpCode->Match2Exp.PatternExp); + PopDependencyExpDes (&DepExpressionOpCode->Match2Exp.StringExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_MODULO_OP: + DepExpressionOpCode->ModExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ModExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->ModExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_MULTIPLY_OP: + DepExpressionOpCode->MultExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->MultExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->MultExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_NOT_EQUAL_OP: + DepExpressionOpCode->NotEqualExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->NotEqualExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->NotEqualExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_OR_OP: + DepExpressionOpCode->OrExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->OrExp.SubExpression1); + PopDependencyExpDes (&DepExpressionOpCode->OrExp.SubExpression2); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SHIFT_LEFT_OP: + DepExpressionOpCode->ShiftLeftExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ShiftLeftExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->ShiftLeftExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SHIFT_RIGHT_OP: + DepExpressionOpCode->ShiftRightExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ShiftRightExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->ShiftRightExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SUBTRACT_OP: + DepExpressionOpCode->SubtractExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->SubtractExp.LeftHandExp); + PopDependencyExpDes (&DepExpressionOpCode->SubtractExp.RightHandExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + // + // ternary-op + // + case EFI_IFR_CONDITIONAL_OP: + DepExpressionOpCode->ConditionalExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->ConditionalExp.CondTrueValExp); + PopDependencyExpDes (&DepExpressionOpCode->ConditionalExp.CondFalseValExp); + PopDependencyExpDes (&DepExpressionOpCode->ConditionalExp.ConditionExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_FIND_OP: + DepExpressionOpCode->FindExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->FindExp.StringToSearchExp); + PopDependencyExpDes (&DepExpressionOpCode->FindExp.StringToCompWithExp); + PopDependencyExpDes (&DepExpressionOpCode->FindExp.IndexExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_MID_OP: + DepExpressionOpCode->MidExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->MidExp.StringOrBufferExp); + PopDependencyExpDes (&DepExpressionOpCode->MidExp.IndexExp); + PopDependencyExpDes (&DepExpressionOpCode->MidExp.LengthExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_TOKEN_OP: + DepExpressionOpCode->TokenExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->TokenExp.StringToSearchExp); + PopDependencyExpDes (&DepExpressionOpCode->TokenExp.DelimiterExp); + PopDependencyExpDes (&DepExpressionOpCode->TokenExp.IndexExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + case EFI_IFR_SPAN_OP: + DepExpressionOpCode->SpanExp.Operand = ExpressionOpCode->Operand; + PopDependencyExpDes (&DepExpressionOpCode->SpanExp.StringToSearchExp); + PopDependencyExpDes (&DepExpressionOpCode->SpanExp.CharsetExp); + PopDependencyExpDes (&DepExpressionOpCode->SpanExp.IndexExp); + PushDependencyExpDes (&DepExpressionOpCode); + break; + + // + // Map + // + case EFI_IFR_MAP_OP: + // + // Go through map expression list. + // + DepExpressionOpCode->MapExp.Operand = ExpressionOpCode->Operand; + MapPairCount = 0; + SubExpressionLink = GetFirstNode (&ExpressionOpCode->MapExpressionList); + while (!IsNull (&ExpressionOpCode->MapExpressionList, SubExpressionLink)) { + MapPairCount++; + SubExpressionLink = GetNextNode (&ExpressionOpCode->MapExpressionList, SubExpressionLink); + if (IsNull (&ExpressionOpCode->MapExpressionList, SubExpressionLink)) { + Status = EFI_INVALID_PARAMETER; + goto Done; + } + + // + // Goto the first expression on next pair. + // + SubExpressionLink = GetNextNode (&ExpressionOpCode->MapExpressionList, SubExpressionLink); + } + + DepExpressionOpCode->MapExp.ExpPair = (HII_DEPENDENCY_EXPRESSION_PAIR *)AllocateZeroPool ( + MapPairCount * sizeof (HII_DEPENDENCY_EXPRESSION_PAIR) + ); + if (DepExpressionOpCode->MapExp.ExpPair == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Done; + } + + DepExpressionOpCode->MapExp.ExpPairNo = MapPairCount; + MapPairCount = 0; + PopDependencyExpDes (&DepExpressionOpCode->MapExp.SubExp); + + // + // Go through map expression list. + // + SubExpressionLink = GetFirstNode (&ExpressionOpCode->MapExpressionList); + while (!IsNull (&ExpressionOpCode->MapExpressionList, SubExpressionLink)) { + SubExpression = HII_EXPRESSION_FROM_LINK (SubExpressionLink); + // + // Get the first expression description in this pair. + // + GetHiiExpressionDependency (SubExpression); + DepExpressionOpCode->MapExp.ExpPair[MapPairCount].MatchExp = SubExpression->RootDependencyExp; + + // + // Get the second expression description in this pair. + // + SubExpressionLink = GetNextNode (&ExpressionOpCode->MapExpressionList, SubExpressionLink); + SubExpression = HII_EXPRESSION_FROM_LINK (SubExpressionLink); + GetHiiExpressionDependency (SubExpression); + DepExpressionOpCode->MapExp.ExpPair[MapPairCount].ReturnExp = SubExpression->RootDependencyExp; + // + // Goto the first expression on next pair. + // + SubExpressionLink = GetNextNode (&ExpressionOpCode->MapExpressionList, SubExpressionLink); + MapPairCount++; + } + + PushDependencyExpDes (&DepExpressionOpCode); + break; + + default: + break; + } + } + + PopDependencyExpDes (&Expression->RootDependencyExp); + +Done: + return Status; +} + +/** + Return the result of the expression list. Check the expression list and + return the highest priority express result. + Priority: DisableIf > SuppressIf > GrayOutIf > FALSE + + @param[in] ExpList The input expression list. + @param[in] Evaluate Whether need to evaluate the expression first. + @param[in] FormSet FormSet associated with this expression. + @param[in] Form Form associated with this expression. + + @retval EXPRESS_RESULT Return the higher priority express result. + DisableIf > SuppressIf > GrayOutIf > FALSE + +**/ +EXPRESS_RESULT +EvaluateExpressionList ( + IN HII_EXPRESSION_LIST *ExpList, + IN BOOLEAN Evaluate, + IN HII_FORMSET *FormSet OPTIONAL, + IN HII_FORM *Form OPTIONAL + ) +{ + UINTN Index; + EXPRESS_RESULT ReturnVal; + EXPRESS_RESULT CompareOne; + EFI_STATUS Status; + + if (ExpList == NULL) { + return ExpressFalse; + } + + ASSERT (ExpList->Signature == HII_EXPRESSION_LIST_SIGNATURE); + Index = 0; + + // + // Check whether need to evaluate the expression first. + // + if (Evaluate) { + while (ExpList->Count > Index) { + Status = EvaluateHiiExpression (FormSet, Form, ExpList->Expression[Index++]); + if (EFI_ERROR (Status)) { + return ExpressFalse; + } + } + } + + // + // Run the list of expressions. + // + ReturnVal = ExpressFalse; + for (Index = 0; Index < ExpList->Count; Index++) { + if (IsHiiValueTrue (&ExpList->Expression[Index]->Result)) { + switch (ExpList->Expression[Index]->Type) { + case EFI_HII_EXPRESSION_SUPPRESS_IF: + CompareOne = ExpressSuppress; + break; + + case EFI_HII_EXPRESSION_GRAY_OUT_IF: + CompareOne = ExpressGrayOut; + break; + + case EFI_HII_EXPRESSION_DISABLE_IF: + CompareOne = ExpressDisable; + break; + + default: + return ExpressFalse; + } + + ReturnVal = ReturnVal < CompareOne ? CompareOne : ReturnVal; + } + } + + return ReturnVal; +} diff --git a/RedfishPkg/Library/HiiUtilityLib/HiiExpression.h b/RedfishPkg/Library/HiiUtilityLib/HiiExpression.h new file mode 100644 index 0000000000..dda96ada60 --- /dev/null +++ b/RedfishPkg/Library/HiiUtilityLib/HiiExpression.h @@ -0,0 +1,191 @@ +/** @file + Definitions of Hii Expression. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef HII_EXPRESSION_H_ +#define HII_EXPRESSION_H_ + +#include + +/** + Get the expression list count. + + @param[in] Level Which type this expression belong to. Form, + statement or option? + + @retval >=0 The expression count + @retval -1 Input parameter error. + +**/ +INTN +GetConditionalExpressionCount ( + IN EXPRESS_LEVEL Level + ); + +/** + Get the expression Buffer pointer. + + @param[in] Level Which type this expression belong to. Form, + statement or option? + + @retval The start pointer of the expression buffer or NULL. + +**/ +HII_EXPRESSION ** +GetConditionalExpressionList ( + IN EXPRESS_LEVEL Level + ); + +/** + Push the expression options onto the Stack. + + @param[in] Pointer Pointer to the current expression. + @param[in] Level Which type this expression belong to. Form, + statement or option? + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushConditionalExpression ( + IN HII_EXPRESSION *Pointer, + IN EXPRESS_LEVEL Level + ); + +/** + Pop the expression options from the Stack + + @param[in] Level Which type this expression belong to. Form, + statement or option? + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopConditionalExpression ( + IN EXPRESS_LEVEL Level + ); + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetCurrentExpressionStack ( + VOID + ); + +/** + Push current expression onto the Stack + + @param[in] Pointer Pointer to current expression. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushCurrentExpression ( + IN VOID *Pointer + ); + +/** + Pop current expression from the Stack + + @param[in] Pointer Pointer to current expression to be pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopCurrentExpression ( + OUT VOID **Pointer + ); + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetMapExpressionListStack ( + VOID + ); + +/** + Push the list of map expression onto the Stack + + @param[in] Pointer Pointer to the list of map expression to be pushed. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PushMapExpressionList ( + IN VOID *Pointer + ); + +/** + Pop the list of map expression from the Stack + + @param[in] Pointer Pointer to the list of map expression to be pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the stack. + +**/ +EFI_STATUS +PopMapExpressionList ( + OUT VOID **Pointer + ); + +/** + Reset stack pointer to begin of the stack. + +**/ +VOID +ResetScopeStack ( + VOID + ); + +/** + Push an Operand onto the Stack + + @param[in] Operand Operand to push. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the + stack. + +**/ +EFI_STATUS +PushScope ( + IN UINT8 Operand + ); + +/** + Pop an Operand from the Stack + + @param[out] Operand Operand to pop. + + @retval EFI_SUCCESS The value was pushed onto the stack. + @retval EFI_OUT_OF_RESOURCES There is not enough system memory to grow the + stack. + +**/ +EFI_STATUS +PopScope ( + OUT UINT8 *Operand + ); + +#endif diff --git a/RedfishPkg/Library/HiiUtilityLib/HiiIfrParse.c b/RedfishPkg/Library/HiiUtilityLib/HiiIfrParse.c new file mode 100644 index 0000000000..a51d7b9c6d --- /dev/null +++ b/RedfishPkg/Library/HiiUtilityLib/HiiIfrParse.c @@ -0,0 +1,2715 @@ +/** @file + The implementation of HII IFR parser. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP
+ Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "HiiInternal.h" + +/** + Initialize Statement header members. + + @param[in] OpCodeData Pointer of the raw OpCode data. + @param[in,out] FormSet Pointer of the current FormSet. + @param[in,out] Form Pointer of the current Form. + + @return The Statement. + +**/ +HII_STATEMENT * +CreateStatement ( + IN UINT8 *OpCodeData, + IN OUT HII_FORMSET *FormSet, + IN OUT HII_FORM *Form + ) +{ + HII_STATEMENT *Statement; + EFI_IFR_STATEMENT_HEADER *StatementHdr; + INTN ConditionalExprCount; + + if (Form == NULL) { + // + // Only guid op may out side the form level. + // + if (((EFI_IFR_OP_HEADER *)OpCodeData)->OpCode != EFI_IFR_GUID_OP) { + return NULL; + } + } + + Statement = (HII_STATEMENT *)AllocateZeroPool (sizeof (HII_STATEMENT)); + if (Statement == NULL) { + return NULL; + } + + InitializeListHead (&Statement->DefaultListHead); + InitializeListHead (&Statement->OptionListHead); + InitializeListHead (&Statement->InconsistentListHead); + InitializeListHead (&Statement->NoSubmitListHead); + InitializeListHead (&Statement->WarningListHead); + + Statement->Signature = HII_STATEMENT_SIGNATURE; + Statement->Operand = ((EFI_IFR_OP_HEADER *)OpCodeData)->OpCode; + Statement->OpCode = (EFI_IFR_OP_HEADER *)OpCodeData; + Statement->QuestionReferToBitField = FALSE; + + StatementHdr = (EFI_IFR_STATEMENT_HEADER *)(OpCodeData + sizeof (EFI_IFR_OP_HEADER)); + CopyMem (&Statement->Prompt, &StatementHdr->Prompt, sizeof (EFI_STRING_ID)); + CopyMem (&Statement->Help, &StatementHdr->Help, sizeof (EFI_STRING_ID)); + + ConditionalExprCount = GetConditionalExpressionCount (ExpressStatement); + if (ConditionalExprCount > 0) { + // + // Form is inside of suppressif + // + Statement->ExpressionList = (HII_EXPRESSION_LIST *)AllocatePool ( + (UINTN)(sizeof (HII_EXPRESSION_LIST) + ((ConditionalExprCount - 1) * sizeof (HII_EXPRESSION *))) + ); + if (Statement->ExpressionList == NULL) { + return NULL; + } + + Statement->ExpressionList->Count = (UINTN)ConditionalExprCount; + Statement->ExpressionList->Signature = HII_EXPRESSION_LIST_SIGNATURE; + CopyMem ( + Statement->ExpressionList->Expression, + GetConditionalExpressionList (ExpressStatement), + (UINTN)(sizeof (HII_EXPRESSION *) * ConditionalExprCount) + ); + } + + // + // Insert this Statement into current Form + // + if (Form == NULL) { + InsertTailList (&FormSet->StatementListOSF, &Statement->Link); + } else { + InsertTailList (&Form->StatementListHead, &Statement->Link); + } + + return Statement; +} + +/** + Initialize Question's members. + + @param[in] OpCodeData Pointer of the raw OpCode data. + @param[in,out] FormSet Pointer of the current FormSet. + @param[in,out] Form Pointer of the current Form. + + @return The Question. + +**/ +HII_STATEMENT * +CreateQuestion ( + IN UINT8 *OpCodeData, + IN OUT HII_FORMSET *FormSet, + IN OUT HII_FORM *Form + ) +{ + HII_STATEMENT *Statement; + EFI_IFR_QUESTION_HEADER *QuestionHdr; + LIST_ENTRY *Link; + HII_FORMSET_STORAGE *Storage; + HII_NAME_VALUE_NODE *NameValueNode; + BOOLEAN Find; + + Statement = CreateStatement (OpCodeData, FormSet, Form); + if (Statement == NULL) { + return NULL; + } + + QuestionHdr = (EFI_IFR_QUESTION_HEADER *)(OpCodeData + sizeof (EFI_IFR_OP_HEADER)); + CopyMem (&Statement->QuestionId, &QuestionHdr->QuestionId, sizeof (EFI_QUESTION_ID)); + CopyMem (&Statement->VarStoreId, &QuestionHdr->VarStoreId, sizeof (EFI_VARSTORE_ID)); + CopyMem (&Statement->VarStoreInfo.VarOffset, &QuestionHdr->VarStoreInfo.VarOffset, sizeof (UINT16)); + + Statement->QuestionFlags = QuestionHdr->Flags; + + if (Statement->VarStoreId == 0) { + // + // VarStoreId of zero indicates no variable storage + // + return Statement; + } + + // + // Find Storage for this Question + // + Link = GetFirstNode (&FormSet->StorageListHead); + while (!IsNull (&FormSet->StorageListHead, Link)) { + Storage = HII_STORAGE_FROM_LINK (Link); + + if (Statement->VarStoreId == Storage->VarStoreId) { + Statement->Storage = Storage; + break; + } + + Link = GetNextNode (&FormSet->StorageListHead, Link); + } + + if (Statement->Storage == NULL) { + return NULL; + } + + // + // Initialize varname for Name/Value or EFI Variable + // + if ((Statement->Storage->Type == EFI_HII_VARSTORE_NAME_VALUE) || + (Statement->Storage->Type == EFI_HII_VARSTORE_EFI_VARIABLE)) + { + Statement->VariableName = GetTokenString (Statement->VarStoreInfo.VarName, FormSet->HiiHandle); + if (Statement->VariableName == NULL) { + return NULL; + } + + if (Statement->Storage->Type == EFI_HII_VARSTORE_NAME_VALUE) { + // + // Check whether old string node already exist. + // + Find = FALSE; + if (!IsListEmpty (&Statement->Storage->NameValueList)) { + Link = GetFirstNode (&Statement->Storage->NameValueList); + while (!IsNull (&Statement->Storage->NameValueList, Link)) { + NameValueNode = HII_NAME_VALUE_NODE_FROM_LINK (Link); + + if (StrCmp (Statement->VariableName, NameValueNode->Name) == 0) { + Find = TRUE; + break; + } + + Link = GetNextNode (&Statement->Storage->NameValueList, Link); + } + } + + if (!Find) { + // + // Insert to Name/Value varstore list + // + NameValueNode = AllocateZeroPool (sizeof (HII_NAME_VALUE_NODE)); + if (NameValueNode == NULL) { + return NULL; + } + + NameValueNode->Signature = HII_NAME_VALUE_NODE_SIGNATURE; + NameValueNode->Name = AllocateCopyPool (StrSize (Statement->VariableName), Statement->VariableName); + if (NameValueNode->Name == NULL) { + FreePool (NameValueNode); + return NULL; + } + + NameValueNode->Value = AllocateZeroPool (0x10); + if (NameValueNode->Value == NULL) { + FreePool (NameValueNode->Name); + FreePool (NameValueNode); + return NULL; + } + + InsertTailList (&Statement->Storage->NameValueList, &NameValueNode->Link); + } + } + } + + return Statement; +} + +/** + Allocate a HII_EXPRESSION node. + + @param[in,out] Form The Form associated with this Expression + @param[in] OpCode The binary opcode data. + + @return Pointer to a HII_EXPRESSION data structure. + +**/ +HII_EXPRESSION * +CreateExpression ( + IN OUT HII_FORM *Form, + IN UINT8 *OpCode + ) +{ + HII_EXPRESSION *Expression; + + Expression = AllocateZeroPool (sizeof (HII_EXPRESSION)); + if (Expression == NULL) { + return NULL; + } + + Expression->Signature = HII_EXPRESSION_SIGNATURE; + InitializeListHead (&Expression->OpCodeListHead); + Expression->OpCode = (EFI_IFR_OP_HEADER *)OpCode; + + return Expression; +} + +/** + Create ConfigHdr string for a storage. + + @param[in] FormSet Pointer of the current FormSet + @param[in,out] Storage Pointer of the storage + + @retval EFI_SUCCESS Initialize ConfigHdr success + +**/ +EFI_STATUS +InitializeConfigHdr ( + IN HII_FORMSET *FormSet, + IN OUT HII_FORMSET_STORAGE *Storage + ) +{ + CHAR16 *Name; + + if ((Storage->Type == EFI_HII_VARSTORE_BUFFER) || + (Storage->Type == EFI_HII_VARSTORE_EFI_VARIABLE_BUFFER)) + { + Name = Storage->Name; + } else { + Name = NULL; + } + + Storage->ConfigHdr = HiiConstructConfigHdr ( + &Storage->Guid, + Name, + FormSet->DriverHandle + ); + + if (Storage->ConfigHdr == NULL) { + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; +} + +/** + Convert Ascii string to Unicode. + + This is an internal function. + + @param[in] AsciiString The Ascii string to be converted. + @param[out] UnicodeString The Unicode string retrieved. + +**/ +VOID +AsciiToUnicode ( + IN CHAR8 *AsciiString, + OUT CHAR16 *UnicodeString + ) +{ + UINT8 Index; + + Index = 0; + while (AsciiString[Index] != 0) { + UnicodeString[Index] = (CHAR16)AsciiString[Index]; + Index++; + } + + UnicodeString[Index] = L'\0'; +} + +/** + Allocate a HII_FORMSET_STORAGE data structure and insert to FormSet Storage List. + + @param[in] FormSet Pointer of the current FormSet + @param[in] StorageType Storage type. + @param[in] OpCodeData Binary data for this opcode. + + @return Pointer to a HII_FORMSET_STORAGE data structure. + +**/ +HII_FORMSET_STORAGE * +CreateStorage ( + IN HII_FORMSET *FormSet, + IN UINT8 StorageType, + IN UINT8 *OpCodeData + ) +{ + HII_FORMSET_STORAGE *Storage; + CHAR8 *AsciiStorageName; + + AsciiStorageName = NULL; + + Storage = AllocateZeroPool (sizeof (HII_FORMSET_STORAGE)); + if (Storage == NULL) { + return NULL; + } + + Storage->Signature = HII_STORAGE_SIGNATURE; + Storage->Type = StorageType; + + switch (StorageType) { + case EFI_HII_VARSTORE_BUFFER: + + CopyMem (&Storage->Guid, &((EFI_IFR_VARSTORE *)OpCodeData)->Guid, sizeof (EFI_GUID)); + CopyMem (&Storage->Size, &((EFI_IFR_VARSTORE *)OpCodeData)->Size, sizeof (UINT16)); + + Storage->Buffer = AllocateZeroPool (Storage->Size); + if (Storage->Buffer == NULL) { + FreePool (Storage); + return NULL; + } + + AsciiStorageName = (CHAR8 *)((EFI_IFR_VARSTORE *)OpCodeData)->Name; + Storage->Name = AllocatePool (sizeof (CHAR16) * (AsciiStrLen (AsciiStorageName) + 1)); + if (Storage->Name == NULL) { + FreePool (Storage); + return NULL; + } + + AsciiToUnicode (AsciiStorageName, Storage->Name); + + break; + + case EFI_HII_VARSTORE_EFI_VARIABLE: + case EFI_HII_VARSTORE_EFI_VARIABLE_BUFFER: + CopyMem (&Storage->Guid, &((EFI_IFR_VARSTORE_EFI *)OpCodeData)->Guid, sizeof (EFI_GUID)); + CopyMem (&Storage->Attributes, &((EFI_IFR_VARSTORE_EFI *)OpCodeData)->Attributes, sizeof (UINT32)); + CopyMem (&Storage->Size, &((EFI_IFR_VARSTORE_EFI *)OpCodeData)->Size, sizeof (UINT16)); + + if (StorageType == EFI_HII_VARSTORE_EFI_VARIABLE_BUFFER) { + Storage->Buffer = AllocateZeroPool (Storage->Size); + if (Storage->Buffer == NULL) { + FreePool (Storage); + return NULL; + } + } + + AsciiStorageName = (CHAR8 *)((EFI_IFR_VARSTORE_EFI *)OpCodeData)->Name; + Storage->Name = AllocatePool (sizeof (CHAR16) * (AsciiStrLen (AsciiStorageName) + 1)); + if (Storage->Name == NULL) { + FreePool (Storage); + return NULL; + } + + AsciiToUnicode (AsciiStorageName, Storage->Name); + + break; + + case EFI_HII_VARSTORE_NAME_VALUE: + CopyMem (&Storage->Guid, &((EFI_IFR_VARSTORE_NAME_VALUE *)OpCodeData)->Guid, sizeof (EFI_GUID)); + InitializeListHead (&Storage->NameValueList); + + break; + + default: + break; + } + + InitializeConfigHdr (FormSet, Storage); + InsertTailList (&FormSet->StorageListHead, &Storage->Link); + + return Storage; +} + +/** + Get formset storage based on the input varstoreid info. + + @param[in] FormSet Pointer of the current FormSet. + @param[in] VarStoreId Varstore ID info. + + @return Pointer to a HII_FORMSET_STORAGE data structure. + +**/ +HII_FORMSET_STORAGE * +GetFstStgFromVarId ( + IN HII_FORMSET *FormSet, + IN EFI_VARSTORE_ID VarStoreId + ) +{ + HII_FORMSET_STORAGE *Storage; + LIST_ENTRY *Link; + BOOLEAN Found; + + Found = FALSE; + Storage = NULL; + // + // Find Formset Storage for this Question + // + Link = GetFirstNode (&FormSet->StorageListHead); + while (!IsNull (&FormSet->StorageListHead, Link)) { + Storage = HII_STORAGE_FROM_LINK (Link); + + if (Storage->VarStoreId == VarStoreId) { + Found = TRUE; + break; + } + + Link = GetNextNode (&FormSet->StorageListHead, Link); + } + + return Found ? Storage : NULL; +} + +/** + Initialize Request Element of a Question. ::= '&' | '&'